]> git.xonotic.org Git - xonotic/darkplaces.git/blob - model_alias.c
patch from div to fix icc warnings
[xonotic/darkplaces.git] / model_alias.c
1 /*
2 Copyright (C) 1996-1997 Id Software, Inc.
3
4 This program is free software; you can redistribute it and/or
5 modify it under the terms of the GNU General Public License
6 as published by the Free Software Foundation; either version 2
7 of the License, or (at your option) any later version.
8
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
12
13 See the GNU General Public License for more details.
14
15 You should have received a copy of the GNU General Public License
16 along with this program; if not, write to the Free Software
17 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
18
19 */
20
21 #include "quakedef.h"
22 #include "image.h"
23 #include "r_shadow.h"
24
25 cvar_t r_skeletal_debugbone = {0, "r_skeletal_debugbone", "-1", "development cvar for testing skeletal model code"};
26 cvar_t r_skeletal_debugbonecomponent = {0, "r_skeletal_debugbonecomponent", "3", "development cvar for testing skeletal model code"};
27 cvar_t r_skeletal_debugbonevalue = {0, "r_skeletal_debugbonevalue", "100", "development cvar for testing skeletal model code"};
28 cvar_t r_skeletal_debugtranslatex = {0, "r_skeletal_debugtranslatex", "1", "development cvar for testing skeletal model code"};
29 cvar_t r_skeletal_debugtranslatey = {0, "r_skeletal_debugtranslatey", "1", "development cvar for testing skeletal model code"};
30 cvar_t r_skeletal_debugtranslatez = {0, "r_skeletal_debugtranslatez", "1", "development cvar for testing skeletal model code"};
31
32 float mod_md3_sin[320];
33
34 void Mod_AliasInit (void)
35 {
36         int i;
37         Cvar_RegisterVariable(&r_skeletal_debugbone);
38         Cvar_RegisterVariable(&r_skeletal_debugbonecomponent);
39         Cvar_RegisterVariable(&r_skeletal_debugbonevalue);
40         Cvar_RegisterVariable(&r_skeletal_debugtranslatex);
41         Cvar_RegisterVariable(&r_skeletal_debugtranslatey);
42         Cvar_RegisterVariable(&r_skeletal_debugtranslatez);
43         for (i = 0;i < 320;i++)
44                 mod_md3_sin[i] = sin(i * M_PI * 2.0f / 256.0);
45 }
46
47 void Mod_Alias_GetMesh_Vertices(const model_t *model, const frameblend_t *frameblend, float *vertex3f, float *normal3f, float *svector3f, float *tvector3f)
48 {
49         if (model->surfmesh.data_vertexweightindex4i)
50         {
51                 int i, k, blends;
52                 const float *v = model->surfmesh.data_vertex3f;
53                 const float *n = model->surfmesh.data_normal3f;
54                 const float *sv = model->surfmesh.data_svector3f;
55                 const float *tv = model->surfmesh.data_tvector3f;
56                 const int *wi = model->surfmesh.data_vertexweightindex4i;
57                 const float *wf = model->surfmesh.data_vertexweightinfluence4f;
58                 float *matrix, m[12], bonepose[256][12], boneposerelative[256][12];
59                 // vertex weighted skeletal
60                 memset(vertex3f, 0, model->surfmesh.num_vertices * sizeof(float[3]));
61                 if (normal3f)
62                         memset(normal3f, 0, model->surfmesh.num_vertices * sizeof(float[3]));
63                 if (svector3f)
64                 {
65                         memset(svector3f, 0, model->surfmesh.num_vertices * sizeof(float[3]));
66                         memset(tvector3f, 0, model->surfmesh.num_vertices * sizeof(float[3]));
67                 }
68                 // interpolate matrices and concatenate them to their parents
69                 for (i = 0;i < model->num_bones;i++)
70                 {
71                         for (k = 0;k < 12;k++)
72                                 m[k] = 0;
73                         for (blends = 0;blends < 4 && frameblend[blends].lerp > 0;blends++)
74                         {
75                                 matrix = model->data_poses + (frameblend[blends].frame * model->num_bones + i) * 12;
76                                 for (k = 0;k < 12;k++)
77                                         m[k] += matrix[k] * frameblend[blends].lerp;
78                         }
79                         if (i == r_skeletal_debugbone.integer)
80                                 m[r_skeletal_debugbonecomponent.integer % 12] += r_skeletal_debugbonevalue.value;
81                         m[3] *= r_skeletal_debugtranslatex.value;
82                         m[7] *= r_skeletal_debugtranslatey.value;
83                         m[11] *= r_skeletal_debugtranslatez.value;
84                         if (model->data_bones[i].parent >= 0)
85                                 R_ConcatTransforms(bonepose[model->data_bones[i].parent], m, bonepose[i]);
86                         else
87                                 for (k = 0;k < 12;k++)
88                                         bonepose[i][k] = m[k];
89                         // create a relative deformation matrix to describe displacement
90                         // from the base mesh, which is used by the actual weighting
91                         R_ConcatTransforms(bonepose[i], model->data_baseboneposeinverse + i * 12, boneposerelative[i]);
92                 }
93                 // blend the vertex bone weights
94                 if (svector3f)
95                 {
96                         for (i = 0;i < model->surfmesh.num_vertices;i++, v += 3, n += 3, sv += 3, tv += 3, wi += 4, wf += 4, vertex3f += 3, normal3f += 3, svector3f += 3, tvector3f += 3)
97                         {
98                                 for (k = 0;k < 4 && wf[k];k++)
99                                 {
100                                         const float *m = boneposerelative[wi[k]];
101                                         float f = wf[k];
102                                         vertex3f[0] += f * (v[0] * m[0] + v[1] * m[1] + v[2] * m[ 2] + m[ 3]);
103                                         vertex3f[1] += f * (v[0] * m[4] + v[1] * m[5] + v[2] * m[ 6] + m[ 7]);
104                                         vertex3f[2] += f * (v[0] * m[8] + v[1] * m[9] + v[2] * m[10] + m[11]);
105                                         normal3f[0] += f * (n[0] * m[0] + n[1] * m[1] + n[2] * m[ 2]);
106                                         normal3f[1] += f * (n[0] * m[4] + n[1] * m[5] + n[2] * m[ 6]);
107                                         normal3f[2] += f * (n[0] * m[8] + n[1] * m[9] + n[2] * m[10]);
108                                         svector3f[0] += f * (sv[0] * m[0] + sv[1] * m[1] + sv[2] * m[ 2]);
109                                         svector3f[1] += f * (sv[0] * m[4] + sv[1] * m[5] + sv[2] * m[ 6]);
110                                         svector3f[2] += f * (sv[0] * m[8] + sv[1] * m[9] + sv[2] * m[10]);
111                                         tvector3f[0] += f * (tv[0] * m[0] + tv[1] * m[1] + tv[2] * m[ 2]);
112                                         tvector3f[1] += f * (tv[0] * m[4] + tv[1] * m[5] + tv[2] * m[ 6]);
113                                         tvector3f[2] += f * (tv[0] * m[8] + tv[1] * m[9] + tv[2] * m[10]);
114                                 }
115                         }
116                 }
117                 else if (normal3f)
118                 {
119                         for (i = 0;i < model->surfmesh.num_vertices;i++, v += 3, n += 3, wi += 4, wf += 4, vertex3f += 3, normal3f += 3)
120                         {
121                                 for (k = 0;k < 4 && wf[k];k++)
122                                 {
123                                         const float *m = boneposerelative[wi[k]];
124                                         float f = wf[k];
125                                         vertex3f[0] += f * (v[0] * m[0] + v[1] * m[1] + v[2] * m[ 2] + m[ 3]);
126                                         vertex3f[1] += f * (v[0] * m[4] + v[1] * m[5] + v[2] * m[ 6] + m[ 7]);
127                                         vertex3f[2] += f * (v[0] * m[8] + v[1] * m[9] + v[2] * m[10] + m[11]);
128                                         normal3f[0] += f * (n[0] * m[0] + n[1] * m[1] + n[2] * m[ 2]);
129                                         normal3f[1] += f * (n[0] * m[4] + n[1] * m[5] + n[2] * m[ 6]);
130                                         normal3f[2] += f * (n[0] * m[8] + n[1] * m[9] + n[2] * m[10]);
131                                 }
132                         }
133                 }
134                 else
135                 {
136                         for (i = 0;i < model->surfmesh.num_vertices;i++, v += 3, wi += 4, wf += 4, vertex3f += 3)
137                         {
138                                 for (k = 0;k < 4 && wf[k];k++)
139                                 {
140                                         const float *m = boneposerelative[wi[k]];
141                                         float f = wf[k];
142                                         vertex3f[0] += f * (v[0] * m[0] + v[1] * m[1] + v[2] * m[ 2] + m[ 3]);
143                                         vertex3f[1] += f * (v[0] * m[4] + v[1] * m[5] + v[2] * m[ 6] + m[ 7]);
144                                         vertex3f[2] += f * (v[0] * m[8] + v[1] * m[9] + v[2] * m[10] + m[11]);
145                                 }
146                         }
147                 }
148         }
149         else if (model->surfmesh.data_morphmd3vertex)
150         {
151                 // vertex morph
152                 int i, numblends, blendnum;
153                 int numverts = model->surfmesh.num_vertices;
154                 numblends = 0;
155                 for (blendnum = 0;blendnum < 4;blendnum++)
156                 {
157                         //VectorMA(translate, model->surfmesh.num_morphmdlframetranslate, frameblend[blendnum].lerp, translate);
158                         if (frameblend[blendnum].lerp > 0)
159                                 numblends = blendnum + 1;
160                 }
161                 memset(vertex3f, 0, numverts * sizeof(float[3]));
162                 if (normal3f)
163                         for (i = 0;i < numverts;i++)
164                                 VectorClear(normal3f + i * 3);
165                 for (blendnum = 0;blendnum < numblends;blendnum++)
166                 {
167                         const md3vertex_t *verts = model->surfmesh.data_morphmd3vertex + numverts * frameblend[blendnum].frame;
168                         float scale = frameblend[blendnum].lerp * (1.0f / 64.0f);
169                         for (i = 0;i < numverts;i++)
170                         {
171                                 vertex3f[i * 3 + 0] += verts[i].origin[0] * scale;
172                                 vertex3f[i * 3 + 1] += verts[i].origin[1] * scale;
173                                 vertex3f[i * 3 + 2] += verts[i].origin[2] * scale;
174                         }
175                         // the yaw and pitch stored in md3 models are 8bit quantized angles
176                         // (0-255), and as such a lookup table is very well suited to
177                         // decoding them, and since cosine is equivilant to sine with an
178                         // extra 45 degree rotation, this uses one lookup table for both
179                         // sine and cosine with a +64 bias to get cosine.
180                         if (normal3f)
181                         {
182                                 float lerp = frameblend[blendnum].lerp;
183                                 for (i = 0;i < numverts;i++)
184                                 {
185                                         normal3f[i * 3 + 0] += mod_md3_sin[verts[i].yaw + 64] * mod_md3_sin[verts[i].pitch     ] * lerp;
186                                         normal3f[i * 3 + 1] += mod_md3_sin[verts[i].yaw     ] * mod_md3_sin[verts[i].pitch     ] * lerp;
187                                         normal3f[i * 3 + 2] +=                                  mod_md3_sin[verts[i].pitch + 64] * lerp;
188                                 }
189                         }
190                 }
191                 if (normal3f)
192                         if (svector3f)
193                                 Mod_BuildTextureVectorsFromNormals(0, model->surfmesh.num_vertices, model->surfmesh.num_triangles, vertex3f, model->surfmesh.data_texcoordtexture2f, normal3f, model->surfmesh.data_element3i, svector3f, tvector3f, r_smoothnormals_areaweighting.integer);
194         }
195         else if (model->surfmesh.data_morphmdlvertex)
196         {
197                 // vertex morph
198                 int i, numblends, blendnum;
199                 int numverts = model->surfmesh.num_vertices;
200                 float translate[3];
201                 VectorClear(translate);
202                 numblends = 0;
203                 for (blendnum = 0;blendnum < 4;blendnum++)
204                 {
205                         if (model->surfmesh.data_morphmd2framesize6f)
206                                 VectorMA(translate, frameblend[blendnum].lerp, model->surfmesh.data_morphmd2framesize6f + frameblend[blendnum].frame * 6 + 3, translate);
207                         else
208                                 VectorMA(translate, frameblend[blendnum].lerp, model->surfmesh.num_morphmdlframetranslate, translate);
209                         if (frameblend[blendnum].lerp > 0)
210                                 numblends = blendnum + 1;
211                 }
212                 for (i = 0;i < numverts;i++)
213                         VectorCopy(translate, vertex3f + i * 3);
214                 if (normal3f)
215                         for (i = 0;i < numverts;i++)
216                                 VectorClear(normal3f + i * 3);
217                 for (blendnum = 0;blendnum < numblends;blendnum++)
218                 {
219                         const trivertx_t *verts = model->surfmesh.data_morphmdlvertex + numverts * frameblend[blendnum].frame;
220                         float scale[3];
221                         if (model->surfmesh.data_morphmd2framesize6f)
222                                 VectorScale(model->surfmesh.data_morphmd2framesize6f + frameblend[blendnum].frame * 6, frameblend[blendnum].lerp, scale);
223                         else
224                                 VectorScale(model->surfmesh.num_morphmdlframescale, frameblend[blendnum].lerp, scale);
225                         for (i = 0;i < numverts;i++)
226                         {
227                                 vertex3f[i * 3 + 0] += verts[i].v[0] * scale[0];
228                                 vertex3f[i * 3 + 1] += verts[i].v[1] * scale[1];
229                                 vertex3f[i * 3 + 2] += verts[i].v[2] * scale[2];
230                         }
231                         // the vertex normals in mdl models are an index into a table of
232                         // 162 unique values, this very crude quantization reduces the
233                         // vertex normal to only one byte, which saves a lot of space but
234                         // also makes lighting pretty coarse
235                         if (normal3f)
236                         {
237                                 float lerp = frameblend[blendnum].lerp;
238                                 for (i = 0;i < numverts;i++)
239                                 {
240                                         const float *vn = m_bytenormals[verts[i].lightnormalindex];
241                                         VectorMA(normal3f + i*3, lerp, vn, normal3f + i*3);
242                                 }
243                         }
244                 }
245                 if (normal3f)
246                         if (svector3f)
247                                 Mod_BuildTextureVectorsFromNormals(0, model->surfmesh.num_vertices, model->surfmesh.num_triangles, vertex3f, model->surfmesh.data_texcoordtexture2f, normal3f, model->surfmesh.data_element3i, svector3f, tvector3f, r_smoothnormals_areaweighting.integer);
248         }
249         else
250                 Host_Error("model %s has no skeletal or vertex morph animation data", model->name);
251 }
252
253 int Mod_Alias_GetTagMatrix(const model_t *model, int poseframe, int tagindex, matrix4x4_t *outmatrix)
254 {
255         const float *boneframe;
256         float tempbonematrix[12], bonematrix[12];
257         *outmatrix = identitymatrix;
258         if (model->num_bones)
259         {
260                 if (tagindex < 0 || tagindex >= model->num_bones)
261                         return 4;
262                 if (poseframe >= model->num_poses)
263                         return 6;
264                 boneframe = model->data_poses + poseframe * model->num_bones * 12;
265                 memcpy(bonematrix, boneframe + tagindex * 12, sizeof(float[12]));
266                 while (model->data_bones[tagindex].parent >= 0)
267                 {
268                         memcpy(tempbonematrix, bonematrix, sizeof(float[12]));
269                         R_ConcatTransforms(boneframe + model->data_bones[tagindex].parent * 12, tempbonematrix, bonematrix);
270                         tagindex = model->data_bones[tagindex].parent;
271                 }
272                 outmatrix->m[0][0] = bonematrix[0];
273                 outmatrix->m[0][1] = bonematrix[1];
274                 outmatrix->m[0][2] = bonematrix[2];
275                 outmatrix->m[0][3] = bonematrix[3];
276                 outmatrix->m[1][0] = bonematrix[4];
277                 outmatrix->m[1][1] = bonematrix[5];
278                 outmatrix->m[1][2] = bonematrix[6];
279                 outmatrix->m[1][3] = bonematrix[7];
280                 outmatrix->m[2][0] = bonematrix[8];
281                 outmatrix->m[2][1] = bonematrix[9];
282                 outmatrix->m[2][2] = bonematrix[10];
283                 outmatrix->m[2][3] = bonematrix[11];
284                 outmatrix->m[3][0] = 0;
285                 outmatrix->m[3][1] = 0;
286                 outmatrix->m[3][2] = 0;
287                 outmatrix->m[3][3] = 1;
288         }
289         else if (model->num_tags)
290         {
291                 if (tagindex < 0 || tagindex >= model->num_tags)
292                         return 4;
293                 if (poseframe >= model->num_tagframes)
294                         return 6;
295                 *outmatrix = model->data_tags[poseframe * model->num_tags + tagindex].matrix;
296         }
297         return 0;
298 }
299
300 int Mod_Alias_GetTagIndexForName(const model_t *model, unsigned int skin, const char *tagname)
301 {
302         int i;
303         if (model->data_overridetagnamesforskin && skin < (unsigned int)model->numskins && model->data_overridetagnamesforskin[(unsigned int)skin].num_overridetagnames)
304                 for (i = 0;i < model->data_overridetagnamesforskin[skin].num_overridetagnames;i++)
305                         if (!strcasecmp(tagname, model->data_overridetagnamesforskin[skin].data_overridetagnames[i].name))
306                                 return i + 1;
307         if (model->num_bones)
308                 for (i = 0;i < model->num_bones;i++)
309                         if (!strcasecmp(tagname, model->data_bones[i].name))
310                                 return i + 1;
311         if (model->num_tags)
312                 for (i = 0;i < model->num_tags;i++)
313                         if (!strcasecmp(tagname, model->data_tags[i].name))
314                                 return i + 1;
315         return 0;
316 }
317
318 static void Mod_BuildBaseBonePoses(void)
319 {
320         int i, k;
321         double scale;
322         float *in12f = loadmodel->data_poses;
323         float *out12f = loadmodel->data_basebonepose;
324         float *outinv12f = loadmodel->data_baseboneposeinverse;
325         for (i = 0;i < loadmodel->num_bones;i++, in12f += 12, out12f += 12, outinv12f += 12)
326         {
327                 if (loadmodel->data_bones[i].parent >= 0)
328                         R_ConcatTransforms(loadmodel->data_basebonepose + 12 * loadmodel->data_bones[i].parent, in12f, out12f);
329                 else
330                         for (k = 0;k < 12;k++)
331                                 out12f[k] = in12f[k];
332
333                 // invert The Matrix
334
335                 // we only support uniform scaling, so assume the first row is enough
336                 // (note the lack of sqrt here, because we're trying to undo the scaling,
337                 // this means multiplying by the inverse scale twice - squaring it, which
338                 // makes the sqrt a waste of time)
339                 scale = 1.0 / (out12f[ 0] * out12f[ 0] + out12f[ 1] * out12f[ 1] + out12f[ 2] * out12f[ 2]);
340
341                 // invert the rotation by transposing and multiplying by the squared
342                 // recipricol of the input matrix scale as described above
343                 outinv12f[ 0] = (float)(out12f[ 0] * scale);
344                 outinv12f[ 1] = (float)(out12f[ 4] * scale);
345                 outinv12f[ 2] = (float)(out12f[ 8] * scale);
346                 outinv12f[ 4] = (float)(out12f[ 1] * scale);
347                 outinv12f[ 5] = (float)(out12f[ 5] * scale);
348                 outinv12f[ 6] = (float)(out12f[ 9] * scale);
349                 outinv12f[ 8] = (float)(out12f[ 2] * scale);
350                 outinv12f[ 9] = (float)(out12f[ 6] * scale);
351                 outinv12f[10] = (float)(out12f[10] * scale);
352
353                 // invert the translate
354                 outinv12f[ 3] = -(out12f[ 3] * outinv12f[ 0] + out12f[ 7] * outinv12f[ 1] + out12f[11] * outinv12f[ 2]);
355                 outinv12f[ 7] = -(out12f[ 3] * outinv12f[ 4] + out12f[ 7] * outinv12f[ 5] + out12f[11] * outinv12f[ 6]);
356                 outinv12f[11] = -(out12f[ 3] * outinv12f[ 8] + out12f[ 7] * outinv12f[ 9] + out12f[11] * outinv12f[10]);
357         }
358 }
359
360 static void Mod_Alias_CalculateBoundingBox(void)
361 {
362         int i, j;
363         int vnum;
364         qboolean firstvertex = true;
365         float dist, yawradius, radius;
366         float *v;
367         float *vertex3f;
368         frameblend_t frameblend[4];
369         memset(frameblend, 0, sizeof(frameblend));
370         frameblend[0].lerp = 1;
371         vertex3f = Mem_Alloc(loadmodel->mempool, loadmodel->surfmesh.num_vertices * sizeof(float[3]));
372         VectorClear(loadmodel->normalmins);
373         VectorClear(loadmodel->normalmaxs);
374         yawradius = 0;
375         radius = 0;
376         for (i = 0;i < loadmodel->numframes;i++)
377         {
378                 for (j = 0, frameblend[0].frame = loadmodel->animscenes[i].firstframe;j < loadmodel->animscenes[i].framecount;j++, frameblend[0].frame++)
379                 {
380                         Mod_Alias_GetMesh_Vertices(loadmodel, frameblend, vertex3f, NULL, NULL, NULL);
381                         for (vnum = 0, v = vertex3f;vnum < loadmodel->surfmesh.num_vertices;vnum++, v += 3)
382                         {
383                                 if (firstvertex)
384                                 {
385                                         firstvertex = false;
386                                         VectorCopy(v, loadmodel->normalmins);
387                                         VectorCopy(v, loadmodel->normalmaxs);
388                                 }
389                                 else
390                                 {
391                                         if (loadmodel->normalmins[0] > v[0]) loadmodel->normalmins[0] = v[0];
392                                         if (loadmodel->normalmins[1] > v[1]) loadmodel->normalmins[1] = v[1];
393                                         if (loadmodel->normalmins[2] > v[2]) loadmodel->normalmins[2] = v[2];
394                                         if (loadmodel->normalmaxs[0] < v[0]) loadmodel->normalmaxs[0] = v[0];
395                                         if (loadmodel->normalmaxs[1] < v[1]) loadmodel->normalmaxs[1] = v[1];
396                                         if (loadmodel->normalmaxs[2] < v[2]) loadmodel->normalmaxs[2] = v[2];
397                                 }
398                                 dist = v[0] * v[0] + v[1] * v[1];
399                                 if (yawradius < dist)
400                                         yawradius = dist;
401                                 dist += v[2] * v[2];
402                                 if (radius < dist)
403                                         radius = dist;
404                         }
405                 }
406         }
407         Mem_Free(vertex3f);
408         radius = sqrt(radius);
409         yawradius = sqrt(yawradius);
410         loadmodel->yawmins[0] = loadmodel->yawmins[1] = -yawradius;
411         loadmodel->yawmaxs[0] = loadmodel->yawmaxs[1] = yawradius;
412         loadmodel->yawmins[2] = loadmodel->normalmins[2];
413         loadmodel->yawmaxs[2] = loadmodel->normalmaxs[2];
414         loadmodel->rotatedmins[0] = loadmodel->rotatedmins[1] = loadmodel->rotatedmins[2] = -radius;
415         loadmodel->rotatedmaxs[0] = loadmodel->rotatedmaxs[1] = loadmodel->rotatedmaxs[2] = radius;
416         loadmodel->radius = radius;
417         loadmodel->radius2 = radius * radius;
418 }
419
420 static void Mod_Alias_Mesh_CompileFrameZero(void)
421 {
422         frameblend_t frameblend[4] = {{0, 1}, {0, 0}, {0, 0}, {0, 0}};
423         loadmodel->surfmesh.data_vertex3f = (float *)Mem_Alloc(loadmodel->mempool, loadmodel->surfmesh.num_vertices * sizeof(float[3][4]));
424         loadmodel->surfmesh.data_svector3f = loadmodel->surfmesh.data_vertex3f + loadmodel->surfmesh.num_vertices * 3;
425         loadmodel->surfmesh.data_tvector3f = loadmodel->surfmesh.data_vertex3f + loadmodel->surfmesh.num_vertices * 6;
426         loadmodel->surfmesh.data_normal3f = loadmodel->surfmesh.data_vertex3f + loadmodel->surfmesh.num_vertices * 9;
427         Mod_Alias_GetMesh_Vertices(loadmodel, frameblend, loadmodel->surfmesh.data_vertex3f, NULL, NULL, NULL);
428         Mod_BuildNormals(0, loadmodel->surfmesh.num_vertices, loadmodel->surfmesh.num_triangles, loadmodel->surfmesh.data_vertex3f, loadmodel->surfmesh.data_element3i, loadmodel->surfmesh.data_normal3f, true);
429         Mod_BuildTextureVectorsFromNormals(0, loadmodel->surfmesh.num_vertices, loadmodel->surfmesh.num_triangles, loadmodel->surfmesh.data_vertex3f, loadmodel->surfmesh.data_texcoordtexture2f, loadmodel->surfmesh.data_normal3f, loadmodel->surfmesh.data_element3i, loadmodel->surfmesh.data_svector3f, loadmodel->surfmesh.data_tvector3f, true);
430 }
431
432 static void Mod_MDLMD2MD3_TraceBox(model_t *model, int frame, trace_t *trace, const vec3_t start, const vec3_t boxmins, const vec3_t boxmaxs, const vec3_t end, int hitsupercontentsmask)
433 {
434         int i;
435         float segmentmins[3], segmentmaxs[3];
436         frameblend_t frameblend[4];
437         msurface_t *surface;
438         static int maxvertices = 0;
439         static float *vertex3f = NULL;
440         memset(trace, 0, sizeof(*trace));
441         trace->fraction = 1;
442         trace->realfraction = 1;
443         trace->hitsupercontentsmask = hitsupercontentsmask;
444         memset(frameblend, 0, sizeof(frameblend));
445         frameblend[0].frame = frame;
446         frameblend[0].lerp = 1;
447         if (maxvertices < model->surfmesh.num_vertices)
448         {
449                 if (vertex3f)
450                         Z_Free(vertex3f);
451                 maxvertices = (model->surfmesh.num_vertices + 255) & ~255;
452                 vertex3f = (float *)Z_Malloc(maxvertices * sizeof(float[3]));
453         }
454         if (VectorLength2(boxmins) + VectorLength2(boxmaxs) == 0)
455         {
456                 // line trace
457                 segmentmins[0] = min(start[0], end[0]) - 1;
458                 segmentmins[1] = min(start[1], end[1]) - 1;
459                 segmentmins[2] = min(start[2], end[2]) - 1;
460                 segmentmaxs[0] = max(start[0], end[0]) + 1;
461                 segmentmaxs[1] = max(start[1], end[1]) + 1;
462                 segmentmaxs[2] = max(start[2], end[2]) + 1;
463                 for (i = 0, surface = model->data_surfaces;i < model->num_surfaces;i++, surface++)
464                 {
465                         Mod_Alias_GetMesh_Vertices(model, frameblend, vertex3f, NULL, NULL, NULL);
466                         Collision_TraceLineTriangleMeshFloat(trace, start, end, model->surfmesh.num_triangles, model->surfmesh.data_element3i, vertex3f, SUPERCONTENTS_SOLID, 0, surface->texture, segmentmins, segmentmaxs);
467                 }
468         }
469         else
470         {
471                 // box trace, performed as brush trace
472                 colbrushf_t *thisbrush_start, *thisbrush_end;
473                 vec3_t boxstartmins, boxstartmaxs, boxendmins, boxendmaxs;
474                 segmentmins[0] = min(start[0], end[0]) + boxmins[0] - 1;
475                 segmentmins[1] = min(start[1], end[1]) + boxmins[1] - 1;
476                 segmentmins[2] = min(start[2], end[2]) + boxmins[2] - 1;
477                 segmentmaxs[0] = max(start[0], end[0]) + boxmaxs[0] + 1;
478                 segmentmaxs[1] = max(start[1], end[1]) + boxmaxs[1] + 1;
479                 segmentmaxs[2] = max(start[2], end[2]) + boxmaxs[2] + 1;
480                 VectorAdd(start, boxmins, boxstartmins);
481                 VectorAdd(start, boxmaxs, boxstartmaxs);
482                 VectorAdd(end, boxmins, boxendmins);
483                 VectorAdd(end, boxmaxs, boxendmaxs);
484                 thisbrush_start = Collision_BrushForBox(&identitymatrix, boxstartmins, boxstartmaxs, 0, 0, NULL);
485                 thisbrush_end = Collision_BrushForBox(&identitymatrix, boxendmins, boxendmaxs, 0, 0, NULL);
486                 for (i = 0, surface = model->data_surfaces;i < model->num_surfaces;i++, surface++)
487                 {
488                         if (maxvertices < model->surfmesh.num_vertices)
489                         {
490                                 if (vertex3f)
491                                         Z_Free(vertex3f);
492                                 maxvertices = (model->surfmesh.num_vertices + 255) & ~255;
493                                 vertex3f = (float *)Z_Malloc(maxvertices * sizeof(float[3]));
494                         }
495                         Mod_Alias_GetMesh_Vertices(model, frameblend, vertex3f, NULL, NULL, NULL);
496                         Collision_TraceBrushTriangleMeshFloat(trace, thisbrush_start, thisbrush_end, model->surfmesh.num_triangles, model->surfmesh.data_element3i, vertex3f, SUPERCONTENTS_SOLID, 0, surface->texture, segmentmins, segmentmaxs);
497                 }
498         }
499 }
500
501 static void Mod_ConvertAliasVerts (int inverts, trivertx_t *v, trivertx_t *out, int *vertremap)
502 {
503         int i, j;
504         for (i = 0;i < inverts;i++)
505         {
506                 if (vertremap[i] < 0 && vertremap[i+inverts] < 0) // only used vertices need apply...
507                         continue;
508                 j = vertremap[i]; // not onseam
509                 if (j >= 0)
510                         out[j] = v[i];
511                 j = vertremap[i+inverts]; // onseam
512                 if (j >= 0)
513                         out[j] = v[i];
514         }
515 }
516
517 static void Mod_MDL_LoadFrames (unsigned char* datapointer, int inverts, int *vertremap)
518 {
519         int i, f, pose, groupframes;
520         float interval;
521         daliasframetype_t *pframetype;
522         daliasframe_t *pinframe;
523         daliasgroup_t *group;
524         daliasinterval_t *intervals;
525         animscene_t *scene;
526         pose = 0;
527         scene = loadmodel->animscenes;
528         for (f = 0;f < loadmodel->numframes;f++)
529         {
530                 pframetype = (daliasframetype_t *)datapointer;
531                 datapointer += sizeof(daliasframetype_t);
532                 if (LittleLong (pframetype->type) == ALIAS_SINGLE)
533                 {
534                         // a single frame is still treated as a group
535                         interval = 0.1f;
536                         groupframes = 1;
537                 }
538                 else
539                 {
540                         // read group header
541                         group = (daliasgroup_t *)datapointer;
542                         datapointer += sizeof(daliasgroup_t);
543                         groupframes = LittleLong (group->numframes);
544
545                         // intervals (time per frame)
546                         intervals = (daliasinterval_t *)datapointer;
547                         datapointer += sizeof(daliasinterval_t) * groupframes;
548
549                         interval = LittleFloat (intervals->interval); // FIXME: support variable framerate groups
550                         if (interval < 0.01f)
551                         {
552                                 Con_Printf("%s has an invalid interval %f, changing to 0.1\n", loadmodel->name, interval);
553                                 interval = 0.1f;
554                         }
555                 }
556
557                 // get scene name from first frame
558                 pinframe = (daliasframe_t *)datapointer;
559
560                 strlcpy(scene->name, pinframe->name, sizeof(scene->name));
561                 scene->firstframe = pose;
562                 scene->framecount = groupframes;
563                 scene->framerate = 1.0f / interval;
564                 scene->loop = true;
565                 scene++;
566
567                 // read frames
568                 for (i = 0;i < groupframes;i++)
569                 {
570                         pinframe = (daliasframe_t *)datapointer;
571                         datapointer += sizeof(daliasframe_t);
572                         Mod_ConvertAliasVerts(inverts, (trivertx_t *)datapointer, loadmodel->surfmesh.data_morphmdlvertex + pose * loadmodel->surfmesh.num_vertices, vertremap);
573                         datapointer += sizeof(trivertx_t) * inverts;
574                         pose++;
575                 }
576         }
577 }
578
579 static skinframe_t missingskinframe;
580 static void Mod_BuildAliasSkinFromSkinFrame(texture_t *skin, skinframe_t *skinframe)
581 {
582         // hack
583         if (skinframe == NULL)
584         {
585                 skinframe = &missingskinframe;
586                 memset(skinframe, 0, sizeof(*skinframe));
587                 skinframe->base = r_texture_notexture;
588         }
589
590         skin->skin = *skinframe;
591         skin->currentframe = skin;
592         skin->basematerialflags = MATERIALFLAG_WALL;
593         if (skin->skin.fog)
594                 skin->basematerialflags |= MATERIALFLAG_ALPHA | MATERIALFLAG_BLENDED | MATERIALFLAG_TRANSPARENT;
595         skin->currentmaterialflags = skin->basematerialflags;
596 }
597
598 static void Mod_BuildAliasSkinsFromSkinFiles(texture_t *skin, skinfile_t *skinfile, char *meshname, char *shadername)
599 {
600         int i;
601         skinfileitem_t *skinfileitem;
602         skinframe_t tempskinframe;
603         if (skinfile)
604         {
605                 // the skin += loadmodel->num_surfaces part of this is because data_textures on alias models is arranged as [numskins][numsurfaces]
606                 for (i = 0;skinfile;skinfile = skinfile->next, i++, skin += loadmodel->num_surfaces)
607                 {
608                         memset(skin, 0, sizeof(*skin));
609                         for (skinfileitem = skinfile->items;skinfileitem;skinfileitem = skinfileitem->next)
610                         {
611                                 // leave the skin unitialized (nodraw) if the replacement is "common/nodraw" or "textures/common/nodraw"
612                                 if (!strcmp(skinfileitem->name, meshname) && strcmp(skinfileitem->replacement, "common/nodraw") && strcmp(skinfileitem->replacement, "textures/common/nodraw"))
613                                 {
614                                         memset(&tempskinframe, 0, sizeof(tempskinframe));
615                                         if (Mod_LoadSkinFrame(&tempskinframe, skinfileitem->replacement, (r_mipskins.integer ? TEXF_MIPMAP : 0) | TEXF_ALPHA | TEXF_PRECACHE | TEXF_PICMIP, true, true))
616                                                 Mod_BuildAliasSkinFromSkinFrame(skin, &tempskinframe);
617                                         else
618                                         {
619                                                 if (cls.state != ca_dedicated)
620                                                         Con_Printf("mesh \"%s\": failed to load skin #%i \"%s\", falling back to mesh's internal shader name \"%s\"\n", meshname, i, skinfileitem->replacement, shadername);
621                                                 if (Mod_LoadSkinFrame(&tempskinframe, shadername, (r_mipskins.integer ? TEXF_MIPMAP : 0) | TEXF_ALPHA | TEXF_PRECACHE | TEXF_PICMIP, true, true))
622                                                         Mod_BuildAliasSkinFromSkinFrame(skin, &tempskinframe);
623                                                 else
624                                                 {
625                                                         if (cls.state != ca_dedicated)
626                                                                 Con_Printf("failed to load skin \"%s\"\n", shadername);
627                                                         Mod_BuildAliasSkinFromSkinFrame(skin, NULL);
628                                                 }
629                                         }
630                                 }
631                         }
632                 }
633         }
634         else
635         {
636                 memset(&tempskinframe, 0, sizeof(tempskinframe));
637                 if (Mod_LoadSkinFrame(&tempskinframe, shadername, (r_mipskins.integer ? TEXF_MIPMAP : 0) | TEXF_ALPHA | TEXF_PRECACHE | TEXF_PICMIP, true, true))
638                         Mod_BuildAliasSkinFromSkinFrame(skin, &tempskinframe);
639                 else
640                 {
641                         if (cls.state != ca_dedicated)
642                                 Con_Printf("Can't find texture \"%s\" for mesh \"%s\", using grey checkerboard\n", shadername, meshname);
643                         Mod_BuildAliasSkinFromSkinFrame(skin, NULL);
644                 }
645         }
646 }
647
648 #define BOUNDI(VALUE,MIN,MAX) if (VALUE < MIN || VALUE >= MAX) Host_Error("model %s has an invalid ##VALUE (%d exceeds %d - %d)", loadmodel->name, VALUE, MIN, MAX);
649 #define BOUNDF(VALUE,MIN,MAX) if (VALUE < MIN || VALUE >= MAX) Host_Error("model %s has an invalid ##VALUE (%f exceeds %f - %f)", loadmodel->name, VALUE, MIN, MAX);
650 void Mod_IDP0_Load(model_t *mod, void *buffer, void *bufferend)
651 {
652         int i, j, version, totalskins, skinwidth, skinheight, groupframes, groupskins, numverts;
653         float scales, scalet, interval;
654         msurface_t *surface;
655         unsigned char *data;
656         mdl_t *pinmodel;
657         stvert_t *pinstverts;
658         dtriangle_t *pintriangles;
659         daliasskintype_t *pinskintype;
660         daliasskingroup_t *pinskingroup;
661         daliasskininterval_t *pinskinintervals;
662         daliasframetype_t *pinframetype;
663         daliasgroup_t *pinframegroup;
664         unsigned char *datapointer, *startframes, *startskins;
665         char name[MAX_QPATH];
666         skinframe_t tempskinframe;
667         animscene_t *tempskinscenes;
668         texture_t *tempaliasskins;
669         float *vertst;
670         int *vertonseam, *vertremap;
671         skinfile_t *skinfiles;
672
673         datapointer = (unsigned char *)buffer;
674         pinmodel = (mdl_t *)datapointer;
675         datapointer += sizeof(mdl_t);
676
677         version = LittleLong (pinmodel->version);
678         if (version != ALIAS_VERSION)
679                 Host_Error ("%s has wrong version number (%i should be %i)",
680                                  loadmodel->name, version, ALIAS_VERSION);
681
682         loadmodel->type = mod_alias;
683         loadmodel->DrawSky = NULL;
684         loadmodel->Draw = R_Q1BSP_Draw;
685         loadmodel->CompileShadowVolume = R_Q1BSP_CompileShadowVolume;
686         loadmodel->DrawShadowVolume = R_Q1BSP_DrawShadowVolume;
687         loadmodel->DrawLight = R_Q1BSP_DrawLight;
688         loadmodel->TraceBox = Mod_MDLMD2MD3_TraceBox;
689
690         loadmodel->num_surfaces = 1;
691         loadmodel->nummodelsurfaces = loadmodel->num_surfaces;
692         data = (unsigned char *)Mem_Alloc(loadmodel->mempool, loadmodel->num_surfaces * sizeof(msurface_t) + loadmodel->num_surfaces * sizeof(int));
693         loadmodel->data_surfaces = (msurface_t *)data;data += loadmodel->num_surfaces * sizeof(msurface_t);
694         loadmodel->surfacelist = (int *)data;data += loadmodel->num_surfaces * sizeof(int);
695         loadmodel->surfacelist[0] = 0;
696
697         loadmodel->numskins = LittleLong(pinmodel->numskins);
698         BOUNDI(loadmodel->numskins,0,65536);
699         skinwidth = LittleLong (pinmodel->skinwidth);
700         BOUNDI(skinwidth,0,65536);
701         skinheight = LittleLong (pinmodel->skinheight);
702         BOUNDI(skinheight,0,65536);
703         numverts = LittleLong(pinmodel->numverts);
704         BOUNDI(numverts,0,65536);
705         loadmodel->surfmesh.num_triangles = LittleLong(pinmodel->numtris);
706         BOUNDI(loadmodel->surfmesh.num_triangles,0,65536);
707         loadmodel->numframes = LittleLong(pinmodel->numframes);
708         BOUNDI(loadmodel->numframes,0,65536);
709         loadmodel->synctype = (synctype_t)LittleLong (pinmodel->synctype);
710         BOUNDI(loadmodel->synctype,0,2);
711         loadmodel->flags = LittleLong (pinmodel->flags);
712
713         for (i = 0;i < 3;i++)
714         {
715                 loadmodel->surfmesh.num_morphmdlframescale[i] = LittleFloat (pinmodel->scale[i]);
716                 loadmodel->surfmesh.num_morphmdlframetranslate[i] = LittleFloat (pinmodel->scale_origin[i]);
717         }
718
719         startskins = datapointer;
720         totalskins = 0;
721         for (i = 0;i < loadmodel->numskins;i++)
722         {
723                 pinskintype = (daliasskintype_t *)datapointer;
724                 datapointer += sizeof(daliasskintype_t);
725                 if (LittleLong(pinskintype->type) == ALIAS_SKIN_SINGLE)
726                         groupskins = 1;
727                 else
728                 {
729                         pinskingroup = (daliasskingroup_t *)datapointer;
730                         datapointer += sizeof(daliasskingroup_t);
731                         groupskins = LittleLong(pinskingroup->numskins);
732                         datapointer += sizeof(daliasskininterval_t) * groupskins;
733                 }
734
735                 for (j = 0;j < groupskins;j++)
736                 {
737                         datapointer += skinwidth * skinheight;
738                         totalskins++;
739                 }
740         }
741
742         pinstverts = (stvert_t *)datapointer;
743         datapointer += sizeof(stvert_t) * numverts;
744
745         pintriangles = (dtriangle_t *)datapointer;
746         datapointer += sizeof(dtriangle_t) * loadmodel->surfmesh.num_triangles;
747
748         startframes = datapointer;
749         loadmodel->surfmesh.num_morphframes = 0;
750         for (i = 0;i < loadmodel->numframes;i++)
751         {
752                 pinframetype = (daliasframetype_t *)datapointer;
753                 datapointer += sizeof(daliasframetype_t);
754                 if (LittleLong (pinframetype->type) == ALIAS_SINGLE)
755                         groupframes = 1;
756                 else
757                 {
758                         pinframegroup = (daliasgroup_t *)datapointer;
759                         datapointer += sizeof(daliasgroup_t);
760                         groupframes = LittleLong(pinframegroup->numframes);
761                         datapointer += sizeof(daliasinterval_t) * groupframes;
762                 }
763
764                 for (j = 0;j < groupframes;j++)
765                 {
766                         datapointer += sizeof(daliasframe_t);
767                         datapointer += sizeof(trivertx_t) * numverts;
768                         loadmodel->surfmesh.num_morphframes++;
769                 }
770         }
771
772         // store texture coordinates into temporary array, they will be stored
773         // after usage is determined (triangle data)
774         vertst = (float *)Mem_Alloc(tempmempool, numverts * 2 * sizeof(float[2]));
775         vertremap = (int *)Mem_Alloc(tempmempool, numverts * 3 * sizeof(int));
776         vertonseam = vertremap + numverts * 2;
777
778         scales = 1.0 / skinwidth;
779         scalet = 1.0 / skinheight;
780         for (i = 0;i < numverts;i++)
781         {
782                 vertonseam[i] = LittleLong(pinstverts[i].onseam);
783                 vertst[i*2+0] = (LittleLong(pinstverts[i].s) + 0.5) * scales;
784                 vertst[i*2+1] = (LittleLong(pinstverts[i].t) + 0.5) * scalet;
785                 vertst[(i+numverts)*2+0] = vertst[i*2+0] + 0.5;
786                 vertst[(i+numverts)*2+1] = vertst[i*2+1];
787         }
788
789 // load triangle data
790         loadmodel->surfmesh.data_element3i = (int *)Mem_Alloc(loadmodel->mempool, sizeof(int[3]) * loadmodel->surfmesh.num_triangles);
791
792         // read the triangle elements
793         for (i = 0;i < loadmodel->surfmesh.num_triangles;i++)
794                 for (j = 0;j < 3;j++)
795                         loadmodel->surfmesh.data_element3i[i*3+j] = LittleLong(pintriangles[i].vertindex[j]);
796         // validate (note numverts is used because this is the original data)
797         Mod_ValidateElements(loadmodel->surfmesh.data_element3i, loadmodel->surfmesh.num_triangles, 0, numverts, __FILE__, __LINE__);
798         // now butcher the elements according to vertonseam and tri->facesfront
799         // and then compact the vertex set to remove duplicates
800         for (i = 0;i < loadmodel->surfmesh.num_triangles;i++)
801                 if (!LittleLong(pintriangles[i].facesfront)) // backface
802                         for (j = 0;j < 3;j++)
803                                 if (vertonseam[loadmodel->surfmesh.data_element3i[i*3+j]])
804                                         loadmodel->surfmesh.data_element3i[i*3+j] += numverts;
805         // count the usage
806         // (this uses vertremap to count usage to save some memory)
807         for (i = 0;i < numverts*2;i++)
808                 vertremap[i] = 0;
809         for (i = 0;i < loadmodel->surfmesh.num_triangles*3;i++)
810                 vertremap[loadmodel->surfmesh.data_element3i[i]]++;
811         // build remapping table and compact array
812         loadmodel->surfmesh.num_vertices = 0;
813         for (i = 0;i < numverts*2;i++)
814         {
815                 if (vertremap[i])
816                 {
817                         vertremap[i] = loadmodel->surfmesh.num_vertices;
818                         vertst[loadmodel->surfmesh.num_vertices*2+0] = vertst[i*2+0];
819                         vertst[loadmodel->surfmesh.num_vertices*2+1] = vertst[i*2+1];
820                         loadmodel->surfmesh.num_vertices++;
821                 }
822                 else
823                         vertremap[i] = -1; // not used at all
824         }
825         // remap the elements to the new vertex set
826         for (i = 0;i < loadmodel->surfmesh.num_triangles * 3;i++)
827                 loadmodel->surfmesh.data_element3i[i] = vertremap[loadmodel->surfmesh.data_element3i[i]];
828         // store the texture coordinates
829         loadmodel->surfmesh.data_texcoordtexture2f = (float *)Mem_Alloc(loadmodel->mempool, sizeof(float[2]) * loadmodel->surfmesh.num_vertices);
830         for (i = 0;i < loadmodel->surfmesh.num_vertices;i++)
831         {
832                 loadmodel->surfmesh.data_texcoordtexture2f[i*2+0] = vertst[i*2+0];
833                 loadmodel->surfmesh.data_texcoordtexture2f[i*2+1] = vertst[i*2+1];
834         }
835
836 // load the frames
837         loadmodel->animscenes = (animscene_t *)Mem_Alloc(loadmodel->mempool, sizeof(animscene_t) * loadmodel->numframes);
838         loadmodel->surfmesh.data_morphmdlvertex = (trivertx_t *)Mem_Alloc(loadmodel->mempool, sizeof(trivertx_t) * loadmodel->surfmesh.num_morphframes * loadmodel->surfmesh.num_vertices);
839         loadmodel->surfmesh.data_neighbor3i = (int *)Mem_Alloc(loadmodel->mempool, loadmodel->surfmesh.num_triangles * sizeof(int[3]));
840         Mod_MDL_LoadFrames (startframes, numverts, vertremap);
841         Mod_BuildTriangleNeighbors(loadmodel->surfmesh.data_neighbor3i, loadmodel->surfmesh.data_element3i, loadmodel->surfmesh.num_triangles);
842         Mod_Alias_CalculateBoundingBox();
843         Mod_Alias_Mesh_CompileFrameZero();
844
845         Mem_Free(vertst);
846         Mem_Free(vertremap);
847
848         // load the skins
849         skinfiles = Mod_LoadSkinFiles();
850         loadmodel->skinscenes = (animscene_t *)Mem_Alloc(loadmodel->mempool, loadmodel->numskins * sizeof(animscene_t));
851         loadmodel->num_textures = loadmodel->num_surfaces;
852         loadmodel->data_textures = (texture_t *)Mem_Alloc(loadmodel->mempool, loadmodel->num_surfaces * totalskins * sizeof(texture_t));
853         if (skinfiles)
854         {
855                 Mod_BuildAliasSkinsFromSkinFiles(loadmodel->data_textures, skinfiles, "default", "");
856                 Mod_FreeSkinFiles(skinfiles);
857                 for (i = 0;i < loadmodel->numskins;i++)
858                 {
859                         loadmodel->skinscenes[i].firstframe = i;
860                         loadmodel->skinscenes[i].framecount = 1;
861                         loadmodel->skinscenes[i].loop = true;
862                         loadmodel->skinscenes[i].framerate = 10;
863                 }
864         }
865         else
866         {
867                 totalskins = 0;
868                 datapointer = startskins;
869                 for (i = 0;i < loadmodel->numskins;i++)
870                 {
871                         pinskintype = (daliasskintype_t *)datapointer;
872                         datapointer += sizeof(daliasskintype_t);
873
874                         if (pinskintype->type == ALIAS_SKIN_SINGLE)
875                         {
876                                 groupskins = 1;
877                                 interval = 0.1f;
878                         }
879                         else
880                         {
881                                 pinskingroup = (daliasskingroup_t *)datapointer;
882                                 datapointer += sizeof(daliasskingroup_t);
883
884                                 groupskins = LittleLong (pinskingroup->numskins);
885
886                                 pinskinintervals = (daliasskininterval_t *)datapointer;
887                                 datapointer += sizeof(daliasskininterval_t) * groupskins;
888
889                                 interval = LittleFloat(pinskinintervals[0].interval);
890                                 if (interval < 0.01f)
891                                 {
892                                         Con_Printf("%s has an invalid interval %f, changing to 0.1\n", loadmodel->name, interval);
893                                         interval = 0.1f;
894                                 }
895                         }
896
897                         sprintf(loadmodel->skinscenes[i].name, "skin %i", i);
898                         loadmodel->skinscenes[i].firstframe = totalskins;
899                         loadmodel->skinscenes[i].framecount = groupskins;
900                         loadmodel->skinscenes[i].framerate = 1.0f / interval;
901                         loadmodel->skinscenes[i].loop = true;
902
903                         for (j = 0;j < groupskins;j++)
904                         {
905                                 if (groupskins > 1)
906                                         sprintf (name, "%s_%i_%i", loadmodel->name, i, j);
907                                 else
908                                         sprintf (name, "%s_%i", loadmodel->name, i);
909                                 if (!Mod_LoadSkinFrame(&tempskinframe, name, (r_mipskins.integer ? TEXF_MIPMAP : 0) | TEXF_ALPHA | TEXF_PICMIP, true, true))
910                                         Mod_LoadSkinFrame_Internal(&tempskinframe, name, (r_mipskins.integer ? TEXF_MIPMAP : 0) | TEXF_PICMIP, true, r_fullbrights.integer, (unsigned char *)datapointer, skinwidth, skinheight, 8, NULL, NULL);
911                                 Mod_BuildAliasSkinFromSkinFrame(loadmodel->data_textures + totalskins * loadmodel->num_surfaces, &tempskinframe);
912                                 datapointer += skinwidth * skinheight;
913                                 totalskins++;
914                         }
915                 }
916                 // check for skins that don't exist in the model, but do exist as external images
917                 // (this was added because yummyluv kept pestering me about support for it)
918                 while (Mod_LoadSkinFrame(&tempskinframe, va("%s_%i", loadmodel->name, loadmodel->numskins), (r_mipskins.integer ? TEXF_MIPMAP : 0) | TEXF_ALPHA | TEXF_PICMIP, true, true))
919                 {
920                         // expand the arrays to make room
921                         tempskinscenes = loadmodel->skinscenes;
922                         loadmodel->skinscenes = (animscene_t *)Mem_Alloc(loadmodel->mempool, (loadmodel->numskins + 1) * sizeof(animscene_t));
923                         memcpy(loadmodel->skinscenes, tempskinscenes, loadmodel->numskins * sizeof(animscene_t));
924                         Mem_Free(tempskinscenes);
925
926                         tempaliasskins = loadmodel->data_textures;
927                         loadmodel->data_textures = (texture_t *)Mem_Alloc(loadmodel->mempool, loadmodel->num_surfaces * (totalskins + 1) * sizeof(texture_t));
928                         memcpy(loadmodel->data_textures, tempaliasskins, loadmodel->num_surfaces * totalskins * sizeof(texture_t));
929                         Mem_Free(tempaliasskins);
930
931                         // store the info about the new skin
932                         Mod_BuildAliasSkinFromSkinFrame(loadmodel->data_textures + totalskins * loadmodel->num_surfaces, &tempskinframe);
933                         strlcpy(loadmodel->skinscenes[loadmodel->numskins].name, name, sizeof(loadmodel->skinscenes[loadmodel->numskins].name));
934                         loadmodel->skinscenes[loadmodel->numskins].firstframe = totalskins;
935                         loadmodel->skinscenes[loadmodel->numskins].framecount = 1;
936                         loadmodel->skinscenes[loadmodel->numskins].framerate = 10.0f;
937                         loadmodel->skinscenes[loadmodel->numskins].loop = true;
938
939                         //increase skin counts
940                         loadmodel->numskins++;
941                         totalskins++;
942                 }
943         }
944
945         surface = loadmodel->data_surfaces;
946         surface->texture = loadmodel->data_textures;
947         surface->num_firsttriangle = 0;
948         surface->num_triangles = loadmodel->surfmesh.num_triangles;
949         surface->num_firstvertex = 0;
950         surface->num_vertices = loadmodel->surfmesh.num_vertices;
951
952         loadmodel->surfmesh.isanimated = loadmodel->numframes > 1 || loadmodel->animscenes[0].framecount > 1;
953 }
954
955 void Mod_IDP2_Load(model_t *mod, void *buffer, void *bufferend)
956 {
957         int i, j, hashindex, numxyz, numst, xyz, st, skinwidth, skinheight, *vertremap, version, end;
958         float iskinwidth, iskinheight;
959         unsigned char *data;
960         msurface_t *surface;
961         md2_t *pinmodel;
962         unsigned char *base, *datapointer;
963         md2frame_t *pinframe;
964         char *inskin;
965         md2triangle_t *intri;
966         unsigned short *inst;
967         struct md2verthash_s
968         {
969                 struct md2verthash_s *next;
970                 unsigned short xyz;
971                 unsigned short st;
972         }
973         *hash, **md2verthash, *md2verthashdata;
974         skinframe_t tempskinframe;
975         skinfile_t *skinfiles;
976
977         pinmodel = (md2_t *)buffer;
978         base = (unsigned char *)buffer;
979
980         version = LittleLong (pinmodel->version);
981         if (version != MD2ALIAS_VERSION)
982                 Host_Error ("%s has wrong version number (%i should be %i)",
983                         loadmodel->name, version, MD2ALIAS_VERSION);
984
985         loadmodel->type = mod_alias;
986         loadmodel->DrawSky = NULL;
987         loadmodel->Draw = R_Q1BSP_Draw;
988         loadmodel->CompileShadowVolume = R_Q1BSP_CompileShadowVolume;
989         loadmodel->DrawShadowVolume = R_Q1BSP_DrawShadowVolume;
990         loadmodel->DrawLight = R_Q1BSP_DrawLight;
991         loadmodel->TraceBox = Mod_MDLMD2MD3_TraceBox;
992
993         if (LittleLong(pinmodel->num_tris) < 1 || LittleLong(pinmodel->num_tris) > 65536)
994                 Host_Error ("%s has invalid number of triangles: %i", loadmodel->name, LittleLong(pinmodel->num_tris));
995         if (LittleLong(pinmodel->num_xyz) < 1 || LittleLong(pinmodel->num_xyz) > 65536)
996                 Host_Error ("%s has invalid number of vertices: %i", loadmodel->name, LittleLong(pinmodel->num_xyz));
997         if (LittleLong(pinmodel->num_frames) < 1 || LittleLong(pinmodel->num_frames) > 65536)
998                 Host_Error ("%s has invalid number of frames: %i", loadmodel->name, LittleLong(pinmodel->num_frames));
999         if (LittleLong(pinmodel->num_skins) < 0 || LittleLong(pinmodel->num_skins) > 256)
1000                 Host_Error ("%s has invalid number of skins: %i", loadmodel->name, LittleLong(pinmodel->num_skins));
1001
1002         end = LittleLong(pinmodel->ofs_end);
1003         if (LittleLong(pinmodel->num_skins) >= 1 && (LittleLong(pinmodel->ofs_skins) <= 0 || LittleLong(pinmodel->ofs_skins) >= end))
1004                 Host_Error ("%s is not a valid model", loadmodel->name);
1005         if (LittleLong(pinmodel->ofs_st) <= 0 || LittleLong(pinmodel->ofs_st) >= end)
1006                 Host_Error ("%s is not a valid model", loadmodel->name);
1007         if (LittleLong(pinmodel->ofs_tris) <= 0 || LittleLong(pinmodel->ofs_tris) >= end)
1008                 Host_Error ("%s is not a valid model", loadmodel->name);
1009         if (LittleLong(pinmodel->ofs_frames) <= 0 || LittleLong(pinmodel->ofs_frames) >= end)
1010                 Host_Error ("%s is not a valid model", loadmodel->name);
1011         if (LittleLong(pinmodel->ofs_glcmds) <= 0 || LittleLong(pinmodel->ofs_glcmds) >= end)
1012                 Host_Error ("%s is not a valid model", loadmodel->name);
1013
1014         loadmodel->numskins = LittleLong(pinmodel->num_skins);
1015         numxyz = LittleLong(pinmodel->num_xyz);
1016         numst = LittleLong(pinmodel->num_st);
1017         loadmodel->surfmesh.num_triangles = LittleLong(pinmodel->num_tris);
1018         loadmodel->numframes = LittleLong(pinmodel->num_frames);
1019         loadmodel->surfmesh.num_morphframes = loadmodel->numframes;
1020         skinwidth = LittleLong(pinmodel->skinwidth);
1021         skinheight = LittleLong(pinmodel->skinheight);
1022         iskinwidth = 1.0f / skinwidth;
1023         iskinheight = 1.0f / skinheight;
1024
1025         loadmodel->num_surfaces = 1;
1026         loadmodel->nummodelsurfaces = loadmodel->num_surfaces;
1027         data = (unsigned char *)Mem_Alloc(loadmodel->mempool, loadmodel->num_surfaces * sizeof(msurface_t) + loadmodel->num_surfaces * sizeof(int) + loadmodel->numframes * sizeof(animscene_t) + loadmodel->numframes * sizeof(float[6]) + loadmodel->surfmesh.num_triangles * sizeof(int[3]) + loadmodel->surfmesh.num_triangles * sizeof(int[3]));
1028         loadmodel->data_surfaces = (msurface_t *)data;data += loadmodel->num_surfaces * sizeof(msurface_t);
1029         loadmodel->surfacelist = (int *)data;data += loadmodel->num_surfaces * sizeof(int);
1030         loadmodel->surfacelist[0] = 0;
1031         loadmodel->animscenes = (animscene_t *)data;data += loadmodel->numframes * sizeof(animscene_t);
1032         loadmodel->surfmesh.data_morphmd2framesize6f = (float *)data;data += loadmodel->numframes * sizeof(float[6]);
1033         loadmodel->surfmesh.data_element3i = (int *)data;data += loadmodel->surfmesh.num_triangles * sizeof(int[3]);
1034         loadmodel->surfmesh.data_neighbor3i = (int *)data;data += loadmodel->surfmesh.num_triangles * sizeof(int[3]);
1035
1036         loadmodel->flags = 0; // there are no MD2 flags
1037         loadmodel->synctype = ST_RAND;
1038
1039         // load the skins
1040         inskin = (char *)(base + LittleLong(pinmodel->ofs_skins));
1041         skinfiles = Mod_LoadSkinFiles();
1042         if (skinfiles)
1043         {
1044                 loadmodel->num_textures = loadmodel->num_surfaces;
1045                 loadmodel->data_textures = (texture_t *)Mem_Alloc(loadmodel->mempool, loadmodel->num_surfaces * loadmodel->numskins * sizeof(texture_t));
1046                 Mod_BuildAliasSkinsFromSkinFiles(loadmodel->data_textures, skinfiles, "default", "");
1047                 Mod_FreeSkinFiles(skinfiles);
1048         }
1049         else if (loadmodel->numskins)
1050         {
1051                 // skins found (most likely not a player model)
1052                 loadmodel->num_textures = loadmodel->num_surfaces;
1053                 loadmodel->data_textures = (texture_t *)Mem_Alloc(loadmodel->mempool, loadmodel->num_surfaces * loadmodel->numskins * sizeof(texture_t));
1054                 for (i = 0;i < loadmodel->numskins;i++, inskin += MD2_SKINNAME)
1055                 {
1056                         if (Mod_LoadSkinFrame(&tempskinframe, inskin, (r_mipskins.integer ? TEXF_MIPMAP : 0) | TEXF_ALPHA | TEXF_PRECACHE | TEXF_PICMIP, true, true))
1057                                 Mod_BuildAliasSkinFromSkinFrame(loadmodel->data_textures + i * loadmodel->num_surfaces, &tempskinframe);
1058                         else
1059                         {
1060                                 Con_Printf("%s is missing skin \"%s\"\n", loadmodel->name, inskin);
1061                                 Mod_BuildAliasSkinFromSkinFrame(loadmodel->data_textures + i * loadmodel->num_surfaces, NULL);
1062                         }
1063                 }
1064         }
1065         else
1066         {
1067                 // no skins (most likely a player model)
1068                 loadmodel->numskins = 1;
1069                 loadmodel->num_textures = loadmodel->num_surfaces;
1070                 loadmodel->data_textures = (texture_t *)Mem_Alloc(loadmodel->mempool, loadmodel->num_surfaces * loadmodel->numskins * sizeof(texture_t));
1071                 Mod_BuildAliasSkinFromSkinFrame(loadmodel->data_textures, NULL);
1072         }
1073
1074         loadmodel->skinscenes = (animscene_t *)Mem_Alloc(loadmodel->mempool, sizeof(animscene_t) * loadmodel->numskins);
1075         for (i = 0;i < loadmodel->numskins;i++)
1076         {
1077                 loadmodel->skinscenes[i].firstframe = i;
1078                 loadmodel->skinscenes[i].framecount = 1;
1079                 loadmodel->skinscenes[i].loop = true;
1080                 loadmodel->skinscenes[i].framerate = 10;
1081         }
1082
1083         // load the triangles and stvert data
1084         inst = (unsigned short *)(base + LittleLong(pinmodel->ofs_st));
1085         intri = (md2triangle_t *)(base + LittleLong(pinmodel->ofs_tris));
1086         md2verthash = (struct md2verthash_s **)Mem_Alloc(tempmempool, 65536 * sizeof(hash));
1087         md2verthashdata = (struct md2verthash_s *)Mem_Alloc(tempmempool, loadmodel->surfmesh.num_triangles * 3 * sizeof(*hash));
1088         // swap the triangle list
1089         loadmodel->surfmesh.num_vertices = 0;
1090         for (i = 0;i < loadmodel->surfmesh.num_triangles;i++)
1091         {
1092                 for (j = 0;j < 3;j++)
1093                 {
1094                         xyz = (unsigned short) LittleShort (intri[i].index_xyz[j]);
1095                         st = (unsigned short) LittleShort (intri[i].index_st[j]);
1096                         if (xyz >= numxyz)
1097                         {
1098                                 Con_Printf("%s has an invalid xyz index (%i) on triangle %i, resetting to 0\n", loadmodel->name, xyz, i);
1099                                 xyz = 0;
1100                         }
1101                         if (st >= numst)
1102                         {
1103                                 Con_Printf("%s has an invalid st index (%i) on triangle %i, resetting to 0\n", loadmodel->name, st, i);
1104                                 st = 0;
1105                         }
1106                         hashindex = (xyz * 256 + st) & 65535;
1107                         for (hash = md2verthash[hashindex];hash;hash = hash->next)
1108                                 if (hash->xyz == xyz && hash->st == st)
1109                                         break;
1110                         if (hash == NULL)
1111                         {
1112                                 hash = md2verthashdata + loadmodel->surfmesh.num_vertices++;
1113                                 hash->xyz = xyz;
1114                                 hash->st = st;
1115                                 hash->next = md2verthash[hashindex];
1116                                 md2verthash[hashindex] = hash;
1117                         }
1118                         loadmodel->surfmesh.data_element3i[i*3+j] = (hash - md2verthashdata);
1119                 }
1120         }
1121
1122         vertremap = (int *)Mem_Alloc(loadmodel->mempool, loadmodel->surfmesh.num_vertices * sizeof(int));
1123         data = (unsigned char *)Mem_Alloc(loadmodel->mempool, loadmodel->surfmesh.num_vertices * sizeof(float[2]) + loadmodel->surfmesh.num_vertices * loadmodel->surfmesh.num_morphframes * sizeof(trivertx_t));
1124         loadmodel->surfmesh.data_texcoordtexture2f = (float *)data;data += loadmodel->surfmesh.num_vertices * sizeof(float[2]);
1125         loadmodel->surfmesh.data_morphmdlvertex = (trivertx_t *)data;data += loadmodel->surfmesh.num_vertices * loadmodel->surfmesh.num_morphframes * sizeof(trivertx_t);
1126         for (i = 0;i < loadmodel->surfmesh.num_vertices;i++)
1127         {
1128                 int sts, stt;
1129                 hash = md2verthashdata + i;
1130                 vertremap[i] = hash->xyz;
1131                 sts = LittleShort(inst[hash->st*2+0]);
1132                 stt = LittleShort(inst[hash->st*2+1]);
1133                 if (sts < 0 || sts >= skinwidth || stt < 0 || stt >= skinheight)
1134                 {
1135                         Con_Printf("%s has an invalid skin coordinate (%i %i) on vert %i, changing to 0 0\n", loadmodel->name, sts, stt, i);
1136                         sts = 0;
1137                         stt = 0;
1138                 }
1139                 loadmodel->surfmesh.data_texcoordtexture2f[i*2+0] = sts * iskinwidth;
1140                 loadmodel->surfmesh.data_texcoordtexture2f[i*2+1] = stt * iskinheight;
1141         }
1142
1143         Mem_Free(md2verthash);
1144         Mem_Free(md2verthashdata);
1145
1146         // load the frames
1147         datapointer = (base + LittleLong(pinmodel->ofs_frames));
1148         for (i = 0;i < loadmodel->surfmesh.num_morphframes;i++)
1149         {
1150                 int k;
1151                 trivertx_t *v;
1152                 trivertx_t *out;
1153                 pinframe = (md2frame_t *)datapointer;
1154                 datapointer += sizeof(md2frame_t);
1155                 // store the frame scale/translate into the appropriate array
1156                 for (j = 0;j < 3;j++)
1157                 {
1158                         loadmodel->surfmesh.data_morphmd2framesize6f[i*6+j] = LittleFloat(pinframe->scale[j]);
1159                         loadmodel->surfmesh.data_morphmd2framesize6f[i*6+3+j] = LittleFloat(pinframe->translate[j]);
1160                 }
1161                 // convert the vertices
1162                 v = (trivertx_t *)datapointer;
1163                 out = loadmodel->surfmesh.data_morphmdlvertex + i * loadmodel->surfmesh.num_vertices;
1164                 for (k = 0;k < loadmodel->surfmesh.num_vertices;k++)
1165                         out[k] = v[vertremap[k]];
1166                 datapointer += numxyz * sizeof(trivertx_t);
1167
1168                 strlcpy(loadmodel->animscenes[i].name, pinframe->name, sizeof(loadmodel->animscenes[i].name));
1169                 loadmodel->animscenes[i].firstframe = i;
1170                 loadmodel->animscenes[i].framecount = 1;
1171                 loadmodel->animscenes[i].framerate = 10;
1172                 loadmodel->animscenes[i].loop = true;
1173         }
1174
1175         Mem_Free(vertremap);
1176
1177         Mod_BuildTriangleNeighbors(loadmodel->surfmesh.data_neighbor3i, loadmodel->surfmesh.data_element3i, loadmodel->surfmesh.num_triangles);
1178         Mod_Alias_CalculateBoundingBox();
1179         Mod_Alias_Mesh_CompileFrameZero();
1180
1181         surface = loadmodel->data_surfaces;
1182         surface->texture = loadmodel->data_textures;
1183         surface->num_firsttriangle = 0;
1184         surface->num_triangles = loadmodel->surfmesh.num_triangles;
1185         surface->num_firstvertex = 0;
1186         surface->num_vertices = loadmodel->surfmesh.num_vertices;
1187
1188         loadmodel->surfmesh.isanimated = loadmodel->numframes > 1 || loadmodel->animscenes[0].framecount > 1;
1189 }
1190
1191 void Mod_IDP3_Load(model_t *mod, void *buffer, void *bufferend)
1192 {
1193         int i, j, k, version, meshvertices, meshtriangles;
1194         unsigned char *data;
1195         msurface_t *surface;
1196         md3modelheader_t *pinmodel;
1197         md3frameinfo_t *pinframe;
1198         md3mesh_t *pinmesh;
1199         md3tag_t *pintag;
1200         skinfile_t *skinfiles;
1201
1202         pinmodel = (md3modelheader_t *)buffer;
1203
1204         if (memcmp(pinmodel->identifier, "IDP3", 4))
1205                 Host_Error ("%s is not a MD3 (IDP3) file", loadmodel->name);
1206         version = LittleLong (pinmodel->version);
1207         if (version != MD3VERSION)
1208                 Host_Error ("%s has wrong version number (%i should be %i)",
1209                         loadmodel->name, version, MD3VERSION);
1210
1211         skinfiles = Mod_LoadSkinFiles();
1212         if (loadmodel->numskins < 1)
1213                 loadmodel->numskins = 1;
1214
1215         loadmodel->type = mod_alias;
1216         loadmodel->DrawSky = NULL;
1217         loadmodel->Draw = R_Q1BSP_Draw;
1218         loadmodel->CompileShadowVolume = R_Q1BSP_CompileShadowVolume;
1219         loadmodel->DrawShadowVolume = R_Q1BSP_DrawShadowVolume;
1220         loadmodel->DrawLight = R_Q1BSP_DrawLight;
1221         loadmodel->TraceBox = Mod_MDLMD2MD3_TraceBox;
1222         loadmodel->flags = LittleLong(pinmodel->flags);
1223         loadmodel->synctype = ST_RAND;
1224
1225         // set up some global info about the model
1226         loadmodel->numframes = LittleLong(pinmodel->num_frames);
1227         loadmodel->num_surfaces = LittleLong(pinmodel->num_meshes);
1228
1229         // make skinscenes for the skins (no groups)
1230         loadmodel->skinscenes = (animscene_t *)Mem_Alloc(loadmodel->mempool, sizeof(animscene_t) * loadmodel->numskins);
1231         for (i = 0;i < loadmodel->numskins;i++)
1232         {
1233                 loadmodel->skinscenes[i].firstframe = i;
1234                 loadmodel->skinscenes[i].framecount = 1;
1235                 loadmodel->skinscenes[i].loop = true;
1236                 loadmodel->skinscenes[i].framerate = 10;
1237         }
1238
1239         // load frameinfo
1240         loadmodel->animscenes = (animscene_t *)Mem_Alloc(loadmodel->mempool, loadmodel->numframes * sizeof(animscene_t));
1241         for (i = 0, pinframe = (md3frameinfo_t *)((unsigned char *)pinmodel + LittleLong(pinmodel->lump_frameinfo));i < loadmodel->numframes;i++, pinframe++)
1242         {
1243                 strlcpy(loadmodel->animscenes[i].name, pinframe->name, sizeof(loadmodel->animscenes[i].name));
1244                 loadmodel->animscenes[i].firstframe = i;
1245                 loadmodel->animscenes[i].framecount = 1;
1246                 loadmodel->animscenes[i].framerate = 10;
1247                 loadmodel->animscenes[i].loop = true;
1248         }
1249
1250         // load tags
1251         loadmodel->num_tagframes = loadmodel->numframes;
1252         loadmodel->num_tags = LittleLong(pinmodel->num_tags);
1253         loadmodel->data_tags = (aliastag_t *)Mem_Alloc(loadmodel->mempool, loadmodel->num_tagframes * loadmodel->num_tags * sizeof(aliastag_t));
1254         for (i = 0, pintag = (md3tag_t *)((unsigned char *)pinmodel + LittleLong(pinmodel->lump_tags));i < loadmodel->num_tagframes * loadmodel->num_tags;i++, pintag++)
1255         {
1256                 strlcpy(loadmodel->data_tags[i].name, pintag->name, sizeof(loadmodel->data_tags[i].name));
1257                 loadmodel->data_tags[i].matrix = identitymatrix;
1258                 for (j = 0;j < 3;j++)
1259                 {
1260                         for (k = 0;k < 3;k++)
1261                                 loadmodel->data_tags[i].matrix.m[j][k] = LittleFloat(pintag->rotationmatrix[k * 3 + j]);
1262                         loadmodel->data_tags[i].matrix.m[j][3] = LittleFloat(pintag->origin[j]);
1263                 }
1264                 //Con_Printf("model \"%s\" frame #%i tag #%i \"%s\"\n", loadmodel->name, i / loadmodel->num_tags, i % loadmodel->num_tags, loadmodel->data_tags[i].name);
1265         }
1266
1267         // load meshes
1268         meshvertices = 0;
1269         meshtriangles = 0;
1270         for (i = 0, pinmesh = (md3mesh_t *)((unsigned char *)pinmodel + LittleLong(pinmodel->lump_meshes));i < loadmodel->num_surfaces;i++, pinmesh = (md3mesh_t *)((unsigned char *)pinmesh + LittleLong(pinmesh->lump_end)))
1271         {
1272                 if (memcmp(pinmesh->identifier, "IDP3", 4))
1273                         Host_Error("Mod_IDP3_Load: invalid mesh identifier (not IDP3)");
1274                 if (LittleLong(pinmesh->num_frames) != loadmodel->numframes)
1275                         Host_Error("Mod_IDP3_Load: mesh numframes differs from header");
1276                 meshvertices += LittleLong(pinmesh->num_vertices);
1277                 meshtriangles += LittleLong(pinmesh->num_triangles);
1278         }
1279
1280         loadmodel->nummodelsurfaces = loadmodel->num_surfaces;
1281         loadmodel->num_textures = loadmodel->num_surfaces;
1282         data = (unsigned char *)Mem_Alloc(loadmodel->mempool, loadmodel->num_surfaces * sizeof(msurface_t) + loadmodel->num_surfaces * sizeof(int) + loadmodel->num_surfaces * loadmodel->numskins * sizeof(texture_t) + meshtriangles * sizeof(int[3]) + meshtriangles * sizeof(int[3]) + meshvertices * sizeof(float[2]) + meshvertices * loadmodel->numframes * sizeof(md3vertex_t));
1283         loadmodel->data_surfaces = (msurface_t *)data;data += loadmodel->num_surfaces * sizeof(msurface_t);
1284         loadmodel->surfacelist = (int *)data;data += loadmodel->num_surfaces * sizeof(int);
1285         loadmodel->data_textures = (texture_t *)data;data += loadmodel->num_surfaces * loadmodel->numskins * sizeof(texture_t);
1286         loadmodel->surfmesh.num_vertices = meshvertices;
1287         loadmodel->surfmesh.num_triangles = meshtriangles;
1288         loadmodel->surfmesh.num_morphframes = loadmodel->numframes; // TODO: remove?
1289         loadmodel->surfmesh.data_element3i = (int *)data;data += meshtriangles * sizeof(int[3]);
1290         loadmodel->surfmesh.data_neighbor3i = (int *)data;data += meshtriangles * sizeof(int[3]);
1291         loadmodel->surfmesh.data_texcoordtexture2f = (float *)data;data += meshvertices * sizeof(float[2]);
1292         loadmodel->surfmesh.data_morphmd3vertex = (md3vertex_t *)data;data += meshvertices * loadmodel->numframes * sizeof(md3vertex_t);
1293
1294         meshvertices = 0;
1295         meshtriangles = 0;
1296         for (i = 0, pinmesh = (md3mesh_t *)((unsigned char *)pinmodel + LittleLong(pinmodel->lump_meshes));i < loadmodel->num_surfaces;i++, pinmesh = (md3mesh_t *)((unsigned char *)pinmesh + LittleLong(pinmesh->lump_end)))
1297         {
1298                 if (memcmp(pinmesh->identifier, "IDP3", 4))
1299                         Host_Error("Mod_IDP3_Load: invalid mesh identifier (not IDP3)");
1300                 loadmodel->surfacelist[i] = i;
1301                 surface = loadmodel->data_surfaces + i;
1302                 surface->texture = loadmodel->data_textures + i;
1303                 surface->num_firsttriangle = meshtriangles;
1304                 surface->num_triangles = LittleLong(pinmesh->num_triangles);
1305                 surface->num_firstvertex = meshvertices;
1306                 surface->num_vertices = LittleLong(pinmesh->num_vertices);
1307                 meshvertices += surface->num_vertices;
1308                 meshtriangles += surface->num_triangles;
1309
1310                 for (j = 0;j < surface->num_triangles * 3;j++)
1311                         loadmodel->surfmesh.data_element3i[j + surface->num_firsttriangle * 3] = surface->num_firstvertex + LittleLong(((int *)((unsigned char *)pinmesh + LittleLong(pinmesh->lump_elements)))[j]);
1312                 for (j = 0;j < surface->num_vertices;j++)
1313                 {
1314                         loadmodel->surfmesh.data_texcoordtexture2f[(j + surface->num_firstvertex) * 2 + 0] = LittleFloat(((float *)((unsigned char *)pinmesh + LittleLong(pinmesh->lump_texcoords)))[j * 2 + 0]);
1315                         loadmodel->surfmesh.data_texcoordtexture2f[(j + surface->num_firstvertex) * 2 + 1] = LittleFloat(((float *)((unsigned char *)pinmesh + LittleLong(pinmesh->lump_texcoords)))[j * 2 + 1]);
1316                 }
1317                 for (j = 0;j < loadmodel->numframes;j++)
1318                 {
1319                         const md3vertex_t *in = (md3vertex_t *)((unsigned char *)pinmesh + LittleLong(pinmesh->lump_framevertices)) + j * surface->num_vertices;
1320                         md3vertex_t *out = loadmodel->surfmesh.data_morphmd3vertex + surface->num_firstvertex + j * loadmodel->surfmesh.num_vertices;
1321                         for (k = 0;k < surface->num_vertices;k++, in++, out++)
1322                         {
1323                                 out->origin[0] = LittleShort(in->origin[0]);
1324                                 out->origin[1] = LittleShort(in->origin[1]);
1325                                 out->origin[2] = LittleShort(in->origin[2]);
1326                                 out->pitch = in->pitch;
1327                                 out->yaw = in->yaw;
1328                         }
1329                 }
1330
1331                 if (LittleLong(pinmesh->num_shaders) >= 1)
1332                         Mod_BuildAliasSkinsFromSkinFiles(loadmodel->data_textures + i, skinfiles, pinmesh->name, ((md3shader_t *)((unsigned char *) pinmesh + LittleLong(pinmesh->lump_shaders)))->name);
1333                 else
1334                         for (j = 0;j < loadmodel->numskins;j++)
1335                                 Mod_BuildAliasSkinFromSkinFrame(loadmodel->data_textures + i + j * loadmodel->num_surfaces, NULL);
1336
1337                 Mod_ValidateElements(loadmodel->surfmesh.data_element3i + surface->num_firsttriangle * 3, surface->num_triangles, surface->num_firstvertex, surface->num_vertices, __FILE__, __LINE__);
1338         }
1339         Mod_BuildTriangleNeighbors(loadmodel->surfmesh.data_neighbor3i, loadmodel->surfmesh.data_element3i, loadmodel->surfmesh.num_triangles);
1340         Mod_Alias_Mesh_CompileFrameZero();
1341         Mod_Alias_CalculateBoundingBox();
1342         Mod_FreeSkinFiles(skinfiles);
1343
1344         loadmodel->surfmesh.isanimated = loadmodel->numframes > 1 || loadmodel->animscenes[0].framecount > 1;
1345 }
1346
1347 void Mod_ZYMOTICMODEL_Load(model_t *mod, void *buffer, void *bufferend)
1348 {
1349         zymtype1header_t *pinmodel, *pheader;
1350         unsigned char *pbase;
1351         int i, j, k, numposes, meshvertices, meshtriangles, *bonecount, *vertbonecounts, count, *renderlist, *renderlistend, *outelements;
1352         float modelradius, corner[2], *poses, *intexcoord2f, *outtexcoord2f, *bonepose;
1353         zymvertex_t *verts, *vertdata;
1354         zymscene_t *scene;
1355         zymbone_t *bone;
1356         char *shadername;
1357         skinfile_t *skinfiles;
1358         unsigned char *data;
1359         msurface_t *surface;
1360
1361         pinmodel = (zymtype1header_t *)buffer;
1362         pbase = (unsigned char *)buffer;
1363         if (memcmp(pinmodel->id, "ZYMOTICMODEL", 12))
1364                 Host_Error ("Mod_ZYMOTICMODEL_Load: %s is not a zymotic model");
1365         if (BigLong(pinmodel->type) != 1)
1366                 Host_Error ("Mod_ZYMOTICMODEL_Load: only type 1 (skeletal pose) models are currently supported (name = %s)", loadmodel->name);
1367
1368         loadmodel->type = mod_alias;
1369         loadmodel->flags = 0; // there are no flags on zym models
1370         loadmodel->synctype = ST_RAND;
1371
1372         // byteswap header
1373         pheader = pinmodel;
1374         pheader->type = BigLong(pinmodel->type);
1375         pheader->filesize = BigLong(pinmodel->filesize);
1376         pheader->mins[0] = BigFloat(pinmodel->mins[0]);
1377         pheader->mins[1] = BigFloat(pinmodel->mins[1]);
1378         pheader->mins[2] = BigFloat(pinmodel->mins[2]);
1379         pheader->maxs[0] = BigFloat(pinmodel->maxs[0]);
1380         pheader->maxs[1] = BigFloat(pinmodel->maxs[1]);
1381         pheader->maxs[2] = BigFloat(pinmodel->maxs[2]);
1382         pheader->radius = BigFloat(pinmodel->radius);
1383         pheader->numverts = BigLong(pinmodel->numverts);
1384         pheader->numtris = BigLong(pinmodel->numtris);
1385         pheader->numshaders = BigLong(pinmodel->numshaders);
1386         pheader->numbones = BigLong(pinmodel->numbones);
1387         pheader->numscenes = BigLong(pinmodel->numscenes);
1388         pheader->lump_scenes.start = BigLong(pinmodel->lump_scenes.start);
1389         pheader->lump_scenes.length = BigLong(pinmodel->lump_scenes.length);
1390         pheader->lump_poses.start = BigLong(pinmodel->lump_poses.start);
1391         pheader->lump_poses.length = BigLong(pinmodel->lump_poses.length);
1392         pheader->lump_bones.start = BigLong(pinmodel->lump_bones.start);
1393         pheader->lump_bones.length = BigLong(pinmodel->lump_bones.length);
1394         pheader->lump_vertbonecounts.start = BigLong(pinmodel->lump_vertbonecounts.start);
1395         pheader->lump_vertbonecounts.length = BigLong(pinmodel->lump_vertbonecounts.length);
1396         pheader->lump_verts.start = BigLong(pinmodel->lump_verts.start);
1397         pheader->lump_verts.length = BigLong(pinmodel->lump_verts.length);
1398         pheader->lump_texcoords.start = BigLong(pinmodel->lump_texcoords.start);
1399         pheader->lump_texcoords.length = BigLong(pinmodel->lump_texcoords.length);
1400         pheader->lump_render.start = BigLong(pinmodel->lump_render.start);
1401         pheader->lump_render.length = BigLong(pinmodel->lump_render.length);
1402         pheader->lump_shaders.start = BigLong(pinmodel->lump_shaders.start);
1403         pheader->lump_shaders.length = BigLong(pinmodel->lump_shaders.length);
1404         pheader->lump_trizone.start = BigLong(pinmodel->lump_trizone.start);
1405         pheader->lump_trizone.length = BigLong(pinmodel->lump_trizone.length);
1406
1407         if (pheader->numtris < 1 || pheader->numverts < 3 || pheader->numshaders < 1)
1408         {
1409                 Con_Printf("%s has no geometry\n");
1410                 return;
1411         }
1412         if (pheader->numscenes < 1 || pheader->lump_poses.length < (int)sizeof(float[3][4]))
1413         {
1414                 Con_Printf("%s has no animations\n");
1415                 return;
1416         }
1417
1418         loadmodel->DrawSky = NULL;
1419         loadmodel->Draw = R_Q1BSP_Draw;
1420         loadmodel->CompileShadowVolume = R_Q1BSP_CompileShadowVolume;
1421         loadmodel->DrawShadowVolume = R_Q1BSP_DrawShadowVolume;
1422         loadmodel->DrawLight = R_Q1BSP_DrawLight;
1423         loadmodel->TraceBox = Mod_MDLMD2MD3_TraceBox;
1424
1425         loadmodel->numframes = pheader->numscenes;
1426         loadmodel->num_surfaces = pheader->numshaders;
1427
1428         skinfiles = Mod_LoadSkinFiles();
1429         if (loadmodel->numskins < 1)
1430                 loadmodel->numskins = 1;
1431
1432         // make skinscenes for the skins (no groups)
1433         loadmodel->skinscenes = (animscene_t *)Mem_Alloc(loadmodel->mempool, sizeof(animscene_t) * loadmodel->numskins);
1434         for (i = 0;i < loadmodel->numskins;i++)
1435         {
1436                 loadmodel->skinscenes[i].firstframe = i;
1437                 loadmodel->skinscenes[i].framecount = 1;
1438                 loadmodel->skinscenes[i].loop = true;
1439                 loadmodel->skinscenes[i].framerate = 10;
1440         }
1441
1442         // model bbox
1443         modelradius = pheader->radius;
1444         for (i = 0;i < 3;i++)
1445         {
1446                 loadmodel->normalmins[i] = pheader->mins[i];
1447                 loadmodel->normalmaxs[i] = pheader->maxs[i];
1448                 loadmodel->rotatedmins[i] = -modelradius;
1449                 loadmodel->rotatedmaxs[i] = modelradius;
1450         }
1451         corner[0] = max(fabs(loadmodel->normalmins[0]), fabs(loadmodel->normalmaxs[0]));
1452         corner[1] = max(fabs(loadmodel->normalmins[1]), fabs(loadmodel->normalmaxs[1]));
1453         loadmodel->yawmaxs[0] = loadmodel->yawmaxs[1] = sqrt(corner[0]*corner[0]+corner[1]*corner[1]);
1454         if (loadmodel->yawmaxs[0] > modelradius)
1455                 loadmodel->yawmaxs[0] = loadmodel->yawmaxs[1] = modelradius;
1456         loadmodel->yawmins[0] = loadmodel->yawmins[1] = -loadmodel->yawmaxs[0];
1457         loadmodel->yawmins[2] = loadmodel->normalmins[2];
1458         loadmodel->yawmaxs[2] = loadmodel->normalmaxs[2];
1459         loadmodel->radius = modelradius;
1460         loadmodel->radius2 = modelradius * modelradius;
1461
1462         // go through the lumps, swapping things
1463
1464         //zymlump_t lump_scenes; // zymscene_t scene[numscenes]; // name and other information for each scene (see zymscene struct)
1465         loadmodel->animscenes = (animscene_t *)Mem_Alloc(loadmodel->mempool, sizeof(animscene_t) * loadmodel->numframes);
1466         scene = (zymscene_t *) (pheader->lump_scenes.start + pbase);
1467         numposes = pheader->lump_poses.length / pheader->numbones / sizeof(float[3][4]);
1468         for (i = 0;i < pheader->numscenes;i++)
1469         {
1470                 memcpy(loadmodel->animscenes[i].name, scene->name, 32);
1471                 loadmodel->animscenes[i].firstframe = BigLong(scene->start);
1472                 loadmodel->animscenes[i].framecount = BigLong(scene->length);
1473                 loadmodel->animscenes[i].framerate = BigFloat(scene->framerate);
1474                 loadmodel->animscenes[i].loop = (BigLong(scene->flags) & ZYMSCENEFLAG_NOLOOP) == 0;
1475                 if ((unsigned int) loadmodel->animscenes[i].firstframe >= (unsigned int) numposes)
1476                         Host_Error("%s scene->firstframe (%i) >= numposes (%i)", loadmodel->name, loadmodel->animscenes[i].firstframe, numposes);
1477                 if ((unsigned int) loadmodel->animscenes[i].firstframe + (unsigned int) loadmodel->animscenes[i].framecount > (unsigned int) numposes)
1478                         Host_Error("%s scene->firstframe (%i) + framecount (%i) >= numposes (%i)", loadmodel->name, loadmodel->animscenes[i].firstframe, loadmodel->animscenes[i].framecount, numposes);
1479                 if (loadmodel->animscenes[i].framerate < 0)
1480                         Host_Error("%s scene->framerate (%f) < 0", loadmodel->name, loadmodel->animscenes[i].framerate);
1481                 scene++;
1482         }
1483
1484         //zymlump_t lump_bones; // zymbone_t bone[numbones];
1485         loadmodel->num_bones = pheader->numbones;
1486         loadmodel->data_bones = (aliasbone_t *)Mem_Alloc(loadmodel->mempool, pheader->numbones * sizeof(aliasbone_t));
1487         bone = (zymbone_t *) (pheader->lump_bones.start + pbase);
1488         for (i = 0;i < pheader->numbones;i++)
1489         {
1490                 memcpy(loadmodel->data_bones[i].name, bone[i].name, sizeof(bone[i].name));
1491                 loadmodel->data_bones[i].flags = BigLong(bone[i].flags);
1492                 loadmodel->data_bones[i].parent = BigLong(bone[i].parent);
1493                 if (loadmodel->data_bones[i].parent >= i)
1494                         Host_Error("%s bone[%i].parent >= %i", loadmodel->name, i, i);
1495         }
1496
1497         //zymlump_t lump_vertbonecounts; // int vertbonecounts[numvertices]; // how many bones influence each vertex (separate mainly to make this compress better)
1498         vertbonecounts = (int *)Mem_Alloc(loadmodel->mempool, pheader->numverts * sizeof(int));
1499         bonecount = (int *) (pheader->lump_vertbonecounts.start + pbase);
1500         for (i = 0;i < pheader->numverts;i++)
1501         {
1502                 vertbonecounts[i] = BigLong(bonecount[i]);
1503                 if (vertbonecounts[i] != 1)
1504                         Host_Error("%s bonecount[%i] != 1 (vertex weight support is impossible in this format)", loadmodel->name, i);
1505         }
1506
1507         loadmodel->num_poses = pheader->lump_poses.length / sizeof(float[3][4]);
1508
1509         meshvertices = pheader->numverts;
1510         meshtriangles = pheader->numtris;
1511
1512         loadmodel->nummodelsurfaces = loadmodel->num_surfaces;
1513         loadmodel->num_textures = loadmodel->num_surfaces;
1514         data = (unsigned char *)Mem_Alloc(loadmodel->mempool, loadmodel->num_surfaces * sizeof(msurface_t) + loadmodel->num_surfaces * sizeof(int) + loadmodel->num_surfaces * loadmodel->numskins * sizeof(texture_t) + meshtriangles * sizeof(int[3]) + meshtriangles * sizeof(int[3]) + meshvertices * sizeof(float[14]) + meshvertices * sizeof(int[4]) + meshvertices * sizeof(float[4]) + loadmodel->num_poses * sizeof(float[36]));
1515         loadmodel->data_surfaces = (msurface_t *)data;data += loadmodel->num_surfaces * sizeof(msurface_t);
1516         loadmodel->surfacelist = (int *)data;data += loadmodel->num_surfaces * sizeof(int);
1517         loadmodel->data_textures = (texture_t *)data;data += loadmodel->num_surfaces * loadmodel->numskins * sizeof(texture_t);
1518         loadmodel->surfmesh.num_vertices = meshvertices;
1519         loadmodel->surfmesh.num_triangles = meshtriangles;
1520         loadmodel->surfmesh.data_element3i = (int *)data;data += meshtriangles * sizeof(int[3]);
1521         loadmodel->surfmesh.data_neighbor3i = (int *)data;data += meshtriangles * sizeof(int[3]);
1522         loadmodel->surfmesh.data_vertex3f = (float *)data;data += meshvertices * sizeof(float[3]);
1523         loadmodel->surfmesh.data_svector3f = (float *)data;data += meshvertices * sizeof(float[3]);
1524         loadmodel->surfmesh.data_tvector3f = (float *)data;data += meshvertices * sizeof(float[3]);
1525         loadmodel->surfmesh.data_normal3f = (float *)data;data += meshvertices * sizeof(float[3]);
1526         loadmodel->surfmesh.data_texcoordtexture2f = (float *)data;data += meshvertices * sizeof(float[2]);
1527         loadmodel->surfmesh.data_vertexweightindex4i = (int *)data;data += meshvertices * sizeof(int[4]);
1528         loadmodel->surfmesh.data_vertexweightinfluence4f = (float *)data;data += meshvertices * sizeof(float[4]);
1529         loadmodel->data_poses = (float *)data;data += loadmodel->num_poses * sizeof(float[12]);
1530         loadmodel->data_basebonepose = (float *)data;data += loadmodel->num_poses * sizeof(float[12]);
1531         loadmodel->data_baseboneposeinverse = (float *)data;data += loadmodel->num_poses * sizeof(float[12]);
1532
1533         //zymlump_t lump_poses; // float pose[numposes][numbones][3][4]; // animation data
1534         poses = (float *) (pheader->lump_poses.start + pbase);
1535         for (i = 0;i < pheader->lump_poses.length / 4;i++)
1536                 loadmodel->data_poses[i] = BigFloat(poses[i]);
1537
1538         //zymlump_t lump_verts; // zymvertex_t vert[numvertices]; // see vertex struct
1539         verts = (zymvertex_t *)Mem_Alloc(loadmodel->mempool, pheader->lump_verts.length);
1540         vertdata = (zymvertex_t *) (pheader->lump_verts.start + pbase);
1541         // reconstruct frame 0 matrices to allow reconstruction of the base mesh
1542         // (converting from weight-blending skeletal animation to
1543         //  deformation-based skeletal animation)
1544         bonepose = (float *)Z_Malloc(loadmodel->num_bones * sizeof(float[12]));
1545         for (i = 0;i < loadmodel->num_bones;i++)
1546         {
1547                 const float *m = loadmodel->data_poses + i * 12;
1548                 if (loadmodel->data_bones[i].parent >= 0)
1549                         R_ConcatTransforms(bonepose + 12 * loadmodel->data_bones[i].parent, m, bonepose + 12 * i);
1550                 else
1551                         for (k = 0;k < 12;k++)
1552                                 bonepose[12*i+k] = m[k];
1553         }
1554         for (j = 0;j < pheader->numverts;j++)
1555         {
1556                 // this format really should have had a per vertexweight weight value...
1557                 // but since it does not, the weighting is completely ignored and
1558                 // only one weight is allowed per vertex
1559                 int boneindex = BigLong(vertdata[j].bonenum);
1560                 const float *m = bonepose + 12 * boneindex;
1561                 float relativeorigin[3];
1562                 relativeorigin[0] = BigFloat(vertdata[j].origin[0]);
1563                 relativeorigin[1] = BigFloat(vertdata[j].origin[1]);
1564                 relativeorigin[2] = BigFloat(vertdata[j].origin[2]);
1565                 // transform the vertex bone weight into the base mesh
1566                 loadmodel->surfmesh.data_vertex3f[j*3+0] = relativeorigin[0] * m[0] + relativeorigin[1] * m[1] + relativeorigin[2] * m[ 2] + m[ 3];
1567                 loadmodel->surfmesh.data_vertex3f[j*3+1] = relativeorigin[0] * m[4] + relativeorigin[1] * m[5] + relativeorigin[2] * m[ 6] + m[ 7];
1568                 loadmodel->surfmesh.data_vertex3f[j*3+2] = relativeorigin[0] * m[8] + relativeorigin[1] * m[9] + relativeorigin[2] * m[10] + m[11];
1569                 // store the weight as the primary weight on this vertex
1570                 loadmodel->surfmesh.data_vertexweightindex4i[j*4+0] = boneindex;
1571                 loadmodel->surfmesh.data_vertexweightinfluence4f[j*4+0] = 1;
1572         }
1573         Z_Free(bonepose);
1574         // normals and tangents are calculated after elements are loaded
1575
1576         //zymlump_t lump_texcoords; // float texcoords[numvertices][2];
1577         outtexcoord2f = loadmodel->surfmesh.data_texcoordtexture2f;
1578         intexcoord2f = (float *) (pheader->lump_texcoords.start + pbase);
1579         for (i = 0;i < pheader->numverts;i++)
1580         {
1581                 outtexcoord2f[i*2+0] = BigFloat(intexcoord2f[i*2+0]);
1582                 // flip T coordinate for OpenGL
1583                 outtexcoord2f[i*2+1] = 1 - BigFloat(intexcoord2f[i*2+1]);
1584         }
1585
1586         //zymlump_t lump_trizone; // byte trizone[numtris]; // see trizone explanation
1587         //loadmodel->alias.zymdata_trizone = Mem_Alloc(loadmodel->mempool, pheader->numtris);
1588         //memcpy(loadmodel->alias.zymdata_trizone, (void *) (pheader->lump_trizone.start + pbase), pheader->numtris);
1589
1590         //zymlump_t lump_shaders; // char shadername[numshaders][32]; // shaders used on this model
1591         //zymlump_t lump_render; // int renderlist[rendersize]; // sorted by shader with run lengths (int count), shaders are sequentially used, each run can be used with glDrawElements (each triangle is 3 int indices)
1592         // byteswap, validate, and swap winding order of tris
1593         count = pheader->numshaders * sizeof(int) + pheader->numtris * sizeof(int[3]);
1594         if (pheader->lump_render.length != count)
1595                 Host_Error("%s renderlist is wrong size (%i bytes, should be %i bytes)", loadmodel->name, pheader->lump_render.length, count);
1596         renderlist = (int *) (pheader->lump_render.start + pbase);
1597         renderlistend = (int *) ((unsigned char *) renderlist + pheader->lump_render.length);
1598         meshtriangles = 0;
1599         for (i = 0;i < loadmodel->num_surfaces;i++)
1600         {
1601                 int firstvertex, lastvertex;
1602                 if (renderlist >= renderlistend)
1603                         Host_Error("%s corrupt renderlist (wrong size)", loadmodel->name);
1604                 count = BigLong(*renderlist);renderlist++;
1605                 if (renderlist + count * 3 > renderlistend || (i == pheader->numshaders - 1 && renderlist + count * 3 != renderlistend))
1606                         Host_Error("%s corrupt renderlist (wrong size)", loadmodel->name);
1607
1608                 loadmodel->surfacelist[i] = i;
1609                 surface = loadmodel->data_surfaces + i;
1610                 surface->texture = loadmodel->data_textures + i;
1611                 surface->num_firsttriangle = meshtriangles;
1612                 surface->num_triangles = count;
1613                 meshtriangles += surface->num_triangles;
1614
1615                 // load the elements
1616                 outelements = loadmodel->surfmesh.data_element3i + surface->num_firsttriangle * 3;
1617                 for (j = 0;j < surface->num_triangles;j++, renderlist += 3)
1618                 {
1619                         outelements[j*3+2] = BigLong(renderlist[0]);
1620                         outelements[j*3+1] = BigLong(renderlist[1]);
1621                         outelements[j*3+0] = BigLong(renderlist[2]);
1622                 }
1623                 // validate the elements and find the used vertex range
1624                 firstvertex = meshvertices;
1625                 lastvertex = 0;
1626                 for (j = 0;j < surface->num_triangles * 3;j++)
1627                 {
1628                         if ((unsigned int)outelements[j] >= (unsigned int)meshvertices)
1629                                 Host_Error("%s corrupt renderlist (out of bounds index)", loadmodel->name);
1630                         firstvertex = min(firstvertex, outelements[j]);
1631                         lastvertex = max(lastvertex, outelements[j]);
1632                 }
1633                 surface->num_firstvertex = firstvertex;
1634                 surface->num_vertices = lastvertex + 1 - firstvertex;
1635
1636                 // since zym models do not have named sections, reuse their shader
1637                 // name as the section name
1638                 shadername = (char *) (pheader->lump_shaders.start + pbase) + i * 32;
1639                 if (shadername[0])
1640                         Mod_BuildAliasSkinsFromSkinFiles(loadmodel->data_textures + i, skinfiles, shadername, shadername);
1641                 else
1642                         for (j = 0;j < loadmodel->numskins;j++)
1643                                 Mod_BuildAliasSkinFromSkinFrame(loadmodel->data_textures + i + j * loadmodel->num_surfaces, NULL);
1644         }
1645         Mod_FreeSkinFiles(skinfiles);
1646         Mem_Free(vertbonecounts);
1647         Mem_Free(verts);
1648
1649         // compute all the mesh information that was not loaded from the file
1650         Mod_ValidateElements(loadmodel->surfmesh.data_element3i, loadmodel->surfmesh.num_triangles, 0, loadmodel->surfmesh.num_vertices, __FILE__, __LINE__);
1651         Mod_BuildBaseBonePoses();
1652         Mod_BuildNormals(0, loadmodel->surfmesh.num_vertices, loadmodel->surfmesh.num_triangles, loadmodel->surfmesh.data_vertex3f, loadmodel->surfmesh.data_element3i, loadmodel->surfmesh.data_normal3f, true);
1653         Mod_BuildTextureVectorsFromNormals(0, loadmodel->surfmesh.num_vertices, loadmodel->surfmesh.num_triangles, loadmodel->surfmesh.data_vertex3f, loadmodel->surfmesh.data_texcoordtexture2f, loadmodel->surfmesh.data_normal3f, loadmodel->surfmesh.data_element3i, loadmodel->surfmesh.data_svector3f, loadmodel->surfmesh.data_tvector3f, true);
1654         Mod_BuildTriangleNeighbors(loadmodel->surfmesh.data_neighbor3i, loadmodel->surfmesh.data_element3i, loadmodel->surfmesh.num_triangles);
1655
1656         loadmodel->surfmesh.isanimated = loadmodel->numframes > 1 || loadmodel->animscenes[0].framecount > 1;
1657 }
1658
1659 void Mod_DARKPLACESMODEL_Load(model_t *mod, void *buffer, void *bufferend)
1660 {
1661         dpmheader_t *pheader;
1662         dpmframe_t *frame;
1663         dpmbone_t *bone;
1664         dpmmesh_t *dpmmesh;
1665         unsigned char *pbase;
1666         int i, j, k, meshvertices, meshtriangles;
1667         skinfile_t *skinfiles;
1668         unsigned char *data;
1669         float *bonepose;
1670
1671         pheader = (dpmheader_t *)buffer;
1672         pbase = (unsigned char *)buffer;
1673         if (memcmp(pheader->id, "DARKPLACESMODEL\0", 16))
1674                 Host_Error ("Mod_DARKPLACESMODEL_Load: %s is not a darkplaces model");
1675         if (BigLong(pheader->type) != 2)
1676                 Host_Error ("Mod_DARKPLACESMODEL_Load: only type 2 (hierarchical skeletal pose) models are currently supported (name = %s)", loadmodel->name);
1677
1678         loadmodel->type = mod_alias;
1679         loadmodel->flags = 0; // there are no flags on zym models
1680         loadmodel->synctype = ST_RAND;
1681
1682         // byteswap header
1683         pheader->type = BigLong(pheader->type);
1684         pheader->filesize = BigLong(pheader->filesize);
1685         pheader->mins[0] = BigFloat(pheader->mins[0]);
1686         pheader->mins[1] = BigFloat(pheader->mins[1]);
1687         pheader->mins[2] = BigFloat(pheader->mins[2]);
1688         pheader->maxs[0] = BigFloat(pheader->maxs[0]);
1689         pheader->maxs[1] = BigFloat(pheader->maxs[1]);
1690         pheader->maxs[2] = BigFloat(pheader->maxs[2]);
1691         pheader->yawradius = BigFloat(pheader->yawradius);
1692         pheader->allradius = BigFloat(pheader->allradius);
1693         pheader->num_bones = BigLong(pheader->num_bones);
1694         pheader->num_meshs = BigLong(pheader->num_meshs);
1695         pheader->num_frames = BigLong(pheader->num_frames);
1696         pheader->ofs_bones = BigLong(pheader->ofs_bones);
1697         pheader->ofs_meshs = BigLong(pheader->ofs_meshs);
1698         pheader->ofs_frames = BigLong(pheader->ofs_frames);
1699
1700         if (pheader->num_bones < 1 || pheader->num_meshs < 1)
1701         {
1702                 Con_Printf("%s has no geometry\n");
1703                 return;
1704         }
1705         if (pheader->num_frames < 1)
1706         {
1707                 Con_Printf("%s has no frames\n");
1708                 return;
1709         }
1710
1711         loadmodel->DrawSky = NULL;
1712         loadmodel->Draw = R_Q1BSP_Draw;
1713         loadmodel->CompileShadowVolume = R_Q1BSP_CompileShadowVolume;
1714         loadmodel->DrawShadowVolume = R_Q1BSP_DrawShadowVolume;
1715         loadmodel->DrawLight = R_Q1BSP_DrawLight;
1716         loadmodel->TraceBox = Mod_MDLMD2MD3_TraceBox;
1717
1718         // model bbox
1719         for (i = 0;i < 3;i++)
1720         {
1721                 loadmodel->normalmins[i] = pheader->mins[i];
1722                 loadmodel->normalmaxs[i] = pheader->maxs[i];
1723                 loadmodel->yawmins[i] = i != 2 ? -pheader->yawradius : pheader->mins[i];
1724                 loadmodel->yawmaxs[i] = i != 2 ? pheader->yawradius : pheader->maxs[i];
1725                 loadmodel->rotatedmins[i] = -pheader->allradius;
1726                 loadmodel->rotatedmaxs[i] = pheader->allradius;
1727         }
1728         loadmodel->radius = pheader->allradius;
1729         loadmodel->radius2 = pheader->allradius * pheader->allradius;
1730
1731         // load external .skin files if present
1732         skinfiles = Mod_LoadSkinFiles();
1733         if (loadmodel->numskins < 1)
1734                 loadmodel->numskins = 1;
1735
1736         meshvertices = 0;
1737         meshtriangles = 0;
1738
1739         // gather combined statistics from the meshes
1740         dpmmesh = (dpmmesh_t *) (pbase + pheader->ofs_meshs);
1741         for (i = 0;i < (int)pheader->num_meshs;i++)
1742         {
1743                 int numverts = BigLong(dpmmesh->num_verts);
1744                 meshvertices += numverts;;
1745                 meshtriangles += BigLong(dpmmesh->num_tris);
1746                 dpmmesh++;
1747         }
1748
1749         loadmodel->numframes = pheader->num_frames;
1750         loadmodel->num_bones = pheader->num_bones;
1751         loadmodel->num_poses = loadmodel->num_bones * loadmodel->numframes;
1752         loadmodel->num_textures = loadmodel->nummodelsurfaces = loadmodel->num_surfaces = pheader->num_meshs;
1753         // do most allocations as one merged chunk
1754         data = (unsigned char *)Mem_Alloc(loadmodel->mempool, loadmodel->num_surfaces * sizeof(msurface_t) + loadmodel->num_surfaces * sizeof(int) + loadmodel->num_surfaces * loadmodel->numskins * sizeof(texture_t) + meshtriangles * sizeof(int[3]) + meshtriangles * sizeof(int[3]) + meshvertices * (sizeof(float[14]) + sizeof(int[4]) + sizeof(float[4])) + loadmodel->num_poses * sizeof(float[36]) + loadmodel->numskins * sizeof(animscene_t) + loadmodel->num_bones * sizeof(aliasbone_t) + loadmodel->numframes * sizeof(animscene_t));
1755         loadmodel->data_surfaces = (msurface_t *)data;data += loadmodel->num_surfaces * sizeof(msurface_t);
1756         loadmodel->surfacelist = (int *)data;data += loadmodel->num_surfaces * sizeof(int);
1757         loadmodel->data_textures = (texture_t *)data;data += loadmodel->num_surfaces * loadmodel->numskins * sizeof(texture_t);
1758         loadmodel->surfmesh.num_vertices = meshvertices;
1759         loadmodel->surfmesh.num_triangles = meshtriangles;
1760         loadmodel->surfmesh.data_element3i = (int *)data;data += meshtriangles * sizeof(int[3]);
1761         loadmodel->surfmesh.data_neighbor3i = (int *)data;data += meshtriangles * sizeof(int[3]);
1762         loadmodel->surfmesh.data_vertex3f = (float *)data;data += meshvertices * sizeof(float[3]);
1763         loadmodel->surfmesh.data_svector3f = (float *)data;data += meshvertices * sizeof(float[3]);
1764         loadmodel->surfmesh.data_tvector3f = (float *)data;data += meshvertices * sizeof(float[3]);
1765         loadmodel->surfmesh.data_normal3f = (float *)data;data += meshvertices * sizeof(float[3]);
1766         loadmodel->surfmesh.data_texcoordtexture2f = (float *)data;data += meshvertices * sizeof(float[2]);
1767         loadmodel->surfmesh.data_vertexweightindex4i = (int *)data;data += meshvertices * sizeof(int[4]);
1768         loadmodel->surfmesh.data_vertexweightinfluence4f = (float *)data;data += meshvertices * sizeof(float[4]);
1769         loadmodel->data_poses = (float *)data;data += loadmodel->num_poses * sizeof(float[12]);
1770         loadmodel->data_basebonepose = (float *)data;data += loadmodel->num_poses * sizeof(float[12]);
1771         loadmodel->data_baseboneposeinverse = (float *)data;data += loadmodel->num_poses * sizeof(float[12]);
1772         loadmodel->skinscenes = (animscene_t *)data;data += loadmodel->numskins * sizeof(animscene_t);
1773         loadmodel->data_bones = (aliasbone_t *)data;data += loadmodel->num_bones * sizeof(aliasbone_t);
1774         loadmodel->animscenes = (animscene_t *)data;data += loadmodel->numframes * sizeof(animscene_t);
1775
1776         for (i = 0;i < loadmodel->numskins;i++)
1777         {
1778                 loadmodel->skinscenes[i].firstframe = i;
1779                 loadmodel->skinscenes[i].framecount = 1;
1780                 loadmodel->skinscenes[i].loop = true;
1781                 loadmodel->skinscenes[i].framerate = 10;
1782         }
1783
1784         // load the bone info
1785         bone = (dpmbone_t *) (pbase + pheader->ofs_bones);
1786         for (i = 0;i < loadmodel->num_bones;i++)
1787         {
1788                 memcpy(loadmodel->data_bones[i].name, bone[i].name, sizeof(bone[i].name));
1789                 loadmodel->data_bones[i].flags = BigLong(bone[i].flags);
1790                 loadmodel->data_bones[i].parent = BigLong(bone[i].parent);
1791                 if (loadmodel->data_bones[i].parent >= i)
1792                         Host_Error("%s bone[%i].parent >= %i", loadmodel->name, i, i);
1793         }
1794
1795         // load the frames
1796         frame = (dpmframe_t *) (pbase + pheader->ofs_frames);
1797         for (i = 0;i < loadmodel->numframes;i++)
1798         {
1799                 const float *poses;
1800                 memcpy(loadmodel->animscenes[i].name, frame->name, sizeof(frame->name));
1801                 loadmodel->animscenes[i].firstframe = i;
1802                 loadmodel->animscenes[i].framecount = 1;
1803                 loadmodel->animscenes[i].loop = true;
1804                 loadmodel->animscenes[i].framerate = 10;
1805                 // load the bone poses for this frame
1806                 poses = (float *) (pbase + BigLong(frame->ofs_bonepositions));
1807                 for (j = 0;j < loadmodel->num_bones*12;j++)
1808                         loadmodel->data_poses[i * loadmodel->num_bones*12 + j] = BigFloat(poses[j]);
1809                 // stuff not processed here: mins, maxs, yawradius, allradius
1810                 frame++;
1811         }
1812
1813         // load the meshes now
1814         dpmmesh = (dpmmesh_t *) (pbase + pheader->ofs_meshs);
1815         meshvertices = 0;
1816         meshtriangles = 0;
1817         // reconstruct frame 0 matrices to allow reconstruction of the base mesh
1818         // (converting from weight-blending skeletal animation to
1819         //  deformation-based skeletal animation)
1820         bonepose = (float *)Z_Malloc(loadmodel->num_bones * sizeof(float[12]));
1821         for (i = 0;i < loadmodel->num_bones;i++)
1822         {
1823                 const float *m = loadmodel->data_poses + i * 12;
1824                 if (loadmodel->data_bones[i].parent >= 0)
1825                         R_ConcatTransforms(bonepose + 12 * loadmodel->data_bones[i].parent, m, bonepose + 12 * i);
1826                 else
1827                         for (k = 0;k < 12;k++)
1828                                 bonepose[12*i+k] = m[k];
1829         }
1830         for (i = 0;i < loadmodel->num_surfaces;i++, dpmmesh++)
1831         {
1832                 const int *inelements;
1833                 int *outelements;
1834                 const float *intexcoord;
1835                 msurface_t *surface;
1836
1837                 loadmodel->surfacelist[i] = i;
1838                 surface = loadmodel->data_surfaces + i;
1839                 surface->texture = loadmodel->data_textures + i;
1840                 surface->num_firsttriangle = meshtriangles;
1841                 surface->num_triangles = BigLong(dpmmesh->num_tris);
1842                 surface->num_firstvertex = meshvertices;
1843                 surface->num_vertices = BigLong(dpmmesh->num_verts);
1844                 meshvertices += surface->num_vertices;
1845                 meshtriangles += surface->num_triangles;
1846
1847                 inelements = (int *) (pbase + BigLong(dpmmesh->ofs_indices));
1848                 outelements = loadmodel->surfmesh.data_element3i + surface->num_firsttriangle * 3;
1849                 for (j = 0;j < surface->num_triangles;j++)
1850                 {
1851                         // swap element order to flip triangles, because Quake uses clockwise (rare) and dpm uses counterclockwise (standard)
1852                         outelements[0] = surface->num_firstvertex + BigLong(inelements[2]);
1853                         outelements[1] = surface->num_firstvertex + BigLong(inelements[1]);
1854                         outelements[2] = surface->num_firstvertex + BigLong(inelements[0]);
1855                         inelements += 3;
1856                         outelements += 3;
1857                 }
1858
1859                 intexcoord = (float *) (pbase + BigLong(dpmmesh->ofs_texcoords));
1860                 for (j = 0;j < surface->num_vertices*2;j++)
1861                         loadmodel->surfmesh.data_texcoordtexture2f[j + surface->num_firstvertex * 2] = BigFloat(intexcoord[j]);
1862
1863                 data = (unsigned char *) (pbase + BigLong(dpmmesh->ofs_verts));
1864                 for (j = surface->num_firstvertex;j < surface->num_firstvertex + surface->num_vertices;j++)
1865                 {
1866                         float sum;
1867                         int l;
1868                         int numweights = BigLong(((dpmvertex_t *)data)->numbones);
1869                         data += sizeof(dpmvertex_t);
1870                         for (k = 0;k < numweights;k++)
1871                         {
1872                                 const dpmbonevert_t *vert = (dpmbonevert_t *) data;
1873                                 int boneindex = BigLong(vert->bonenum);
1874                                 const float *m = bonepose + 12 * boneindex;
1875                                 float influence = BigFloat(vert->influence);
1876                                 float relativeorigin[3], relativenormal[3];
1877                                 relativeorigin[0] = BigFloat(vert->origin[0]);
1878                                 relativeorigin[1] = BigFloat(vert->origin[1]);
1879                                 relativeorigin[2] = BigFloat(vert->origin[2]);
1880                                 relativenormal[0] = BigFloat(vert->normal[0]);
1881                                 relativenormal[1] = BigFloat(vert->normal[1]);
1882                                 relativenormal[2] = BigFloat(vert->normal[2]);
1883                                 // blend the vertex bone weights into the base mesh
1884                                 loadmodel->surfmesh.data_vertex3f[j*3+0] += relativeorigin[0] * m[0] + relativeorigin[1] * m[1] + relativeorigin[2] * m[ 2] + influence * m[ 3];
1885                                 loadmodel->surfmesh.data_vertex3f[j*3+1] += relativeorigin[0] * m[4] + relativeorigin[1] * m[5] + relativeorigin[2] * m[ 6] + influence * m[ 7];
1886                                 loadmodel->surfmesh.data_vertex3f[j*3+2] += relativeorigin[0] * m[8] + relativeorigin[1] * m[9] + relativeorigin[2] * m[10] + influence * m[11];
1887                                 loadmodel->surfmesh.data_normal3f[j*3+0] += relativenormal[0] * m[0] + relativenormal[1] * m[1] + relativenormal[2] * m[ 2];
1888                                 loadmodel->surfmesh.data_normal3f[j*3+1] += relativenormal[0] * m[4] + relativenormal[1] * m[5] + relativenormal[2] * m[ 6];
1889                                 loadmodel->surfmesh.data_normal3f[j*3+2] += relativenormal[0] * m[8] + relativenormal[1] * m[9] + relativenormal[2] * m[10];
1890                                 if (!k)
1891                                 {
1892                                         // store the first (and often only) weight
1893                                         loadmodel->surfmesh.data_vertexweightinfluence4f[j*4+0] = influence;
1894                                         loadmodel->surfmesh.data_vertexweightindex4i[j*4+0] = boneindex;
1895                                 }
1896                                 else
1897                                 {
1898                                         // sort the new weight into this vertex's weight table
1899                                         // (which only accepts up to 4 bones per vertex)
1900                                         for (l = 0;l < 4;l++)
1901                                         {
1902                                                 if (loadmodel->surfmesh.data_vertexweightinfluence4f[j*4+l] < influence)
1903                                                 {
1904                                                         // move weaker influence weights out of the way first
1905                                                         int l2;
1906                                                         for (l2 = 3;l2 > l;l2--)
1907                                                         {
1908                                                                 loadmodel->surfmesh.data_vertexweightinfluence4f[j*4+l2] = loadmodel->surfmesh.data_vertexweightinfluence4f[j*4+l2-1];
1909                                                                 loadmodel->surfmesh.data_vertexweightindex4i[j*4+l2] = loadmodel->surfmesh.data_vertexweightindex4i[j*4+l2-1];
1910                                                         }
1911                                                         // store the new weight
1912                                                         loadmodel->surfmesh.data_vertexweightinfluence4f[j*4+l] = influence;
1913                                                         loadmodel->surfmesh.data_vertexweightindex4i[j*4+l] = boneindex;
1914                                                         break;
1915                                                 }
1916                                         }
1917                                 }
1918                                 data += sizeof(dpmbonevert_t);
1919                         }
1920                         sum = 0;
1921                         for (l = 0;l < 4;l++)
1922                                 sum += loadmodel->surfmesh.data_vertexweightinfluence4f[j*4+l];
1923                         if (sum && fabs(sum - 1) > (1.0f / 256.0f))
1924                         {
1925                                 float f = 1.0f / sum;
1926                                 for (l = 0;l < 4;l++)
1927                                         loadmodel->surfmesh.data_vertexweightinfluence4f[j*4+l] *= f;
1928                         }
1929                 }
1930
1931                 // since dpm models do not have named sections, reuse their shader name as the section name
1932                 if (dpmmesh->shadername[0])
1933                         Mod_BuildAliasSkinsFromSkinFiles(loadmodel->data_textures + i, skinfiles, dpmmesh->shadername, dpmmesh->shadername);
1934                 else
1935                         for (j = 0;j < loadmodel->numskins;j++)
1936                                 Mod_BuildAliasSkinFromSkinFrame(loadmodel->data_textures + i + j * loadmodel->num_surfaces, NULL);
1937
1938                 Mod_ValidateElements(loadmodel->surfmesh.data_element3i + surface->num_firsttriangle * 3, surface->num_triangles, surface->num_firstvertex, surface->num_vertices, __FILE__, __LINE__);
1939         }
1940         Z_Free(bonepose);
1941         Mod_FreeSkinFiles(skinfiles);
1942
1943         // compute all the mesh information that was not loaded from the file
1944         Mod_BuildBaseBonePoses();
1945         Mod_BuildTextureVectorsFromNormals(0, loadmodel->surfmesh.num_vertices, loadmodel->surfmesh.num_triangles, loadmodel->surfmesh.data_vertex3f, loadmodel->surfmesh.data_texcoordtexture2f, loadmodel->surfmesh.data_normal3f, loadmodel->surfmesh.data_element3i, loadmodel->surfmesh.data_svector3f, loadmodel->surfmesh.data_tvector3f, true);
1946         Mod_BuildTriangleNeighbors(loadmodel->surfmesh.data_neighbor3i, loadmodel->surfmesh.data_element3i, loadmodel->surfmesh.num_triangles);
1947
1948         loadmodel->surfmesh.isanimated = loadmodel->numframes > 1 || loadmodel->animscenes[0].framecount > 1;
1949 }
1950
1951 static void Mod_PSKMODEL_AnimKeyToMatrix(float *origin, float *quat, matrix4x4_t *m)
1952 {
1953         float x = quat[0], y = quat[1], z = quat[2], w = quat[3];
1954         m->m[0][0]=1-2*(y*y+z*z);m->m[0][1]=  2*(x*y-z*w);m->m[0][2]=  2*(x*z+y*w);m->m[0][3]=origin[0];
1955         m->m[1][0]=  2*(x*y+z*w);m->m[1][1]=1-2*(x*x+z*z);m->m[1][2]=  2*(y*z-x*w);m->m[1][3]=origin[1];
1956         m->m[2][0]=  2*(x*z-y*w);m->m[2][1]=  2*(y*z+x*w);m->m[2][2]=1-2*(x*x+y*y);m->m[2][3]=origin[2];
1957         m->m[3][0]=  0          ;m->m[3][1]=  0          ;m->m[3][2]=  0          ;m->m[3][3]=1;
1958 }
1959
1960 // no idea why PSK/PSA files contain weird quaternions but they do...
1961 #define PSKQUATNEGATIONS
1962 void Mod_PSKMODEL_Load(model_t *mod, void *buffer, void *bufferend)
1963 {
1964         int i, j, index, version, recordsize, numrecords, meshvertices, meshtriangles;
1965         int numpnts, numvtxw, numfaces, nummatts, numbones, numrawweights, numanimbones, numanims, numanimkeys;
1966         fs_offset_t filesize;
1967         pskpnts_t *pnts;
1968         pskvtxw_t *vtxw;
1969         pskface_t *faces;
1970         pskmatt_t *matts;
1971         pskboneinfo_t *bones;
1972         pskrawweights_t *rawweights;
1973         pskboneinfo_t *animbones;
1974         pskaniminfo_t *anims;
1975         pskanimkeys_t *animkeys;
1976         void *animfilebuffer, *animbuffer, *animbufferend;
1977         unsigned char *data;
1978         pskchunk_t *pchunk;
1979         skinfile_t *skinfiles;
1980         char animname[MAX_QPATH];
1981
1982         pchunk = (pskchunk_t *)buffer;
1983         if (strcmp(pchunk->id, "ACTRHEAD"))
1984                 Host_Error ("Mod_PSKMODEL_Load: %s is not an Unreal Engine ActorX (.psk + .psa) model");
1985
1986         loadmodel->type = mod_alias;
1987         loadmodel->DrawSky = NULL;
1988         loadmodel->Draw = R_Q1BSP_Draw;
1989         loadmodel->CompileShadowVolume = R_Q1BSP_CompileShadowVolume;
1990         loadmodel->DrawShadowVolume = R_Q1BSP_DrawShadowVolume;
1991         loadmodel->DrawLight = R_Q1BSP_DrawLight;
1992         loadmodel->TraceBox = Mod_MDLMD2MD3_TraceBox;
1993         loadmodel->flags = 0; // there are no flags on zym models
1994         loadmodel->synctype = ST_RAND;
1995
1996         FS_StripExtension(loadmodel->name, animname, sizeof(animname));
1997         strlcat(animname, ".psa", sizeof(animname));
1998         animbuffer = animfilebuffer = FS_LoadFile(animname, loadmodel->mempool, false, &filesize);
1999         animbufferend = (void *)((unsigned char*)animbuffer + (int)filesize);
2000         if (animbuffer == NULL)
2001                 Host_Error("%s: can't find .psa file (%s)", loadmodel->name, animname);
2002
2003         numpnts = 0;
2004         pnts = NULL;
2005         numvtxw = 0;
2006         vtxw = NULL;
2007         numfaces = 0;
2008         faces = NULL;
2009         nummatts = 0;
2010         matts = NULL;
2011         numbones = 0;
2012         bones = NULL;
2013         numrawweights = 0;
2014         rawweights = NULL;
2015         numanims = 0;
2016         anims = NULL;
2017         numanimkeys = 0;
2018         animkeys = NULL;
2019
2020         while (buffer < bufferend)
2021         {
2022                 pchunk = (pskchunk_t *)buffer;
2023                 buffer = (void *)((unsigned char *)buffer + sizeof(pskchunk_t));
2024                 version = LittleLong(pchunk->version);
2025                 recordsize = LittleLong(pchunk->recordsize);
2026                 numrecords = LittleLong(pchunk->numrecords);
2027                 if (developer.integer >= 100)
2028                         Con_Printf("%s: %s %x: %i * %i = %i\n", loadmodel->name, pchunk->id, version, recordsize, numrecords, recordsize * numrecords);
2029                 if (version != 0x1e83b9 && version != 0x1e9179 && version != 0x2e && version != 0x12f2bc && version != 0x12f2f0)
2030                         Con_Printf ("%s: chunk %s has unknown version %x (0x1e83b9, 0x1e9179, 0x2e, 0x12f2bc, 0x12f2f0 are currently supported), trying to load anyway!\n", loadmodel->name, pchunk->id, version);
2031                 if (!strcmp(pchunk->id, "ACTRHEAD"))
2032                 {
2033                         // nothing to do
2034                 }
2035                 else if (!strcmp(pchunk->id, "PNTS0000"))
2036                 {
2037                         pskpnts_t *p;
2038                         if (recordsize != sizeof(*p))
2039                                 Host_Error("%s: %s has unsupported recordsize", loadmodel->name, pchunk->id);
2040                         // byteswap in place and keep the pointer
2041                         numpnts = numrecords;
2042                         pnts = (pskpnts_t *)buffer;
2043                         for (index = 0, p = (pskpnts_t *)buffer;index < numrecords;index++, p++)
2044                         {
2045                                 p->origin[0] = LittleFloat(p->origin[0]);
2046                                 p->origin[1] = LittleFloat(p->origin[1]);
2047                                 p->origin[2] = LittleFloat(p->origin[2]);
2048                         }
2049                         buffer = p;
2050                 }
2051                 else if (!strcmp(pchunk->id, "VTXW0000"))
2052                 {
2053                         pskvtxw_t *p;
2054                         if (recordsize != sizeof(*p))
2055                                 Host_Error("%s: %s has unsupported recordsize", loadmodel->name, pchunk->id);
2056                         // byteswap in place and keep the pointer
2057                         numvtxw = numrecords;
2058                         vtxw = (pskvtxw_t *)buffer;
2059                         for (index = 0, p = (pskvtxw_t *)buffer;index < numrecords;index++, p++)
2060                         {
2061                                 p->pntsindex = LittleShort(p->pntsindex);
2062                                 p->texcoord[0] = LittleFloat(p->texcoord[0]);
2063                                 p->texcoord[1] = LittleFloat(p->texcoord[1]);
2064                                 if (p->pntsindex >= numpnts)
2065                                 {
2066                                         Con_Printf("%s: vtxw->pntsindex %i >= numpnts %i\n", loadmodel->name, p->pntsindex, numpnts);
2067                                         p->pntsindex = 0;
2068                                 }
2069                         }
2070                         buffer = p;
2071                 }
2072                 else if (!strcmp(pchunk->id, "FACE0000"))
2073                 {
2074                         pskface_t *p;
2075                         if (recordsize != sizeof(*p))
2076                                 Host_Error("%s: %s has unsupported recordsize", loadmodel->name, pchunk->id);
2077                         // byteswap in place and keep the pointer
2078                         numfaces = numrecords;
2079                         faces = (pskface_t *)buffer;
2080                         for (index = 0, p = (pskface_t *)buffer;index < numrecords;index++, p++)
2081                         {
2082                                 p->vtxwindex[0] = LittleShort(p->vtxwindex[0]);
2083                                 p->vtxwindex[1] = LittleShort(p->vtxwindex[1]);
2084                                 p->vtxwindex[2] = LittleShort(p->vtxwindex[2]);
2085                                 p->group = LittleLong(p->group);
2086                                 if (p->vtxwindex[0] >= numvtxw)
2087                                 {
2088                                         Con_Printf("%s: face->vtxwindex[0] %i >= numvtxw %i\n", loadmodel->name, p->vtxwindex[0], numvtxw);
2089                                         p->vtxwindex[0] = 0;
2090                                 }
2091                                 if (p->vtxwindex[1] >= numvtxw)
2092                                 {
2093                                         Con_Printf("%s: face->vtxwindex[1] %i >= numvtxw %i\n", loadmodel->name, p->vtxwindex[1], numvtxw);
2094                                         p->vtxwindex[1] = 0;
2095                                 }
2096                                 if (p->vtxwindex[2] >= numvtxw)
2097                                 {
2098                                         Con_Printf("%s: face->vtxwindex[2] %i >= numvtxw %i\n", loadmodel->name, p->vtxwindex[2], numvtxw);
2099                                         p->vtxwindex[2] = 0;
2100                                 }
2101                         }
2102                         buffer = p;
2103                 }
2104                 else if (!strcmp(pchunk->id, "MATT0000"))
2105                 {
2106                         pskmatt_t *p;
2107                         if (recordsize != sizeof(*p))
2108                                 Host_Error("%s: %s has unsupported recordsize", loadmodel->name, pchunk->id);
2109                         // byteswap in place and keep the pointer
2110                         nummatts = numrecords;
2111                         matts = (pskmatt_t *)buffer;
2112                         for (index = 0, p = (pskmatt_t *)buffer;index < numrecords;index++, p++)
2113                         {
2114                                 // nothing to do
2115                         }
2116                         buffer = p;
2117                 }
2118                 else if (!strcmp(pchunk->id, "REFSKELT"))
2119                 {
2120                         pskboneinfo_t *p;
2121                         if (recordsize != sizeof(*p))
2122                                 Host_Error("%s: %s has unsupported recordsize", loadmodel->name, pchunk->id);
2123                         // byteswap in place and keep the pointer
2124                         numbones = numrecords;
2125                         bones = (pskboneinfo_t *)buffer;
2126                         for (index = 0, p = (pskboneinfo_t *)buffer;index < numrecords;index++, p++)
2127                         {
2128                                 p->numchildren = LittleLong(p->numchildren);
2129                                 p->parent = LittleLong(p->parent);
2130                                 p->basepose.quat[0] = LittleFloat(p->basepose.quat[0]);
2131                                 p->basepose.quat[1] = LittleFloat(p->basepose.quat[1]);
2132                                 p->basepose.quat[2] = LittleFloat(p->basepose.quat[2]);
2133                                 p->basepose.quat[3] = LittleFloat(p->basepose.quat[3]);
2134                                 p->basepose.origin[0] = LittleFloat(p->basepose.origin[0]);
2135                                 p->basepose.origin[1] = LittleFloat(p->basepose.origin[1]);
2136                                 p->basepose.origin[2] = LittleFloat(p->basepose.origin[2]);
2137                                 p->basepose.unknown = LittleFloat(p->basepose.unknown);
2138                                 p->basepose.size[0] = LittleFloat(p->basepose.size[0]);
2139                                 p->basepose.size[1] = LittleFloat(p->basepose.size[1]);
2140                                 p->basepose.size[2] = LittleFloat(p->basepose.size[2]);
2141 #ifdef PSKQUATNEGATIONS
2142                                 if (index)
2143                                 {
2144                                         p->basepose.quat[0] *= -1;
2145                                         p->basepose.quat[1] *= -1;
2146                                         p->basepose.quat[2] *= -1;
2147                                 }
2148                                 else
2149                                 {
2150                                         p->basepose.quat[0] *=  1;
2151                                         p->basepose.quat[1] *= -1;
2152                                         p->basepose.quat[2] *=  1;
2153                                 }
2154 #endif
2155                                 if (p->parent < 0 || p->parent >= numbones)
2156                                 {
2157                                         Con_Printf("%s: bone->parent %i >= numbones %i\n", loadmodel->name, p->parent, numbones);
2158                                         p->parent = 0;
2159                                 }
2160                         }
2161                         buffer = p;
2162                 }
2163                 else if (!strcmp(pchunk->id, "RAWWEIGHTS"))
2164                 {
2165                         pskrawweights_t *p;
2166                         if (recordsize != sizeof(*p))
2167                                 Host_Error("%s: %s has unsupported recordsize", loadmodel->name, pchunk->id);
2168                         // byteswap in place and keep the pointer
2169                         numrawweights = numrecords;
2170                         rawweights = (pskrawweights_t *)buffer;
2171                         for (index = 0, p = (pskrawweights_t *)buffer;index < numrecords;index++, p++)
2172                         {
2173                                 p->weight = LittleFloat(p->weight);
2174                                 p->pntsindex = LittleLong(p->pntsindex);
2175                                 p->boneindex = LittleLong(p->boneindex);
2176                                 if (p->pntsindex < 0 || p->pntsindex >= numpnts)
2177                                 {
2178                                         Con_Printf("%s: weight->pntsindex %i >= numpnts %i\n", loadmodel->name, p->pntsindex, numpnts);
2179                                         p->pntsindex = 0;
2180                                 }
2181                                 if (p->boneindex < 0 || p->boneindex >= numbones)
2182                                 {
2183                                         Con_Printf("%s: weight->boneindex %i >= numbones %i\n", loadmodel->name, p->boneindex, numbones);
2184                                         p->boneindex = 0;
2185                                 }
2186                         }
2187                         buffer = p;
2188                 }
2189         }
2190
2191         while (animbuffer < animbufferend)
2192         {
2193                 pchunk = (pskchunk_t *)animbuffer;
2194                 animbuffer = (void *)((unsigned char *)animbuffer + sizeof(pskchunk_t));
2195                 version = LittleLong(pchunk->version);
2196                 recordsize = LittleLong(pchunk->recordsize);
2197                 numrecords = LittleLong(pchunk->numrecords);
2198                 if (developer.integer >= 100)
2199                         Con_Printf("%s: %s %x: %i * %i = %i\n", animname, pchunk->id, version, recordsize, numrecords, recordsize * numrecords);
2200                 if (version != 0x1e83b9 && version != 0x1e9179 && version != 0x2e && version != 0x12f2bc && version != 0x12f2f0)
2201                         Con_Printf ("%s: chunk %s has unknown version %x (0x1e83b9, 0x1e9179, 0x2e, 0x12f2bc, 0x12f2f0 are currently supported), trying to load anyway!\n", animname, pchunk->id, version);
2202                 if (!strcmp(pchunk->id, "ANIMHEAD"))
2203                 {
2204                         // nothing to do
2205                 }
2206                 else if (!strcmp(pchunk->id, "BONENAMES"))
2207                 {
2208                         pskboneinfo_t *p;
2209                         if (recordsize != sizeof(*p))
2210                                 Host_Error("%s: %s has unsupported recordsize", animname, pchunk->id);
2211                         // byteswap in place and keep the pointer
2212                         numanimbones = numrecords;
2213                         animbones = (pskboneinfo_t *)animbuffer;
2214                         // NOTE: supposedly psa does not need to match the psk model, the
2215                         // bones missing from the psa would simply use their base
2216                         // positions from the psk, but this is hard for me to implement
2217                         // and people can easily make animations that match.
2218                         if (numanimbones != numbones)
2219                                 Host_Error("%s: this loader only supports animations with the same bones as the mesh");
2220                         for (index = 0, p = (pskboneinfo_t *)animbuffer;index < numrecords;index++, p++)
2221                         {
2222                                 p->numchildren = LittleLong(p->numchildren);
2223                                 p->parent = LittleLong(p->parent);
2224                                 p->basepose.quat[0] = LittleFloat(p->basepose.quat[0]);
2225                                 p->basepose.quat[1] = LittleFloat(p->basepose.quat[1]);
2226                                 p->basepose.quat[2] = LittleFloat(p->basepose.quat[2]);
2227                                 p->basepose.quat[3] = LittleFloat(p->basepose.quat[3]);
2228                                 p->basepose.origin[0] = LittleFloat(p->basepose.origin[0]);
2229                                 p->basepose.origin[1] = LittleFloat(p->basepose.origin[1]);
2230                                 p->basepose.origin[2] = LittleFloat(p->basepose.origin[2]);
2231                                 p->basepose.unknown = LittleFloat(p->basepose.unknown);
2232                                 p->basepose.size[0] = LittleFloat(p->basepose.size[0]);
2233                                 p->basepose.size[1] = LittleFloat(p->basepose.size[1]);
2234                                 p->basepose.size[2] = LittleFloat(p->basepose.size[2]);
2235 #ifdef PSKQUATNEGATIONS
2236                                 if (index)
2237                                 {
2238                                         p->basepose.quat[0] *= -1;
2239                                         p->basepose.quat[1] *= -1;
2240                                         p->basepose.quat[2] *= -1;
2241                                 }
2242                                 else
2243                                 {
2244                                         p->basepose.quat[0] *=  1;
2245                                         p->basepose.quat[1] *= -1;
2246                                         p->basepose.quat[2] *=  1;
2247                                 }
2248 #endif
2249                                 if (p->parent < 0 || p->parent >= numanimbones)
2250                                 {
2251                                         Con_Printf("%s: bone->parent %i >= numanimbones %i\n", animname, p->parent, numanimbones);
2252                                         p->parent = 0;
2253                                 }
2254                                 // check that bones are the same as in the base
2255                                 if (strcmp(p->name, bones[index].name) || p->parent != bones[index].parent)
2256                                         Host_Error("%s: this loader only supports animations with the same bones as the mesh", animname);
2257                         }
2258                         animbuffer = p;
2259                 }
2260                 else if (!strcmp(pchunk->id, "ANIMINFO"))
2261                 {
2262                         pskaniminfo_t *p;
2263                         if (recordsize != sizeof(*p))
2264                                 Host_Error("%s: %s has unsupported recordsize", animname, pchunk->id);
2265                         // byteswap in place and keep the pointer
2266                         numanims = numrecords;
2267                         anims = (pskaniminfo_t *)animbuffer;
2268                         for (index = 0, p = (pskaniminfo_t *)animbuffer;index < numrecords;index++, p++)
2269                         {
2270                                 p->numbones = LittleLong(p->numbones);
2271                                 p->playtime = LittleFloat(p->playtime);
2272                                 p->fps = LittleFloat(p->fps);
2273                                 p->firstframe = LittleLong(p->firstframe);
2274                                 p->numframes = LittleLong(p->numframes);
2275                                 if (p->numbones != numbones)
2276                                         Con_Printf("%s: animinfo->numbones != numbones, trying to load anyway!\n", animname);
2277                         }
2278                         animbuffer = p;
2279                 }
2280                 else if (!strcmp(pchunk->id, "ANIMKEYS"))
2281                 {
2282                         pskanimkeys_t *p;
2283                         if (recordsize != sizeof(*p))
2284                                 Host_Error("%s: %s has unsupported recordsize", animname, pchunk->id);
2285                         numanimkeys = numrecords;
2286                         animkeys = (pskanimkeys_t *)animbuffer;
2287                         for (index = 0, p = (pskanimkeys_t *)animbuffer;index < numrecords;index++, p++)
2288                         {
2289                                 p->origin[0] = LittleFloat(p->origin[0]);
2290                                 p->origin[1] = LittleFloat(p->origin[1]);
2291                                 p->origin[2] = LittleFloat(p->origin[2]);
2292                                 p->quat[0] = LittleFloat(p->quat[0]);
2293                                 p->quat[1] = LittleFloat(p->quat[1]);
2294                                 p->quat[2] = LittleFloat(p->quat[2]);
2295                                 p->quat[3] = LittleFloat(p->quat[3]);
2296                                 p->frametime = LittleFloat(p->frametime);
2297 #ifdef PSKQUATNEGATIONS
2298                                 if (index % numbones)
2299                                 {
2300                                         p->quat[0] *= -1;
2301                                         p->quat[1] *= -1;
2302                                         p->quat[2] *= -1;
2303                                 }
2304                                 else
2305                                 {
2306                                         p->quat[0] *=  1;
2307                                         p->quat[1] *= -1;
2308                                         p->quat[2] *=  1;
2309                                 }
2310 #endif
2311                         }
2312                         animbuffer = p;
2313                         // TODO: allocate bonepose stuff
2314                 }
2315                 else
2316                         Con_Printf("%s: unknown chunk ID \"%s\"\n", animname, pchunk->id);
2317         }
2318
2319         if (!numpnts || !pnts || !numvtxw || !vtxw || !numfaces || !faces || !nummatts || !matts || !numbones || !bones || !numrawweights || !rawweights || !numanims || !anims || !numanimkeys || !animkeys)
2320                 Host_Error("%s: missing required chunks", loadmodel->name);
2321
2322         loadmodel->numframes = 0;
2323         for (index = 0;index < numanims;index++)
2324                 loadmodel->numframes += anims[index].numframes;
2325
2326         if (numanimkeys != numbones * loadmodel->numframes)
2327                 Host_Error("%s: %s has incorrect number of animation keys", animname, pchunk->id);
2328
2329         meshvertices = numvtxw;
2330         meshtriangles = numfaces;
2331
2332         // load external .skin files if present
2333         skinfiles = Mod_LoadSkinFiles();
2334         if (loadmodel->numskins < 1)
2335                 loadmodel->numskins = 1;
2336         loadmodel->num_bones = numbones;
2337         loadmodel->num_poses = loadmodel->num_bones * loadmodel->numframes;
2338         loadmodel->num_textures = loadmodel->nummodelsurfaces = loadmodel->num_surfaces = nummatts;
2339         // do most allocations as one merged chunk
2340         data = (unsigned char *)Mem_Alloc(loadmodel->mempool, loadmodel->num_surfaces * sizeof(msurface_t) + loadmodel->num_surfaces * sizeof(int) + loadmodel->num_surfaces * loadmodel->numskins * sizeof(texture_t) + meshtriangles * sizeof(int[3]) + meshtriangles * sizeof(int[3]) + meshvertices * (sizeof(float[14]) + sizeof(int[4]) + sizeof(float[4])) + loadmodel->num_poses * sizeof(float[36]) + loadmodel->numskins * sizeof(animscene_t) + loadmodel->num_bones * sizeof(aliasbone_t) + loadmodel->numframes * sizeof(animscene_t));
2341         loadmodel->data_surfaces = (msurface_t *)data;data += loadmodel->num_surfaces * sizeof(msurface_t);
2342         loadmodel->surfacelist = (int *)data;data += loadmodel->num_surfaces * sizeof(int);
2343         loadmodel->data_textures = (texture_t *)data;data += loadmodel->num_surfaces * loadmodel->numskins * sizeof(texture_t);
2344         loadmodel->surfmesh.num_vertices = meshvertices;
2345         loadmodel->surfmesh.num_triangles = meshtriangles;
2346         loadmodel->surfmesh.data_element3i = (int *)data;data += meshtriangles * sizeof(int[3]);
2347         loadmodel->surfmesh.data_neighbor3i = (int *)data;data += meshtriangles * sizeof(int[3]);
2348         loadmodel->surfmesh.data_vertex3f = (float *)data;data += meshvertices * sizeof(float[3]);
2349         loadmodel->surfmesh.data_svector3f = (float *)data;data += meshvertices * sizeof(float[3]);
2350         loadmodel->surfmesh.data_tvector3f = (float *)data;data += meshvertices * sizeof(float[3]);
2351         loadmodel->surfmesh.data_normal3f = (float *)data;data += meshvertices * sizeof(float[3]);
2352         loadmodel->surfmesh.data_texcoordtexture2f = (float *)data;data += meshvertices * sizeof(float[2]);
2353         loadmodel->surfmesh.data_vertexweightindex4i = (int *)data;data += meshvertices * sizeof(int[4]);
2354         loadmodel->surfmesh.data_vertexweightinfluence4f = (float *)data;data += meshvertices * sizeof(float[4]);
2355         loadmodel->data_poses = (float *)data;data += loadmodel->num_poses * sizeof(float[12]);
2356         loadmodel->data_basebonepose = (float *)data;data += loadmodel->num_poses * sizeof(float[12]);
2357         loadmodel->data_baseboneposeinverse = (float *)data;data += loadmodel->num_poses * sizeof(float[12]);
2358         loadmodel->skinscenes = (animscene_t *)data;data += loadmodel->numskins * sizeof(animscene_t);
2359         loadmodel->data_bones = (aliasbone_t *)data;data += loadmodel->num_bones * sizeof(aliasbone_t);
2360         loadmodel->animscenes = (animscene_t *)data;data += loadmodel->numframes * sizeof(animscene_t);
2361
2362         for (i = 0;i < loadmodel->numskins;i++)
2363         {
2364                 loadmodel->skinscenes[i].firstframe = i;
2365                 loadmodel->skinscenes[i].framecount = 1;
2366                 loadmodel->skinscenes[i].loop = true;
2367                 loadmodel->skinscenes[i].framerate = 10;
2368         }
2369
2370         // create surfaces
2371         for (index = 0, i = 0;index < nummatts;index++)
2372         {
2373                 // since psk models do not have named sections, reuse their shader name as the section name
2374                 if (matts[index].name[0])
2375                         Mod_BuildAliasSkinsFromSkinFiles(loadmodel->data_textures + index, skinfiles, matts[index].name, matts[index].name);
2376                 else
2377                         for (j = 0;j < loadmodel->numskins;j++)
2378                                 Mod_BuildAliasSkinFromSkinFrame(loadmodel->data_textures + index + j * loadmodel->num_surfaces, NULL);
2379                 loadmodel->surfacelist[index] = index;
2380                 loadmodel->data_surfaces[index].texture = loadmodel->data_textures + index;
2381                 loadmodel->data_surfaces[index].num_firstvertex = 0;
2382                 loadmodel->data_surfaces[index].num_vertices = loadmodel->surfmesh.num_vertices;
2383         }
2384
2385         // copy over the vertex locations and texcoords
2386         for (index = 0;index < numvtxw;index++)
2387         {
2388                 loadmodel->surfmesh.data_vertex3f[index*3+0] = pnts[vtxw[index].pntsindex].origin[0];
2389                 loadmodel->surfmesh.data_vertex3f[index*3+1] = pnts[vtxw[index].pntsindex].origin[1];
2390                 loadmodel->surfmesh.data_vertex3f[index*3+2] = pnts[vtxw[index].pntsindex].origin[2];
2391                 loadmodel->surfmesh.data_texcoordtexture2f[index*2+0] = vtxw[index].texcoord[0];
2392                 loadmodel->surfmesh.data_texcoordtexture2f[index*2+1] = vtxw[index].texcoord[1];
2393         }
2394
2395         // loading the faces is complicated because we need to sort them into surfaces by mattindex
2396         for (index = 0;index < numfaces;index++)
2397                 loadmodel->data_surfaces[faces[index].mattindex].num_triangles++;
2398         for (index = 0, i = 0;index < nummatts;index++)
2399         {
2400                 loadmodel->data_surfaces[index].num_firsttriangle = i;
2401                 i += loadmodel->data_surfaces[index].num_triangles;
2402                 loadmodel->data_surfaces[index].num_triangles = 0;
2403         }
2404         for (index = 0;index < numfaces;index++)
2405         {
2406                 i = (loadmodel->data_surfaces[faces[index].mattindex].num_firsttriangle + loadmodel->data_surfaces[faces[index].mattindex].num_triangles++)*3;
2407                 loadmodel->surfmesh.data_element3i[i+0] = faces[index].vtxwindex[0];
2408                 loadmodel->surfmesh.data_element3i[i+1] = faces[index].vtxwindex[1];
2409                 loadmodel->surfmesh.data_element3i[i+2] = faces[index].vtxwindex[2];
2410         }
2411
2412         // copy over the bones
2413         for (index = 0;index < numbones;index++)
2414         {
2415                 strlcpy(loadmodel->data_bones[index].name, bones[index].name, sizeof(loadmodel->data_bones[index].name));
2416                 loadmodel->data_bones[index].parent = (index || bones[index].parent > 0) ? bones[index].parent : -1;
2417                 if (loadmodel->data_bones[index].parent >= index)
2418                         Host_Error("%s bone[%i].parent >= %i", loadmodel->name, index, index);
2419         }
2420
2421         // sort the psk point weights into the vertex weight tables
2422         // (which only accept up to 4 bones per vertex)
2423         for (index = 0;index < numvtxw;index++)
2424         {
2425                 int l;
2426                 float sum;
2427                 for (j = 0;j < numrawweights;j++)
2428                 {
2429                         if (rawweights[j].pntsindex == vtxw[index].pntsindex)
2430                         {
2431                                 int boneindex = rawweights[j].boneindex;
2432                                 float influence = rawweights[j].weight;
2433                                 for (l = 0;l < 4;l++)
2434                                 {
2435                                         if (loadmodel->surfmesh.data_vertexweightinfluence4f[index*4+l] < influence)
2436                                         {
2437                                                 // move lower influence weights out of the way first
2438                                                 int l2;
2439                                                 for (l2 = 3;l2 > l;l2--)
2440                                                 {
2441                                                         loadmodel->surfmesh.data_vertexweightinfluence4f[index*4+l2] = loadmodel->surfmesh.data_vertexweightinfluence4f[index*4+l2-1];
2442                                                         loadmodel->surfmesh.data_vertexweightindex4i[index*4+l2] = loadmodel->surfmesh.data_vertexweightindex4i[index*4+l2-1];
2443                                                 }
2444                                                 // store the new weight
2445                                                 loadmodel->surfmesh.data_vertexweightinfluence4f[index*4+l] = influence;
2446                                                 loadmodel->surfmesh.data_vertexweightindex4i[index*4+l] = boneindex;
2447                                                 break;
2448                                         }
2449                                 }
2450                         }
2451                 }
2452                 sum = 0;
2453                 for (l = 0;l < 4;l++)
2454                         sum += loadmodel->surfmesh.data_vertexweightinfluence4f[index*4+l];
2455                 if (sum && fabs(sum - 1) > (1.0f / 256.0f))
2456                 {
2457                         float f = 1.0f / sum;
2458                         for (l = 0;l < 4;l++)
2459                                 loadmodel->surfmesh.data_vertexweightinfluence4f[index*4+l] *= f;
2460                 }
2461         }
2462
2463         // set up the animscenes based on the anims
2464         for (index = 0, i = 0;index < numanims;index++)
2465         {
2466                 for (j = 0;j < anims[index].numframes;j++, i++)
2467                 {
2468                         dpsnprintf(loadmodel->animscenes[i].name, sizeof(loadmodel->animscenes[i].name), "%s_%d", anims[index].name, j);
2469                         loadmodel->animscenes[i].firstframe = i;
2470                         loadmodel->animscenes[i].framecount = 1;
2471                         loadmodel->animscenes[i].loop = true;
2472                         loadmodel->animscenes[i].framerate = 10;
2473                 }
2474         }
2475
2476         // load the poses from the animkeys
2477         for (index = 0;index < numanimkeys;index++)
2478         {
2479                 matrix4x4_t matrix;
2480                 Mod_PSKMODEL_AnimKeyToMatrix(animkeys[index].origin, animkeys[index].quat, &matrix);
2481                 loadmodel->data_poses[index*12+0] = matrix.m[0][0];
2482                 loadmodel->data_poses[index*12+1] = matrix.m[0][1];
2483                 loadmodel->data_poses[index*12+2] = matrix.m[0][2];
2484                 loadmodel->data_poses[index*12+3] = matrix.m[0][3];
2485                 loadmodel->data_poses[index*12+4] = matrix.m[1][0];
2486                 loadmodel->data_poses[index*12+5] = matrix.m[1][1];
2487                 loadmodel->data_poses[index*12+6] = matrix.m[1][2];
2488                 loadmodel->data_poses[index*12+7] = matrix.m[1][3];
2489                 loadmodel->data_poses[index*12+8] = matrix.m[2][0];
2490                 loadmodel->data_poses[index*12+9] = matrix.m[2][1];
2491                 loadmodel->data_poses[index*12+10] = matrix.m[2][2];
2492                 loadmodel->data_poses[index*12+11] = matrix.m[2][3];
2493         }
2494         Mod_FreeSkinFiles(skinfiles);
2495         Mem_Free(animfilebuffer);
2496
2497         // compute all the mesh information that was not loaded from the file
2498         // TODO: honor smoothing groups somehow?
2499         Mod_ValidateElements(loadmodel->surfmesh.data_element3i, loadmodel->surfmesh.num_triangles, 0, loadmodel->surfmesh.num_vertices, __FILE__, __LINE__);
2500         Mod_BuildBaseBonePoses();
2501         Mod_BuildNormals(0, loadmodel->surfmesh.num_vertices, loadmodel->surfmesh.num_triangles, loadmodel->surfmesh.data_vertex3f, loadmodel->surfmesh.data_element3i, loadmodel->surfmesh.data_normal3f, true);
2502         Mod_BuildTextureVectorsFromNormals(0, loadmodel->surfmesh.num_vertices, loadmodel->surfmesh.num_triangles, loadmodel->surfmesh.data_vertex3f, loadmodel->surfmesh.data_texcoordtexture2f, loadmodel->surfmesh.data_normal3f, loadmodel->surfmesh.data_element3i, loadmodel->surfmesh.data_svector3f, loadmodel->surfmesh.data_tvector3f, true);
2503         Mod_BuildTriangleNeighbors(loadmodel->surfmesh.data_neighbor3i, loadmodel->surfmesh.data_element3i, loadmodel->surfmesh.num_triangles);
2504         Mod_Alias_CalculateBoundingBox();
2505
2506         loadmodel->surfmesh.isanimated = loadmodel->numframes > 1 || loadmodel->animscenes[0].framecount > 1;
2507 }
2508