ac96240f5ece058873618d06d37088c8be52df74
[xonotic/netradiant.git] / radiant / patch.cpp
1 /*
2 Copyright (C) 2001-2006, William Joseph.
3 All Rights Reserved.
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 "patch.h"
23
24 #include <glib/gslist.h>
25 #include "preferences.h"
26 #include "brush_primit.h"
27 #include "signal/signal.h"
28
29
30 Signal0 g_patchTextureChangedCallbacks;
31
32 void Patch_addTextureChangedCallback(const SignalHandler& handler)
33 {
34   g_patchTextureChangedCallbacks.connectLast(handler);
35 }
36
37 void Patch_textureChanged()
38 {
39   g_patchTextureChangedCallbacks();
40 }
41
42
43 Shader* PatchInstance::m_state_selpoint;
44 Shader* Patch::m_state_ctrl;
45 Shader* Patch::m_state_lattice;
46 EPatchType Patch::m_type;
47
48
49 std::size_t MAX_PATCH_WIDTH = 0;
50 std::size_t MAX_PATCH_HEIGHT = 0;
51
52 int g_PatchSubdivideThreshold = 4;
53
54 void BezierCurveTree_Delete(BezierCurveTree *pCurve)
55 {
56   if(pCurve)
57   {
58     BezierCurveTree_Delete(pCurve->left);
59     BezierCurveTree_Delete(pCurve->right);
60     delete pCurve;
61   }
62 }
63
64 std::size_t BezierCurveTree_Setup(BezierCurveTree *pCurve, std::size_t index, std::size_t stride)
65 {
66   if(pCurve)
67   {
68     if(pCurve->left && pCurve->right)
69     {
70       index = BezierCurveTree_Setup(pCurve->left, index, stride);
71       pCurve->index = index*stride;
72       index++;
73       index = BezierCurveTree_Setup(pCurve->right, index, stride);
74     }
75     else
76     {
77       pCurve->index = BEZIERCURVETREE_MAX_INDEX;
78     }
79   }
80   
81   return index;
82 }
83
84 bool BezierCurve_IsCurved(BezierCurve *pCurve)
85 {
86   Vector3 vTemp(vector3_subtracted(pCurve->right, pCurve->left));
87   Vector3 v1(vector3_subtracted(pCurve->crd, pCurve->left));
88   Vector3 v2(vector3_subtracted(pCurve->right, pCurve->crd));
89
90   if(vector3_equal(v1, g_vector3_identity) || vector3_equal(vTemp, v1)) // return 0 if 1->2 == 0 or 1->2 == 1->3
91     return false;
92
93   vector3_normalise(v1);
94   vector3_normalise(v2);
95   if(vector3_equal(v1, v2))
96     return false;
97   
98   Vector3 v3(vTemp);
99   const double width = vector3_length(v3);
100   vector3_scale(v3, 1.0 / width);
101
102   if(vector3_equal(v1, v3) && vector3_equal(v2, v3))
103     return false;
104   
105   const double angle = acos(vector3_dot(v1, v2)) / c_pi;
106
107   const double index = width * angle;
108
109   if(index > static_cast<double>(g_PatchSubdivideThreshold))
110     return true;
111   return false;
112 }
113
114 void BezierInterpolate(BezierCurve *pCurve)
115 {
116   pCurve->left = vector3_mid(pCurve->left, pCurve->crd);
117   pCurve->right = vector3_mid(pCurve->crd, pCurve->right);
118   pCurve->crd = vector3_mid(pCurve->left, pCurve->right);
119 }
120
121 const std::size_t PATCH_MAX_SUBDIVISION_DEPTH = 16;
122
123 void BezierCurveTree_FromCurveList(BezierCurveTree *pTree, GSList *pCurveList, std::size_t depth = 0)
124 {
125   GSList *pLeftList = 0;
126   GSList *pRightList = 0;
127   BezierCurve *pCurve, *pLeftCurve, *pRightCurve;
128   bool bSplit = false;
129
130   for (GSList *l = pCurveList; l; l = l->next)
131   {
132     pCurve = (BezierCurve *)(l->data);
133     if(bSplit || BezierCurve_IsCurved(pCurve))
134     {
135       bSplit = true;
136       pLeftCurve = new BezierCurve;
137       pRightCurve = new BezierCurve;
138       pLeftCurve->left = pCurve->left;
139       pRightCurve->right = pCurve->right;
140       BezierInterpolate(pCurve);
141       pLeftCurve->crd = pCurve->left;
142       pRightCurve->crd = pCurve->right;
143       pLeftCurve->right = pCurve->crd;
144       pRightCurve->left = pCurve->crd;
145
146       pLeftList = g_slist_prepend(pLeftList, pLeftCurve);
147       pRightList = g_slist_prepend(pRightList, pRightCurve);
148     }
149   }
150
151   if(pLeftList != 0 && pRightList != 0 && depth != PATCH_MAX_SUBDIVISION_DEPTH)
152   {
153     pTree->left = new BezierCurveTree;
154     pTree->right = new BezierCurveTree;
155     BezierCurveTree_FromCurveList(pTree->left, pLeftList, depth + 1);
156     BezierCurveTree_FromCurveList(pTree->right, pRightList, depth + 1);
157
158     for(GSList* l = pLeftList; l != 0; l = g_slist_next(l))
159     {
160       delete (BezierCurve*)l->data;
161     }
162
163     for(GSList* l = pRightList; l != 0; l = g_slist_next(l))
164     {
165       delete (BezierCurve*)l->data;
166     }
167     
168     g_slist_free(pLeftList);
169     g_slist_free(pRightList);
170   }
171   else
172   {
173     pTree->left = 0;
174     pTree->right = 0;
175   }
176 }
177
178
179 int Patch::m_CycleCapIndex = 0;
180
181
182 void Patch::setDims (std::size_t w, std::size_t h)
183 {
184   if((w%2)==0)
185     w -= 1;
186   ASSERT_MESSAGE(w <= MAX_PATCH_WIDTH, "patch too wide");
187   if(w > MAX_PATCH_WIDTH)
188     w = MAX_PATCH_WIDTH;
189   else if(w < MIN_PATCH_WIDTH)
190     w = MIN_PATCH_WIDTH;
191   
192   if((h%2)==0)
193     m_height -= 1;
194   ASSERT_MESSAGE(h <= MAX_PATCH_HEIGHT, "patch too tall");
195   if(h > MAX_PATCH_HEIGHT)
196     h = MAX_PATCH_HEIGHT;
197   else if(h < MIN_PATCH_HEIGHT)
198     h = MIN_PATCH_HEIGHT;
199
200   m_width = w; m_height = h;
201
202   if(m_width * m_height != m_ctrl.size())
203   {
204     m_ctrl.resize(m_width * m_height);
205     onAllocate(m_ctrl.size());
206   }
207 }
208
209 inline const Colour4b& colour_for_index(std::size_t i, std::size_t width)
210 {
211   return (i%2 || (i/width)%2) ? colour_inside : colour_corner;
212 }
213
214 inline bool float_valid(float f)
215 {
216   return f == f;
217 }
218
219 bool Patch::isValid() const
220 {
221   if(!m_width || !m_height)
222   {
223     return false;
224   }
225
226   for(const_iterator i = m_ctrl.begin(); i != m_ctrl.end(); ++i)
227   {
228     if(!float_valid((*i).m_vertex.x())
229       || !float_valid((*i).m_vertex.y())
230       || !float_valid((*i).m_vertex.z())
231       || !float_valid((*i).m_texcoord.x())
232       || !float_valid((*i).m_texcoord.y()))
233     {
234       globalErrorStream() << "patch has invalid control points\n";
235       return false;
236     }
237   }
238   return true;
239 }
240
241 void Patch::UpdateCachedData()
242 {
243   m_ctrl_vertices.clear();
244   m_lattice_indices.clear();
245
246   if(!isValid())
247   {
248     m_tess.m_numStrips = 0;
249     m_tess.m_lenStrips = 0;
250     m_tess.m_nArrayHeight = 0;
251     m_tess.m_nArrayWidth = 0;
252     m_tess.m_curveTreeU.resize(0);
253     m_tess.m_curveTreeV.resize(0);
254     m_tess.m_indices.resize(0);
255     m_tess.m_vertices.resize(0);
256     m_tess.m_arrayHeight.resize(0);
257     m_tess.m_arrayWidth.resize(0);
258     m_aabb_local = AABB();
259     return;
260   }
261
262   BuildTesselationCurves(ROW);
263   BuildTesselationCurves(COL);
264   BuildVertexArray();
265   AccumulateBBox();
266
267   IndexBuffer ctrl_indices;
268
269   m_lattice_indices.reserve(((m_width * (m_height - 1)) + (m_height * (m_width - 1))) << 1);
270   ctrl_indices.reserve(m_ctrlTransformed.size());
271   {
272     UniqueVertexBuffer<PointVertex> inserter(m_ctrl_vertices);
273     for(iterator i = m_ctrlTransformed.begin(); i != m_ctrlTransformed.end(); ++i)
274     {
275       ctrl_indices.insert(inserter.insert(pointvertex_quantised(PointVertex(reinterpret_cast<const Vertex3f&>((*i).m_vertex), colour_for_index(i - m_ctrlTransformed.begin(), m_width)))));
276     }
277   }
278   {
279     for(IndexBuffer::iterator i = ctrl_indices.begin(); i != ctrl_indices.end(); ++i)
280     {
281       if(std::size_t(i - ctrl_indices.begin()) % m_width)
282       {
283         m_lattice_indices.insert(*(i - 1));
284         m_lattice_indices.insert(*i);
285       }
286       if(std::size_t(i - ctrl_indices.begin()) >= m_width)
287       {
288         m_lattice_indices.insert(*(i - m_width));
289         m_lattice_indices.insert(*i);
290       }
291     }
292   }
293
294 #if 0
295   {
296     Array<RenderIndex>::iterator first = m_tess.m_indices.begin();
297     for(std::size_t s=0; s<m_tess.m_numStrips; s++)
298     {
299       Array<RenderIndex>::iterator last = first + m_tess.m_lenStrips;
300
301       for(Array<RenderIndex>::iterator i(first); i+2 != last; i += 2)
302       {
303         ArbitraryMeshTriangle_sumTangents(m_tess.m_vertices[*(i+0)], m_tess.m_vertices[*(i+1)], m_tess.m_vertices[*(i+2)]);
304         ArbitraryMeshTriangle_sumTangents(m_tess.m_vertices[*(i+2)], m_tess.m_vertices[*(i+1)], m_tess.m_vertices[*(i+3)]);
305       }
306
307       first = last;
308     }
309
310     for(Array<ArbitraryMeshVertex>::iterator i = m_tess.m_vertices.begin(); i != m_tess.m_vertices.end(); ++i)
311     {
312       vector3_normalise(reinterpret_cast<Vector3&>((*i).tangent));
313       vector3_normalise(reinterpret_cast<Vector3&>((*i).bitangent));
314     }
315   }
316 #endif
317
318   SceneChangeNotify();
319 }
320
321 void Patch::InvertMatrix()
322 {
323   undoSave();
324
325   PatchControlArray_invert(m_ctrl, m_width, m_height);
326
327   controlPointsChanged();
328 }
329
330 void Patch::TransposeMatrix()
331 {
332   undoSave();
333
334   {
335     Array<PatchControl> tmp(m_width * m_height);
336     copy_ctrl(tmp.data(), m_ctrl.data(), m_ctrl.data() + m_width * m_height);
337
338     PatchControlIter from = tmp.data();
339     for(std::size_t h = 0; h != m_height; ++h)
340     {
341       PatchControlIter to = m_ctrl.data() + h;
342       for(std::size_t w = 0; w != m_width; ++w, ++from, to += m_height)
343       {
344         *to = *from;
345       }
346     }
347   }
348
349   {
350     std::size_t tmp = m_width;
351     m_width = m_height;
352     m_height = tmp;
353   }
354    
355   controlPointsChanged();
356 }
357
358 void Patch::Redisperse(EMatrixMajor mt)
359 {
360   std::size_t w, h, width, height, row_stride, col_stride;
361   PatchControl* p1, * p2, * p3;
362
363   undoSave();
364
365   switch(mt)
366   {
367   case COL:
368     width = (m_width-1)>>1;
369     height = m_height;
370     col_stride = 1;
371     row_stride = m_width;
372     break;
373   case ROW:
374     width = (m_height-1)>>1;
375     height = m_width;
376     col_stride = m_width;
377     row_stride = 1;
378     break;
379   default:
380     ERROR_MESSAGE("neither row-major nor column-major");
381     return;
382   }
383
384   for(h=0;h<height;h++)
385   {
386     p1 = m_ctrl.data()+(h*row_stride);
387     for(w=0;w<width;w++)
388     {
389       p2 = p1+col_stride;
390       p3 = p2+col_stride;
391       p2->m_vertex = vector3_mid(p1->m_vertex, p3->m_vertex);
392       p1 = p3;
393     }
394   }
395   
396   controlPointsChanged();
397 }
398
399 void Patch::Smooth(EMatrixMajor mt)
400 {
401   std::size_t w, h, width, height, row_stride, col_stride;
402   bool wrap;
403   PatchControl* p1, * p2, * p3, * p2b;
404
405   undoSave();
406
407   switch(mt)
408   {
409   case COL:
410     width = (m_width-1)>>1;
411     height = m_height;
412     col_stride = 1;
413     row_stride = m_width;
414     break;
415   case ROW:
416     width = (m_height-1)>>1;
417     height = m_width;
418     col_stride = m_width;
419     row_stride = 1;
420     break;
421   default:
422     ERROR_MESSAGE("neither row-major nor column-major");
423     return;
424   }
425
426   wrap = true;
427   for(h=0;h<height;h++)
428   {
429         p1 = m_ctrl.data()+(h*row_stride);
430         p2 = p1+(2*width)*col_stride;
431         //globalErrorStream() << "compare " << p1->m_vertex << " and " << p2->m_vertex << "\n";
432         if(vector3_length_squared(vector3_subtracted(p1->m_vertex, p2->m_vertex)) > 1.0)
433         {
434           //globalErrorStream() << "too far\n";
435           wrap = false;
436           break;
437         }
438   }
439
440   for(h=0;h<height;h++)
441   {
442     p1 = m_ctrl.data()+(h*row_stride)+col_stride;
443     for(w=0;w<width-1;w++)
444     {
445       p2 = p1+col_stride;
446       p3 = p2+col_stride;
447       p2->m_vertex = vector3_mid(p1->m_vertex, p3->m_vertex);
448       p1 = p3;
449     }
450         if(wrap)
451         {
452           p1 = m_ctrl.data()+(h*row_stride)+(2*width-1)*col_stride;
453           p2 = m_ctrl.data()+(h*row_stride);
454           p2b = m_ctrl.data()+(h*row_stride)+(2*width)*col_stride;
455           p3 = m_ctrl.data()+(h*row_stride)+col_stride;
456           p2->m_vertex = p2b->m_vertex = vector3_mid(p1->m_vertex, p3->m_vertex);
457         }
458   }
459   
460   controlPointsChanged();
461 }
462
463 void Patch::InsertRemove(bool bInsert, bool bColumn, bool bFirst)
464 {
465   undoSave();
466
467   if(bInsert)
468   {
469     if(bColumn && (m_width + 2 <= MAX_PATCH_WIDTH))
470       InsertPoints(COL, bFirst);
471     else if(m_height + 2 <= MAX_PATCH_HEIGHT)
472       InsertPoints(ROW, bFirst);
473   }
474   else
475   {
476     if(bColumn && (m_width - 2 >= MIN_PATCH_WIDTH))
477       RemovePoints(COL, bFirst);
478     else if(m_height - 2 >= MIN_PATCH_HEIGHT)
479       RemovePoints(ROW, bFirst);
480   }
481
482   controlPointsChanged();
483 }
484
485 Patch* Patch::MakeCap(Patch* patch, EPatchCap eType, EMatrixMajor mt, bool bFirst)
486 {
487   std::size_t i, width, height;
488
489   switch(mt)
490   {
491   case ROW:
492     width = m_width;
493     height = m_height;
494     break;
495   case COL:
496     width = m_height;
497     height = m_width;
498     break;
499   default:
500     ERROR_MESSAGE("neither row-major nor column-major");
501     return 0;
502   }
503
504   Array<Vector3> p(width);
505
506   std::size_t nIndex = (bFirst) ? 0 : height-1;
507   if(mt == ROW)
508   {
509     for (i=0; i<width; i++)
510     {
511       p[(bFirst)?i:(width-1)-i] = ctrlAt(nIndex, i).m_vertex;
512     }
513   }
514   else
515   {
516     for (i=0; i<width; i++)
517     {
518       p[(bFirst)?i:(width-1)-i] = ctrlAt(i, nIndex).m_vertex;
519     }
520   }
521
522   patch->ConstructSeam(eType, p.data(), width);
523   return patch;
524 }
525
526 void Patch::FlipTexture(int nAxis)
527 {
528   undoSave();
529
530   for(PatchControlIter i = m_ctrl.data(); i != m_ctrl.data() + m_ctrl.size(); ++i)
531   {
532     (*i).m_texcoord[nAxis] = -(*i).m_texcoord[nAxis];
533   }
534   
535   controlPointsChanged();
536 }
537
538 void Patch::TranslateTexture(float s, float t)
539 {
540   undoSave();
541
542   s = -1 * s / m_state->getTexture().width;
543   t = t / m_state->getTexture().height;
544
545   for(PatchControlIter i = m_ctrl.data(); i != m_ctrl.data() + m_ctrl.size(); ++i)
546   {
547     (*i).m_texcoord[0] += s;
548     (*i).m_texcoord[1] += t;
549   }
550
551   controlPointsChanged();
552 }
553
554 void Patch::ScaleTexture(float s, float t)
555 {
556   undoSave();
557
558   for(PatchControlIter i = m_ctrl.data(); i != m_ctrl.data() + m_ctrl.size(); ++i)
559   {
560     (*i).m_texcoord[0] *= s;
561     (*i).m_texcoord[1] *= t;
562   }
563
564   controlPointsChanged();
565 }
566
567 void Patch::RotateTexture(float angle)
568 {
569   undoSave();
570
571   const float s = static_cast<float>(sin(degrees_to_radians(angle)));
572   const float c = static_cast<float>(cos(degrees_to_radians(angle)));
573     
574   for(PatchControlIter i = m_ctrl.data(); i != m_ctrl.data() + m_ctrl.size(); ++i)
575   {
576     const float x = (*i).m_texcoord[0];
577     const float y = (*i).m_texcoord[1];
578     (*i).m_texcoord[0] = (x * c) - (y * s);
579     (*i).m_texcoord[1] = (y * c) + (x * s);
580   }
581
582   controlPointsChanged();
583 }
584
585
586 void Patch::SetTextureRepeat(float s, float t)
587 {
588   std::size_t w, h;
589   float si, ti, sc, tc;
590   PatchControl *pDest;
591   
592   undoSave();
593
594   si = s / (float)(m_width - 1);
595   ti = t / (float)(m_height - 1);
596
597   pDest = m_ctrl.data();
598   for (h=0, tc = 0.0f; h<m_height; h++, tc+=ti)
599   {
600     for (w=0, sc = 0.0f; w<m_width; w++, sc+=si) 
601     {
602       pDest->m_texcoord[0] = sc;
603       pDest->m_texcoord[1] = tc;
604       pDest++;
605     }
606   }
607
608   controlPointsChanged();
609 }
610
611 /*
612 void Patch::SetTextureInfo(texdef_t *pt)
613 {
614   if(pt->getShift()[0] || pt->getShift()[1])
615     TranslateTexture (pt->getShift()[0], pt->getShift()[1]);
616   else if(pt->getScale()[0] || pt->getScale()[1])
617   {
618     if(pt->getScale()[0] == 0.0f) pt->setScale(0, 1.0f);
619     if(pt->getScale()[1] == 0.0f) pt->setScale(1, 1.0f);
620     ScaleTexture (pt->getScale()[0], pt->getScale()[1]);
621   }
622   else if(pt->rotate)
623     RotateTexture (pt->rotate);
624 }
625 */
626
627 inline int texture_axis(const Vector3& normal)
628 {
629   // axis dominance order: Z, X, Y
630   return (normal.x() >= normal.y()) ? (normal.x() > normal.z()) ? 0 : 2 : (normal.y() > normal.z()) ? 1 : 2; 
631 }
632
633 void Patch::CapTexture()
634 {
635   const PatchControl& p1 = m_ctrl[m_width];
636   const PatchControl& p2 = m_ctrl[m_width*(m_height-1)];
637   const PatchControl& p3 = m_ctrl[(m_width*m_height)-1];
638
639   
640   Vector3 normal(g_vector3_identity);
641
642   {
643     Vector3 tmp(vector3_cross(
644       vector3_subtracted(p2.m_vertex, m_ctrl[0].m_vertex),
645       vector3_subtracted(p3.m_vertex, m_ctrl[0].m_vertex)
646     ));
647     if(!vector3_equal(tmp, g_vector3_identity))
648     {
649       vector3_add(normal, tmp);
650     }
651   }
652   {
653     Vector3 tmp(vector3_cross(
654       vector3_subtracted(p1.m_vertex, p3.m_vertex),
655       vector3_subtracted(m_ctrl[0].m_vertex, p3.m_vertex)
656     ));
657     if(!vector3_equal(tmp, g_vector3_identity))
658     {
659       vector3_add(normal, tmp);
660     }
661   }
662
663   ProjectTexture(texture_axis(normal));
664 }
665
666 // uses longest parallel chord to calculate texture coords for each row/col
667 void Patch::NaturalTexture()
668 {
669   undoSave();
670
671   {
672     float fSize = (float)m_state->getTexture().width * Texdef_getDefaultTextureScale();
673   
674     double texBest = 0;
675     double tex = 0;
676     PatchControl* pWidth = m_ctrl.data();
677     for (std::size_t w=0; w<m_width; w++, pWidth++) 
678     {
679       {
680         PatchControl* pHeight = pWidth;
681         for (std::size_t h=0; h<m_height; h++, pHeight+=m_width)
682           pHeight->m_texcoord[0] = static_cast<float>(tex);
683       }
684
685       if(w+1 == m_width)
686         break;
687
688       {
689         PatchControl* pHeight = pWidth;
690         for (std::size_t h=0; h<m_height; h++, pHeight+=m_width)
691         {
692           Vector3 v(vector3_subtracted(pHeight->m_vertex, (pHeight+1)->m_vertex));
693           double length = tex + (vector3_length(v) / fSize);
694           if(fabs(length) > texBest) texBest = length;
695         }
696       }
697
698       tex=texBest;
699     }
700   }
701
702   {
703     float fSize = -(float)m_state->getTexture().height * Texdef_getDefaultTextureScale();
704
705     double texBest = 0;
706     double tex = 0;
707     PatchControl* pHeight = m_ctrl.data();
708     for (std::size_t h=0; h<m_height; h++, pHeight+=m_width) 
709     {
710       {
711         PatchControl* pWidth = pHeight;
712         for (std::size_t w=0; w<m_width; w++, pWidth++)
713           pWidth->m_texcoord[1] = static_cast<float>(tex);
714       }
715
716       if(h+1 == m_height)
717         break;
718
719       {
720         PatchControl* pWidth = pHeight;
721         for (std::size_t w=0; w<m_width; w++, pWidth++)
722         {
723           Vector3 v(vector3_subtracted(pWidth->m_vertex, (pWidth+m_width)->m_vertex));
724           double length = tex + (vector3_length(v) / fSize);
725           if(fabs(length) > texBest) texBest = length;
726         }
727       }
728
729       tex=texBest;
730     }
731   }
732
733   controlPointsChanged();
734 }
735
736
737
738 // private:
739
740 void Patch::AccumulateBBox()
741 {
742   m_aabb_local = AABB();
743
744   for(PatchControlArray::iterator i = m_ctrlTransformed.begin(); i != m_ctrlTransformed.end(); ++i)
745   {
746     aabb_extend_by_point_safe(m_aabb_local, (*i).m_vertex);
747   }
748
749   m_boundsChanged();
750   m_lightsChanged();
751 }
752
753 void Patch::InsertPoints(EMatrixMajor mt, bool bFirst)
754 {
755   std::size_t width, height, row_stride, col_stride; 
756
757   switch(mt)
758   {
759   case ROW:
760     col_stride = 1;
761     row_stride = m_width;
762     width = m_width;
763     height = m_height;
764     break;
765   case COL:
766     col_stride = m_width;
767     row_stride = 1;
768     width = m_height;
769     height = m_width;
770     break;
771   default:
772     ERROR_MESSAGE("neither row-major nor column-major");
773     return;
774   }
775
776   std::size_t pos = 0;
777   {
778     PatchControl* p1 = m_ctrl.data();
779         /*
780           if(GlobalSelectionSystem().countSelected() != 0) 
781           {  
782                   scene::Instance& instance = GlobalSelectionSystem().ultimateSelected();
783                   PatchInstance* patch = Instance_getPatch(instance);
784                   patch->m_selectable.isSelected();
785           }
786         */
787         for(std::size_t w = 0; w != width; ++w, p1 += col_stride)
788     {
789       {
790         PatchControl* p2 = p1;
791         for(std::size_t h = 1; h < height; h += 2, p2 += 2 * row_stride)
792         {
793           if(0)//p2->m_selectable.isSelected())
794           {
795             pos = h;
796             break;
797           }
798         }
799         if(pos != 0)
800         {
801           break;
802         }
803       }
804   
805       {
806         PatchControl* p2 = p1;
807         for(std::size_t h = 0; h < height; h += 2, p2 += 2 * row_stride)
808         {
809           if(0)//p2->m_selectable.isSelected())
810           {
811             pos = h;
812             break;
813           }
814         }
815         if(pos != 0)
816         {
817           break;
818         }
819       }
820     }
821   }
822
823   Array<PatchControl> tmp(m_ctrl);
824
825   std::size_t row_stride2, col_stride2;
826   switch(mt)
827   {
828   case ROW:
829     setDims(m_width, m_height+2);
830     col_stride2 = 1;
831     row_stride2 = m_width;
832     break;
833   case COL:
834     setDims(m_width+2, m_height);
835     col_stride2 = m_width;
836     row_stride2 = 1;
837     break;
838   default:
839     ERROR_MESSAGE("neither row-major nor column-major");
840     return;
841   }
842     if(bFirst)
843     {
844                 pos = height - 1;
845     }
846     else
847     {
848                 pos = 2;
849     }
850         
851   if(pos >= height)
852   {
853     if(bFirst)
854     {
855       pos = height - 1;
856     }
857     else
858     {
859       pos = 2;
860     }
861   }
862   else if(pos == 0)
863   {
864     pos = 2;
865   }
866   else if(pos % 2)
867   {
868     ++pos;
869   }
870
871
872   for(std::size_t w = 0; w != width; ++w)
873   {
874     PatchControl* p1 = tmp.data() + (w*col_stride);
875     PatchControl* p2 = m_ctrl.data() + (w*col_stride2);
876     for(std::size_t h = 0; h != height; ++h, p2 += row_stride2, p1 += row_stride)
877     {
878       if(h == pos)
879       {
880         p2 += 2 * row_stride2;
881       }
882       *p2 = *p1;
883     }
884
885     p1 = tmp.data() + (w*col_stride+pos*row_stride);
886     p2 = m_ctrl.data() + (w*col_stride2+pos*row_stride2);
887     
888     PatchControl* r2a = (p2+row_stride2);
889     PatchControl* r2b = (p2-row_stride2);
890     PatchControl* c2a = (p1-2*row_stride);
891     PatchControl* c2b = (p1-row_stride);
892
893     // set two new row points
894     *(p2+2*row_stride2) = *p1;
895     *r2a = *c2b;
896     
897     for(std::size_t i = 0; i != 3; ++i)
898     {
899       r2a->m_vertex[i] = float_mid(c2b->m_vertex[i], p1->m_vertex[i]);
900
901       r2b->m_vertex[i] = float_mid(c2a->m_vertex[i], c2b->m_vertex[i]);
902
903       p2->m_vertex[i] = float_mid(r2a->m_vertex[i], r2b->m_vertex[i]);
904     }
905     for(std::size_t i = 0; i != 2; ++i)
906     {
907       r2a->m_texcoord[i] = float_mid(c2b->m_texcoord[i], p1->m_texcoord[i]);
908
909       r2b->m_texcoord[i] = float_mid(c2a->m_texcoord[i], c2b->m_texcoord[i]);
910
911       p2->m_texcoord[i] = float_mid(r2a->m_texcoord[i], r2b->m_texcoord[i]);
912     }
913   }
914 }
915
916 void Patch::RemovePoints(EMatrixMajor mt, bool bFirst)
917 {
918   std::size_t width, height, row_stride, col_stride; 
919
920   switch(mt)
921   {
922   case ROW:
923     col_stride = 1;
924     row_stride = m_width;
925     width = m_width;
926     height = m_height;
927     break;
928   case COL:
929     col_stride = m_width;
930     row_stride = 1;
931     width = m_height;
932     height = m_width;
933     break;
934   default:
935     ERROR_MESSAGE("neither row-major nor column-major");
936     return;
937   }
938
939   std::size_t pos = 0;
940   {
941     PatchControl* p1 = m_ctrl.data();
942     for(std::size_t w = 0; w != width; ++w, p1 += col_stride)
943     {
944       {
945         PatchControl* p2 = p1;
946         for(std::size_t h=1; h < height; h += 2, p2 += 2 * row_stride)
947         {
948           if(0)//p2->m_selectable.isSelected())
949           {
950             pos = h;
951             break;
952           }
953         }
954         if(pos != 0)
955         {
956           break;
957         }
958       }
959   
960       {
961         PatchControl* p2 = p1;
962         for(std::size_t h=0; h < height; h += 2, p2 += 2 * row_stride)
963         {
964           if(0)//p2->m_selectable.isSelected())
965           {
966             pos = h;
967             break;
968           }
969         }
970         if(pos != 0)
971         {
972           break;
973         }
974       }
975     }
976   }
977
978   Array<PatchControl> tmp(m_ctrl);
979
980   std::size_t row_stride2, col_stride2;
981   switch(mt)
982   {
983   case ROW:
984     setDims(m_width, m_height-2);
985     col_stride2 = 1;
986     row_stride2 = m_width;
987     break;
988   case COL:
989     setDims(m_width-2, m_height);
990     col_stride2 = m_width;
991     row_stride2 = 1;
992     break;
993   default:
994     ERROR_MESSAGE("neither row-major nor column-major");
995     return;
996   }
997     if(bFirst)
998     {
999                 pos=height-3;
1000     }
1001     else
1002     {
1003                 pos=2;
1004     }
1005   if(pos >= height)
1006   {
1007     if(bFirst)
1008     {
1009       pos=height-3;
1010     }
1011     else
1012     {
1013       pos=2;
1014     }
1015   }
1016   else if(pos == 0)
1017   {
1018     pos=2;
1019   }
1020   else if(pos > height - 3)
1021   {
1022     pos = height - 3;
1023   }
1024   else if(pos % 2)
1025   {
1026     ++pos;
1027   }
1028
1029   for(std::size_t w = 0; w != width; w++)
1030   {
1031     PatchControl* p1 = tmp.data() + (w*col_stride);
1032     PatchControl* p2 = m_ctrl.data() + (w*col_stride2);
1033     for(std::size_t h = 0; h != height; ++h, p2 += row_stride2, p1 += row_stride)
1034     {
1035       if(h == pos)
1036       {
1037         p1 += 2 * row_stride2; h += 2;
1038       }
1039       *p2 = *p1;
1040     }
1041
1042     p1 = tmp.data() + (w*col_stride+pos*row_stride);
1043     p2 = m_ctrl.data() + (w*col_stride2+pos*row_stride2);
1044     
1045     for(std::size_t i=0; i<3; i++)
1046     {
1047       (p2-row_stride2)->m_vertex[i] = ((p1+2*row_stride)->m_vertex[i]+(p1-2*row_stride)->m_vertex[i]) * 0.5f;
1048
1049       (p2-row_stride2)->m_vertex[i] = (p2-row_stride2)->m_vertex[i]+(2.0f * ((p1)->m_vertex[i]-(p2-row_stride2)->m_vertex[i]));
1050     }
1051     for(std::size_t i=0; i<2; i++)
1052     {
1053       (p2-row_stride2)->m_texcoord[i] = ((p1+2*row_stride)->m_texcoord[i]+(p1-2*row_stride)->m_texcoord[i]) * 0.5f;
1054
1055       (p2-row_stride2)->m_texcoord[i] = (p2-row_stride2)->m_texcoord[i]+(2.0f * ((p1)->m_texcoord[i]-(p2-row_stride2)->m_texcoord[i]));
1056     }
1057   }
1058 }
1059
1060 void Patch::ConstructSeam(EPatchCap eType, Vector3* p, std::size_t width)
1061 {
1062   switch(eType)
1063   {
1064   case eCapIBevel:
1065     {
1066       setDims(3, 3);
1067       m_ctrl[0].m_vertex = p[0];
1068       m_ctrl[1].m_vertex = p[1];
1069       m_ctrl[2].m_vertex = p[1];
1070       m_ctrl[3].m_vertex = p[1];
1071       m_ctrl[4].m_vertex = p[1];
1072       m_ctrl[5].m_vertex = p[1];
1073       m_ctrl[6].m_vertex = p[2];
1074       m_ctrl[7].m_vertex = p[1];
1075       m_ctrl[8].m_vertex = p[1];
1076     }
1077     break;
1078   case eCapBevel:
1079     {
1080       setDims(3, 3);
1081       Vector3 p3(vector3_added(p[2], vector3_subtracted(p[0], p[1])));
1082       m_ctrl[0].m_vertex = p3;
1083       m_ctrl[1].m_vertex = p3;
1084       m_ctrl[2].m_vertex = p[2];
1085       m_ctrl[3].m_vertex = p3;
1086       m_ctrl[4].m_vertex = p3;
1087       m_ctrl[5].m_vertex = p[1];
1088       m_ctrl[6].m_vertex = p3;
1089       m_ctrl[7].m_vertex = p3;
1090       m_ctrl[8].m_vertex = p[0];
1091     }
1092     break;
1093   case eCapEndCap:
1094     {
1095       Vector3 p5(vector3_mid(p[0], p[4]));
1096
1097       setDims(3, 3);
1098       m_ctrl[0].m_vertex = p[0];
1099       m_ctrl[1].m_vertex = p5;
1100       m_ctrl[2].m_vertex = p[4];
1101       m_ctrl[3].m_vertex = p[1];
1102       m_ctrl[4].m_vertex = p[2];
1103       m_ctrl[5].m_vertex = p[3];
1104       m_ctrl[6].m_vertex = p[2];
1105       m_ctrl[7].m_vertex = p[2];
1106       m_ctrl[8].m_vertex = p[2];
1107     }
1108     break;
1109   case eCapIEndCap:
1110     {
1111       setDims(5, 3);
1112       m_ctrl[0].m_vertex = p[4];
1113       m_ctrl[1].m_vertex = p[3];
1114       m_ctrl[2].m_vertex = p[2];
1115       m_ctrl[3].m_vertex = p[1];
1116       m_ctrl[4].m_vertex = p[0];
1117       m_ctrl[5].m_vertex = p[3];
1118       m_ctrl[6].m_vertex = p[3];
1119       m_ctrl[7].m_vertex = p[2];
1120       m_ctrl[8].m_vertex = p[1];
1121       m_ctrl[9].m_vertex = p[1];
1122       m_ctrl[10].m_vertex = p[3];
1123       m_ctrl[11].m_vertex = p[3];
1124       m_ctrl[12].m_vertex = p[2];
1125       m_ctrl[13].m_vertex = p[1];
1126       m_ctrl[14].m_vertex = p[1];
1127     }
1128     break;
1129   case eCapCylinder:
1130     {
1131       std::size_t mid = (width - 1) >> 1;
1132
1133       bool degenerate = (mid % 2) != 0;
1134
1135       std::size_t newHeight = mid + (degenerate ? 2 : 1);
1136
1137       setDims(3, newHeight);
1138  
1139       if(degenerate)
1140       {
1141         ++mid;
1142         for(std::size_t i = width; i != width + 2; ++i)
1143         {
1144           p[i] = p[width - 1];
1145         }
1146       }
1147
1148       {
1149         PatchControl* pCtrl = m_ctrl.data();
1150         for(std::size_t i = 0; i != m_height; ++i, pCtrl += m_width)
1151         {
1152           pCtrl->m_vertex = p[i];
1153         }
1154       }
1155       {
1156         PatchControl* pCtrl = m_ctrl.data() + 2;
1157         std::size_t h = m_height - 1;
1158         for(std::size_t i = 0; i != m_height; ++i, pCtrl += m_width)
1159         {
1160           pCtrl->m_vertex = p[h + (h - i)];
1161         }
1162       }
1163
1164       Redisperse(COL);
1165     }
1166     break;
1167   default:
1168     ERROR_MESSAGE("invalid patch-cap type");
1169     return;
1170   }
1171   CapTexture();
1172   controlPointsChanged();
1173 }
1174
1175 void Patch::ProjectTexture(int nAxis)
1176 {
1177   undoSave();
1178
1179   int s, t;
1180   
1181   switch (nAxis)
1182   {
1183   case 2:
1184     s = 0;
1185     t = 1;
1186     break;
1187   case 0:
1188     s = 1;
1189     t = 2;
1190     break;
1191   case 1:
1192     s = 0;
1193     t = 2;
1194     break;
1195   default:
1196     ERROR_MESSAGE("invalid axis");
1197     return;
1198   }
1199
1200   float fWidth = 1 / (m_state->getTexture().width * Texdef_getDefaultTextureScale());
1201   float fHeight = 1 / (m_state->getTexture().height * -Texdef_getDefaultTextureScale());
1202
1203   for(PatchControlIter i = m_ctrl.data(); i != m_ctrl.data() + m_ctrl.size(); ++i)
1204   {
1205     (*i).m_texcoord[0] = (*i).m_vertex[s] * fWidth;
1206     (*i).m_texcoord[1] = (*i).m_vertex[t] * fHeight;
1207   }
1208
1209   controlPointsChanged();
1210 }
1211
1212 void Patch::constructPlane(const AABB& aabb, int axis, std::size_t width, std::size_t height)
1213 {
1214   setDims(width, height);
1215
1216   int x, y, z;
1217   switch(axis)
1218   {
1219   case 2: x=0; y=1; z=2; break;
1220   case 1: x=0; y=2; z=1; break;
1221   case 0: x=1; y=2; z=0; break;
1222   default:
1223     ERROR_MESSAGE("invalid view-type");
1224     return;
1225   }
1226   
1227   if(m_width < MIN_PATCH_WIDTH || m_width > MAX_PATCH_WIDTH) m_width = 3;
1228   if(m_height < MIN_PATCH_HEIGHT || m_height > MAX_PATCH_HEIGHT) m_height = 3;
1229   
1230   Vector3 vStart;
1231   vStart[x] = aabb.origin[x] - aabb.extents[x];
1232   vStart[y] = aabb.origin[y] - aabb.extents[y];
1233   vStart[z] = aabb.origin[z];
1234   
1235   float xAdj = fabsf((vStart[x] - (aabb.origin[x] + aabb.extents[x])) / (float)(m_width - 1));
1236   float yAdj = fabsf((vStart[y] - (aabb.origin[y] + aabb.extents[y])) / (float)(m_height - 1));
1237
1238   Vector3 vTmp;
1239   vTmp[z] = vStart[z];
1240   PatchControl* pCtrl = m_ctrl.data();
1241
1242   vTmp[y]=vStart[y];
1243   for (std::size_t h=0; h<m_height; h++)
1244   {
1245     vTmp[x]=vStart[x];
1246     for (std::size_t w=0; w<m_width; w++, ++pCtrl)
1247     {
1248       pCtrl->m_vertex = vTmp;
1249       vTmp[x]+=xAdj;
1250     }
1251     vTmp[y]+=yAdj;
1252   }
1253
1254   NaturalTexture();
1255 }
1256
1257 void Patch::ConstructPrefab(const AABB& aabb, EPatchPrefab eType, int axis, std::size_t width, std::size_t height)
1258 {
1259   Vector3 vPos[3];
1260     
1261   if(eType != ePlane)
1262   {
1263     vPos[0] = vector3_subtracted(aabb.origin, aabb.extents);
1264     vPos[1] = aabb.origin;
1265     vPos[2] = vector3_added(aabb.origin, aabb.extents);
1266   }
1267   
1268   if(eType == ePlane)
1269   {
1270     constructPlane(aabb, axis, width, height);
1271   }
1272   else if(eType == eSqCylinder
1273     || eType == eCylinder
1274     || eType == eDenseCylinder
1275     || eType == eVeryDenseCylinder
1276     || eType == eCone
1277     || eType == eSphere)
1278   {
1279     unsigned char *pIndex;
1280     unsigned char pCylIndex[] =
1281     {
1282       0, 0,
1283       1, 0,
1284       2, 0,
1285       2, 1,
1286       2, 2,
1287       1, 2,
1288       0, 2,
1289       0, 1,
1290       0, 0
1291     };
1292
1293     
1294     PatchControl *pStart;
1295     switch(eType)
1296     {
1297     case eSqCylinder: setDims(9, 3);
1298       pStart = m_ctrl.data();
1299       break;
1300     case eDenseCylinder: 
1301     case eVeryDenseCylinder: 
1302     case eCylinder:
1303       setDims(9, 3);
1304       pStart = m_ctrl.data() + 1;
1305       break;
1306     case eCone: setDims(9, 3);
1307       pStart = m_ctrl.data() + 1;
1308       break;
1309     case eSphere:
1310       setDims(9, 5);
1311       pStart = m_ctrl.data() + (9+1);
1312       break;
1313     default:
1314       ERROR_MESSAGE("this should be unreachable");
1315       return;
1316     }
1317
1318     for(std::size_t h=0; h<3; h++, pStart+=9)
1319     {
1320       pIndex = pCylIndex;
1321       PatchControl* pCtrl = pStart;
1322       for(std::size_t w=0; w<8; w++, pCtrl++)
1323       {
1324         pCtrl->m_vertex[0] = vPos[pIndex[0]][0];
1325         pCtrl->m_vertex[1] = vPos[pIndex[1]][1];
1326         pCtrl->m_vertex[2] = vPos[h][2];
1327         pIndex+=2;
1328       }
1329     }
1330
1331     switch(eType)
1332     {
1333     case eSqCylinder:
1334       {
1335         PatchControl* pCtrl=m_ctrl.data();
1336         for(std::size_t h=0; h<3; h++, pCtrl+=9)
1337         {
1338           pCtrl[8].m_vertex = pCtrl[0].m_vertex;
1339         }
1340       }
1341       break;
1342     case eDenseCylinder:
1343     case eVeryDenseCylinder:
1344     case eCylinder:
1345       {
1346         PatchControl* pCtrl=m_ctrl.data();
1347         for (std::size_t h=0; h<3; h++, pCtrl+=9)
1348         {
1349           pCtrl[0].m_vertex = pCtrl[8].m_vertex;
1350         }
1351       }
1352       break;
1353     case eCone:
1354       {
1355         PatchControl* pCtrl=m_ctrl.data();
1356         for (std::size_t h=0; h<2; h++, pCtrl+=9)
1357         {
1358           pCtrl[0].m_vertex = pCtrl[8].m_vertex;
1359         }
1360       }
1361       {
1362         PatchControl* pCtrl=m_ctrl.data()+9*2;
1363         for (std::size_t w=0; w<9; w++, pCtrl++)
1364         {
1365           pCtrl->m_vertex[0] = vPos[1][0];
1366           pCtrl->m_vertex[1] = vPos[1][1];
1367           pCtrl->m_vertex[2] = vPos[2][2];
1368         }
1369       }
1370       break;
1371     case eSphere:
1372       {
1373         PatchControl* pCtrl=m_ctrl.data()+9;
1374         for (std::size_t h=0; h<3; h++, pCtrl+=9)
1375         {
1376           pCtrl[0].m_vertex = pCtrl[8].m_vertex;
1377         }
1378       }
1379       {
1380         PatchControl* pCtrl = m_ctrl.data();
1381         for (std::size_t w=0; w<9; w++, pCtrl++)
1382         {
1383           pCtrl->m_vertex[0] = vPos[1][0];
1384           pCtrl->m_vertex[1] = vPos[1][1];
1385           pCtrl->m_vertex[2] = vPos[0][2];
1386         }
1387       }
1388       {
1389         PatchControl* pCtrl = m_ctrl.data()+(9*4);
1390         for (std::size_t w=0; w<9; w++, pCtrl++)
1391         {
1392           pCtrl->m_vertex[0] = vPos[1][0];
1393           pCtrl->m_vertex[1] = vPos[1][1];
1394           pCtrl->m_vertex[2] = vPos[2][2];
1395         }
1396       }
1397           break;
1398     default:
1399       ERROR_MESSAGE("this should be unreachable");
1400       return;
1401     }
1402   }
1403   else if  (eType == eBevel)
1404   {
1405     unsigned char *pIndex;
1406     unsigned char pBevIndex[] =
1407     {
1408       0, 0,
1409       2, 0,
1410       2, 2,
1411     };
1412
1413     setDims(3, 3);
1414
1415     PatchControl* pCtrl = m_ctrl.data();
1416     for(std::size_t h=0; h<3; h++)
1417     {
1418       pIndex=pBevIndex;
1419       for(std::size_t w=0; w<3; w++, pIndex+=2, pCtrl++)
1420       {
1421         pCtrl->m_vertex[0] = vPos[pIndex[0]][0];
1422         pCtrl->m_vertex[1] = vPos[pIndex[1]][1];
1423         pCtrl->m_vertex[2] = vPos[h][2];
1424       }
1425     }
1426   }
1427   else if(eType == eEndCap)
1428   {
1429     unsigned char *pIndex;
1430     unsigned char pEndIndex[] =
1431     {
1432       2, 0,
1433       2, 2,
1434       1, 2,
1435       0, 2,
1436       0, 0,
1437     };
1438
1439     setDims(5, 3);
1440
1441     PatchControl* pCtrl = m_ctrl.data();
1442     for(std::size_t h=0; h<3; h++)
1443     {
1444       pIndex=pEndIndex;
1445       for(std::size_t w=0; w<5; w++, pIndex+=2, pCtrl++)
1446       {
1447         pCtrl->m_vertex[0] = vPos[pIndex[0]][0];
1448         pCtrl->m_vertex[1] = vPos[pIndex[1]][1];
1449         pCtrl->m_vertex[2] = vPos[h][2];
1450       }
1451     }
1452   }
1453
1454   if(eType == eDenseCylinder)
1455   {
1456     InsertRemove(true, false, true);
1457   }
1458
1459   if(eType == eVeryDenseCylinder)
1460   {
1461     InsertRemove(true, false, false);
1462     InsertRemove(true, false, true);
1463   }
1464
1465   NaturalTexture();
1466 }
1467
1468 void Patch::RenderDebug(RenderStateFlags state) const
1469 {
1470   for (std::size_t i = 0; i<m_tess.m_numStrips; i++)
1471   {
1472     glBegin(GL_QUAD_STRIP);
1473     for (std::size_t j = 0; j<m_tess.m_lenStrips; j++)
1474     {
1475       glNormal3fv(normal3f_to_array((m_tess.m_vertices.data() + m_tess.m_indices[i*m_tess.m_lenStrips+j])->normal));
1476       glTexCoord2fv(texcoord2f_to_array((m_tess.m_vertices.data() + m_tess.m_indices[i*m_tess.m_lenStrips+j])->texcoord));
1477       glVertex3fv(vertex3f_to_array((m_tess.m_vertices.data() + m_tess.m_indices[i*m_tess.m_lenStrips+j])->vertex));
1478     }
1479     glEnd();
1480   }
1481 }
1482
1483 void RenderablePatchSolid::RenderNormals() const
1484 {
1485   const std::size_t width = m_tess.m_numStrips+1;
1486   const std::size_t height = m_tess.m_lenStrips>>1;
1487   glBegin(GL_LINES);
1488   for(std::size_t i=0;i<width;i++)
1489   {
1490     for(std::size_t j=0;j<height;j++)
1491     {
1492       {
1493         Vector3 vNormal(
1494           vector3_added(
1495             vertex3f_to_vector3((m_tess.m_vertices.data() + (j*width+i))->vertex),
1496             vector3_scaled(normal3f_to_vector3((m_tess.m_vertices.data() + (j*width+i))->normal), 8)
1497           )
1498         );
1499         glVertex3fv(vertex3f_to_array((m_tess.m_vertices.data() + (j*width+i))->vertex));
1500         glVertex3fv(&vNormal[0]);
1501       }
1502       {
1503         Vector3 vNormal(
1504           vector3_added(
1505             vertex3f_to_vector3((m_tess.m_vertices.data() + (j*width+i))->vertex),
1506             vector3_scaled(normal3f_to_vector3((m_tess.m_vertices.data() + (j*width+i))->tangent), 8)
1507           )
1508         );
1509         glVertex3fv(vertex3f_to_array((m_tess.m_vertices.data() + (j*width+i))->vertex));
1510         glVertex3fv(&vNormal[0]);
1511       }
1512       {
1513         Vector3 vNormal(
1514           vector3_added(
1515             vertex3f_to_vector3((m_tess.m_vertices.data() + (j*width+i))->vertex),
1516             vector3_scaled(normal3f_to_vector3((m_tess.m_vertices.data() + (j*width+i))->bitangent), 8)
1517           )
1518         );
1519         glVertex3fv(vertex3f_to_array((m_tess.m_vertices.data() + (j*width+i))->vertex));
1520         glVertex3fv(&vNormal[0]);
1521       }
1522     }
1523   }
1524   glEnd();
1525 }
1526
1527 #define DEGEN_0a  0x01
1528 #define DEGEN_1a  0x02
1529 #define DEGEN_2a  0x04
1530 #define DEGEN_0b  0x08
1531 #define DEGEN_1b  0x10
1532 #define DEGEN_2b  0x20
1533 #define SPLIT     0x40
1534 #define AVERAGE   0x80
1535
1536
1537 unsigned int subarray_get_degen(PatchControlIter subarray, std::size_t strideU, std::size_t strideV)
1538 {
1539   unsigned int nDegen = 0;
1540   const PatchControl* p1;
1541   const PatchControl* p2;
1542
1543   p1 = subarray;
1544   p2 = p1 + strideU;
1545   if(vector3_equal(p1->m_vertex, p2->m_vertex))
1546     nDegen |= DEGEN_0a;
1547   p1 = p2;
1548   p2 = p1 + strideU;
1549   if(vector3_equal(p1->m_vertex, p2->m_vertex))
1550     nDegen |= DEGEN_0b;
1551
1552   p1 = subarray + strideV;
1553   p2 = p1 + strideU;
1554   if(vector3_equal(p1->m_vertex, p2->m_vertex))
1555     nDegen |= DEGEN_1a;
1556   p1 = p2;
1557   p2 = p1 + strideU;
1558   if(vector3_equal(p1->m_vertex, p2->m_vertex))
1559     nDegen |= DEGEN_1b;
1560
1561   p1 = subarray + (strideV << 1);
1562   p2 = p1 + strideU;
1563   if(vector3_equal(p1->m_vertex, p2->m_vertex))
1564     nDegen |= DEGEN_2a;
1565   p1 = p2;
1566   p2 = p1 + strideU;
1567   if(vector3_equal(p1->m_vertex, p2->m_vertex))
1568     nDegen |= DEGEN_2b;
1569
1570   return nDegen;
1571 }
1572
1573
1574 inline void deCasteljau3(const Vector3& P0, const Vector3& P1, const Vector3& P2, Vector3& P01, Vector3& P12, Vector3& P012)
1575 {
1576   P01 = vector3_mid(P0, P1);
1577   P12 = vector3_mid(P1, P2);
1578   P012 = vector3_mid(P01, P12);
1579 }
1580
1581 inline void BezierInterpolate3( const Vector3& start, Vector3& left, Vector3& mid, Vector3& right, const Vector3& end )
1582 {
1583   left = vector3_mid(start, mid);
1584   right = vector3_mid(mid, end);
1585   mid = vector3_mid(left, right);
1586 }
1587
1588 inline void BezierInterpolate2( const Vector2& start, Vector2& left, Vector2& mid, Vector2& right, const Vector2& end )
1589 {
1590   left[0]= float_mid(start[0], mid[0]);
1591   left[1] = float_mid(start[1], mid[1]);
1592   right[0] = float_mid(mid[0], end[0]);
1593   right[1] = float_mid(mid[1], end[1]);
1594   mid[0] = float_mid(left[0], right[0]);
1595   mid[1] = float_mid(left[1], right[1]);
1596 }
1597
1598
1599 inline Vector2& texcoord_for_index(Array<ArbitraryMeshVertex>& vertices, std::size_t index)
1600 {
1601   return reinterpret_cast<Vector2&>(vertices[index].texcoord);
1602 }
1603
1604 inline Vector3& vertex_for_index(Array<ArbitraryMeshVertex>& vertices, std::size_t index)
1605 {
1606   return reinterpret_cast<Vector3&>(vertices[index].vertex);
1607 }
1608
1609 inline Vector3& normal_for_index(Array<ArbitraryMeshVertex>& vertices, std::size_t index)
1610 {
1611   return reinterpret_cast<Vector3&>(vertices[index].normal);
1612 }
1613
1614 inline Vector3& tangent_for_index(Array<ArbitraryMeshVertex>& vertices, std::size_t index)
1615 {
1616   return reinterpret_cast<Vector3&>(vertices[index].tangent);
1617 }
1618
1619 inline Vector3& bitangent_for_index(Array<ArbitraryMeshVertex>& vertices, std::size_t index)
1620 {
1621   return reinterpret_cast<Vector3&>(vertices[index].bitangent);
1622 }
1623
1624 inline const Vector2& texcoord_for_index(const Array<ArbitraryMeshVertex>& vertices, std::size_t index)
1625 {
1626   return reinterpret_cast<const Vector2&>(vertices[index].texcoord);
1627 }
1628
1629 inline const Vector3& vertex_for_index(const Array<ArbitraryMeshVertex>& vertices, std::size_t index)
1630 {
1631   return reinterpret_cast<const Vector3&>(vertices[index].vertex);
1632 }
1633
1634 inline const Vector3& normal_for_index(const Array<ArbitraryMeshVertex>& vertices, std::size_t index)
1635 {
1636   return reinterpret_cast<const Vector3&>(vertices[index].normal);
1637 }
1638
1639 inline const Vector3& tangent_for_index(const Array<ArbitraryMeshVertex>& vertices, std::size_t index)
1640 {
1641   return reinterpret_cast<const Vector3&>(vertices[index].tangent);
1642 }
1643
1644 inline const Vector3& bitangent_for_index(const Array<ArbitraryMeshVertex>& vertices, std::size_t index)
1645 {
1646   return reinterpret_cast<const Vector3&>(vertices[index].bitangent);
1647 }
1648
1649 #include "math/curve.h"
1650
1651 inline PatchControl QuadraticBezier_evaluate(const PatchControl* firstPoint, double t)
1652 {
1653   PatchControl result = { Vector3(0, 0, 0), Vector2(0, 0) };
1654   double denominator = 0;
1655
1656   {
1657     double weight = BernsteinPolynomial<Zero, Two>::apply(t);
1658     vector3_add(result.m_vertex, vector3_scaled(firstPoint[0].m_vertex, weight));
1659     vector2_add(result.m_texcoord, vector2_scaled(firstPoint[0].m_texcoord, weight));
1660     denominator += weight;
1661   }
1662   {
1663     double weight = BernsteinPolynomial<One, Two>::apply(t);
1664     vector3_add(result.m_vertex, vector3_scaled(firstPoint[1].m_vertex, weight));
1665     vector2_add(result.m_texcoord, vector2_scaled(firstPoint[1].m_texcoord, weight));
1666     denominator += weight;
1667   }
1668   {
1669     double weight = BernsteinPolynomial<Two, Two>::apply(t);
1670     vector3_add(result.m_vertex, vector3_scaled(firstPoint[2].m_vertex, weight));
1671     vector2_add(result.m_texcoord, vector2_scaled(firstPoint[2].m_texcoord, weight));
1672     denominator += weight;
1673   }
1674
1675   vector3_divide(result.m_vertex, denominator);
1676   vector2_divide(result.m_texcoord, denominator);
1677   return result;
1678 }
1679
1680 inline Vector3 vector3_linear_interpolated(const Vector3& a, const Vector3& b, double t)
1681 {
1682   return vector3_added(vector3_scaled(a, 1.0 - t), vector3_scaled(b, t));
1683 }
1684
1685 inline Vector2 vector2_linear_interpolated(const Vector2& a, const Vector2& b, double t)
1686 {
1687   return vector2_added(vector2_scaled(a, 1.0 - t), vector2_scaled(b, t));
1688 }
1689
1690 void normalise_safe(Vector3& normal)
1691 {
1692   if(!vector3_equal(normal, g_vector3_identity))
1693   {
1694     vector3_normalise(normal);
1695   }
1696 }
1697
1698 inline void QuadraticBezier_evaluate(const PatchControl& a, const PatchControl& b, const PatchControl& c, double t, PatchControl& point, PatchControl& left, PatchControl& right)
1699 {
1700   left.m_vertex = vector3_linear_interpolated(a.m_vertex, b.m_vertex, t);
1701   left.m_texcoord = vector2_linear_interpolated(a.m_texcoord, b.m_texcoord, t);
1702   right.m_vertex = vector3_linear_interpolated(b.m_vertex, c.m_vertex, t);
1703   right.m_texcoord = vector2_linear_interpolated(b.m_texcoord, c.m_texcoord, t);
1704   point.m_vertex = vector3_linear_interpolated(left.m_vertex, right.m_vertex, t);
1705   point.m_texcoord = vector2_linear_interpolated(left.m_texcoord, right.m_texcoord, t);
1706 }
1707
1708 void Patch::TesselateSubMatrixFixed(ArbitraryMeshVertex* vertices, std::size_t strideX, std::size_t strideY, unsigned int nFlagsX, unsigned int nFlagsY, PatchControl* subMatrix[3][3])
1709 {
1710   double incrementU = 1.0 / m_subdivisions_x;
1711   double incrementV = 1.0 / m_subdivisions_y;
1712   const std::size_t width = m_subdivisions_x + 1;
1713   const std::size_t height = m_subdivisions_y + 1;
1714
1715   for(std::size_t i = 0; i != width; ++i)
1716   {
1717     double tU = (i + 1 == width) ? 1 : i * incrementU;
1718     PatchControl pointX[3];
1719     PatchControl leftX[3];
1720     PatchControl rightX[3];
1721     QuadraticBezier_evaluate(*subMatrix[0][0], *subMatrix[0][1], *subMatrix[0][2], tU, pointX[0], leftX[0], rightX[0]);
1722     QuadraticBezier_evaluate(*subMatrix[1][0], *subMatrix[1][1], *subMatrix[1][2], tU, pointX[1], leftX[1], rightX[1]);
1723     QuadraticBezier_evaluate(*subMatrix[2][0], *subMatrix[2][1], *subMatrix[2][2], tU, pointX[2], leftX[2], rightX[2]);
1724
1725     ArbitraryMeshVertex* p = vertices + i * strideX;
1726     for(std::size_t j = 0; j != height; ++j)
1727     {
1728       if((j == 0 || j + 1 == height) && (i == 0 || i + 1 == width))
1729       {
1730       }
1731       else
1732       {
1733         double tV = (j + 1 == height) ? 1 : j * incrementV;
1734
1735         PatchControl pointY[3];
1736         PatchControl leftY[3];
1737         PatchControl rightY[3];
1738         QuadraticBezier_evaluate(*subMatrix[0][0], *subMatrix[1][0], *subMatrix[2][0], tV, pointY[0], leftY[0], rightY[0]);
1739         QuadraticBezier_evaluate(*subMatrix[0][1], *subMatrix[1][1], *subMatrix[2][1], tV, pointY[1], leftY[1], rightY[1]);
1740         QuadraticBezier_evaluate(*subMatrix[0][2], *subMatrix[1][2], *subMatrix[2][2], tV, pointY[2], leftY[2], rightY[2]);
1741
1742         PatchControl point;
1743         PatchControl left;
1744         PatchControl right;
1745         QuadraticBezier_evaluate(pointX[0], pointX[1], pointX[2], tV, point, left, right);
1746         PatchControl up;
1747         PatchControl down;
1748         QuadraticBezier_evaluate(pointY[0], pointY[1], pointY[2], tU, point, up, down);
1749
1750         vertex3f_to_vector3(p->vertex) = point.m_vertex;
1751         texcoord2f_to_vector2(p->texcoord) = point.m_texcoord;
1752
1753         ArbitraryMeshVertex a, b, c;
1754
1755         a.vertex = vertex3f_for_vector3(left.m_vertex);
1756         a.texcoord = texcoord2f_for_vector2(left.m_texcoord);
1757         b.vertex = vertex3f_for_vector3(right.m_vertex);
1758         b.texcoord = texcoord2f_for_vector2(right.m_texcoord);
1759
1760         if(i != 0)
1761         {
1762           c.vertex = vertex3f_for_vector3(up.m_vertex);
1763           c.texcoord = texcoord2f_for_vector2(up.m_texcoord);
1764         }
1765         else
1766         {
1767           c.vertex = vertex3f_for_vector3(down.m_vertex);
1768           c.texcoord = texcoord2f_for_vector2(down.m_texcoord);
1769         }
1770
1771         Vector3 normal = vector3_normalised(vector3_cross(right.m_vertex - left.m_vertex, up.m_vertex - down.m_vertex));
1772
1773         Vector3 tangent, bitangent;
1774         ArbitraryMeshTriangle_calcTangents(a, b, c, tangent, bitangent);
1775         vector3_normalise(tangent);
1776         vector3_normalise(bitangent);
1777        
1778         if(((nFlagsX & AVERAGE) != 0 && i == 0) || ((nFlagsY & AVERAGE) != 0  && j == 0))
1779         {
1780           normal3f_to_vector3(p->normal) = vector3_normalised(vector3_added(normal3f_to_vector3(p->normal), normal));
1781           normal3f_to_vector3(p->tangent) = vector3_normalised(vector3_added(normal3f_to_vector3(p->tangent), tangent));
1782           normal3f_to_vector3(p->bitangent) = vector3_normalised(vector3_added(normal3f_to_vector3(p->bitangent), bitangent));
1783         }
1784         else
1785         {
1786           normal3f_to_vector3(p->normal) = normal;
1787           normal3f_to_vector3(p->tangent) = tangent;
1788           normal3f_to_vector3(p->bitangent) = bitangent;
1789         }
1790       }
1791
1792       p += strideY;
1793     }
1794   }
1795 }
1796
1797 void Patch::TesselateSubMatrix( const BezierCurveTree *BX, const BezierCurveTree *BY,
1798                                         std::size_t offStartX, std::size_t offStartY,
1799                                         std::size_t offEndX, std::size_t offEndY,
1800                                         std::size_t nFlagsX, std::size_t nFlagsY,
1801                                         Vector3& left, Vector3& mid, Vector3& right,
1802                                         Vector2& texLeft, Vector2& texMid, Vector2& texRight,
1803                                         bool bTranspose )
1804 {
1805   int newFlagsX, newFlagsY;
1806
1807   Vector3 tmp;
1808   Vector3 vertex_0_0, vertex_0_1, vertex_1_0, vertex_1_1, vertex_2_0, vertex_2_1;
1809   Vector2 texTmp;
1810   Vector2 texcoord_0_0, texcoord_0_1, texcoord_1_0, texcoord_1_1, texcoord_2_0, texcoord_2_1;
1811
1812   {
1813    // texcoords
1814
1815     BezierInterpolate2( texcoord_for_index(m_tess.m_vertices, offStartX + offStartY),
1816                      texcoord_0_0,
1817                      texcoord_for_index(m_tess.m_vertices, BX->index + offStartY),
1818                      texcoord_0_1,
1819                      texcoord_for_index(m_tess.m_vertices, offEndX + offStartY) );
1820
1821
1822     BezierInterpolate2( texcoord_for_index(m_tess.m_vertices, offStartX + offEndY),
1823                      texcoord_2_0,
1824                      texcoord_for_index(m_tess.m_vertices, BX->index + offEndY),
1825                      texcoord_2_1,
1826                      texcoord_for_index(m_tess.m_vertices, offEndX + offEndY) );
1827
1828     texTmp = texMid;
1829
1830     BezierInterpolate2(texLeft,
1831                       texcoord_1_0,
1832                       texTmp,
1833                       texcoord_1_1,
1834                       texRight);
1835
1836     if(!BezierCurveTree_isLeaf(BY))
1837     {
1838       texcoord_for_index(m_tess.m_vertices, BX->index + BY->index) = texTmp;
1839     }
1840
1841   
1842     if(!BezierCurveTree_isLeaf(BX->left))
1843     {
1844       texcoord_for_index(m_tess.m_vertices, BX->left->index + offStartY) = texcoord_0_0;
1845       texcoord_for_index(m_tess.m_vertices, BX->left->index + offEndY) = texcoord_2_0;
1846
1847       if(!BezierCurveTree_isLeaf(BY))
1848       {
1849         texcoord_for_index(m_tess.m_vertices, BX->left->index + BY->index) = texcoord_1_0;
1850       }
1851     }
1852     if(!BezierCurveTree_isLeaf(BX->right))
1853     {
1854       texcoord_for_index(m_tess.m_vertices, BX->right->index + offStartY) = texcoord_0_1;
1855       texcoord_for_index(m_tess.m_vertices, BX->right->index + offEndY) = texcoord_2_1;
1856
1857       if(!BezierCurveTree_isLeaf(BY))
1858       {
1859         texcoord_for_index(m_tess.m_vertices, BX->right->index + BY->index) = texcoord_1_1;
1860       }
1861     }
1862
1863
1864     // verts
1865
1866     BezierInterpolate3( vertex_for_index(m_tess.m_vertices, offStartX + offStartY),
1867                      vertex_0_0,
1868                      vertex_for_index(m_tess.m_vertices, BX->index + offStartY),
1869                      vertex_0_1,
1870                      vertex_for_index(m_tess.m_vertices, offEndX + offStartY) );
1871
1872
1873     BezierInterpolate3( vertex_for_index(m_tess.m_vertices, offStartX + offEndY),
1874                      vertex_2_0,
1875                      vertex_for_index(m_tess.m_vertices, BX->index + offEndY),
1876                      vertex_2_1,
1877                      vertex_for_index(m_tess.m_vertices, offEndX + offEndY) );
1878
1879
1880     tmp = mid;
1881
1882     BezierInterpolate3( left,
1883                      vertex_1_0,
1884                      tmp,
1885                      vertex_1_1,
1886                      right );
1887
1888     if(!BezierCurveTree_isLeaf(BY))
1889     {
1890       vertex_for_index(m_tess.m_vertices, BX->index + BY->index) = tmp;
1891     }
1892
1893   
1894     if(!BezierCurveTree_isLeaf(BX->left))
1895     {
1896       vertex_for_index(m_tess.m_vertices, BX->left->index + offStartY) = vertex_0_0;
1897       vertex_for_index(m_tess.m_vertices, BX->left->index + offEndY) = vertex_2_0;
1898
1899       if(!BezierCurveTree_isLeaf(BY))
1900       {
1901         vertex_for_index(m_tess.m_vertices, BX->left->index + BY->index) = vertex_1_0;
1902       }
1903     }
1904     if(!BezierCurveTree_isLeaf(BX->right))
1905     {
1906       vertex_for_index(m_tess.m_vertices, BX->right->index + offStartY) = vertex_0_1;
1907       vertex_for_index(m_tess.m_vertices, BX->right->index + offEndY) = vertex_2_1;
1908
1909       if(!BezierCurveTree_isLeaf(BY))
1910       {
1911         vertex_for_index(m_tess.m_vertices, BX->right->index + BY->index) = vertex_1_1;
1912       }
1913     }
1914
1915     // normals
1916
1917     if(nFlagsX & SPLIT)
1918     {
1919       ArbitraryMeshVertex a, b, c;
1920       Vector3 tangentU;
1921  
1922       if(!(nFlagsX & DEGEN_0a) || !(nFlagsX & DEGEN_0b))
1923       {
1924         tangentU = vector3_subtracted(vertex_0_1, vertex_0_0);
1925         a.vertex = vertex3f_for_vector3(vertex_0_0);
1926         a.texcoord = texcoord2f_for_vector2(texcoord_0_0);
1927         c.vertex = vertex3f_for_vector3(vertex_0_1);
1928         c.texcoord = texcoord2f_for_vector2(texcoord_0_1);
1929       }
1930       else if(!(nFlagsX & DEGEN_1a) || !(nFlagsX & DEGEN_1b))
1931       {
1932         tangentU = vector3_subtracted(vertex_1_1, vertex_1_0);
1933         a.vertex = vertex3f_for_vector3(vertex_1_0);
1934         a.texcoord = texcoord2f_for_vector2(texcoord_1_0);
1935         c.vertex = vertex3f_for_vector3(vertex_1_1);
1936         c.texcoord = texcoord2f_for_vector2(texcoord_1_1);
1937       }
1938       else
1939       {
1940         tangentU = vector3_subtracted(vertex_2_1, vertex_2_0);
1941         a.vertex = vertex3f_for_vector3(vertex_2_0);
1942         a.texcoord = texcoord2f_for_vector2(texcoord_2_0);
1943         c.vertex = vertex3f_for_vector3(vertex_2_1);
1944         c.texcoord = texcoord2f_for_vector2(texcoord_2_1);
1945       }
1946
1947       Vector3 tangentV;
1948
1949       if((nFlagsY & DEGEN_0a) && (nFlagsY & DEGEN_1a) && (nFlagsY & DEGEN_2a))
1950       {
1951         tangentV = vector3_subtracted(vertex_for_index(m_tess.m_vertices, BX->index + offEndY), tmp);
1952         b.vertex = vertex3f_for_vector3(tmp);//m_tess.m_vertices[BX->index + offEndY].vertex;
1953         b.texcoord = texcoord2f_for_vector2(texTmp);//m_tess.m_vertices[BX->index + offEndY].texcoord;
1954       }
1955       else
1956       {
1957         tangentV = vector3_subtracted(tmp, vertex_for_index(m_tess.m_vertices, BX->index + offStartY));
1958         b.vertex = vertex3f_for_vector3(tmp);//m_tess.m_vertices[BX->index + offStartY].vertex;
1959         b.texcoord = texcoord2f_for_vector2(texTmp); //m_tess.m_vertices[BX->index + offStartY].texcoord;
1960       }
1961   
1962
1963       Vector3 normal, s, t;
1964       ArbitraryMeshVertex& v = m_tess.m_vertices[offStartY + BX->index];
1965       Vector3& p = normal3f_to_vector3(v.normal);
1966       Vector3& ps = normal3f_to_vector3(v.tangent);
1967       Vector3& pt = normal3f_to_vector3(v.bitangent);
1968
1969       if(bTranspose)
1970       {
1971         normal = vector3_cross(tangentV, tangentU);
1972       }
1973       else
1974       {
1975         normal = vector3_cross(tangentU, tangentV);
1976       }
1977       normalise_safe(normal);
1978
1979       ArbitraryMeshTriangle_calcTangents(a, b, c, s, t);
1980       normalise_safe(s);
1981       normalise_safe(t);
1982
1983       if(nFlagsX & AVERAGE)
1984       {
1985         p = vector3_normalised(vector3_added(p, normal));
1986         ps = vector3_normalised(vector3_added(ps, s));
1987         pt = vector3_normalised(vector3_added(pt, t));
1988       }
1989       else
1990       {
1991         p = normal;
1992         ps = s;
1993         pt = t;
1994       }
1995     }
1996
1997     {
1998       ArbitraryMeshVertex a, b, c;
1999       Vector3 tangentU;
2000
2001       if(!(nFlagsX & DEGEN_2a) || !(nFlagsX & DEGEN_2b))
2002       {
2003         tangentU = vector3_subtracted(vertex_2_1, vertex_2_0);
2004         a.vertex = vertex3f_for_vector3(vertex_2_0);
2005         a.texcoord = texcoord2f_for_vector2(texcoord_2_0);
2006         c.vertex = vertex3f_for_vector3(vertex_2_1);
2007         c.texcoord = texcoord2f_for_vector2(texcoord_2_1);
2008       }
2009       else if(!(nFlagsX & DEGEN_1a) || !(nFlagsX & DEGEN_1b))
2010       {
2011         tangentU = vector3_subtracted(vertex_1_1, vertex_1_0);
2012         a.vertex = vertex3f_for_vector3(vertex_1_0);
2013         a.texcoord = texcoord2f_for_vector2(texcoord_1_0);
2014         c.vertex = vertex3f_for_vector3(vertex_1_1);
2015         c.texcoord = texcoord2f_for_vector2(texcoord_1_1);
2016       }
2017       else
2018       {
2019         tangentU = vector3_subtracted(vertex_0_1, vertex_0_0);
2020         a.vertex = vertex3f_for_vector3(vertex_0_0);
2021         a.texcoord = texcoord2f_for_vector2(texcoord_0_0);
2022         c.vertex = vertex3f_for_vector3(vertex_0_1);
2023         c.texcoord = texcoord2f_for_vector2(texcoord_0_1);
2024       }
2025
2026       Vector3 tangentV;
2027
2028       if((nFlagsY & DEGEN_0b) && (nFlagsY & DEGEN_1b) && (nFlagsY & DEGEN_2b))
2029       {
2030         tangentV = vector3_subtracted(tmp, vertex_for_index(m_tess.m_vertices, BX->index + offStartY));
2031         b.vertex = vertex3f_for_vector3(tmp);//m_tess.m_vertices[BX->index + offStartY].vertex;
2032         b.texcoord = texcoord2f_for_vector2(texTmp);//m_tess.m_vertices[BX->index + offStartY].texcoord;
2033       }
2034       else
2035       {
2036         tangentV = vector3_subtracted(vertex_for_index(m_tess.m_vertices, BX->index + offEndY), tmp);
2037         b.vertex = vertex3f_for_vector3(tmp);//m_tess.m_vertices[BX->index + offEndY].vertex;
2038         b.texcoord = texcoord2f_for_vector2(texTmp);//m_tess.m_vertices[BX->index + offEndY].texcoord;
2039       }
2040
2041       ArbitraryMeshVertex& v = m_tess.m_vertices[offEndY+BX->index];
2042       Vector3& p = normal3f_to_vector3(v.normal);
2043       Vector3& ps = normal3f_to_vector3(v.tangent);
2044       Vector3& pt = normal3f_to_vector3(v.bitangent);
2045
2046       if(bTranspose)
2047       {
2048         p = vector3_cross(tangentV, tangentU);
2049       }
2050       else
2051       {
2052         p = vector3_cross(tangentU, tangentV);
2053       }
2054       normalise_safe(p);
2055
2056       ArbitraryMeshTriangle_calcTangents(a, b, c, ps, pt);
2057       normalise_safe(ps);
2058       normalise_safe(pt);
2059     }
2060   }
2061
2062   
2063   newFlagsX = newFlagsY = 0;
2064
2065   if((nFlagsX & DEGEN_0a) && (nFlagsX & DEGEN_0b))
2066   {
2067     newFlagsX |= DEGEN_0a;
2068     newFlagsX |= DEGEN_0b;
2069   }
2070   if((nFlagsX & DEGEN_1a) && (nFlagsX & DEGEN_1b))
2071   {
2072     newFlagsX |= DEGEN_1a;
2073     newFlagsX |= DEGEN_1b;
2074   }
2075   if((nFlagsX & DEGEN_2a) && (nFlagsX & DEGEN_2b))
2076   {
2077     newFlagsX |= DEGEN_2a;
2078     newFlagsX |= DEGEN_2b;
2079   }
2080   if((nFlagsY & DEGEN_0a) && (nFlagsY & DEGEN_1a) && (nFlagsY & DEGEN_2a))
2081   {
2082     newFlagsY |= DEGEN_0a;
2083     newFlagsY |= DEGEN_1a;
2084     newFlagsY |= DEGEN_2a;
2085   }
2086   if((nFlagsY & DEGEN_0b) && (nFlagsY & DEGEN_1b) && (nFlagsY & DEGEN_2b))
2087   {
2088     newFlagsY |= DEGEN_0b;
2089     newFlagsY |= DEGEN_1b;
2090     newFlagsY |= DEGEN_2b;
2091   }
2092
2093   
2094   //if((nFlagsX & DEGEN_0a) && (nFlagsX & DEGEN_1a) && (nFlagsX & DEGEN_2a)) { newFlagsX |= DEGEN_0a; newFlagsX |= DEGEN_1a; newFlagsX |= DEGEN_2a; }
2095   //if((nFlagsX & DEGEN_0b) && (nFlagsX & DEGEN_1b) && (nFlagsX & DEGEN_2b)) { newFlagsX |= DEGEN_0b; newFlagsX |= DEGEN_1b; newFlagsX |= DEGEN_2b; }
2096   
2097   newFlagsX |= (nFlagsX & SPLIT);
2098   newFlagsX |= (nFlagsX & AVERAGE);
2099       
2100   if(!BezierCurveTree_isLeaf(BY))
2101   {
2102     {
2103       int nTemp = newFlagsY;
2104
2105       if((nFlagsY & DEGEN_0a) && (nFlagsY & DEGEN_0b))
2106       {
2107         newFlagsY |= DEGEN_0a;
2108         newFlagsY |= DEGEN_0b;
2109       }
2110       newFlagsY |= (nFlagsY & SPLIT);
2111       newFlagsY |= (nFlagsY & AVERAGE);
2112
2113       Vector3& p = vertex_for_index(m_tess.m_vertices, BX->index+BY->index);
2114       Vector3 vTemp(p);
2115
2116       Vector2& p2 = texcoord_for_index(m_tess.m_vertices, BX->index+BY->index);
2117       Vector2 stTemp(p2);
2118
2119       TesselateSubMatrix( BY, BX->left,
2120                           offStartY, offStartX,
2121                           offEndY, BX->index,
2122                           newFlagsY, newFlagsX,
2123                           vertex_0_0, vertex_1_0, vertex_2_0,
2124                           texcoord_0_0, texcoord_1_0, texcoord_2_0,
2125                           !bTranspose );
2126
2127       newFlagsY = nTemp;
2128       p = vTemp;
2129       p2 = stTemp;
2130     }
2131
2132     if((nFlagsY & DEGEN_2a) && (nFlagsY & DEGEN_2b)) { newFlagsY |= DEGEN_2a; newFlagsY |= DEGEN_2b; }
2133     
2134     TesselateSubMatrix( BY, BX->right,
2135                         offStartY, BX->index,
2136                         offEndY, offEndX,
2137                         newFlagsY, newFlagsX,
2138                         vertex_0_1, vertex_1_1, vertex_2_1,
2139                         texcoord_0_1, texcoord_1_1, texcoord_2_1,
2140                         !bTranspose );
2141   }
2142   else
2143   {
2144     if(!BezierCurveTree_isLeaf(BX->left))
2145     {
2146       TesselateSubMatrix( BX->left,  BY,
2147                           offStartX, offStartY,
2148                           BX->index, offEndY,
2149                           newFlagsX, newFlagsY,
2150                           left, vertex_1_0, tmp,
2151                           texLeft, texcoord_1_0, texTmp,
2152                           bTranspose );
2153     }
2154
2155     if(!BezierCurveTree_isLeaf(BX->right))
2156     {
2157       TesselateSubMatrix( BX->right, BY,
2158                           BX->index, offStartY,
2159                           offEndX, offEndY,
2160                           newFlagsX, newFlagsY,
2161                           tmp, vertex_1_1, right,
2162                           texTmp, texcoord_1_1, texRight,
2163                           bTranspose );
2164     }
2165   }
2166
2167 }
2168
2169 void Patch::BuildTesselationCurves(EMatrixMajor major)
2170 {
2171   std::size_t nArrayStride, length, cross, strideU, strideV;
2172   switch(major)
2173   {
2174   case ROW:
2175     nArrayStride = 1;
2176     length = (m_width - 1) >> 1;
2177     cross = m_height;
2178     strideU = 1;
2179     strideV = m_width;
2180
2181     if(!m_patchDef3)
2182     {
2183       BezierCurveTreeArray_deleteAll(m_tess.m_curveTreeU);
2184     }
2185
2186     break;
2187   case COL:
2188     nArrayStride = m_tess.m_nArrayWidth;
2189     length = (m_height - 1) >> 1;
2190     cross = m_width;
2191     strideU = m_width;
2192     strideV = 1;
2193
2194     if(!m_patchDef3)
2195     {
2196       BezierCurveTreeArray_deleteAll(m_tess.m_curveTreeV);
2197     }
2198
2199     break;
2200   default:
2201     ERROR_MESSAGE("neither row-major nor column-major");
2202     return;
2203   }
2204
2205   Array<std::size_t> arrayLength(length);
2206   Array<BezierCurveTree*> pCurveTree(length);
2207
2208   std::size_t nArrayLength = 1;
2209
2210   if(m_patchDef3)
2211   {
2212     for(Array<std::size_t>::iterator i = arrayLength.begin(); i != arrayLength.end(); ++i)
2213     {
2214       *i = Array<std::size_t>::value_type((major == ROW) ? m_subdivisions_x : m_subdivisions_y);
2215       nArrayLength += *i;
2216     }
2217   }
2218   else
2219   {
2220     // create a list of the horizontal control curves in each column of sub-patches
2221     // adaptively tesselate each horizontal control curve in the list
2222     // create a binary tree representing the combined tesselation of the list
2223     for(std::size_t i = 0; i != length; ++i)
2224     {
2225       PatchControl* p1 = m_ctrlTransformed.data() + (i * 2 * strideU);
2226       GSList* pCurveList = 0;
2227       for(std::size_t j = 0; j < cross; j += 2)
2228       {
2229         PatchControl* p2 = p1+strideV;
2230         PatchControl* p3 = p2+strideV;
2231
2232         // directly taken from one row of control points
2233         {
2234           BezierCurve* pCurve = new BezierCurve;
2235           pCurve->crd = (p1+strideU)->m_vertex;
2236           pCurve->left = p1->m_vertex;
2237           pCurve->right = (p1+(strideU<<1))->m_vertex;
2238           pCurveList = g_slist_prepend(pCurveList, pCurve);
2239         }
2240
2241         if(j+2 >= cross)
2242         {
2243           break;
2244         }
2245         
2246         // interpolated from three columns of control points
2247         {
2248           BezierCurve* pCurve = new BezierCurve;
2249           pCurve->crd = vector3_mid((p1+strideU)->m_vertex, (p3+strideU)->m_vertex);
2250           pCurve->left = vector3_mid(p1->m_vertex, p3->m_vertex);
2251           pCurve->right = vector3_mid((p1+(strideU<<1))->m_vertex, (p3+(strideU<<1))->m_vertex);
2252     
2253           pCurve->crd = vector3_mid(pCurve->crd, (p2+strideU)->m_vertex);
2254           pCurve->left = vector3_mid(pCurve->left, p2->m_vertex);
2255           pCurve->right = vector3_mid(pCurve->right, (p2+(strideU<<1))->m_vertex);
2256           pCurveList = g_slist_prepend(pCurveList, pCurve);
2257         }
2258
2259         p1 = p3;
2260       }
2261
2262       pCurveTree[i] = new BezierCurveTree;
2263       BezierCurveTree_FromCurveList(pCurveTree[i], pCurveList);
2264       for(GSList* l = pCurveList; l != 0; l = g_slist_next(l))
2265       {
2266         delete static_cast<BezierCurve*>((*l).data);
2267       }
2268       g_slist_free(pCurveList);
2269
2270       // set up array indices for binary tree
2271       // accumulate subarray width
2272       arrayLength[i] = Array<std::size_t>::value_type(BezierCurveTree_Setup(pCurveTree[i], nArrayLength, nArrayStride) - (nArrayLength - 1));
2273       // accumulate total array width
2274       nArrayLength += arrayLength[i];
2275     }
2276   }
2277
2278   switch(major)
2279   {
2280   case ROW:
2281     m_tess.m_nArrayWidth = nArrayLength;
2282     std::swap(m_tess.m_arrayWidth, arrayLength);
2283
2284     if(!m_patchDef3)
2285     {
2286       std::swap(m_tess.m_curveTreeU, pCurveTree);
2287     }
2288     break;
2289   case COL:
2290     m_tess.m_nArrayHeight = nArrayLength;
2291     std::swap(m_tess.m_arrayHeight, arrayLength);
2292
2293     if(!m_patchDef3)
2294     {
2295       std::swap(m_tess.m_curveTreeV, pCurveTree);
2296     }
2297     break;
2298   }
2299 }
2300
2301 inline void vertex_assign_ctrl(ArbitraryMeshVertex& vertex, const PatchControl& ctrl)
2302 {
2303   vertex.vertex = vertex3f_for_vector3(ctrl.m_vertex);
2304   vertex.texcoord = texcoord2f_for_vector2(ctrl.m_texcoord);
2305 }
2306
2307 inline void vertex_clear_normal(ArbitraryMeshVertex& vertex)
2308 {
2309   vertex.normal = Normal3f(0, 0, 0);
2310   vertex.tangent = Normal3f(0, 0, 0);
2311   vertex.bitangent = Normal3f(0, 0, 0);
2312 }
2313       
2314 inline void tangents_remove_degenerate(Vector3 tangents[6], Vector2 textureTangents[6], unsigned int flags)
2315 {
2316   if(flags & DEGEN_0a)
2317   {
2318     const std::size_t i =
2319       (flags & DEGEN_0b)
2320       ? (flags & DEGEN_1a)
2321         ? (flags & DEGEN_1b)
2322           ? (flags & DEGEN_2a)
2323             ? 5
2324             : 4
2325           : 3
2326         : 2
2327       : 1;
2328     tangents[0] = tangents[i];
2329     textureTangents[0] = textureTangents[i];
2330   }
2331   if(flags & DEGEN_0b)
2332   {
2333     const std::size_t i =
2334       (flags & DEGEN_0a)
2335       ? (flags & DEGEN_1b)
2336         ? (flags & DEGEN_1a)
2337           ? (flags & DEGEN_2b)
2338             ? 4
2339             : 5
2340           : 2
2341         : 3
2342       : 0;
2343     tangents[1] = tangents[i];
2344     textureTangents[1] = textureTangents[i];
2345   }
2346   if(flags & DEGEN_2a)
2347   {
2348     const std::size_t i =
2349       (flags & DEGEN_2b)
2350       ? (flags & DEGEN_1a)
2351         ? (flags & DEGEN_1b)
2352           ? (flags & DEGEN_0a)
2353             ? 1
2354             : 0
2355           : 3
2356         : 2
2357       : 5;
2358     tangents[4] = tangents[i];
2359     textureTangents[4] = textureTangents[i];
2360   }
2361   if(flags & DEGEN_2b)
2362   {
2363     const std::size_t i =
2364       (flags & DEGEN_2a)
2365       ? (flags & DEGEN_1b)
2366         ? (flags & DEGEN_1a)
2367           ? (flags & DEGEN_0b)
2368             ? 0
2369             : 1
2370           : 2
2371         : 3
2372       : 4;
2373     tangents[5] = tangents[i];
2374     textureTangents[5] = textureTangents[i];
2375   }
2376 }
2377
2378 void bestTangents00(unsigned int degenerateFlags, double dot, double length, std::size_t& index0, std::size_t& index1)
2379 {
2380   if(fabs(dot + length) < 0.001) // opposing direction = degenerate
2381   {
2382     if(!(degenerateFlags & DEGEN_1a)) // if this tangent is degenerate we cannot use it
2383     {
2384       index0 = 2;
2385       index1 = 0;
2386     }
2387     else if(!(degenerateFlags & DEGEN_0b))
2388     {
2389       index0 = 0;
2390       index1 = 1;
2391     }
2392     else
2393     {
2394       index0 = 1;
2395       index1 = 0;
2396     }
2397   }
2398   else if(fabs(dot - length) < 0.001) // same direction = degenerate
2399   {
2400     if(degenerateFlags & DEGEN_0b)
2401     {
2402       index0 = 0;
2403       index1 = 1;
2404     }
2405     else
2406     {
2407       index0 = 1;
2408       index1 = 0;
2409     }
2410   }
2411 }
2412
2413 void bestTangents01(unsigned int degenerateFlags, double dot, double length, std::size_t& index0, std::size_t& index1)
2414 {
2415   if(fabs(dot - length) < 0.001) // same direction = degenerate
2416   {
2417     if(!(degenerateFlags & DEGEN_1a)) // if this tangent is degenerate we cannot use it
2418     {
2419       index0 = 2;
2420       index1 = 1;
2421     }
2422     else if(!(degenerateFlags & DEGEN_2b))
2423     {
2424       index0 = 4;
2425       index1 = 0;
2426     }
2427     else
2428     {
2429       index0 = 5;
2430       index1 = 1;
2431     }
2432   }
2433   else if(fabs(dot + length) < 0.001) // opposing direction = degenerate
2434   {
2435     if(degenerateFlags & DEGEN_2b)
2436     {
2437       index0 = 4;
2438       index1 = 0;
2439     }
2440     else
2441     {
2442       index0 = 5;
2443       index1 = 1;
2444     }
2445   }
2446 }
2447  
2448 void bestTangents10(unsigned int degenerateFlags, double dot, double length, std::size_t& index0, std::size_t& index1)
2449 {
2450   if(fabs(dot - length) < 0.001) // same direction = degenerate
2451   {
2452     if(!(degenerateFlags & DEGEN_1b)) // if this tangent is degenerate we cannot use it
2453     {
2454       index0 = 3;
2455       index1 = 4;
2456     }
2457     else if(!(degenerateFlags & DEGEN_0a))
2458     {
2459       index0 = 1;
2460       index1 = 5;
2461     }
2462     else
2463     {
2464       index0 = 0;
2465       index1 = 4;
2466     }
2467   }
2468   else if(fabs(dot + length) < 0.001) // opposing direction = degenerate
2469   {
2470     if(degenerateFlags & DEGEN_0a)
2471     {
2472       index0 = 1;
2473       index1 = 5;
2474     }
2475     else
2476     {
2477       index0 = 0;
2478       index1 = 4;
2479     }
2480   }
2481 }
2482
2483 void bestTangents11(unsigned int degenerateFlags, double dot, double length, std::size_t& index0, std::size_t& index1)
2484 {
2485   if(fabs(dot + length) < 0.001) // opposing direction = degenerate
2486   {
2487     if(!(degenerateFlags & DEGEN_1b)) // if this tangent is degenerate we cannot use it
2488     {
2489       index0 = 3;
2490       index1 = 5;
2491     }
2492     else if(!(degenerateFlags & DEGEN_2a))
2493     {
2494       index0 = 5;
2495       index1 = 4;
2496     }
2497     else
2498     {
2499       index0 = 4;
2500       index1 = 5;
2501     }
2502   }
2503   else if(fabs(dot - length) < 0.001) // same direction = degenerate
2504   {
2505     if(degenerateFlags & DEGEN_2a)
2506     {
2507       index0 = 5;
2508       index1 = 4;
2509     }
2510     else
2511     {
2512       index0 = 4;
2513       index1 = 5;
2514     }
2515   }
2516 }
2517
2518 void Patch::accumulateVertexTangentSpace(std::size_t index, Vector3 tangentX[6], Vector3 tangentY[6], Vector2 tangentS[6], Vector2 tangentT[6], std::size_t index0, std::size_t index1)
2519 {
2520   {
2521     Vector3 normal(vector3_cross(tangentX[index0], tangentY[index1]));
2522     if(!vector3_equal(normal, g_vector3_identity))
2523     {
2524       vector3_add(normal_for_index(m_tess.m_vertices, index), vector3_normalised(normal));
2525     }
2526   }
2527
2528   {
2529     ArbitraryMeshVertex a, b, c;
2530     a.vertex = Vertex3f(0, 0, 0);
2531     a.texcoord = TexCoord2f(0, 0);
2532     b.vertex = vertex3f_for_vector3(tangentX[index0]);
2533     b.texcoord = texcoord2f_for_vector2(tangentS[index0]);
2534     c.vertex = vertex3f_for_vector3(tangentY[index1]);
2535     c.texcoord = texcoord2f_for_vector2(tangentT[index1]);
2536
2537     Vector3 s, t;
2538     ArbitraryMeshTriangle_calcTangents(a, b, c, s, t);
2539     if(!vector3_equal(s, g_vector3_identity))
2540     {
2541       vector3_add(tangent_for_index(m_tess.m_vertices, index), vector3_normalised(s));
2542     }
2543     if(!vector3_equal(t, g_vector3_identity))
2544     {
2545       vector3_add(bitangent_for_index(m_tess.m_vertices, index), vector3_normalised(t));
2546     }
2547   }
2548 }
2549
2550 const std::size_t PATCH_MAX_VERTEX_ARRAY = 1048576;
2551
2552 void Patch::BuildVertexArray()
2553 {
2554   const std::size_t strideU = 1;
2555   const std::size_t strideV = m_width;
2556
2557   const std::size_t numElems = m_tess.m_nArrayWidth*m_tess.m_nArrayHeight; // total number of elements in vertex array
2558
2559   const bool bWidthStrips = (m_tess.m_nArrayWidth >= m_tess.m_nArrayHeight); // decide if horizontal strips are longer than vertical
2560
2561
2562   // allocate vertex, normal, texcoord and primitive-index arrays
2563   m_tess.m_vertices.resize(numElems);
2564   m_tess.m_indices.resize(m_tess.m_nArrayWidth *2 * (m_tess.m_nArrayHeight - 1));
2565
2566   // set up strip indices
2567   if(bWidthStrips)
2568   {
2569     m_tess.m_numStrips = m_tess.m_nArrayHeight-1;
2570     m_tess.m_lenStrips = m_tess.m_nArrayWidth*2;
2571   
2572     for(std::size_t i=0; i<m_tess.m_nArrayWidth; i++)
2573     {
2574       for(std::size_t j=0; j<m_tess.m_numStrips; j++)
2575       {
2576         m_tess.m_indices[(j*m_tess.m_lenStrips)+i*2] = RenderIndex(j*m_tess.m_nArrayWidth+i);
2577         m_tess.m_indices[(j*m_tess.m_lenStrips)+i*2+1] = RenderIndex((j+1)*m_tess.m_nArrayWidth+i);
2578         // reverse because radiant uses CULL_FRONT
2579         //m_tess.m_indices[(j*m_tess.m_lenStrips)+i*2+1] = RenderIndex(j*m_tess.m_nArrayWidth+i);
2580         //m_tess.m_indices[(j*m_tess.m_lenStrips)+i*2] = RenderIndex((j+1)*m_tess.m_nArrayWidth+i);
2581       }
2582     }
2583   }
2584   else
2585   {
2586     m_tess.m_numStrips = m_tess.m_nArrayWidth-1;
2587     m_tess.m_lenStrips = m_tess.m_nArrayHeight*2;
2588
2589     for(std::size_t i=0; i<m_tess.m_nArrayHeight; i++)
2590     {
2591       for(std::size_t j=0; j<m_tess.m_numStrips; j++)
2592       {
2593         m_tess.m_indices[(j*m_tess.m_lenStrips)+i*2] = RenderIndex(((m_tess.m_nArrayHeight-1)-i)*m_tess.m_nArrayWidth+j);
2594         m_tess.m_indices[(j*m_tess.m_lenStrips)+i*2+1] = RenderIndex(((m_tess.m_nArrayHeight-1)-i)*m_tess.m_nArrayWidth+j+1);
2595         // reverse because radiant uses CULL_FRONT
2596         //m_tess.m_indices[(j*m_tess.m_lenStrips)+i*2+1] = RenderIndex(((m_tess.m_nArrayHeight-1)-i)*m_tess.m_nArrayWidth+j);
2597         //m_tess.m_indices[(j*m_tess.m_lenStrips)+i*2] = RenderIndex(((m_tess.m_nArrayHeight-1)-i)*m_tess.m_nArrayWidth+j+1);
2598         
2599       }
2600     }
2601   }
2602
2603   {
2604     PatchControlIter pCtrl = m_ctrlTransformed.data();
2605     for(std::size_t j = 0, offStartY = 0; j+1 < m_height; j += 2, pCtrl += (strideU + strideV))
2606     {
2607       // set up array offsets for this sub-patch
2608       const bool leafY = (m_patchDef3) ? false : BezierCurveTree_isLeaf(m_tess.m_curveTreeV[j>>1]);
2609       const std::size_t offMidY = (m_patchDef3) ? 0 : m_tess.m_curveTreeV[j>>1]->index;
2610       const std::size_t widthY = m_tess.m_arrayHeight[j>>1] * m_tess.m_nArrayWidth;
2611       const std::size_t offEndY = offStartY + widthY;
2612
2613       for(std::size_t i = 0, offStartX = 0; i+1 < m_width; i += 2, pCtrl += (strideU << 1))
2614       {
2615         const bool leafX = (m_patchDef3) ? false : BezierCurveTree_isLeaf(m_tess.m_curveTreeU[i>>1]);
2616         const std::size_t offMidX = (m_patchDef3) ? 0 : m_tess.m_curveTreeU[i>>1]->index;
2617         const std::size_t widthX = m_tess.m_arrayWidth[i>>1];
2618         const std::size_t offEndX = offStartX + widthX;
2619
2620         PatchControl *subMatrix[3][3];
2621         subMatrix[0][0] = pCtrl;
2622         subMatrix[0][1] = subMatrix[0][0]+strideU;
2623         subMatrix[0][2] = subMatrix[0][1]+strideU;
2624         subMatrix[1][0] = subMatrix[0][0]+strideV;
2625         subMatrix[1][1] = subMatrix[1][0]+strideU;
2626         subMatrix[1][2] = subMatrix[1][1]+strideU;
2627         subMatrix[2][0] = subMatrix[1][0]+strideV;
2628         subMatrix[2][1] = subMatrix[2][0]+strideU;
2629         subMatrix[2][2] = subMatrix[2][1]+strideU;
2630
2631         // assign on-patch control points to vertex array
2632         if(i == 0 && j == 0)
2633         {
2634           vertex_clear_normal(m_tess.m_vertices[offStartX + offStartY]);
2635         }
2636         vertex_assign_ctrl(m_tess.m_vertices[offStartX + offStartY], *subMatrix[0][0]);
2637         if(j == 0)
2638         {
2639           vertex_clear_normal(m_tess.m_vertices[offEndX + offStartY]);
2640         }
2641         vertex_assign_ctrl(m_tess.m_vertices[offEndX + offStartY], *subMatrix[0][2]);
2642         if(i == 0)
2643         {
2644           vertex_clear_normal(m_tess.m_vertices[offStartX + offEndY]);
2645         }
2646         vertex_assign_ctrl(m_tess.m_vertices[offStartX + offEndY], *subMatrix[2][0]);
2647       
2648         vertex_clear_normal(m_tess.m_vertices[offEndX + offEndY]);
2649         vertex_assign_ctrl(m_tess.m_vertices[offEndX + offEndY], *subMatrix[2][2]);
2650
2651         if(!m_patchDef3)
2652         {
2653           // assign remaining control points to vertex array
2654           if(!leafX)
2655           {
2656             vertex_assign_ctrl(m_tess.m_vertices[offMidX + offStartY], *subMatrix[0][1]);
2657             vertex_assign_ctrl(m_tess.m_vertices[offMidX + offEndY], *subMatrix[2][1]);
2658           }
2659           if(!leafY)
2660           {
2661             vertex_assign_ctrl(m_tess.m_vertices[offStartX + offMidY], *subMatrix[1][0]);
2662             vertex_assign_ctrl(m_tess.m_vertices[offEndX + offMidY], *subMatrix[1][2]);
2663
2664             if(!leafX)
2665             {
2666               vertex_assign_ctrl(m_tess.m_vertices[offMidX + offMidY], *subMatrix[1][1]);
2667             }
2668           }
2669         }
2670
2671         // test all 12 edges for degeneracy
2672         unsigned int nFlagsX = subarray_get_degen(pCtrl, strideU, strideV);
2673         unsigned int nFlagsY = subarray_get_degen(pCtrl, strideV, strideU);
2674         Vector3 tangentX[6], tangentY[6];
2675         Vector2 tangentS[6], tangentT[6];
2676
2677         // set up tangents for each of the 12 edges if they were not degenerate
2678         if(!(nFlagsX & DEGEN_0a))
2679         {
2680           tangentX[0] = vector3_subtracted(subMatrix[0][1]->m_vertex, subMatrix[0][0]->m_vertex);
2681           tangentS[0] = vector2_subtracted(subMatrix[0][1]->m_texcoord, subMatrix[0][0]->m_texcoord);
2682         }
2683         if(!(nFlagsX & DEGEN_0b))
2684         {
2685           tangentX[1] = vector3_subtracted(subMatrix[0][2]->m_vertex, subMatrix[0][1]->m_vertex);
2686           tangentS[1] = vector2_subtracted(subMatrix[0][2]->m_texcoord, subMatrix[0][1]->m_texcoord);
2687         }
2688         if(!(nFlagsX & DEGEN_1a))
2689         {
2690           tangentX[2] = vector3_subtracted(subMatrix[1][1]->m_vertex, subMatrix[1][0]->m_vertex);
2691           tangentS[2] = vector2_subtracted(subMatrix[1][1]->m_texcoord, subMatrix[1][0]->m_texcoord);
2692         }
2693         if(!(nFlagsX & DEGEN_1b))
2694         {
2695           tangentX[3] = vector3_subtracted(subMatrix[1][2]->m_vertex, subMatrix[1][1]->m_vertex);
2696           tangentS[3] = vector2_subtracted(subMatrix[1][2]->m_texcoord, subMatrix[1][1]->m_texcoord);
2697         }
2698         if(!(nFlagsX & DEGEN_2a))
2699         {
2700           tangentX[4] = vector3_subtracted(subMatrix[2][1]->m_vertex, subMatrix[2][0]->m_vertex);
2701           tangentS[4] = vector2_subtracted(subMatrix[2][1]->m_texcoord, subMatrix[2][0]->m_texcoord);
2702         }
2703         if(!(nFlagsX & DEGEN_2b))
2704         {
2705           tangentX[5] = vector3_subtracted(subMatrix[2][2]->m_vertex, subMatrix[2][1]->m_vertex);
2706           tangentS[5] = vector2_subtracted(subMatrix[2][2]->m_texcoord, subMatrix[2][1]->m_texcoord);
2707         }
2708
2709         if(!(nFlagsY & DEGEN_0a))
2710         {
2711           tangentY[0] = vector3_subtracted(subMatrix[1][0]->m_vertex, subMatrix[0][0]->m_vertex);
2712           tangentT[0] = vector2_subtracted(subMatrix[1][0]->m_texcoord, subMatrix[0][0]->m_texcoord);
2713         }
2714         if(!(nFlagsY & DEGEN_0b))
2715         {
2716           tangentY[1] = vector3_subtracted(subMatrix[2][0]->m_vertex, subMatrix[1][0]->m_vertex);
2717           tangentT[1] = vector2_subtracted(subMatrix[2][0]->m_texcoord, subMatrix[1][0]->m_texcoord);
2718         }
2719         if(!(nFlagsY & DEGEN_1a))
2720         {
2721           tangentY[2] = vector3_subtracted(subMatrix[1][1]->m_vertex, subMatrix[0][1]->m_vertex);
2722           tangentT[2] = vector2_subtracted(subMatrix[1][1]->m_texcoord, subMatrix[0][1]->m_texcoord);
2723         }
2724         if(!(nFlagsY & DEGEN_1b))
2725         {
2726           tangentY[3] = vector3_subtracted(subMatrix[2][1]->m_vertex, subMatrix[1][1]->m_vertex);
2727           tangentT[3] = vector2_subtracted(subMatrix[2][1]->m_texcoord, subMatrix[1][1]->m_texcoord);
2728         }
2729         if(!(nFlagsY & DEGEN_2a))
2730         {
2731           tangentY[4] = vector3_subtracted(subMatrix[1][2]->m_vertex, subMatrix[0][2]->m_vertex);
2732           tangentT[4] = vector2_subtracted(subMatrix[1][2]->m_texcoord, subMatrix[0][2]->m_texcoord);
2733         }
2734         if(!(nFlagsY & DEGEN_2b))
2735         {
2736           tangentY[5] = vector3_subtracted(subMatrix[2][2]->m_vertex, subMatrix[1][2]->m_vertex);
2737           tangentT[5] = vector2_subtracted(subMatrix[2][2]->m_texcoord, subMatrix[1][2]->m_texcoord);
2738         }
2739
2740         // set up remaining edge tangents by borrowing the tangent from the closest parallel non-degenerate edge
2741         tangents_remove_degenerate(tangentX, tangentS, nFlagsX);
2742         tangents_remove_degenerate(tangentY, tangentT, nFlagsY);
2743
2744         {
2745           // x=0, y=0
2746           std::size_t index = offStartX + offStartY;
2747           std::size_t index0 = 0;
2748           std::size_t index1 = 0;
2749
2750           double dot = vector3_dot(tangentX[index0], tangentY[index1]);
2751           double length = vector3_length(tangentX[index0]) * vector3_length(tangentY[index1]);
2752
2753           bestTangents00(nFlagsX, dot, length, index0, index1);
2754
2755           accumulateVertexTangentSpace(index, tangentX, tangentY, tangentS, tangentT, index0, index1);
2756         }
2757
2758         {
2759           // x=1, y=0
2760           std::size_t index = offEndX + offStartY;
2761           std::size_t index0 = 1;
2762           std::size_t index1 = 4;
2763
2764           double dot = vector3_dot(tangentX[index0],tangentY[index1]);
2765           double length = vector3_length(tangentX[index0]) * vector3_length(tangentY[index1]);
2766
2767           bestTangents10(nFlagsX, dot, length, index0, index1);
2768
2769           accumulateVertexTangentSpace(index, tangentX, tangentY, tangentS, tangentT, index0, index1);
2770         }
2771
2772         {
2773           // x=0, y=1
2774           std::size_t index = offStartX + offEndY;
2775           std::size_t index0 = 4;
2776           std::size_t index1 = 1;
2777
2778           double dot = vector3_dot(tangentX[index0], tangentY[index1]);
2779           double length = vector3_length(tangentX[index1]) * vector3_length(tangentY[index1]);
2780
2781           bestTangents01(nFlagsX, dot, length, index0, index1);
2782
2783           accumulateVertexTangentSpace(index, tangentX, tangentY, tangentS, tangentT, index0, index1);
2784         }
2785
2786         {
2787           // x=1, y=1
2788           std::size_t index = offEndX + offEndY;
2789           std::size_t index0 = 5;
2790           std::size_t index1 = 5;
2791
2792           double dot = vector3_dot(tangentX[index0],tangentY[index1]);
2793           double length = vector3_length(tangentX[index0]) * vector3_length(tangentY[index1]);
2794
2795           bestTangents11(nFlagsX, dot, length, index0, index1);
2796
2797           accumulateVertexTangentSpace(index, tangentX, tangentY, tangentS, tangentT, index0, index1);
2798         }
2799
2800         //normalise normals that won't be accumulated again
2801         if(i!=0 || j!=0)
2802         {
2803           normalise_safe(normal_for_index(m_tess.m_vertices, offStartX + offStartY));
2804           normalise_safe(tangent_for_index(m_tess.m_vertices, offStartX + offStartY));
2805           normalise_safe(bitangent_for_index(m_tess.m_vertices, offStartX + offStartY));
2806         }
2807         if(i+3 == m_width)
2808         {
2809           normalise_safe(normal_for_index(m_tess.m_vertices, offEndX + offStartY));
2810           normalise_safe(tangent_for_index(m_tess.m_vertices, offEndX + offStartY));
2811           normalise_safe(bitangent_for_index(m_tess.m_vertices, offEndX + offStartY));
2812         }
2813         if(j+3 == m_height)
2814         {
2815           normalise_safe(normal_for_index(m_tess.m_vertices, offStartX + offEndY));
2816           normalise_safe(tangent_for_index(m_tess.m_vertices, offStartX + offEndY));
2817           normalise_safe(bitangent_for_index(m_tess.m_vertices, offStartX + offEndY));
2818         }
2819         if(i+3 == m_width && j+3 == m_height)
2820         {
2821           normalise_safe(normal_for_index(m_tess.m_vertices, offEndX + offEndY));
2822           normalise_safe(tangent_for_index(m_tess.m_vertices, offEndX + offEndY));
2823           normalise_safe(bitangent_for_index(m_tess.m_vertices, offEndX + offEndY));
2824         }
2825
2826         // set flags to average normals between shared edges
2827         if(j != 0)
2828         {
2829           nFlagsX |= AVERAGE;
2830         }
2831         if(i != 0)
2832         {
2833           nFlagsY |= AVERAGE;
2834         }
2835         // set flags to save evaluating shared edges twice
2836         nFlagsX |= SPLIT;
2837         nFlagsY |= SPLIT;    
2838       
2839         // if the patch is curved.. tesselate recursively
2840         // use the relevant control curves for this sub-patch
2841         if(m_patchDef3)
2842         {
2843           TesselateSubMatrixFixed(m_tess.m_vertices.data() + offStartX + offStartY, 1, m_tess.m_nArrayWidth, nFlagsX, nFlagsY, subMatrix);
2844         }
2845         else
2846         {
2847           if(!leafX)
2848           {
2849             TesselateSubMatrix( m_tess.m_curveTreeU[i>>1], m_tess.m_curveTreeV[j>>1],
2850                                 offStartX, offStartY, offEndX, offEndY, // array offsets
2851                                 nFlagsX, nFlagsY,
2852                                 subMatrix[1][0]->m_vertex, subMatrix[1][1]->m_vertex, subMatrix[1][2]->m_vertex,
2853                                 subMatrix[1][0]->m_texcoord, subMatrix[1][1]->m_texcoord, subMatrix[1][2]->m_texcoord,
2854                                 false );
2855           }
2856           else if(!leafY)
2857           {
2858             TesselateSubMatrix( m_tess.m_curveTreeV[j>>1], m_tess.m_curveTreeU[i>>1],
2859                                 offStartY, offStartX, offEndY, offEndX, // array offsets
2860                                 nFlagsY, nFlagsX,
2861                                 subMatrix[0][1]->m_vertex, subMatrix[1][1]->m_vertex, subMatrix[2][1]->m_vertex,
2862                                 subMatrix[0][1]->m_texcoord, subMatrix[1][1]->m_texcoord, subMatrix[2][1]->m_texcoord,
2863                                 true );
2864           }
2865         }
2866
2867         offStartX = offEndX;
2868       }
2869       offStartY = offEndY;
2870     }
2871   }
2872 }
2873
2874
2875
2876 class PatchFilterWrapper : public Filter
2877 {
2878   bool m_active;
2879   bool m_invert;
2880   PatchFilter& m_filter;
2881 public:
2882   PatchFilterWrapper(PatchFilter& filter, bool invert) : m_invert(invert), m_filter(filter)
2883   {
2884   }
2885   void setActive(bool active)
2886   {
2887     m_active = active;
2888   }
2889   bool active()
2890   {
2891     return m_active;
2892   }
2893   bool filter(const Patch& patch)
2894   {
2895     return m_invert ^ m_filter.filter(patch);
2896   }
2897 };
2898
2899
2900 typedef std::list<PatchFilterWrapper> PatchFilters;
2901 PatchFilters g_patchFilters;
2902
2903 void add_patch_filter(PatchFilter& filter, int mask, bool invert)
2904 {
2905   g_patchFilters.push_back(PatchFilterWrapper(filter, invert));
2906   GlobalFilterSystem().addFilter(g_patchFilters.back(), mask);
2907 }
2908
2909 bool patch_filtered(Patch& patch)
2910 {
2911   for(PatchFilters::iterator i = g_patchFilters.begin(); i != g_patchFilters.end(); ++i)
2912   {
2913     if((*i).active() && (*i).filter(patch))
2914     {
2915       return true;
2916     }
2917   }
2918   return false;
2919 }