]> de.git.xonotic.org Git - xonotic/netradiant.git/blob - radiant/brush_primit.cpp
load notex textures from a builtin vfs
[xonotic/netradiant.git] / radiant / brush_primit.cpp
1 /*
2    Copyright (C) 1999-2006 Id Software, Inc. and contributors.
3    For a list of contributors, see the accompanying CONTRIBUTORS file.
4
5    This file is part of GtkRadiant.
6
7    GtkRadiant is free software; you can redistribute it and/or modify
8    it under the terms of the GNU General Public License as published by
9    the Free Software Foundation; either version 2 of the License, or
10    (at your option) any later version.
11
12    GtkRadiant is distributed in the hope that it will be useful,
13    but WITHOUT ANY WARRANTY; without even the implied warranty of
14    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15    GNU General Public License for more details.
16
17    You should have received a copy of the GNU General Public License
18    along with GtkRadiant; if not, write to the Free Software
19    Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
20  */
21
22 #include "brush_primit.h"
23 #include "globaldefs.h"
24
25 #include "debugging/debugging.h"
26
27 #include "itexdef.h"
28 #include "itextures.h"
29
30 #include <algorithm>
31
32 #include "stringio.h"
33 #include "texturelib.h"
34 #include "math/matrix.h"
35 #include "math/plane.h"
36 #include "math/aabb.h"
37
38 #include "winding.h"
39 #include "preferences.h"
40
41
42 /*!
43    \brief Construct a transform from XYZ space to ST space (3d to 2d).
44    This will be one of three axis-aligned spaces, depending on the surface normal.
45    NOTE: could also be done by swapping values.
46  */
47 void Normal_GetTransform(const Vector3 &normal, Matrix4 &transform)
48 {
49     switch (projectionaxis_for_normal(normal)) {
50         case eProjectionAxisZ:
51             transform[0] = 1;
52             transform[1] = 0;
53             transform[2] = 0;
54
55             transform[4] = 0;
56             transform[5] = 1;
57             transform[6] = 0;
58
59             transform[8] = 0;
60             transform[9] = 0;
61             transform[10] = 1;
62             break;
63         case eProjectionAxisY:
64             transform[0] = 1;
65             transform[1] = 0;
66             transform[2] = 0;
67
68             transform[4] = 0;
69             transform[5] = 0;
70             transform[6] = -1;
71
72             transform[8] = 0;
73             transform[9] = 1;
74             transform[10] = 0;
75             break;
76         case eProjectionAxisX:
77             transform[0] = 0;
78             transform[1] = 0;
79             transform[2] = 1;
80
81             transform[4] = 1;
82             transform[5] = 0;
83             transform[6] = 0;
84
85             transform[8] = 0;
86             transform[9] = 1;
87             transform[10] = 0;
88             break;
89     }
90     transform[3] = transform[7] = transform[11] = transform[12] = transform[13] = transform[14] = 0;
91     transform[15] = 1;
92 }
93
94 /*!
95    \brief Construct a transform in ST space from the texdef.
96    Transforms constructed from quake's texdef format are (-shift)*(1/scale)*(-rotate) with x translation sign flipped.
97    This would really make more sense if it was inverseof(shift*rotate*scale).. oh well.
98  */
99 inline void Texdef_toTransform(const texdef_t &texdef, float width, float height, Matrix4 &transform)
100 {
101     double inverse_scale[2];
102
103     // transform to texdef shift/scale/rotate
104     inverse_scale[0] = 1 / (texdef.scale[0] * width);
105     inverse_scale[1] = 1 / (texdef.scale[1] * -height);
106     transform[12] = texdef.shift[0] / width;
107     transform[13] = -texdef.shift[1] / -height;
108     double c = cos(degrees_to_radians(-texdef.rotate));
109     double s = sin(degrees_to_radians(-texdef.rotate));
110     transform[0] = static_cast<float>( c * inverse_scale[0] );
111     transform[1] = static_cast<float>( s * inverse_scale[1] );
112     transform[4] = static_cast<float>( -s * inverse_scale[0] );
113     transform[5] = static_cast<float>( c * inverse_scale[1] );
114     transform[2] = transform[3] = transform[6] = transform[7] = transform[8] = transform[9] = transform[11] = transform[14] = 0;
115     transform[10] = transform[15] = 1;
116 }
117
118 inline void BPTexdef_toTransform(const brushprimit_texdef_t &bp_texdef, Matrix4 &transform)
119 {
120     transform = g_matrix4_identity;
121     transform.xx() = bp_texdef.coords[0][0];
122     transform.yx() = bp_texdef.coords[0][1];
123     transform.tx() = bp_texdef.coords[0][2];
124     transform.xy() = bp_texdef.coords[1][0];
125     transform.yy() = bp_texdef.coords[1][1];
126     transform.ty() = bp_texdef.coords[1][2];
127 }
128
129 inline void Texdef_toTransform(const TextureProjection &projection, float width, float height, Matrix4 &transform)
130 {
131     if (g_bp_globals.m_texdefTypeId == TEXDEFTYPEID_BRUSHPRIMITIVES) {
132         BPTexdef_toTransform(projection.m_brushprimit_texdef, transform);
133     } else {
134         Texdef_toTransform(projection.m_texdef, width, height, transform);
135     }
136 }
137
138 // handles degenerate cases, just in case library atan2 doesn't
139 inline double arctangent_yx(double y, double x)
140 {
141     if (fabs(x) > 1.0E-6) {
142         return atan2(y, x);
143     } else if (y > 0) {
144         return c_half_pi;
145     } else {
146         return -c_half_pi;
147     }
148 }
149
150 inline void Texdef_fromTransform(texdef_t &texdef, float width, float height, const Matrix4 &transform)
151 {
152     texdef.scale[0] = static_cast<float>((1.0 / vector2_length(Vector2(transform[0], transform[4]))) / width );
153     texdef.scale[1] = static_cast<float>((1.0 / vector2_length(Vector2(transform[1], transform[5]))) / height );
154
155     texdef.rotate = static_cast<float>( -radians_to_degrees(arctangent_yx(-transform[4], transform[0])));
156
157     if (texdef.rotate == -180.0f) {
158         texdef.rotate = 180.0f;
159     }
160
161     texdef.shift[0] = transform[12] * width;
162     texdef.shift[1] = transform[13] * height;
163
164     // If the 2d cross-product of the x and y axes is positive, one of the axes has a negative scale.
165     if (vector2_cross(Vector2(transform[0], transform[4]), Vector2(transform[1], transform[5])) > 0) {
166         if (texdef.rotate >= 180.0f) {
167             texdef.rotate -= 180.0f;
168             texdef.scale[0] = -texdef.scale[0];
169         } else {
170             texdef.scale[1] = -texdef.scale[1];
171         }
172     }
173     //globalOutputStream() << "fromTransform: " << texdef.shift[0] << " " << texdef.shift[1] << " " << texdef.scale[0] << " " << texdef.scale[1] << " " << texdef.rotate << "\n";
174 }
175
176 inline void BPTexdef_fromTransform(brushprimit_texdef_t &bp_texdef, const Matrix4 &transform)
177 {
178     bp_texdef.coords[0][0] = transform.xx();
179     bp_texdef.coords[0][1] = transform.yx();
180     bp_texdef.coords[0][2] = transform.tx();
181     bp_texdef.coords[1][0] = transform.xy();
182     bp_texdef.coords[1][1] = transform.yy();
183     bp_texdef.coords[1][2] = transform.ty();
184 }
185
186 inline void Texdef_fromTransform(TextureProjection &projection, float width, float height, const Matrix4 &transform)
187 {
188     ASSERT_MESSAGE((transform[0] != 0 || transform[4] != 0)
189                    && (transform[1] != 0 || transform[5] != 0), "invalid texture matrix");
190
191     if (g_bp_globals.m_texdefTypeId == TEXDEFTYPEID_BRUSHPRIMITIVES) {
192         BPTexdef_fromTransform(projection.m_brushprimit_texdef, transform);
193     } else {
194         Texdef_fromTransform(projection.m_texdef, width, height, transform);
195     }
196 }
197
198 inline void Texdef_normalise(texdef_t &texdef, float width, float height)
199 {
200     // it may be useful to also normalise the rotation here, if this function is used elsewhere.
201     texdef.shift[0] = float_mod(texdef.shift[0], width);
202     texdef.shift[1] = float_mod(texdef.shift[1], height);
203     //globalOutputStream() << "normalise: " << texdef.shift[0] << " " << texdef.shift[1] << " " << texdef.scale[0] << " " << texdef.scale[1] << " " << texdef.rotate << "\n";
204 }
205
206 inline void BPTexdef_normalise(brushprimit_texdef_t &bp_texdef, float width, float height)
207 {
208     bp_texdef.coords[0][2] = float_mod(bp_texdef.coords[0][2], width);
209     bp_texdef.coords[1][2] = float_mod(bp_texdef.coords[1][2], height);
210 }
211
212 /// \brief Normalise \p projection for a given texture \p width and \p height.
213 ///
214 /// All texture-projection translation (shift) values are congruent modulo the dimensions of the texture.
215 /// This function normalises shift values to the smallest positive congruent values.
216 void Texdef_normalise(TextureProjection &projection, float width, float height)
217 {
218     if (g_bp_globals.m_texdefTypeId == TEXDEFTYPEID_BRUSHPRIMITIVES) {
219         BPTexdef_normalise(projection.m_brushprimit_texdef, width, height);
220     } else {
221         Texdef_normalise(projection.m_texdef, width, height);
222     }
223 }
224
225 void ComputeAxisBase(const Vector3 &normal, Vector3 &texS, Vector3 &texT);
226
227 inline void DebugAxisBase(const Vector3 &normal)
228 {
229     Vector3 x, y;
230     ComputeAxisBase(normal, x, y);
231     globalOutputStream() << "BP debug: " << x << y << normal << "\n";
232 }
233
234 void Texdef_basisForNormal(const TextureProjection &projection, const Vector3 &normal, Matrix4 &basis)
235 {
236     if (g_bp_globals.m_texdefTypeId == TEXDEFTYPEID_BRUSHPRIMITIVES) {
237         basis = g_matrix4_identity;
238         ComputeAxisBase(normal, vector4_to_vector3(basis.x()), vector4_to_vector3(basis.y()));
239         vector4_to_vector3(basis.z()) = normal;
240         matrix4_transpose(basis);
241         //DebugAxisBase(normal);
242     } else if (g_bp_globals.m_texdefTypeId == TEXDEFTYPEID_HALFLIFE) {
243         basis = g_matrix4_identity;
244         vector4_to_vector3(basis.x()) = projection.m_basis_s;
245         vector4_to_vector3(basis.y()) = vector3_negated(projection.m_basis_t);
246         vector4_to_vector3(basis.z()) = vector3_normalised(
247                 vector3_cross(vector4_to_vector3(basis.x()), vector4_to_vector3(basis.y())));
248         matrix4_multiply_by_matrix4(basis, matrix4_rotation_for_z_degrees(-projection.m_texdef.rotate));
249         //globalOutputStream() << "debug: " << projection.m_basis_s << projection.m_basis_t << normal << "\n";
250         matrix4_transpose(basis);
251     } else {
252         Normal_GetTransform(normal, basis);
253     }
254 }
255
256 void
257 Texdef_EmitTextureCoordinates(const TextureProjection &projection, std::size_t width, std::size_t height, Winding &w,
258                               const Vector3 &normal, const Matrix4 &localToWorld)
259 {
260     if (w.numpoints < 3) {
261         return;
262     }
263     //globalOutputStream() << "normal: " << normal << "\n";
264
265     Matrix4 local2tex;
266     Texdef_toTransform(projection, (float) width, (float) height, local2tex);
267     //globalOutputStream() << "texdef: " << static_cast<const Vector3&>(local2tex.x()) << static_cast<const Vector3&>(local2tex.y()) << "\n";
268
269 #if 0
270     {
271         TextureProjection tmp;
272         Texdef_fromTransform( tmp, (float)width, (float)height, local2tex );
273         Matrix4 tmpTransform;
274         Texdef_toTransform( tmp, (float)width, (float)height, tmpTransform );
275         ASSERT_MESSAGE( matrix4_equal_epsilon( local2tex, tmpTransform, 0.0001f ), "bleh" );
276     }
277 #endif
278
279     {
280         Matrix4 xyz2st;
281         // we don't care if it's not normalised...
282         Texdef_basisForNormal(projection, matrix4_transformed_direction(localToWorld, normal), xyz2st);
283         //globalOutputStream() << "basis: " << static_cast<const Vector3&>(xyz2st.x()) << static_cast<const Vector3&>(xyz2st.y()) << static_cast<const Vector3&>(xyz2st.z()) << "\n";
284         matrix4_multiply_by_matrix4(local2tex, xyz2st);
285     }
286
287     Vector3 tangent(vector3_normalised(vector4_to_vector3(matrix4_transposed(local2tex).x())));
288     Vector3 bitangent(vector3_normalised(vector4_to_vector3(matrix4_transposed(local2tex).y())));
289
290     matrix4_multiply_by_matrix4(local2tex, localToWorld);
291
292     for (Winding::iterator i = w.begin(); i != w.end(); ++i) {
293         Vector3 texcoord = matrix4_transformed_point(local2tex, (*i).vertex);
294         (*i).texcoord[0] = texcoord[0];
295         (*i).texcoord[1] = texcoord[1];
296
297         (*i).tangent = tangent;
298         (*i).bitangent = bitangent;
299     }
300 }
301
302 /*!
303    \brief Provides the axis-base of the texture ST space for this normal,
304    as they had been transformed to world XYZ space.
305  */
306 void TextureAxisFromNormal(const Vector3 &normal, Vector3 &s, Vector3 &t)
307 {
308     switch (projectionaxis_for_normal(normal)) {
309         case eProjectionAxisZ:
310             s[0] = 1;
311             s[1] = 0;
312             s[2] = 0;
313
314             t[0] = 0;
315             t[1] = -1;
316             t[2] = 0;
317
318             break;
319         case eProjectionAxisY:
320             s[0] = 1;
321             s[1] = 0;
322             s[2] = 0;
323
324             t[0] = 0;
325             t[1] = 0;
326             t[2] = -1;
327
328             break;
329         case eProjectionAxisX:
330             s[0] = 0;
331             s[1] = 1;
332             s[2] = 0;
333
334             t[0] = 0;
335             t[1] = 0;
336             t[2] = -1;
337
338             break;
339     }
340 }
341
342 void Texdef_Assign(texdef_t &td, const texdef_t &other)
343 {
344     td = other;
345 }
346
347 void Texdef_Shift(texdef_t &td, float s, float t)
348 {
349     td.shift[0] += s;
350     td.shift[1] += t;
351 }
352
353 void Texdef_Scale(texdef_t &td, float s, float t)
354 {
355     td.scale[0] += s;
356     td.scale[1] += t;
357 }
358
359 void Texdef_Rotate(texdef_t &td, float angle)
360 {
361     td.rotate += angle;
362     td.rotate = static_cast<float>( float_to_integer(td.rotate) % 360 );
363 }
364
365 // NOTE: added these from Ritual's Q3Radiant
366 void ClearBounds(Vector3 &mins, Vector3 &maxs)
367 {
368     mins[0] = mins[1] = mins[2] = 99999;
369     maxs[0] = maxs[1] = maxs[2] = -99999;
370 }
371
372 void AddPointToBounds(const Vector3 &v, Vector3 &mins, Vector3 &maxs)
373 {
374     int i;
375     float val;
376
377     for (i = 0; i < 3; i++) {
378         val = v[i];
379         if (val < mins[i]) {
380             mins[i] = val;
381         }
382         if (val > maxs[i]) {
383             maxs[i] = val;
384         }
385     }
386 }
387
388 template<typename Element>
389 inline BasicVector3<Element> vector3_inverse(const BasicVector3<Element> &self)
390 {
391     return BasicVector3<Element>(
392             Element(1.0 / self.x()),
393             Element(1.0 / self.y()),
394             Element(1.0 / self.z())
395     );
396 }
397
398 // low level functions .. put in mathlib?
399 #define BPMatCopy(a, b) {b[0][0] = a[0][0]; b[0][1] = a[0][1]; b[0][2] = a[0][2]; b[1][0] = a[1][0]; b[1][1] = a[1][1]; b[1][2] = a[1][2]; }
400 // apply a scale transformation to the BP matrix
401 #define BPMatScale(m, sS, sT) {m[0][0] *= sS; m[1][0] *= sS; m[0][1] *= sT; m[1][1] *= sT; }
402 // apply a translation transformation to a BP matrix
403 #define BPMatTranslate(m, s, t) {m[0][2] += m[0][0] * s + m[0][1] * t; m[1][2] += m[1][0] * s + m[1][1] * t; }
404
405 // 2D homogeneous matrix product C = A*B
406 void BPMatMul(float A[2][3], float B[2][3], float C[2][3]);
407
408 // apply a rotation (degrees)
409 void BPMatRotate(float A[2][3], float theta);
410
411 #if GDEF_DEBUG
412
413 void BPMatDump(float A[2][3]);
414
415 #endif
416
417 #if GDEF_DEBUG
418 //#define DBG_BP
419 #endif
420
421
422 bp_globals_t g_bp_globals;
423 float g_texdef_default_scale;
424
425 // compute a determinant using Sarrus rule
426 //++timo "inline" this with a macro
427 // NOTE : the three vectors are understood as columns of the matrix
428 inline float SarrusDet(const Vector3 &a, const Vector3 &b, const Vector3 &c)
429 {
430     return a[0] * b[1] * c[2] + b[0] * c[1] * a[2] + c[0] * a[1] * b[2]
431            - c[0] * b[1] * a[2] - a[1] * b[0] * c[2] - a[0] * b[2] * c[1];
432 }
433
434 // in many case we know three points A,B,C in two axis base B1 and B2
435 // and we want the matrix M so that A(B1) = T * A(B2)
436 // NOTE: 2D homogeneous space stuff
437 // NOTE: we don't do any check to see if there's a solution or we have a particular case .. need to make sure before calling
438 // NOTE: the third coord of the A,B,C point is ignored
439 // NOTE: see the commented out section to fill M and D
440 //++timo TODO: update the other members to use this when possible
441 void MatrixForPoints(Vector3 M[3], Vector3 D[2], brushprimit_texdef_t *T)
442 {
443 //      Vector3 M[3]; // columns of the matrix .. easier that way (the indexing is not standard! it's column-line .. later computations are easier that way)
444     float det;
445 //      Vector3 D[2];
446     M[2][0] = 1.0f;
447     M[2][1] = 1.0f;
448     M[2][2] = 1.0f;
449 #if 0
450     // fill the data vectors
451     M[0][0] = A2[0]; M[0][1] = B2[0]; M[0][2] = C2[0];
452     M[1][0] = A2[1]; M[1][1] = B2[1]; M[1][2] = C2[1];
453     M[2][0] = 1.0f; M[2][1] = 1.0f; M[2][2] = 1.0f;
454     D[0][0] = A1[0];
455     D[0][1] = B1[0];
456     D[0][2] = C1[0];
457     D[1][0] = A1[1];
458     D[1][1] = B1[1];
459     D[1][2] = C1[1];
460 #endif
461     // solve
462     det = SarrusDet(M[0], M[1], M[2]);
463     T->coords[0][0] = SarrusDet(D[0], M[1], M[2]) / det;
464     T->coords[0][1] = SarrusDet(M[0], D[0], M[2]) / det;
465     T->coords[0][2] = SarrusDet(M[0], M[1], D[0]) / det;
466     T->coords[1][0] = SarrusDet(D[1], M[1], M[2]) / det;
467     T->coords[1][1] = SarrusDet(M[0], D[1], M[2]) / det;
468     T->coords[1][2] = SarrusDet(M[0], M[1], D[1]) / det;
469 }
470
471 //++timo replace everywhere texX by texS etc. ( ----> and in q3map !)
472 // NOTE : ComputeAxisBase here and in q3map code must always BE THE SAME !
473 // WARNING : special case behaviour of atan2(y,x) <-> atan(y/x) might not be the same everywhere when x == 0
474 // rotation by (0,RotY,RotZ) assigns X to normal
475 void ComputeAxisBase(const Vector3 &normal, Vector3 &texS, Vector3 &texT)
476 {
477 #if 1
478     const Vector3 up(0, 0, 1);
479     const Vector3 down(0, 0, -1);
480
481     if (vector3_equal_epsilon(normal, up, float(1e-6))) {
482         texS = Vector3(0, 1, 0);
483         texT = Vector3(1, 0, 0);
484     } else if (vector3_equal_epsilon(normal, down, float(1e-6))) {
485         texS = Vector3(0, 1, 0);
486         texT = Vector3(-1, 0, 0);
487     } else {
488         texS = vector3_normalised(vector3_cross(normal, up));
489         texT = vector3_normalised(vector3_cross(normal, texS));
490         vector3_negate(texS);
491     }
492
493 #else
494     float RotY,RotZ;
495     // do some cleaning
496     /*
497        if (fabs(normal[0])<1e-6)
498           normal[0]=0.0f;
499        if (fabs(normal[1])<1e-6)
500           normal[1]=0.0f;
501        if (fabs(normal[2])<1e-6)
502           normal[2]=0.0f;
503      */
504     RotY = -atan2( normal[2],sqrt( normal[1] * normal[1] + normal[0] * normal[0] ) );
505     RotZ = atan2( normal[1],normal[0] );
506     // rotate (0,1,0) and (0,0,1) to compute texS and texT
507     texS[0] = -sin( RotZ );
508     texS[1] = cos( RotZ );
509     texS[2] = 0;
510     // the texT vector is along -Z ( T texture coorinates axis )
511     texT[0] = -sin( RotY ) * cos( RotZ );
512     texT[1] = -sin( RotY ) * sin( RotZ );
513     texT[2] = -cos( RotY );
514 #endif
515 }
516
517 #if 0 // texdef conversion
518 void FaceToBrushPrimitFace( face_t *f ){
519     Vector3 texX,texY;
520     Vector3 proj;
521     // ST of (0,0) (1,0) (0,1)
522     float ST[3][5]; // [ point index ] [ xyz ST ]
523     //++timo not used as long as brushprimit_texdef and texdef are static
524 /*      f->brushprimit_texdef.contents=f->texdef.contents;
525     f->brushprimit_texdef.flags=f->texdef.flags;
526     f->brushprimit_texdef.value=f->texdef.value;
527     strcpy(f->brushprimit_texdef.name,f->texdef.name); */
528 #ifdef DBG_BP
529     if ( f->plane.normal[0] == 0.0f && f->plane.normal[1] == 0.0f && f->plane.normal[2] == 0.0f ) {
530         globalOutputStream() << "Warning : f->plane.normal is (0,0,0) in FaceToBrushPrimitFace\n";
531     }
532     // check d_texture
533     if ( !f->d_texture ) {
534         globalOutputStream() << "Warning : f.d_texture is 0 in FaceToBrushPrimitFace\n";
535         return;
536     }
537 #endif
538     // compute axis base
539     ComputeAxisBase( f->plane.normal,texX,texY );
540     // compute projection vector
541     VectorCopy( f->plane.normal,proj );
542     VectorScale( proj,f->plane.dist,proj );
543     // (0,0) in plane axis base is (0,0,0) in world coordinates + projection on the affine plane
544     // (1,0) in plane axis base is texX in world coordinates + projection on the affine plane
545     // (0,1) in plane axis base is texY in world coordinates + projection on the affine plane
546     // use old texture code to compute the ST coords of these points
547     VectorCopy( proj,ST[0] );
548     EmitTextureCoordinates( ST[0], f->pShader->getTexture(), f );
549     VectorCopy( texX,ST[1] );
550     VectorAdd( ST[1],proj,ST[1] );
551     EmitTextureCoordinates( ST[1], f->pShader->getTexture(), f );
552     VectorCopy( texY,ST[2] );
553     VectorAdd( ST[2],proj,ST[2] );
554     EmitTextureCoordinates( ST[2], f->pShader->getTexture(), f );
555     // compute texture matrix
556     f->brushprimit_texdef.coords[0][2] = ST[0][3];
557     f->brushprimit_texdef.coords[1][2] = ST[0][4];
558     f->brushprimit_texdef.coords[0][0] = ST[1][3] - f->brushprimit_texdef.coords[0][2];
559     f->brushprimit_texdef.coords[1][0] = ST[1][4] - f->brushprimit_texdef.coords[1][2];
560     f->brushprimit_texdef.coords[0][1] = ST[2][3] - f->brushprimit_texdef.coords[0][2];
561     f->brushprimit_texdef.coords[1][1] = ST[2][4] - f->brushprimit_texdef.coords[1][2];
562 }
563
564 // compute texture coordinates for the winding points
565 void EmitBrushPrimitTextureCoordinates( face_t * f, Winding * w ){
566     Vector3 texX,texY;
567     float x,y;
568     // compute axis base
569     ComputeAxisBase( f->plane.normal,texX,texY );
570     // in case the texcoords matrix is empty, build a default one
571     // same behaviour as if scale[0]==0 && scale[1]==0 in old code
572     if ( f->brushprimit_texdef.coords[0][0] == 0 && f->brushprimit_texdef.coords[1][0] == 0 && f->brushprimit_texdef.coords[0][1] == 0 && f->brushprimit_texdef.coords[1][1] == 0 ) {
573         f->brushprimit_texdef.coords[0][0] = 1.0f;
574         f->brushprimit_texdef.coords[1][1] = 1.0f;
575         ConvertTexMatWithQTexture( &f->brushprimit_texdef, 0, &f->brushprimit_texdef, f->pShader->getTexture() );
576     }
577     int i;
578     for ( i = 0 ; i < w.numpoints ; i++ )
579     {
580         x = vector3_dot( w.point_at( i ),texX );
581         y = vector3_dot( w.point_at( i ),texY );
582 #if 0
583 #ifdef DBG_BP
584         if ( g_bp_globals.bNeedConvert ) {
585             // check we compute the same ST as the traditional texture computation used before
586             float S = f->brushprimit_texdef.coords[0][0] * x + f->brushprimit_texdef.coords[0][1] * y + f->brushprimit_texdef.coords[0][2];
587             float T = f->brushprimit_texdef.coords[1][0] * x + f->brushprimit_texdef.coords[1][1] * y + f->brushprimit_texdef.coords[1][2];
588             if ( fabs( S - w.point_at( i )[3] ) > 1e-2 || fabs( T - w.point_at( i )[4] ) > 1e-2 ) {
589                 if ( fabs( S - w.point_at( i )[3] ) > 1e-4 || fabs( T - w.point_at( i )[4] ) > 1e-4 ) {
590                     globalOutputStream() << "Warning : precision loss in brush -> brush primitive texture computation\n";
591                 }
592                 else{
593                     globalOutputStream() << "Warning : brush -> brush primitive texture computation bug detected\n";
594                 }
595             }
596         }
597 #endif
598 #endif
599         w.point_at( i )[3] = f->brushprimit_texdef.coords[0][0] * x + f->brushprimit_texdef.coords[0][1] * y + f->brushprimit_texdef.coords[0][2];
600         w.point_at( i )[4] = f->brushprimit_texdef.coords[1][0] * x + f->brushprimit_texdef.coords[1][1] * y + f->brushprimit_texdef.coords[1][2];
601     }
602 }
603 #endif
604
605 typedef float texmat_t[2][3];
606
607 void TexMat_Scale(texmat_t texmat, float s, float t)
608 {
609     texmat[0][0] *= s;
610     texmat[0][1] *= s;
611     texmat[0][2] *= s;
612     texmat[1][0] *= t;
613     texmat[1][1] *= t;
614     texmat[1][2] *= t;
615 }
616
617 void TexMat_Assign(texmat_t texmat, const texmat_t other)
618 {
619     texmat[0][0] = other[0][0];
620     texmat[0][1] = other[0][1];
621     texmat[0][2] = other[0][2];
622     texmat[1][0] = other[1][0];
623     texmat[1][1] = other[1][1];
624     texmat[1][2] = other[1][2];
625 }
626
627 void ConvertTexMatWithDimensions(const texmat_t texmat1, std::size_t w1, std::size_t h1,
628                                  texmat_t texmat2, std::size_t w2, std::size_t h2)
629 {
630     TexMat_Assign(texmat2, texmat1);
631     TexMat_Scale(texmat2, static_cast<float>( w1 ) / static_cast<float>( w2 ),
632                  static_cast<float>( h1 ) / static_cast<float>( h2 ));
633 }
634
635 #if 0
636 // convert a texture matrix between two qtexture_t
637 // if 0 for qtexture_t, basic 2x2 texture is assumed ( straight mapping between s/t coordinates and geometric coordinates )
638 void ConvertTexMatWithQTexture( const float texMat1[2][3], const qtexture_t *qtex1, float texMat2[2][3], const qtexture_t *qtex2 ){
639     ConvertTexMatWithDimensions( texMat1, ( qtex1 ) ? qtex1->width : 2, ( qtex1 ) ? qtex1->height : 2,
640                                  texMat2, ( qtex2 ) ? qtex2->width : 2, ( qtex2 ) ? qtex2->height : 2 );
641 }
642
643 void ConvertTexMatWithQTexture( const brushprimit_texdef_t *texMat1, const qtexture_t *qtex1, brushprimit_texdef_t *texMat2, const qtexture_t *qtex2 ){
644     ConvertTexMatWithQTexture( texMat1->coords, qtex1, texMat2->coords, qtex2 );
645 }
646 #endif
647
648 // compute a fake shift scale rot representation from the texture matrix
649 // these shift scale rot values are to be understood in the local axis base
650 // Note: this code looks similar to Texdef_fromTransform, but the algorithm is slightly different.
651
652 void TexMatToFakeTexCoords(const brushprimit_texdef_t &bp_texdef, texdef_t &texdef)
653 {
654     texdef.scale[0] = static_cast<float>( 1.0 /
655                                           vector2_length(Vector2(bp_texdef.coords[0][0], bp_texdef.coords[1][0])));
656     texdef.scale[1] = static_cast<float>( 1.0 /
657                                           vector2_length(Vector2(bp_texdef.coords[0][1], bp_texdef.coords[1][1])));
658
659     texdef.rotate = -static_cast<float>( radians_to_degrees(
660             arctangent_yx(bp_texdef.coords[1][0], bp_texdef.coords[0][0])));
661
662     texdef.shift[0] = -bp_texdef.coords[0][2];
663     texdef.shift[1] = bp_texdef.coords[1][2];
664
665     // determine whether or not an axis is flipped using a 2d cross-product
666     double cross = vector2_cross(Vector2(bp_texdef.coords[0][0], bp_texdef.coords[0][1]),
667                                  Vector2(bp_texdef.coords[1][0], bp_texdef.coords[1][1]));
668     if (cross < 0) {
669         // This is a bit of a compromise when using BPs--since we don't know *which* axis was flipped,
670         // we pick one (rather arbitrarily) using the following convention: If the X-axis is between
671         // 0 and 180, we assume it's the Y-axis that flipped, otherwise we assume it's the X-axis and
672         // subtract out 180 degrees to compensate.
673         if (texdef.rotate >= 180.0f) {
674             texdef.rotate -= 180.0f;
675             texdef.scale[0] = -texdef.scale[0];
676         } else {
677             texdef.scale[1] = -texdef.scale[1];
678         }
679     }
680 }
681
682 // compute back the texture matrix from fake shift scale rot
683 void FakeTexCoordsToTexMat(const texdef_t &texdef, brushprimit_texdef_t &bp_texdef)
684 {
685     double r = degrees_to_radians(-texdef.rotate);
686     double c = cos(r);
687     double s = sin(r);
688     double x = 1.0f / texdef.scale[0];
689     double y = 1.0f / texdef.scale[1];
690     bp_texdef.coords[0][0] = static_cast<float>( x * c );
691     bp_texdef.coords[1][0] = static_cast<float>( x * s );
692     bp_texdef.coords[0][1] = static_cast<float>( y * -s );
693     bp_texdef.coords[1][1] = static_cast<float>( y * c );
694     bp_texdef.coords[0][2] = -texdef.shift[0];
695     bp_texdef.coords[1][2] = texdef.shift[1];
696 }
697
698 #if 0 // texture locking (brush primit)
699 // used for texture locking
700 // will move the texture according to a geometric vector
701 void ShiftTextureGeometric_BrushPrimit( face_t *f, Vector3& delta ){
702     Vector3 texS,texT;
703     float tx,ty;
704     Vector3 M[3]; // columns of the matrix .. easier that way
705     float det;
706     Vector3 D[2];
707     // compute plane axis base ( doesn't change with translation )
708     ComputeAxisBase( f->plane.normal, texS, texT );
709     // compute translation vector in plane axis base
710     tx = vector3_dot( delta, texS );
711     ty = vector3_dot( delta, texT );
712     // fill the data vectors
713     M[0][0] = tx; M[0][1] = 1.0f + tx; M[0][2] = tx;
714     M[1][0] = ty; M[1][1] = ty; M[1][2] = 1.0f + ty;
715     M[2][0] = 1.0f; M[2][1] = 1.0f; M[2][2] = 1.0f;
716     D[0][0] = f->brushprimit_texdef.coords[0][2];
717     D[0][1] = f->brushprimit_texdef.coords[0][0] + f->brushprimit_texdef.coords[0][2];
718     D[0][2] = f->brushprimit_texdef.coords[0][1] + f->brushprimit_texdef.coords[0][2];
719     D[1][0] = f->brushprimit_texdef.coords[1][2];
720     D[1][1] = f->brushprimit_texdef.coords[1][0] + f->brushprimit_texdef.coords[1][2];
721     D[1][2] = f->brushprimit_texdef.coords[1][1] + f->brushprimit_texdef.coords[1][2];
722     // solve
723     det = SarrusDet( M[0], M[1], M[2] );
724     f->brushprimit_texdef.coords[0][0] = SarrusDet( D[0], M[1], M[2] ) / det;
725     f->brushprimit_texdef.coords[0][1] = SarrusDet( M[0], D[0], M[2] ) / det;
726     f->brushprimit_texdef.coords[0][2] = SarrusDet( M[0], M[1], D[0] ) / det;
727     f->brushprimit_texdef.coords[1][0] = SarrusDet( D[1], M[1], M[2] ) / det;
728     f->brushprimit_texdef.coords[1][1] = SarrusDet( M[0], D[1], M[2] ) / det;
729     f->brushprimit_texdef.coords[1][2] = SarrusDet( M[0], M[1], D[1] ) / det;
730 }
731
732 // shift a texture (texture adjustments) along it's current texture axes
733 // x and y are geometric values, which we must compute as ST increments
734 // this depends on the texture size and the pixel/texel ratio
735 void ShiftTextureRelative_BrushPrimit( face_t *f, float x, float y ){
736     float s,t;
737     // as a ratio against texture size
738     // the scale of the texture is not relevant here (we work directly on a transformation from the base vectors)
739     s = ( x * 2.0 ) / (float)f->pShader->getTexture().width;
740     t = ( y * 2.0 ) / (float)f->pShader->getTexture().height;
741     f->brushprimit_texdef.coords[0][2] -= s;
742     f->brushprimit_texdef.coords[1][2] -= t;
743 }
744 #endif
745
746 // TTimo: FIXME: I don't like that, it feels broken
747 //   (and it's likely that it's not used anymore)
748 // best fitted 2D vector is x.X+y.Y
749 void ComputeBest2DVector(Vector3 &v, Vector3 &X, Vector3 &Y, int &x, int &y)
750 {
751     double sx, sy;
752     sx = vector3_dot(v, X);
753     sy = vector3_dot(v, Y);
754     if (fabs(sy) > fabs(sx)) {
755         x = 0;
756         if (sy > 0.0) {
757             y = 1;
758         } else {
759             y = -1;
760         }
761     } else {
762         y = 0;
763         if (sx > 0.0) {
764             x = 1;
765         } else {
766             x = -1;
767         }
768     }
769 }
770
771
772 #if 0 // texdef conversion
773 void BrushPrimitFaceToFace( face_t *face ){
774     // we have parsed brush primitives and need conversion back to standard format
775     // NOTE: converting back is a quick hack, there's some information lost and we can't do anything about it
776     // FIXME: if we normalize the texture matrix to a standard 2x2 size, we end up with wrong scaling
777     // I tried various tweaks, no luck .. seems shifting is lost
778     brushprimit_texdef_t aux;
779     ConvertTexMatWithQTexture( &face->brushprimit_texdef, face->pShader->getTexture(), &aux, 0 );
780     TexMatToFakeTexCoords( aux.coords, face->texdef.shift, &face->texdef.rotate, face->texdef.scale );
781     face->texdef.scale[0] /= 2.0;
782     face->texdef.scale[1] /= 2.0;
783 }
784 #endif
785
786
787 #if 0 // texture locking (brush primit)
788 // TEXTURE LOCKING -----------------------------------------------------------------------------------------------------
789 // (Relevant to the editor only?)
790
791 // internally used for texture locking on rotation and flipping
792 // the general algorithm is the same for both lockings, it's only the geometric transformation part that changes
793 // so I wanted to keep it in a single function
794 // if there are more linear transformations that need the locking, going to a C++ or code pointer solution would be best
795 // (but right now I want to keep brush_primit.cpp striclty C)
796
797 bool txlock_bRotation;
798
799 // rotation locking params
800 int txl_nAxis;
801 float txl_fDeg;
802 Vector3 txl_vOrigin;
803
804 // flip locking params
805 Vector3 txl_matrix[3];
806 Vector3 txl_origin;
807
808 void TextureLockTransformation_BrushPrimit( face_t *f ){
809     Vector3 Orig,texS,texT;      // axis base of initial plane
810     // used by transformation algo
811     Vector3 temp; int j;
812     Vector3 vRotate;                        // rotation vector
813
814     Vector3 rOrig,rvecS,rvecT;   // geometric transformation of (0,0) (1,0) (0,1) { initial plane axis base }
815     Vector3 rNormal,rtexS,rtexT; // axis base for the transformed plane
816     Vector3 lOrig,lvecS,lvecT;  // [2] are not used ( but usefull for debugging )
817     Vector3 M[3];
818     float det;
819     Vector3 D[2];
820
821     // compute plane axis base
822     ComputeAxisBase( f->plane.normal, texS, texT );
823     VectorSet( Orig, 0.0f, 0.0f, 0.0f );
824
825     // compute coordinates of (0,0) (1,0) (0,1) ( expressed in initial plane axis base ) after transformation
826     // (0,0) (1,0) (0,1) ( expressed in initial plane axis base ) <-> (0,0,0) texS texT ( expressed world axis base )
827     // input: Orig, texS, texT (and the global locking params)
828     // ouput: rOrig, rvecS, rvecT, rNormal
829     if ( txlock_bRotation ) {
830         // rotation vector
831         VectorSet( vRotate, 0.0f, 0.0f, 0.0f );
832         vRotate[txl_nAxis] = txl_fDeg;
833         VectorRotateOrigin( Orig, vRotate, txl_vOrigin, rOrig );
834         VectorRotateOrigin( texS, vRotate, txl_vOrigin, rvecS );
835         VectorRotateOrigin( texT, vRotate, txl_vOrigin, rvecT );
836         // compute normal of plane after rotation
837         VectorRotate( f->plane.normal, vRotate, rNormal );
838     }
839     else
840     {
841         for ( j = 0 ; j < 3 ; j++ )
842             rOrig[j] = vector3_dot( vector3_subtracted( Orig, txl_origin ), txl_matrix[j] ) + txl_origin[j];
843         for ( j = 0 ; j < 3 ; j++ )
844             rvecS[j] = vector3_dot( vector3_subtracted( texS, txl_origin ), txl_matrix[j] ) + txl_origin[j];
845         for ( j = 0 ; j < 3 ; j++ )
846             rvecT[j] = vector3_dot( vector3_subtracted( texT, txl_origin ), txl_matrix[j] ) + txl_origin[j];
847         // we also need the axis base of the target plane, apply the transformation matrix to the normal too..
848         for ( j = 0 ; j < 3 ; j++ )
849             rNormal[j] = vector3_dot( f->plane.normal, txl_matrix[j] );
850     }
851
852     // compute rotated plane axis base
853     ComputeAxisBase( rNormal, rtexS, rtexT );
854     // compute S/T coordinates of the three points in rotated axis base ( in M matrix )
855     lOrig[0] = vector3_dot( rOrig, rtexS );
856     lOrig[1] = vector3_dot( rOrig, rtexT );
857     lvecS[0] = vector3_dot( rvecS, rtexS );
858     lvecS[1] = vector3_dot( rvecS, rtexT );
859     lvecT[0] = vector3_dot( rvecT, rtexS );
860     lvecT[1] = vector3_dot( rvecT, rtexT );
861     M[0][0] = lOrig[0]; M[1][0] = lOrig[1]; M[2][0] = 1.0f;
862     M[0][1] = lvecS[0]; M[1][1] = lvecS[1]; M[2][1] = 1.0f;
863     M[0][2] = lvecT[0]; M[1][2] = lvecT[1]; M[2][2] = 1.0f;
864     // fill data vector
865     D[0][0] = f->brushprimit_texdef.coords[0][2];
866     D[0][1] = f->brushprimit_texdef.coords[0][0] + f->brushprimit_texdef.coords[0][2];
867     D[0][2] = f->brushprimit_texdef.coords[0][1] + f->brushprimit_texdef.coords[0][2];
868     D[1][0] = f->brushprimit_texdef.coords[1][2];
869     D[1][1] = f->brushprimit_texdef.coords[1][0] + f->brushprimit_texdef.coords[1][2];
870     D[1][2] = f->brushprimit_texdef.coords[1][1] + f->brushprimit_texdef.coords[1][2];
871     // solve
872     det = SarrusDet( M[0], M[1], M[2] );
873     f->brushprimit_texdef.coords[0][0] = SarrusDet( D[0], M[1], M[2] ) / det;
874     f->brushprimit_texdef.coords[0][1] = SarrusDet( M[0], D[0], M[2] ) / det;
875     f->brushprimit_texdef.coords[0][2] = SarrusDet( M[0], M[1], D[0] ) / det;
876     f->brushprimit_texdef.coords[1][0] = SarrusDet( D[1], M[1], M[2] ) / det;
877     f->brushprimit_texdef.coords[1][1] = SarrusDet( M[0], D[1], M[2] ) / det;
878     f->brushprimit_texdef.coords[1][2] = SarrusDet( M[0], M[1], D[1] ) / det;
879 }
880
881 // texture locking
882 // called before the points on the face are actually rotated
883 void RotateFaceTexture_BrushPrimit( face_t *f, int nAxis, float fDeg, Vector3& vOrigin ){
884     // this is a placeholder to call the general texture locking algorithm
885     txlock_bRotation = true;
886     txl_nAxis = nAxis;
887     txl_fDeg = fDeg;
888     VectorCopy( vOrigin, txl_vOrigin );
889     TextureLockTransformation_BrushPrimit( f );
890 }
891
892 // compute the new brush primit texture matrix for a transformation matrix and a flip order flag (change plane orientation)
893 // this matches the select_matrix algo used in select.cpp
894 // this needs to be called on the face BEFORE any geometric transformation
895 // it will compute the texture matrix that will represent the same texture on the face after the geometric transformation is done
896 void ApplyMatrix_BrushPrimit( face_t *f, Vector3 matrix[3], Vector3& origin ){
897     // this is a placeholder to call the general texture locking algorithm
898     txlock_bRotation = false;
899     VectorCopy( matrix[0], txl_matrix[0] );
900     VectorCopy( matrix[1], txl_matrix[1] );
901     VectorCopy( matrix[2], txl_matrix[2] );
902     VectorCopy( origin, txl_origin );
903     TextureLockTransformation_BrushPrimit( f );
904 }
905 #endif
906
907 // don't do C==A!
908 void BPMatMul(float A[2][3], float B[2][3], float C[2][3])
909 {
910     C[0][0] = A[0][0] * B[0][0] + A[0][1] * B[1][0];
911     C[1][0] = A[1][0] * B[0][0] + A[1][1] * B[1][0];
912     C[0][1] = A[0][0] * B[0][1] + A[0][1] * B[1][1];
913     C[1][1] = A[1][0] * B[0][1] + A[1][1] * B[1][1];
914     C[0][2] = A[0][0] * B[0][2] + A[0][1] * B[1][2] + A[0][2];
915     C[1][2] = A[1][0] * B[0][2] + A[1][1] * B[1][2] + A[1][2];
916 }
917
918 void BPMatDump(float A[2][3])
919 {
920     globalOutputStream() << "" << A[0][0]
921                          << " " << A[0][1]
922                          << " " << A[0][2]
923                          << "\n" << A[1][0]
924                          << " " << A[1][2]
925                          << " " << A[1][2]
926                          << "\n0 0 1\n";
927 }
928
929 void BPMatRotate(float A[2][3], float theta)
930 {
931     float m[2][3];
932     float aux[2][3];
933     memset(&m, 0, sizeof(float) * 6);
934     m[0][0] = static_cast<float>( cos(degrees_to_radians(theta)));
935     m[0][1] = static_cast<float>( -sin(degrees_to_radians(theta)));
936     m[1][0] = -m[0][1];
937     m[1][1] = m[0][0];
938     BPMatMul(A, m, aux);
939     BPMatCopy(aux, A);
940 }
941
942 #if 0 // camera-relative texture shift
943 // get the relative axes of the current texturing
944 void BrushPrimit_GetRelativeAxes( face_t *f, Vector3& vecS, Vector3& vecT ){
945     float vS[2],vT[2];
946     // first we compute them as expressed in plane axis base
947     // BP matrix has coordinates of plane axis base expressed in geometric axis base
948     // so we use the line vectors
949     vS[0] = f->brushprimit_texdef.coords[0][0];
950     vS[1] = f->brushprimit_texdef.coords[0][1];
951     vT[0] = f->brushprimit_texdef.coords[1][0];
952     vT[1] = f->brushprimit_texdef.coords[1][1];
953     // now compute those vectors in geometric space
954     Vector3 texS, texT; // axis base of the plane (geometric)
955     ComputeAxisBase( f->plane.normal, texS, texT );
956     // vecS[] = vS[0].texS[] + vS[1].texT[]
957     // vecT[] = vT[0].texS[] + vT[1].texT[]
958     vecS[0] = vS[0] * texS[0] + vS[1] * texT[0];
959     vecS[1] = vS[0] * texS[1] + vS[1] * texT[1];
960     vecS[2] = vS[0] * texS[2] + vS[1] * texT[2];
961     vecT[0] = vT[0] * texS[0] + vT[1] * texT[0];
962     vecT[1] = vT[0] * texS[1] + vT[1] * texT[1];
963     vecT[2] = vT[0] * texS[2] + vT[1] * texT[2];
964 }
965
966 // brush primitive texture adjustments, use the camera view to map adjustments
967 // ShiftTextureRelative_BrushPrimit ( s , t ) will shift relative to the texture
968 void ShiftTextureRelative_Camera( face_t *f, int x, int y ){
969     Vector3 vecS, vecT;
970     float XY[2]; // the values we are going to send for translation
971     float sgn[2]; // +1 or -1
972     int axis[2];
973     CamWnd* pCam;
974
975     // get the two relative texture axes for the current texturing
976     BrushPrimit_GetRelativeAxes( f, vecS, vecT );
977
978     // center point of the face, project it on the camera space
979     Vector3 C;
980     VectorClear( C );
981     int i;
982     for ( i = 0; i < f->face_winding->numpoints; i++ )
983     {
984         VectorAdd( C,f->face_winding->point_at( i ),C );
985     }
986     VectorScale( C,1.0 / f->face_winding->numpoints,C );
987
988     pCam = g_pParentWnd->GetCamWnd();
989     pCam->MatchViewAxes( C, vecS, axis[0], sgn[0] );
990     pCam->MatchViewAxes( C, vecT, axis[1], sgn[1] );
991
992     // this happens when the two directions can't be mapped on two different directions on the screen
993     // then the move will occur against a single axis
994     // (i.e. the user is not positioned well enough to send understandable shift commands)
995     // NOTE: in most cases this warning is not very relevant because the user would use one of the two axes
996     // for which the solution is easy (the other one being unknown)
997     // so this warning could be removed
998     if ( axis[0] == axis[1] ) {
999         globalOutputStream() << "Warning: degenerate in ShiftTextureRelative_Camera\n";
1000     }
1001
1002     // compute the X Y geometric increments
1003     // those geometric increments will be applied along the texture axes (the ones we computed above)
1004     XY[0] = 0;
1005     XY[1] = 0;
1006     if ( x != 0 ) {
1007         // moving right/left
1008         XY[axis[0]] += sgn[0] * x;
1009     }
1010     if ( y != 0 ) {
1011         XY[axis[1]] += sgn[1] * y;
1012     }
1013     // we worked out a move along vecS vecT, and we now it's geometric amplitude
1014     // apply it
1015     ShiftTextureRelative_BrushPrimit( f, XY[0], XY[1] );
1016 }
1017 #endif
1018
1019
1020 void BPTexdef_Assign(brushprimit_texdef_t &bp_td, const brushprimit_texdef_t &bp_other)
1021 {
1022     bp_td = bp_other;
1023 }
1024
1025 void BPTexdef_Shift(brushprimit_texdef_t &bp_td, float s, float t)
1026 {
1027     // shift a texture (texture adjustments) along it's current texture axes
1028     // x and y are geometric values, which we must compute as ST increments
1029     // this depends on the texture size and the pixel/texel ratio
1030     // as a ratio against texture size
1031     // the scale of the texture is not relevant here (we work directly on a transformation from the base vectors)
1032     bp_td.coords[0][2] -= s;
1033     bp_td.coords[1][2] += t;
1034 }
1035
1036 void BPTexdef_Scale(brushprimit_texdef_t &bp_td, float s, float t)
1037 {
1038     // apply same scale as the spinner button of the surface inspector
1039     texdef_t texdef;
1040     // compute fake shift scale rot
1041     TexMatToFakeTexCoords(bp_td, texdef);
1042     // update
1043     texdef.scale[0] += s;
1044     texdef.scale[1] += t;
1045     // compute new normalized texture matrix
1046     FakeTexCoordsToTexMat(texdef, bp_td);
1047 }
1048
1049 void BPTexdef_Rotate(brushprimit_texdef_t &bp_td, float angle)
1050 {
1051     // apply same scale as the spinner button of the surface inspector
1052     texdef_t texdef;
1053     // compute fake shift scale rot
1054     TexMatToFakeTexCoords(bp_td, texdef);
1055     // update
1056     texdef.rotate += angle;
1057     // compute new normalized texture matrix
1058     FakeTexCoordsToTexMat(texdef, bp_td);
1059 }
1060
1061 void BPTexdef_Construct(brushprimit_texdef_t &bp_td, std::size_t width, std::size_t height)
1062 {
1063     bp_td.coords[0][0] = 1.0f;
1064     bp_td.coords[1][1] = 1.0f;
1065     ConvertTexMatWithDimensions(bp_td.coords, 2, 2, bp_td.coords, width, height);
1066 }
1067
1068 void Texdef_Assign(TextureProjection &projection, const TextureProjection &other)
1069 {
1070     if (g_bp_globals.m_texdefTypeId == TEXDEFTYPEID_BRUSHPRIMITIVES) {
1071         BPTexdef_Assign(projection.m_brushprimit_texdef, other.m_brushprimit_texdef);
1072     } else {
1073         Texdef_Assign(projection.m_texdef, other.m_texdef);
1074         if (g_bp_globals.m_texdefTypeId == TEXDEFTYPEID_HALFLIFE) {
1075             projection.m_basis_s = other.m_basis_s;
1076             projection.m_basis_t = other.m_basis_t;
1077         }
1078     }
1079 }
1080
1081 void Texdef_Shift(TextureProjection &projection, float s, float t)
1082 {
1083     if (g_bp_globals.m_texdefTypeId == TEXDEFTYPEID_BRUSHPRIMITIVES) {
1084         BPTexdef_Shift(projection.m_brushprimit_texdef, s, t);
1085     } else {
1086         Texdef_Shift(projection.m_texdef, s, t);
1087     }
1088 }
1089
1090 void Texdef_Scale(TextureProjection &projection, float s, float t)
1091 {
1092     if (g_bp_globals.m_texdefTypeId == TEXDEFTYPEID_BRUSHPRIMITIVES) {
1093         BPTexdef_Scale(projection.m_brushprimit_texdef, s, t);
1094     } else {
1095         Texdef_Scale(projection.m_texdef, s, t);
1096     }
1097 }
1098
1099 void Texdef_Rotate(TextureProjection &projection, float angle)
1100 {
1101     if (g_bp_globals.m_texdefTypeId == TEXDEFTYPEID_BRUSHPRIMITIVES) {
1102         BPTexdef_Rotate(projection.m_brushprimit_texdef, angle);
1103     } else {
1104         Texdef_Rotate(projection.m_texdef, angle);
1105     }
1106 }
1107
1108 void Texdef_FitTexture(TextureProjection &projection, std::size_t width, std::size_t height, const Vector3 &normal,
1109                        const Winding &w, float s_repeat, float t_repeat)
1110 {
1111     if (w.numpoints < 3) {
1112         return;
1113     }
1114
1115     Matrix4 st2tex;
1116     Texdef_toTransform(projection, (float) width, (float) height, st2tex);
1117
1118     // the current texture transform
1119     Matrix4 local2tex = st2tex;
1120     {
1121         Matrix4 xyz2st;
1122         Texdef_basisForNormal(projection, normal, xyz2st);
1123         matrix4_multiply_by_matrix4(local2tex, xyz2st);
1124     }
1125
1126     // the bounds of the current texture transform
1127     AABB bounds;
1128     for (Winding::const_iterator i = w.begin(); i != w.end(); ++i) {
1129         Vector3 texcoord = matrix4_transformed_point(local2tex, (*i).vertex);
1130         aabb_extend_by_point_safe(bounds, texcoord);
1131     }
1132     bounds.origin.z() = 0;
1133     bounds.extents.z() = 1;
1134
1135     // the bounds of a perfectly fitted texture transform
1136     AABB perfect(Vector3(s_repeat * 0.5, t_repeat * 0.5, 0), Vector3(s_repeat * 0.5, t_repeat * 0.5, 1));
1137
1138     // the difference between the current texture transform and the perfectly fitted transform
1139     Matrix4 matrix(matrix4_translation_for_vec3(bounds.origin - perfect.origin));
1140     matrix4_pivoted_scale_by_vec3(matrix, bounds.extents / perfect.extents, perfect.origin);
1141     matrix4_affine_invert(matrix);
1142
1143     // apply the difference to the current texture transform
1144     matrix4_premultiply_by_matrix4(st2tex, matrix);
1145
1146     Texdef_fromTransform(projection, (float) width, (float) height, st2tex);
1147     Texdef_normalise(projection, (float) width, (float) height);
1148 }
1149
1150 float Texdef_getDefaultTextureScale()
1151 {
1152     return g_texdef_default_scale;
1153 }
1154
1155 void TexDef_Construct_Default(TextureProjection &projection)
1156 {
1157     projection.m_texdef.scale[0] = Texdef_getDefaultTextureScale();
1158     projection.m_texdef.scale[1] = Texdef_getDefaultTextureScale();
1159
1160     if (g_bp_globals.m_texdefTypeId == TEXDEFTYPEID_BRUSHPRIMITIVES) {
1161         FakeTexCoordsToTexMat(projection.m_texdef, projection.m_brushprimit_texdef);
1162     }
1163 }
1164
1165
1166 void ShiftScaleRotate_fromFace(texdef_t &shiftScaleRotate, const TextureProjection &projection)
1167 {
1168     if (g_bp_globals.m_texdefTypeId == TEXDEFTYPEID_BRUSHPRIMITIVES) {
1169         TexMatToFakeTexCoords(projection.m_brushprimit_texdef, shiftScaleRotate);
1170     } else {
1171         shiftScaleRotate = projection.m_texdef;
1172     }
1173 }
1174
1175 void ShiftScaleRotate_toFace(const texdef_t &shiftScaleRotate, TextureProjection &projection)
1176 {
1177     if (g_bp_globals.m_texdefTypeId == TEXDEFTYPEID_BRUSHPRIMITIVES) {
1178         // compute texture matrix
1179         // the matrix returned must be understood as a qtexture_t with width=2 height=2
1180         FakeTexCoordsToTexMat(shiftScaleRotate, projection.m_brushprimit_texdef);
1181     } else {
1182         projection.m_texdef = shiftScaleRotate;
1183     }
1184 }
1185
1186
1187 inline void print_vector3(const Vector3 &v)
1188 {
1189     globalOutputStream() << "( " << v.x() << " " << v.y() << " " << v.z() << " )\n";
1190 }
1191
1192 inline void print_3x3(const Matrix4 &m)
1193 {
1194     globalOutputStream() << "( " << m.xx() << " " << m.xy() << " " << m.xz() << " ) "
1195                          << "( " << m.yx() << " " << m.yy() << " " << m.yz() << " ) "
1196                          << "( " << m.zx() << " " << m.zy() << " " << m.zz() << " )\n";
1197 }
1198
1199
1200 inline Matrix4 matrix4_rotation_for_vector3(const Vector3 &x, const Vector3 &y, const Vector3 &z)
1201 {
1202     return Matrix4(
1203             x.x(), x.y(), x.z(), 0,
1204             y.x(), y.y(), y.z(), 0,
1205             z.x(), z.y(), z.z(), 0,
1206             0, 0, 0, 1
1207     );
1208 }
1209
1210 inline Matrix4 matrix4_swap_axes(const Vector3 &from, const Vector3 &to)
1211 {
1212     if (from.x() != 0 && to.y() != 0) {
1213         return matrix4_rotation_for_vector3(to, from, g_vector3_axis_z);
1214     }
1215
1216     if (from.x() != 0 && to.z() != 0) {
1217         return matrix4_rotation_for_vector3(to, g_vector3_axis_y, from);
1218     }
1219
1220     if (from.y() != 0 && to.z() != 0) {
1221         return matrix4_rotation_for_vector3(g_vector3_axis_x, to, from);
1222     }
1223
1224     if (from.y() != 0 && to.x() != 0) {
1225         return matrix4_rotation_for_vector3(from, to, g_vector3_axis_z);
1226     }
1227
1228     if (from.z() != 0 && to.x() != 0) {
1229         return matrix4_rotation_for_vector3(from, g_vector3_axis_y, to);
1230     }
1231
1232     if (from.z() != 0 && to.y() != 0) {
1233         return matrix4_rotation_for_vector3(g_vector3_axis_x, from, to);
1234     }
1235
1236     ERROR_MESSAGE("unhandled axis swap case");
1237
1238     return g_matrix4_identity;
1239 }
1240
1241 inline Matrix4 matrix4_reflection_for_plane(const Plane3 &plane)
1242 {
1243     return Matrix4(
1244             static_cast<float>( 1 - (2 * plane.a * plane.a)),
1245             static_cast<float>( -2 * plane.a * plane.b ),
1246             static_cast<float>( -2 * plane.a * plane.c ),
1247             0,
1248             static_cast<float>( -2 * plane.b * plane.a ),
1249             static_cast<float>( 1 - (2 * plane.b * plane.b)),
1250             static_cast<float>( -2 * plane.b * plane.c ),
1251             0,
1252             static_cast<float>( -2 * plane.c * plane.a ),
1253             static_cast<float>( -2 * plane.c * plane.b ),
1254             static_cast<float>( 1 - (2 * plane.c * plane.c)),
1255             0,
1256             static_cast<float>( -2 * plane.d * plane.a ),
1257             static_cast<float>( -2 * plane.d * plane.b ),
1258             static_cast<float>( -2 * plane.d * plane.c ),
1259             1
1260     );
1261 }
1262
1263 inline Matrix4 matrix4_reflection_for_plane45(const Plane3 &plane, const Vector3 &from, const Vector3 &to)
1264 {
1265     Vector3 first = from;
1266     Vector3 second = to;
1267
1268     if ((vector3_dot(from, plane.normal()) > 0) == (vector3_dot(to, plane.normal()) > 0)) {
1269         first = vector3_negated(first);
1270         second = vector3_negated(second);
1271     }
1272
1273 #if 0
1274     globalOutputStream() << "normal: ";
1275     print_vector3( plane.normal() );
1276
1277     globalOutputStream() << "from: ";
1278     print_vector3( first );
1279
1280     globalOutputStream() << "to: ";
1281     print_vector3( second );
1282 #endif
1283
1284     Matrix4 swap = matrix4_swap_axes(first, second);
1285
1286     swap.tx() = -static_cast<float>( -2 * plane.a * plane.d );
1287     swap.ty() = -static_cast<float>( -2 * plane.b * plane.d );
1288     swap.tz() = -static_cast<float>( -2 * plane.c * plane.d );
1289
1290     return swap;
1291 }
1292
1293 void Texdef_transformLocked(TextureProjection &projection, std::size_t width, std::size_t height, const Plane3 &plane,
1294                             const Matrix4 &identity2transformed)
1295 {
1296     //globalOutputStream() << "identity2transformed: " << identity2transformed << "\n";
1297
1298     //globalOutputStream() << "plane.normal(): " << plane.normal() << "\n";
1299
1300     Vector3 normalTransformed(matrix4_transformed_direction(identity2transformed, plane.normal()));
1301
1302     //globalOutputStream() << "normalTransformed: " << normalTransformed << "\n";
1303
1304     // identity: identity space
1305     // transformed: transformation
1306     // stIdentity: base st projection space before transformation
1307     // stTransformed: base st projection space after transformation
1308     // stOriginal: original texdef space
1309
1310     // stTransformed2stOriginal = stTransformed -> transformed -> identity -> stIdentity -> stOriginal
1311
1312     Matrix4 identity2stIdentity;
1313     Texdef_basisForNormal(projection, plane.normal(), identity2stIdentity);
1314     //globalOutputStream() << "identity2stIdentity: " << identity2stIdentity << "\n";
1315
1316     if (g_bp_globals.m_texdefTypeId == TEXDEFTYPEID_HALFLIFE) {
1317         matrix4_transform_direction(identity2transformed, projection.m_basis_s);
1318         matrix4_transform_direction(identity2transformed, projection.m_basis_t);
1319     }
1320
1321     Matrix4 transformed2stTransformed;
1322     Texdef_basisForNormal(projection, normalTransformed, transformed2stTransformed);
1323
1324     Matrix4 stTransformed2identity(
1325             matrix4_affine_inverse(matrix4_multiplied_by_matrix4(transformed2stTransformed, identity2transformed)));
1326
1327     Vector3 originalProjectionAxis(vector4_to_vector3(matrix4_affine_inverse(identity2stIdentity).z()));
1328
1329     Vector3 transformedProjectionAxis(vector4_to_vector3(stTransformed2identity.z()));
1330
1331     Matrix4 stIdentity2stOriginal;
1332     Texdef_toTransform(projection, (float) width, (float) height, stIdentity2stOriginal);
1333     Matrix4 identity2stOriginal(matrix4_multiplied_by_matrix4(stIdentity2stOriginal, identity2stIdentity));
1334
1335     //globalOutputStream() << "originalProj: " << originalProjectionAxis << "\n";
1336     //globalOutputStream() << "transformedProj: " << transformedProjectionAxis << "\n";
1337     double dot = vector3_dot(originalProjectionAxis, transformedProjectionAxis);
1338     //globalOutputStream() << "dot: " << dot << "\n";
1339     if (dot == 0) {
1340         // The projection axis chosen for the transformed normal is at 90 degrees
1341         // to the transformed projection axis chosen for the original normal.
1342         // This happens when the projection axis is ambiguous - e.g. for the plane
1343         // 'X == Y' the projection axis could be either X or Y.
1344         //globalOutputStream() << "flipped\n";
1345 #if 0
1346         globalOutputStream() << "projection off by 90\n";
1347         globalOutputStream() << "normal: ";
1348         print_vector3( plane.normal() );
1349         globalOutputStream() << "original projection: ";
1350         print_vector3( originalProjectionAxis );
1351         globalOutputStream() << "transformed projection: ";
1352         print_vector3( transformedProjectionAxis );
1353 #endif
1354
1355         Matrix4 identityCorrected = matrix4_reflection_for_plane45(plane, originalProjectionAxis,
1356                                                                    transformedProjectionAxis);
1357
1358         identity2stOriginal = matrix4_multiplied_by_matrix4(identity2stOriginal, identityCorrected);
1359     }
1360
1361     Matrix4 stTransformed2stOriginal = matrix4_multiplied_by_matrix4(identity2stOriginal, stTransformed2identity);
1362
1363     Texdef_fromTransform(projection, (float) width, (float) height, stTransformed2stOriginal);
1364     Texdef_normalise(projection, (float) width, (float) height);
1365 }
1366
1367 #if 1
1368
1369 void Q3_to_matrix(const texdef_t &texdef, float width, float height, const Vector3 &normal, Matrix4 &matrix)
1370 {
1371     Normal_GetTransform(normal, matrix);
1372
1373     Matrix4 transform;
1374
1375     Texdef_toTransform(texdef, width, height, transform);
1376
1377     matrix4_multiply_by_matrix4(matrix, transform);
1378 }
1379
1380 void BP_from_matrix(brushprimit_texdef_t &bp_texdef, const Vector3 &normal, const Matrix4 &transform)
1381 {
1382     Matrix4 basis;
1383     basis = g_matrix4_identity;
1384     ComputeAxisBase(normal, vector4_to_vector3(basis.x()), vector4_to_vector3(basis.y()));
1385     vector4_to_vector3(basis.z()) = normal;
1386     matrix4_transpose(basis);
1387     matrix4_affine_invert(basis);
1388
1389     Matrix4 basis2texture = matrix4_multiplied_by_matrix4(basis, transform);
1390
1391     BPTexdef_fromTransform(bp_texdef, basis2texture);
1392 }
1393
1394 void Q3_to_BP(const texdef_t &texdef, float width, float height, const Vector3 &normal, brushprimit_texdef_t &bp_texdef)
1395 {
1396     Matrix4 matrix;
1397     Q3_to_matrix(texdef, width, height, normal, matrix);
1398     BP_from_matrix(bp_texdef, normal, matrix);
1399 }
1400
1401 #endif