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