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