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