Solaris had a problem finding finite so had to conditionally
[blender.git] / intern / elbeem / intern / isosurface.cpp
1 /******************************************************************************
2  *
3  * El'Beem - Free Surface Fluid Simulation with the Lattice Boltzmann Method
4  * Copyright 2003-2006 Nils Thuerey
5  *
6  * Marching Cubes surface mesh generation
7  *
8  *****************************************************************************/
9
10 #include "isosurface.h"
11 #include "mcubes_tables.h"
12 #include "particletracer.h"
13 #include <algorithm>
14 #include <stdio.h>
15
16 #if !defined(linux) && (defined (__sparc) || defined (__sparc__))
17 #include <ieeefp.h>
18 #endif
19
20
21 // just use default rounding for platforms where its not available
22 #ifndef round
23 #define round(x) (x)
24 #endif
25
26 /******************************************************************************
27  * Constructor
28  *****************************************************************************/
29 IsoSurface::IsoSurface(double iso) :
30         ntlGeometryObject(),
31         mSizex(-1), mSizey(-1), mSizez(-1),
32         mpData(NULL),
33   mIsoValue( iso ), 
34         mPoints(), 
35         mUseFullEdgeArrays(false),
36         mpEdgeVerticesX(NULL), mpEdgeVerticesY(NULL), mpEdgeVerticesZ(NULL),
37         mEdgeArSize(-1),
38         mIndices(),
39
40   mStart(0.0), mEnd(0.0), mDomainExtent(0.0),
41   mInitDone(false),
42         mSmoothSurface(0.0), mSmoothNormals(0.0),
43         mAcrossEdge(), mAdjacentFaces(),
44         mCutoff(-1), mCutArray(NULL), // off by default
45         mpIsoParts(NULL), mPartSize(0.), mSubdivs(0),
46         mFlagCnt(1),
47         mSCrad1(0.), mSCrad2(0.), mSCcenter(0.)
48 {
49 }
50
51
52 /******************************************************************************
53  * The real init...
54  *****************************************************************************/
55 void IsoSurface::initializeIsosurface(int setx, int sety, int setz, ntlVec3Gfx extent) 
56 {
57         // range 1-10 (max due to subd array in triangulate)
58         if(mSubdivs<1) mSubdivs=1;
59         if(mSubdivs>10) mSubdivs=10;
60
61         // init solver and size
62         mSizex = setx;
63         mSizey = sety;
64         if(setz == 1) {// 2D, create thin 2D surface
65                 setz = 5; 
66         }
67         mSizez = setz;
68         mDomainExtent = extent;
69
70         /* check triangulation size (for raytraing) */
71         if( ( mStart[0] >= mEnd[0] ) && ( mStart[1] >= mEnd[1] ) && ( mStart[2] >= mEnd[2] ) ){
72                 // extent was not set, use normalized one from parametrizer
73                 mStart = ntlVec3Gfx(0.0) - extent*0.5;
74                 mEnd = ntlVec3Gfx(0.0) + extent*0.5;
75         }
76
77   // init 
78         mIndices.clear();
79   mPoints.clear();
80
81         int nodes = mSizez*mSizey*mSizex;
82   mpData = new float[nodes];
83   for(int i=0;i<nodes;i++) { mpData[i] = 0.0; }
84
85   // allocate edge arrays  (last slices are never used...)
86         int initsize = -1;
87         if(mUseFullEdgeArrays) {
88                 mEdgeArSize = nodes;
89                 mpEdgeVerticesX = new int[nodes];
90                 mpEdgeVerticesY = new int[nodes];
91                 mpEdgeVerticesZ = new int[nodes];
92                 initsize = 3*nodes;
93         } else {
94                 int sliceNodes = 2*mSizex*mSizey*mSubdivs*mSubdivs;
95                 mEdgeArSize = sliceNodes;
96                 mpEdgeVerticesX = new int[sliceNodes];
97                 mpEdgeVerticesY = new int[sliceNodes];
98                 mpEdgeVerticesZ = new int[sliceNodes];
99                 initsize = 3*sliceNodes;
100         }
101   for(int i=0;i<mEdgeArSize;i++) { mpEdgeVerticesX[i] = mpEdgeVerticesY[i] = mpEdgeVerticesZ[i] = -1; }
102         // WARNING - make sure this is consistent with calculateMemreqEstimate
103   
104         // marching cubes are ready 
105         mInitDone = true;
106         debMsgStd("IsoSurface::initializeIsosurface",DM_MSG,"Inited, edgenodes:"<<initsize<<" subdivs:"<<mSubdivs<<" fulledg:"<<mUseFullEdgeArrays , 10);
107 }
108
109
110
111 /*! Reset all values */
112 void IsoSurface::resetAll(gfxReal val) {
113         int nodes = mSizez*mSizey*mSizex;
114   for(int i=0;i<nodes;i++) { mpData[i] = val; }
115 }
116
117
118 /******************************************************************************
119  * Destructor
120  *****************************************************************************/
121 IsoSurface::~IsoSurface( void )
122 {
123         if(mpData) delete [] mpData;
124         if(mpEdgeVerticesX) delete [] mpEdgeVerticesX;
125         if(mpEdgeVerticesY) delete [] mpEdgeVerticesY;
126         if(mpEdgeVerticesZ) delete [] mpEdgeVerticesZ;
127 }
128
129
130
131
132
133 /******************************************************************************
134  * triangulate the scalar field given by pointer
135  *****************************************************************************/
136 void IsoSurface::triangulate( void )
137 {
138   double gsx,gsy,gsz; // grid spacing in x,y,z direction
139   double px,py,pz;    // current position in grid in x,y,z direction
140   IsoLevelCube cubie;    // struct for a small subcube
141         myTime_t tritimestart = getTime(); 
142
143         if(!mpData) {
144                 errFatal("IsoSurface::triangulate","no LBM object, and no scalar field...!",SIMWORLD_INITERROR);
145                 return;
146         }
147
148   // get grid spacing (-2 to have same spacing as sim)
149   gsx = (mEnd[0]-mStart[0])/(double)(mSizex-2.0);
150   gsy = (mEnd[1]-mStart[1])/(double)(mSizey-2.0);
151   gsz = (mEnd[2]-mStart[2])/(double)(mSizez-2.0);
152
153   // clean up previous frame
154         mIndices.clear();
155         mPoints.clear();
156
157         // reset edge vertices
158   for(int i=0;i<mEdgeArSize;i++) {
159                 mpEdgeVerticesX[i] = -1;
160                 mpEdgeVerticesY[i] = -1;
161                 mpEdgeVerticesZ[i] = -1;
162         }
163
164         ntlVec3Gfx pos[8];
165         float value[8];
166         int cubeIndex;      // index entry of the cube 
167         int triIndices[12]; // vertex indices 
168         int *eVert[12];
169         IsoLevelVertex ilv;
170
171         // edges between which points?
172         const int mcEdges[24] = { 
173                 0,1,  1,2,  2,3,  3,0,
174                 4,5,  5,6,  6,7,  7,4,
175                 0,4,  1,5,  2,6,  3,7 };
176
177         const int cubieOffsetX[8] = {
178                 0,1,1,0,  0,1,1,0 };
179         const int cubieOffsetY[8] = {
180                 0,0,1,1,  0,0,1,1 };
181         const int cubieOffsetZ[8] = {
182                 0,0,0,0,  1,1,1,1 };
183
184         const int coAdd=2;
185   // let the cubes march 
186         if(mSubdivs<=1) {
187
188                 pz = mStart[2]-gsz*0.5;
189                 for(int k=1;k<(mSizez-2);k++) {
190                         pz += gsz;
191                         py = mStart[1]-gsy*0.5;
192                         for(int j=1;j<(mSizey-2);j++) {
193                                 py += gsy;
194                                 px = mStart[0]-gsx*0.5;
195                                 for(int i=1;i<(mSizex-2);i++) {
196                                         px += gsx;
197
198                                         value[0] = *getData(i  ,j  ,k  );
199                                         value[1] = *getData(i+1,j  ,k  );
200                                         value[2] = *getData(i+1,j+1,k  );
201                                         value[3] = *getData(i  ,j+1,k  );
202                                         value[4] = *getData(i  ,j  ,k+1);
203                                         value[5] = *getData(i+1,j  ,k+1);
204                                         value[6] = *getData(i+1,j+1,k+1);
205                                         value[7] = *getData(i  ,j+1,k+1);
206
207                                         // check intersections of isosurface with edges, and calculate cubie index
208                                         cubeIndex = 0;
209                                         if (value[0] < mIsoValue) cubeIndex |= 1;
210                                         if (value[1] < mIsoValue) cubeIndex |= 2;
211                                         if (value[2] < mIsoValue) cubeIndex |= 4;
212                                         if (value[3] < mIsoValue) cubeIndex |= 8;
213                                         if (value[4] < mIsoValue) cubeIndex |= 16;
214                                         if (value[5] < mIsoValue) cubeIndex |= 32;
215                                         if (value[6] < mIsoValue) cubeIndex |= 64;
216                                         if (value[7] < mIsoValue) cubeIndex |= 128;
217
218                                         // No triangles to generate?
219                                         if (mcEdgeTable[cubeIndex] == 0) {
220                                                 continue;
221                                         }
222
223                                         // where to look up if this point already exists
224                                         int edgek = 0;
225                                         if(mUseFullEdgeArrays) edgek=k;
226                                         const int baseIn = ISOLEVEL_INDEX( i+0, j+0, edgek+0);
227                                         eVert[ 0] = &mpEdgeVerticesX[ baseIn ];
228                                         eVert[ 1] = &mpEdgeVerticesY[ baseIn + 1 ];
229                                         eVert[ 2] = &mpEdgeVerticesX[ ISOLEVEL_INDEX( i+0, j+1, edgek+0) ];
230                                         eVert[ 3] = &mpEdgeVerticesY[ baseIn ];
231
232                                         eVert[ 4] = &mpEdgeVerticesX[ ISOLEVEL_INDEX( i+0, j+0, edgek+1) ];
233                                         eVert[ 5] = &mpEdgeVerticesY[ ISOLEVEL_INDEX( i+1, j+0, edgek+1) ];
234                                         eVert[ 6] = &mpEdgeVerticesX[ ISOLEVEL_INDEX( i+0, j+1, edgek+1) ];
235                                         eVert[ 7] = &mpEdgeVerticesY[ ISOLEVEL_INDEX( i+0, j+0, edgek+1) ];
236
237                                         eVert[ 8] = &mpEdgeVerticesZ[ baseIn ];
238                                         eVert[ 9] = &mpEdgeVerticesZ[ ISOLEVEL_INDEX( i+1, j+0, edgek+0) ];
239                                         eVert[10] = &mpEdgeVerticesZ[ ISOLEVEL_INDEX( i+1, j+1, edgek+0) ];
240                                         eVert[11] = &mpEdgeVerticesZ[ ISOLEVEL_INDEX( i+0, j+1, edgek+0) ];
241
242                                         // grid positions
243                                         pos[0] = ntlVec3Gfx(px    ,py    ,pz);
244                                         pos[1] = ntlVec3Gfx(px+gsx,py    ,pz);
245                                         pos[2] = ntlVec3Gfx(px+gsx,py+gsy,pz);
246                                         pos[3] = ntlVec3Gfx(px    ,py+gsy,pz);
247                                         pos[4] = ntlVec3Gfx(px    ,py    ,pz+gsz);
248                                         pos[5] = ntlVec3Gfx(px+gsx,py    ,pz+gsz);
249                                         pos[6] = ntlVec3Gfx(px+gsx,py+gsy,pz+gsz);
250                                         pos[7] = ntlVec3Gfx(px    ,py+gsy,pz+gsz);
251
252                                         // check all edges
253                                         for(int e=0;e<12;e++) {
254                                                 if (mcEdgeTable[cubeIndex] & (1<<e)) {
255                                                         // is the vertex already calculated?
256                                                         if(*eVert[ e ] < 0) {
257                                                                 // interpolate edge
258                                                                 const int e1 = mcEdges[e*2  ];
259                                                                 const int e2 = mcEdges[e*2+1];
260                                                                 const ntlVec3Gfx p1 = pos[ e1  ];    // scalar field pos 1
261                                                                 const ntlVec3Gfx p2 = pos[ e2  ];    // scalar field pos 2
262                                                                 const float valp1  = value[ e1  ];  // scalar field val 1
263                                                                 const float valp2  = value[ e2  ];  // scalar field val 2
264                                                                 const float mu = (mIsoValue - valp1) / (valp2 - valp1);
265
266                                                                 // init isolevel vertex
267                                                                 ilv.v = p1 + (p2-p1)*mu;
268                                                                 ilv.n = getNormal( i+cubieOffsetX[e1], j+cubieOffsetY[e1], k+cubieOffsetZ[e1]) * (1.0-mu) +
269                                                                                                 getNormal( i+cubieOffsetX[e2], j+cubieOffsetY[e2], k+cubieOffsetZ[e2]) * (    mu) ;
270                                                                 mPoints.push_back( ilv );
271
272                                                                 triIndices[e] = (mPoints.size()-1);
273                                                                 // store vertex 
274                                                                 *eVert[ e ] = triIndices[e];
275                                                         }       else {
276                                                                 // retrieve  from vert array
277                                                                 triIndices[e] = *eVert[ e ];
278                                                         }
279                                                 } // along all edges 
280                                         }
281
282                                         if( (i<coAdd+mCutoff) || (j<coAdd+mCutoff) ||
283                                                         ((mCutoff>0) && (k<coAdd)) ||// bottom layer
284                                                         (i>mSizex-2-coAdd-mCutoff) ||
285                                                         (j>mSizey-2-coAdd-mCutoff) ) {
286                                                 if(mCutArray) {
287                                                         if(k < mCutArray[j*this->mSizex+i]) continue;
288                                                 } else { continue; }
289                                         }
290
291                                         // Create the triangles... 
292                                         for(int e=0; mcTriTable[cubeIndex][e]!=-1; e+=3) {
293                                                 mIndices.push_back( triIndices[ mcTriTable[cubeIndex][e+0] ] );
294                                                 mIndices.push_back( triIndices[ mcTriTable[cubeIndex][e+1] ] );
295                                                 mIndices.push_back( triIndices[ mcTriTable[cubeIndex][e+2] ] );
296                                         }
297                                         
298                                 }//i
299                         }// j
300
301                         // copy edge arrays
302                         if(!mUseFullEdgeArrays) {
303                         for(int j=0;j<(mSizey-0);j++) 
304                                 for(int i=0;i<(mSizex-0);i++) {
305                                         //int edgek = 0;
306                                         const int dst = ISOLEVEL_INDEX( i+0, j+0, 0);
307                                         const int src = ISOLEVEL_INDEX( i+0, j+0, 1);
308                                         mpEdgeVerticesX[ dst ] = mpEdgeVerticesX[ src ];
309                                         mpEdgeVerticesY[ dst ] = mpEdgeVerticesY[ src ];
310                                         mpEdgeVerticesZ[ dst ] = mpEdgeVerticesZ[ src ];
311                                         mpEdgeVerticesX[ src ]=-1;
312                                         mpEdgeVerticesY[ src ]=-1;
313                                         mpEdgeVerticesZ[ src ]=-1;
314                                 }
315                         } // */
316
317                 } // k
318
319         // precalculate normals using an approximation of the scalar field gradient 
320                 for(int ni=0;ni<(int)mPoints.size();ni++) { normalize( mPoints[ni].n ); }
321
322         } else { // subdivs
323
324 #define EDGEAR_INDEX(Ai,Aj,Ak, Bi,Bj) ((mSizex*mSizey*mSubdivs*mSubdivs*(Ak))+\
325                 (mSizex*mSubdivs*((Aj)*mSubdivs+(Bj)))+((Ai)*mSubdivs)+(Bi))
326
327 #define ISOTRILININT(fi,fj,fk) ( \
328                                 (1.-(fi))*(1.-(fj))*(1.-(fk))*orgval[0] + \
329                                 (   (fi))*(1.-(fj))*(1.-(fk))*orgval[1] + \
330                                 (   (fi))*(   (fj))*(1.-(fk))*orgval[2] + \
331                                 (1.-(fi))*(   (fj))*(1.-(fk))*orgval[3] + \
332                                 (1.-(fi))*(1.-(fj))*(   (fk))*orgval[4] + \
333                                 (   (fi))*(1.-(fj))*(   (fk))*orgval[5] + \
334                                 (   (fi))*(   (fj))*(   (fk))*orgval[6] + \
335                                 (1.-(fi))*(   (fj))*(   (fk))*orgval[7] )
336
337                 // use subdivisions
338                 gfxReal subdfac = 1./(gfxReal)(mSubdivs);
339                 gfxReal orgGsx = gsx;
340                 gfxReal orgGsy = gsy;
341                 gfxReal orgGsz = gsz;
342                 gsx *= subdfac;
343                 gsy *= subdfac;
344                 gsz *= subdfac;
345                 if(mUseFullEdgeArrays) {
346                         errMsg("IsoSurface::triangulate","Disabling mUseFullEdgeArrays!");
347                 }
348
349                 // subdiv local arrays
350                 gfxReal orgval[8];
351                 gfxReal subdAr[2][11][11]; // max 10 subdivs!
352                 ParticleObject* *arppnt = new ParticleObject*[mSizez*mSizey*mSizex];
353
354                 // construct pointers
355                 // part test
356                 int pInUse = 0;
357                 int pUsedTest = 0;
358                 // reset particles
359                 // reset list array
360                 for(int k=0;k<(mSizez);k++) 
361                         for(int j=0;j<(mSizey);j++) 
362                                 for(int i=0;i<(mSizex);i++) {
363                                         arppnt[ISOLEVEL_INDEX(i,j,k)] = NULL;
364                                 }
365                 if(mpIsoParts) {
366                         for(vector<ParticleObject>::iterator pit= mpIsoParts->getParticlesBegin();
367                                         pit!= mpIsoParts->getParticlesEnd(); pit++) {
368                                 if( (*pit).getActive()==false ) continue;
369                                 if( (*pit).getType()!=PART_DROP) continue;
370                                 (*pit).setNext(NULL);
371                         }
372                         // build per node lists
373                         for(vector<ParticleObject>::iterator pit= mpIsoParts->getParticlesBegin();
374                                         pit!= mpIsoParts->getParticlesEnd(); pit++) {
375                                 if( (*pit).getActive()==false ) continue;
376                                 if( (*pit).getType()!=PART_DROP) continue;
377                                 // check lifetime ignored here
378                                 ParticleObject *p = &(*pit);
379                                 const ntlVec3Gfx ppos = p->getPos();
380                                 const int pi= (int)round(ppos[0])+0; 
381                                 const int pj= (int)round(ppos[1])+0; 
382                                 int       pk= (int)round(ppos[2])+0;// no offset necessary
383                                 // 2d should be handled by solver. if(LBMDIM==2) { pk = 0; }
384
385                                 if(pi<0) continue;
386                                 if(pj<0) continue;
387                                 if(pk<0) continue;
388                                 if(pi>mSizex-1) continue;
389                                 if(pj>mSizey-1) continue;
390                                 if(pk>mSizez-1) continue;
391                                 ParticleObject* &pnt = arppnt[ISOLEVEL_INDEX(pi,pj,pk)]; 
392                                 if(pnt) {
393                                         // append
394                                         ParticleObject* listpnt = pnt;
395                                         while(listpnt) {
396                                                 if(!listpnt->getNext()) {
397                                                         listpnt->setNext(p); listpnt = NULL;
398                                                 } else {
399                                                         listpnt = listpnt->getNext();
400                                                 }
401                                         }
402                                 } else {
403                                         // start new list
404                                         pnt = p;
405                                 }
406                                 pInUse++;
407                         }
408                 } // mpIsoParts
409
410                 debMsgStd("IsoSurface::triangulate",DM_MSG,"Starting. Parts in use:"<<pInUse<<", Subdivs:"<<mSubdivs, 9);
411                 pz = mStart[2]-(double)(0.*gsz)-0.5*orgGsz;
412                 for(int ok=1;ok<(mSizez-2)*mSubdivs;ok++) {
413                         pz += gsz;
414                         const int k = ok/mSubdivs;
415                         if(k<=0) continue; // skip zero plane
416                         for(int j=1;j<(mSizey-2);j++) {
417                                 for(int i=1;i<(mSizex-2);i++) {
418
419                                         orgval[0] = *getData(i  ,j  ,k  );
420                                         orgval[1] = *getData(i+1,j  ,k  );
421                                         orgval[2] = *getData(i+1,j+1,k  ); // with subdivs
422                                         orgval[3] = *getData(i  ,j+1,k  );
423                                         orgval[4] = *getData(i  ,j  ,k+1);
424                                         orgval[5] = *getData(i+1,j  ,k+1);
425                                         orgval[6] = *getData(i+1,j+1,k+1); // with subdivs
426                                         orgval[7] = *getData(i  ,j+1,k+1);
427
428                                         // prebuild subsampled array slice
429                                         const int sdkOffset = ok-k*mSubdivs; 
430                                         for(int sdk=0; sdk<2; sdk++) 
431                                                 for(int sdj=0; sdj<mSubdivs+1; sdj++) 
432                                                         for(int sdi=0; sdi<mSubdivs+1; sdi++) {
433                                                                 subdAr[sdk][sdj][sdi] = ISOTRILININT(sdi*subdfac, sdj*subdfac, (sdkOffset+sdk)*subdfac);
434                                                         }
435
436                                         const int poDistOffset=2;
437                                         for(int pok=-poDistOffset; pok<1+poDistOffset; pok++) {
438                                                 if(k+pok<0) continue;
439                                                 if(k+pok>=mSizez-1) continue;
440                                         for(int poj=-poDistOffset; poj<1+poDistOffset; poj++) {
441                                                 if(j+poj<0) continue;
442                                                 if(j+poj>=mSizey-1) continue;
443                                         for(int poi=-poDistOffset; poi<1+poDistOffset; poi++) {
444                                                 if(i+poi<0) continue;
445                                                 if(i+poi>=mSizex-1) continue; 
446                                                 ParticleObject *p;
447                                                 p = arppnt[ISOLEVEL_INDEX(i+poi,j+poj,k+pok)];
448                                                 while(p) { // */
449                                         /*
450                                         for(vector<ParticleObject>::iterator pit= mpIsoParts->getParticlesBegin();
451                                                         pit!= mpIsoParts->getParticlesEnd(); pit++) { { { {
452                                                 // debug test! , full list slow!
453                                                 if(( (*pit).getActive()==false ) || ( (*pit).getType()!=PART_DROP)) continue;
454                                                 ParticleObject *p;
455                                                 p = &(*pit); // */
456
457                                                         pUsedTest++;
458                                                         ntlVec3Gfx ppos = p->getPos();
459                                                         const int spi= (int)round( (ppos[0]+1.-(gfxReal)i) *(gfxReal)mSubdivs-1.5); 
460                                                         const int spj= (int)round( (ppos[1]+1.-(gfxReal)j) *(gfxReal)mSubdivs-1.5); 
461                                                         const int spk= (int)round( (ppos[2]+1.-(gfxReal)k) *(gfxReal)mSubdivs-1.5)-sdkOffset; // why -2?
462                                                         // 2d should be handled by solver. if(LBMDIM==2) { spk = 0; }
463
464                                                         gfxReal pfLen = p->getSize()*1.5*mPartSize;  // test, was 1.1
465                                                         const gfxReal minPfLen = subdfac*0.8;
466                                                         if(pfLen<minPfLen) pfLen = minPfLen;
467                                                         //errMsg("ISOPPP"," at "<<PRINT_IJK<<"  pp"<<ppos<<"  sp"<<PRINT_VEC(spi,spj,spk)<<" pflen"<<pfLen );
468                                                         //errMsg("ISOPPP"," subdfac="<<subdfac<<" size"<<p->getSize()<<" ps"<<mPartSize );
469                                                         const int icellpsize = (int)(1.*pfLen*(gfxReal)mSubdivs)+1;
470                                                         for(int swk=-icellpsize; swk<=icellpsize; swk++) {
471                                                                 if(spk+swk<         0) { continue; }
472                                                                 if(spk+swk>         1) { continue; } // */
473                                                         for(int swj=-icellpsize; swj<=icellpsize; swj++) {
474                                                                 if(spj+swj<         0) { continue; }
475                                                                 if(spj+swj>mSubdivs+0) { continue; } // */
476                                                         for(int swi=-icellpsize; swi<=icellpsize; swi++) {
477                                                                 if(spi+swi<         0) { continue; } 
478                                                                 if(spi+swi>mSubdivs+0) { continue; } // */
479                                                                 ntlVec3Gfx cellp = ntlVec3Gfx(
480                                                                                 (1.5+(gfxReal)(spi+swi))           *subdfac + (gfxReal)(i-1),
481                                                                                 (1.5+(gfxReal)(spj+swj))           *subdfac + (gfxReal)(j-1),
482                                                                                 (1.5+(gfxReal)(spk+swk)+sdkOffset) *subdfac + (gfxReal)(k-1)
483                                                                                 );
484                                                                 //if(swi==0 && swj==0 && swk==0) subdAr[spk][spj][spi] = 1.; // DEBUG
485                                                                 // clip domain boundaries again 
486                                                                 if(cellp[0]<1.) { continue; } 
487                                                                 if(cellp[1]<1.) { continue; } 
488                                                                 if(cellp[2]<1.) { continue; } 
489                                                                 if(cellp[0]>(gfxReal)mSizex-3.) { continue; } 
490                                                                 if(cellp[1]>(gfxReal)mSizey-3.) { continue; } 
491                                                                 if(cellp[2]>(gfxReal)mSizez-3.) { continue; } 
492                                                                 gfxReal len = norm(cellp-ppos);
493                                                                 gfxReal isoadd = 0.; 
494                                                                 const gfxReal baseIsoVal = mIsoValue*1.1;
495                                                                 if(len<pfLen) { 
496                                                                         isoadd = baseIsoVal*1.;
497                                                                 } else { 
498                                                                         // falloff linear with pfLen (kernel size=2pfLen
499                                                                         isoadd = baseIsoVal*(1. - (len-pfLen)/(pfLen)); 
500                                                                 }
501                                                                 if(isoadd<0.) { continue; }
502                                                                 //errMsg("ISOPPP"," at "<<PRINT_IJK<<" sp"<<PRINT_VEC(spi+swi,spj+swj,spk+swk)<<" cellp"<<cellp<<" pp"<<ppos << " l"<< len<< " add"<< isoadd);
503                                                                 const gfxReal arval = subdAr[spk+swk][spj+swj][spi+swi];
504                                                                 if(arval>1.) { continue; }
505                                                                 subdAr[spk+swk][spj+swj][spi+swi] = arval + isoadd;
506                                                         } } }
507
508                                                         p = p->getNext();
509                                                 }
510                                         } } } // poDist loops */
511
512                                         py = mStart[1]+(((double)j-0.5)*orgGsy)-gsy;
513                                         for(int sj=0;sj<mSubdivs;sj++) {
514                                                 py += gsy;
515                                                 px = mStart[0]+(((double)i-0.5)*orgGsx)-gsx;
516                                                 for(int si=0;si<mSubdivs;si++) {
517                                                         px += gsx;
518                                                         value[0] = subdAr[0+0][sj+0][si+0]; 
519                                                         value[1] = subdAr[0+0][sj+0][si+1]; 
520                                                         value[2] = subdAr[0+0][sj+1][si+1]; 
521                                                         value[3] = subdAr[0+0][sj+1][si+0]; 
522                                                         value[4] = subdAr[0+1][sj+0][si+0]; 
523                                                         value[5] = subdAr[0+1][sj+0][si+1]; 
524                                                         value[6] = subdAr[0+1][sj+1][si+1]; 
525                                                         value[7] = subdAr[0+1][sj+1][si+0]; 
526
527                                                         // check intersections of isosurface with edges, and calculate cubie index
528                                                         cubeIndex = 0;
529                                                         if (value[0] < mIsoValue) cubeIndex |= 1;
530                                                         if (value[1] < mIsoValue) cubeIndex |= 2; // with subdivs
531                                                         if (value[2] < mIsoValue) cubeIndex |= 4;
532                                                         if (value[3] < mIsoValue) cubeIndex |= 8;
533                                                         if (value[4] < mIsoValue) cubeIndex |= 16;
534                                                         if (value[5] < mIsoValue) cubeIndex |= 32; // with subdivs
535                                                         if (value[6] < mIsoValue) cubeIndex |= 64;
536                                                         if (value[7] < mIsoValue) cubeIndex |= 128;
537
538                                                         if (mcEdgeTable[cubeIndex] >  0) {
539
540                                                         // where to look up if this point already exists
541                                                         const int edgek = 0;
542                                                         const int baseIn = EDGEAR_INDEX( i+0, j+0, edgek+0, si,sj);
543                                                         eVert[ 0] = &mpEdgeVerticesX[ baseIn ];
544                                                         eVert[ 1] = &mpEdgeVerticesY[ baseIn + 1 ];
545                                                         eVert[ 2] = &mpEdgeVerticesX[ EDGEAR_INDEX( i, j, edgek+0, si+0,sj+1) ];
546                                                         eVert[ 3] = &mpEdgeVerticesY[ baseIn ];                             
547                                                                                                                                                                                                                                                                                                                                         
548                                                         eVert[ 4] = &mpEdgeVerticesX[ EDGEAR_INDEX( i, j, edgek+1, si+0,sj+0) ];
549                                                         eVert[ 5] = &mpEdgeVerticesY[ EDGEAR_INDEX( i, j, edgek+1, si+1,sj+0) ]; // with subdivs
550                                                         eVert[ 6] = &mpEdgeVerticesX[ EDGEAR_INDEX( i, j, edgek+1, si+0,sj+1) ];
551                                                         eVert[ 7] = &mpEdgeVerticesY[ EDGEAR_INDEX( i, j, edgek+1, si+0,sj+0) ];
552                                                                                                                                                                                                                                                                                                                                         
553                                                         eVert[ 8] = &mpEdgeVerticesZ[ baseIn ];                             
554                                                         eVert[ 9] = &mpEdgeVerticesZ[ EDGEAR_INDEX( i, j, edgek+0, si+1,sj+0) ]; // with subdivs
555                                                         eVert[10] = &mpEdgeVerticesZ[ EDGEAR_INDEX( i, j, edgek+0, si+1,sj+1) ];
556                                                         eVert[11] = &mpEdgeVerticesZ[ EDGEAR_INDEX( i, j, edgek+0, si+0,sj+1) ];
557
558                                                         // grid positions
559                                                         pos[0] = ntlVec3Gfx(px    ,py    ,pz);
560                                                         pos[1] = ntlVec3Gfx(px+gsx,py    ,pz);
561                                                         pos[2] = ntlVec3Gfx(px+gsx,py+gsy,pz); // with subdivs
562                                                         pos[3] = ntlVec3Gfx(px    ,py+gsy,pz);
563                                                         pos[4] = ntlVec3Gfx(px    ,py    ,pz+gsz);
564                                                         pos[5] = ntlVec3Gfx(px+gsx,py    ,pz+gsz);
565                                                         pos[6] = ntlVec3Gfx(px+gsx,py+gsy,pz+gsz); // with subdivs
566                                                         pos[7] = ntlVec3Gfx(px    ,py+gsy,pz+gsz);
567
568                                                         // check all edges
569                                                         for(int e=0;e<12;e++) {
570                                                                 if (mcEdgeTable[cubeIndex] & (1<<e)) {
571                                                                         // is the vertex already calculated?
572                                                                         if(*eVert[ e ] < 0) {
573                                                                                 // interpolate edge
574                                                                                 const int e1 = mcEdges[e*2  ];
575                                                                                 const int e2 = mcEdges[e*2+1];
576                                                                                 const ntlVec3Gfx p1 = pos[ e1  ];   // scalar field pos 1
577                                                                                 const ntlVec3Gfx p2 = pos[ e2  ];   // scalar field pos 2
578                                                                                 const float valp1  = value[ e1  ];  // scalar field val 1
579                                                                                 const float valp2  = value[ e2  ];  // scalar field val 2
580                                                                                 const float mu = (mIsoValue - valp1) / (valp2 - valp1);
581
582                                                                                 // init isolevel vertex
583                                                                                 ilv.v = p1 + (p2-p1)*mu; // with subdivs
584                                                                                 mPoints.push_back( ilv );
585                                                                                 triIndices[e] = (mPoints.size()-1);
586                                                                                 // store vertex 
587                                                                                 *eVert[ e ] = triIndices[e]; 
588                                                                         }       else {
589                                                                                 // retrieve  from vert array
590                                                                                 triIndices[e] = *eVert[ e ];
591                                                                         }
592                                                                 } // along all edges 
593                                                         }
594                                                         // removed cutoff treatment...
595
596                                                         // Create the triangles... 
597                                                         for(int e=0; mcTriTable[cubeIndex][e]!=-1; e+=3) {
598                                                                 mIndices.push_back( triIndices[ mcTriTable[cubeIndex][e+0] ] );
599                                                                 mIndices.push_back( triIndices[ mcTriTable[cubeIndex][e+1] ] ); // with subdivs
600                                                                 mIndices.push_back( triIndices[ mcTriTable[cubeIndex][e+2] ] );
601                                                                 //errMsg("TTT"," i1"<<mIndices[mIndices.size()-3]<<" "<< " i2"<<mIndices[mIndices.size()-2]<<" "<< " i3"<<mIndices[mIndices.size()-1]<<" "<< mIndices.size() );
602                                                         }
603
604                                                         } // triangles in edge table?
605                                                         
606                                                 }//si
607                                         }// sj
608
609                                 }//i
610                         }// j
611
612                         // copy edge arrays
613                         for(int j=0;j<(mSizey-0)*mSubdivs;j++) 
614                                 for(int i=0;i<(mSizex-0)*mSubdivs;i++) {
615                                         //int edgek = 0;
616                                         const int dst = EDGEAR_INDEX( 0, 0, 0, i,j);
617                                         const int src = EDGEAR_INDEX( 0, 0, 1, i,j);
618                                         mpEdgeVerticesX[ dst ] = mpEdgeVerticesX[ src ];
619                                         mpEdgeVerticesY[ dst ] = mpEdgeVerticesY[ src ]; // with subdivs
620                                         mpEdgeVerticesZ[ dst ] = mpEdgeVerticesZ[ src ];
621                                         mpEdgeVerticesX[ src ]=-1;
622                                         mpEdgeVerticesY[ src ]=-1; // with subdivs
623                                         mpEdgeVerticesZ[ src ]=-1;
624                                 }
625                         // */
626
627                 } // ok, k subdiv loop
628
629                 //delete [] subdAr;
630                 delete [] arppnt;
631                 computeNormals();
632         } // with subdivs
633
634         // perform smoothing
635         float smoSubdfac = 1.;
636         if(mSubdivs>0) {
637                 //smoSubdfac = 1./(float)(mSubdivs);
638                 smoSubdfac = pow(0.55,(double)mSubdivs); // slightly stronger
639         }
640         if(mSmoothSurface>0. || mSmoothNormals>0.) debMsgStd("IsoSurface::triangulate",DM_MSG,"Smoothing...",10);
641         if(mSmoothSurface>0.0) { 
642                 smoothSurface(mSmoothSurface*smoSubdfac, (mSmoothNormals<=0.0) ); 
643         }
644         if(mSmoothNormals>0.0) { 
645                 smoothNormals(mSmoothNormals*smoSubdfac); 
646         }
647
648         myTime_t tritimeend = getTime(); 
649         debMsgStd("IsoSurface::triangulate",DM_MSG,"took "<< getTimeString(tritimeend-tritimestart)<<", S("<<mSmoothSurface<<","<<mSmoothNormals<<"),"<<
650                         " verts:"<<mPoints.size()<<" tris:"<<(mIndices.size()/3)<<" subdivs:"<<mSubdivs
651                  , 10 );
652         if(mpIsoParts) debMsgStd("IsoSurface::triangulate",DM_MSG,"parts:"<<mpIsoParts->getNumParticles(), 10);
653 }
654
655
656         
657
658
659 /******************************************************************************
660  * Get triangles for rendering
661  *****************************************************************************/
662 void IsoSurface::getTriangles(double t, vector<ntlTriangle> *triangles, 
663                                                                                                          vector<ntlVec3Gfx> *vertices, 
664                                                                                                          vector<ntlVec3Gfx> *normals, int objectId )
665 {
666         if(!mInitDone) {
667                 debugOut("IsoSurface::getTriangles warning: Not initialized! ", 10);
668                 return;
669         }
670         t = 0.;
671         //return; // DEBUG
672
673   /* triangulate field */
674   triangulate();
675         //errMsg("TRIS"," "<<mIndices.size() );
676
677         // new output with vertice reuse
678         int iniVertIndex = (*vertices).size();
679         int iniNormIndex = (*normals).size();
680         if(iniVertIndex != iniNormIndex) {
681                 errFatal("getTriangles Error","For '"<<mName<<"': Vertices and normal array sizes to not match!!!",SIMWORLD_GENERICERROR);
682                 return; 
683         }
684         //errMsg("NM"," ivi"<<iniVertIndex<<" ini"<<iniNormIndex<<" vs"<<vertices->size()<<" ns"<<normals->size()<<" ts"<<triangles->size() );
685         //errMsg("NM"," ovs"<<mVertices.size()<<" ons"<<mVertNormals.size()<<" ots"<<mIndices.size() );
686
687   for(int i=0;i<(int)mPoints.size();i++) {
688                 vertices->push_back( mPoints[i].v );
689         }
690   for(int i=0;i<(int)mPoints.size();i++) {
691                 normals->push_back( mPoints[i].n );
692         }
693
694         //errMsg("N2"," ivi"<<iniVertIndex<<" ini"<<iniNormIndex<<" vs"<<vertices->size()<<" ns"<<normals->size()<<" ts"<<triangles->size() );
695         //errMsg("N2"," ovs"<<mVertices.size()<<" ons"<<mVertNormals.size()<<" ots"<<mIndices.size() );
696
697   for(int i=0;i<(int)mIndices.size();i+=3) {
698                 const int smooth = 1;
699     int t1 = mIndices[i];
700     int t2 = mIndices[i+1];
701                 int t3 = mIndices[i+2];
702                 //errMsg("NM"," tri"<<t1<<" "<<t2<<" "<<t3 );
703
704                 ntlTriangle tri;
705
706                 tri.getPoints()[0] = t1+iniVertIndex;
707                 tri.getPoints()[1] = t2+iniVertIndex;
708                 tri.getPoints()[2] = t3+iniVertIndex;
709
710                 /* init flags */
711                 int flag = 0; 
712                 if(getVisible()){ flag |= TRI_GEOMETRY; }
713                 if(getCastShadows() ) { 
714                         flag |= TRI_CASTSHADOWS; } 
715
716                 /* init geo init id */
717                 int geoiId = getGeoInitId(); 
718                 if(geoiId > 0) { 
719                         flag |= (1<< (geoiId+4)); 
720                         flag |= mGeoInitType; 
721                 } 
722
723                 tri.setFlags( flag );
724
725                 /* triangle normal missing */
726                 tri.setNormal( ntlVec3Gfx(0.0) );
727                 tri.setSmoothNormals( smooth );
728                 tri.setObjectId( objectId );
729                 triangles->push_back( tri ); 
730         }
731         //errMsg("N3"," ivi"<<iniVertIndex<<" ini"<<iniNormIndex<<" vs"<<vertices->size()<<" ns"<<normals->size()<<" ts"<<triangles->size() );
732         return;
733 }
734
735
736
737 inline ntlVec3Gfx IsoSurface::getNormal(int i, int j,int k) {
738         // WARNING - this requires a security boundary layer... 
739         ntlVec3Gfx ret(0.0);
740         ret[0] = *getData(i-1,j  ,k  ) - 
741                  *getData(i+1,j  ,k  );
742         ret[1] = *getData(i  ,j-1,k  ) - 
743                  *getData(i  ,j+1,k  );
744         ret[2] = *getData(i  ,j  ,k-1  ) - 
745                  *getData(i  ,j  ,k+1  );
746         return ret;
747 }
748
749
750
751
752 /******************************************************************************
753  * 
754  * Surface improvement, inspired by trimesh2 library
755  * (http://www.cs.princeton.edu/gfx/proj/trimesh2/)
756  * 
757  *****************************************************************************/
758
759 void IsoSurface::setSmoothRad(float radi1, float radi2, ntlVec3Gfx mscc) {
760         mSCrad1 = radi1*radi1;
761         mSCrad2 = radi2*radi2;
762         mSCcenter = mscc;
763 }
764
765 // compute normals for all generated triangles
766 void IsoSurface::computeNormals() {
767   for(int i=0;i<(int)mPoints.size();i++) {
768                 mPoints[i].n = ntlVec3Gfx(0.);
769         }
770
771   for(int i=0;i<(int)mIndices.size();i+=3) {
772     const int t1 = mIndices[i];
773     const int t2 = mIndices[i+1];
774                 const int t3 = mIndices[i+2];
775                 const ntlVec3Gfx p1 = mPoints[t1].v;
776                 const ntlVec3Gfx p2 = mPoints[t2].v;
777                 const ntlVec3Gfx p3 = mPoints[t3].v;
778                 const ntlVec3Gfx n1=p1-p2;
779                 const ntlVec3Gfx n2=p2-p3;
780                 const ntlVec3Gfx n3=p3-p1;
781                 const gfxReal len1 = normNoSqrt(n1);
782                 const gfxReal len2 = normNoSqrt(n2);
783                 const gfxReal len3 = normNoSqrt(n3);
784                 const ntlVec3Gfx norm = cross(n1,n2);
785                 mPoints[t1].n += norm * (1./(len1*len3));
786                 mPoints[t2].n += norm * (1./(len1*len2));
787                 mPoints[t3].n += norm * (1./(len2*len3));
788         }
789
790   for(int i=0;i<(int)mPoints.size();i++) {
791                 normalize(mPoints[i].n);
792         }
793 }
794
795 // Diffuse a vector field at 1 vertex, weighted by
796 // a gaussian of width 1/sqrt(invsigma2)
797 bool IsoSurface::diffuseVertexField(ntlVec3Gfx *field, const int pointerScale, int src, float invsigma2, ntlVec3Gfx &target)
798 {
799         if((neighbors[src].size()<1) || (pointareas[src]<=0.0)) return 0;
800         const ntlVec3Gfx srcp = mPoints[src].v;
801         const ntlVec3Gfx srcn = mPoints[src].n;
802         if(mSCrad1>0.0 && mSCrad2>0.0) {
803                 ntlVec3Gfx dp = mSCcenter-srcp; dp[2] = 0.0; // only xy-plane
804                 float rd = normNoSqrt(dp);
805                 if(rd > mSCrad2) {
806                         return 0;
807                 } else if(rd > mSCrad1) {
808                         // optimize?
809                         float org = 1.0/sqrt(invsigma2);
810                         org *= (1.0- (rd-mSCrad1) / (mSCrad2-mSCrad1));
811                         invsigma2 = 1.0/(org*org);
812                         //errMsg("TRi","p"<<srcp<<" rd:"<<rd<<" r1:"<<mSCrad1<<" r2:"<<mSCrad2<<" org:"<<org<<" is:"<<invsigma2);
813                 } else {
814                 }
815         }
816         target = ntlVec3Gfx(0.0);
817         target += *(field+pointerScale*src) *pointareas[src];
818         float smstrSum = pointareas[src];
819
820         int flag = mFlagCnt; 
821         mFlagCnt++;
822         flags[src] = flag;
823         mDboundary = neighbors[src];
824         while (!mDboundary.empty()) {
825                 const int bbn = mDboundary.back();
826                 mDboundary.pop_back();
827                 if(flags[bbn]==flag) continue;
828                 flags[bbn] = flag;
829
830                 // normal check
831                 const float nvdot = dot(srcn, mPoints[bbn].n); // faster than before d2 calc?
832                 if(nvdot <= 0.0f) continue;
833
834                 // gaussian weight of width 1/sqrt(invsigma2)
835                 const float d2 = invsigma2 * normNoSqrt(mPoints[bbn].v - srcp);
836                 if(d2 >= 9.0f) continue;
837
838                 // aggressive smoothing factor
839                 float smstr = nvdot * pointareas[bbn];
840                 // Accumulate weight times field at neighbor
841                 target += *(field+pointerScale*bbn)*smstr;
842                 smstrSum += smstr;
843
844                 for(int i = 0; i < (int)neighbors[bbn].size(); i++) {
845                         const int nn = neighbors[bbn][i];
846                         if (flags[nn] == flag) continue;
847                         mDboundary.push_back(nn);
848                 }
849         }
850         target /= smstrSum;
851         return 1;
852 }
853
854         
855 // perform smoothing of the surface (and possible normals)
856 void IsoSurface::smoothSurface(float sigma, bool normSmooth)
857 {
858         int nv = mPoints.size();
859         if ((int)flags.size() != nv) flags.resize(nv);
860         int nf = mIndices.size()/3;
861
862         { // need neighbors
863                 vector<int> numneighbors(mPoints.size());
864                 int i;
865                 for (i = 0; i < (int)mIndices.size()/3; i++) {
866                         numneighbors[mIndices[i*3+0]]++;
867                         numneighbors[mIndices[i*3+1]]++;
868                         numneighbors[mIndices[i*3+2]]++;
869                 }
870
871                 neighbors.clear();
872                 neighbors.resize(mPoints.size());
873                 for (i = 0; i < (int)mPoints.size(); i++) {
874                         neighbors[i].clear();
875                         neighbors[i].reserve(numneighbors[i]+2); // Slop for boundaries
876                 }
877
878                 for (i = 0; i < (int)mIndices.size()/3; i++) {
879                         for (int j = 0; j < 3; j++) {
880                                 vector<int> &me = neighbors[ mIndices[i*3+j]];
881                                 int n1 =  mIndices[i*3+((j+1)%3)];
882                                 int n2 =  mIndices[i*3+((j+2)%3)];
883                                 if (std::find(me.begin(), me.end(), n1) == me.end())
884                                         me.push_back(n1);
885                                 if (std::find(me.begin(), me.end(), n2) == me.end())
886                                         me.push_back(n2);
887                         }
888                 }
889         } // need neighbor
890
891         { // need pointarea
892                 pointareas.clear();
893                 pointareas.resize(nv);
894                 cornerareas.clear();
895                 cornerareas.resize(nf);
896
897                 for (int i = 0; i < nf; i++) {
898                         // Edges
899                         ntlVec3Gfx e[3] = { 
900                                 mPoints[mIndices[i*3+2]].v - mPoints[mIndices[i*3+1]].v,
901                                 mPoints[mIndices[i*3+0]].v - mPoints[mIndices[i*3+2]].v,
902                                 mPoints[mIndices[i*3+1]].v - mPoints[mIndices[i*3+0]].v };
903
904                         // Compute corner weights
905                         float area = 0.5f * norm( cross(e[0], e[1]));
906                         float l2[3] = { normNoSqrt(e[0]), normNoSqrt(e[1]), normNoSqrt(e[2]) };
907                         float ew[3] = { l2[0] * (l2[1] + l2[2] - l2[0]),
908                                         l2[1] * (l2[2] + l2[0] - l2[1]),
909                                         l2[2] * (l2[0] + l2[1] - l2[2]) };
910                         if (ew[0] <= 0.0f) {
911                                 cornerareas[i][1] = -0.25f * l2[2] * area /
912                                                                 dot(e[0] , e[2]);
913                                 cornerareas[i][2] = -0.25f * l2[1] * area /
914                                                                 dot(e[0] , e[1]);
915                                 cornerareas[i][0] = area - cornerareas[i][1] -
916                                                                 cornerareas[i][2];
917                         } else if (ew[1] <= 0.0f) {
918                                 cornerareas[i][2] = -0.25f * l2[0] * area /
919                                                                 dot(e[1] , e[0]);
920                                 cornerareas[i][0] = -0.25f * l2[2] * area /
921                                                                 dot(e[1] , e[2]);
922                                 cornerareas[i][1] = area - cornerareas[i][2] -
923                                                                 cornerareas[i][0];
924                         } else if (ew[2] <= 0.0f) {
925                                 cornerareas[i][0] = -0.25f * l2[1] * area /
926                                                                 dot(e[2] , e[1]);
927                                 cornerareas[i][1] = -0.25f * l2[0] * area /
928                                                                 dot(e[2] , e[0]);
929                                 cornerareas[i][2] = area - cornerareas[i][0] -
930                                                                 cornerareas[i][1];
931                         } else {
932                                 float ewscale = 0.5f * area / (ew[0] + ew[1] + ew[2]);
933                                 for (int j = 0; j < 3; j++)
934                                         cornerareas[i][j] = ewscale * (ew[(j+1)%3] +
935                                                                                          ew[(j+2)%3]);
936                         }
937
938                         // NT important, check this...
939 #ifndef WIN32
940                         if(! finite(cornerareas[i][0]) ) cornerareas[i][0]=1e-6;
941                         if(! finite(cornerareas[i][1]) ) cornerareas[i][1]=1e-6;
942                         if(! finite(cornerareas[i][2]) ) cornerareas[i][2]=1e-6;
943 #else // WIN32
944                         // FIXME check as well...
945                         if(! (cornerareas[i][0]>=0.0) ) cornerareas[i][0]=1e-6;
946                         if(! (cornerareas[i][1]>=0.0) ) cornerareas[i][1]=1e-6;
947                         if(! (cornerareas[i][2]>=0.0) ) cornerareas[i][2]=1e-6;
948 #endif // WIN32
949
950                         pointareas[mIndices[i*3+0]] += cornerareas[i][0];
951                         pointareas[mIndices[i*3+1]] += cornerareas[i][1];
952                         pointareas[mIndices[i*3+2]] += cornerareas[i][2];
953                 }
954
955         } // need pointarea
956         // */
957
958         float invsigma2 = 1.0f / (sigma*sigma);
959
960         vector<ntlVec3Gfx> dflt(nv);
961         for (int i = 0; i < nv; i++) {
962                 if(diffuseVertexField( &mPoints[0].v, 2,
963                                    i, invsigma2, dflt[i])) {
964                         // Just keep the displacement
965                         dflt[i] -= mPoints[i].v;
966                 } else { dflt[i] = 0.0; } //?mPoints[i].v; }
967         }
968
969         // Slightly better small-neighborhood approximation
970         for (int i = 0; i < nf; i++) {
971                 ntlVec3Gfx c = mPoints[mIndices[i*3+0]].v +
972                           mPoints[mIndices[i*3+1]].v +
973                           mPoints[mIndices[i*3+2]].v;
974                 c /= 3.0f;
975                 for (int j = 0; j < 3; j++) {
976                         int v = mIndices[i*3+j];
977                         ntlVec3Gfx d =(c - mPoints[v].v) * 0.5f;
978                         dflt[v] += d * (cornerareas[i][j] /
979                                    pointareas[mIndices[i*3+j]] *
980                                    exp(-0.5f * invsigma2 * normNoSqrt(d)) );
981                 }
982         }
983
984         // Filter displacement field
985         vector<ntlVec3Gfx> dflt2(nv);
986         for (int i = 0; i < nv; i++) {
987                 if(diffuseVertexField( &dflt[0], 1,
988                                    i, invsigma2, dflt2[i])) { }
989                 else { /*mPoints[i].v=0.0;*/ dflt2[i] = 0.0; }//dflt2[i]; }
990         }
991
992         // Update vertex positions
993         for (int i = 0; i < nv; i++) {
994                 mPoints[i].v += dflt[i] - dflt2[i]; // second Laplacian
995         }
996
997         // when normals smoothing off, this cleans up quite well
998         // costs ca. 50% additional time though
999         float nsFac = 1.5f;
1000         if(normSmooth) { float ninvsigma2 = 1.0f / (nsFac*nsFac*sigma*sigma);
1001                 for (int i = 0; i < nv; i++) {
1002                         if( diffuseVertexField( &mPoints[0].n, 2, i, ninvsigma2, dflt[i]) ) {
1003                                 normalize(dflt[i]);
1004                         } else {
1005                                 dflt[i] = mPoints[i].n;
1006                         }
1007                 }
1008                 for (int i = 0; i < nv; i++) {
1009                         mPoints[i].n = dflt[i];
1010                 } 
1011         } // smoothNormals copy */
1012
1013         //errMsg("SMSURF","done v:"<<sigma); // DEBUG
1014 }
1015
1016 // only smoothen the normals
1017 void IsoSurface::smoothNormals(float sigma) {
1018         // reuse from smoothSurface
1019         if(neighbors.size() != mPoints.size()) { 
1020                 // need neighbor
1021                 vector<int> numneighbors(mPoints.size());
1022                 int i;
1023                 for (i = 0; i < (int)mIndices.size()/3; i++) {
1024                         numneighbors[mIndices[i*3+0]]++;
1025                         numneighbors[mIndices[i*3+1]]++;
1026                         numneighbors[mIndices[i*3+2]]++;
1027                 }
1028
1029                 neighbors.clear();
1030                 neighbors.resize(mPoints.size());
1031                 for (i = 0; i < (int)mPoints.size(); i++) {
1032                         neighbors[i].clear();
1033                         neighbors[i].reserve(numneighbors[i]+2); // Slop for boundaries
1034                 }
1035
1036                 for (i = 0; i < (int)mIndices.size()/3; i++) {
1037                         for (int j = 0; j < 3; j++) {
1038                                 vector<int> &me = neighbors[ mIndices[i*3+j]];
1039                                 int n1 =  mIndices[i*3+((j+1)%3)];
1040                                 int n2 =  mIndices[i*3+((j+2)%3)];
1041                                 if (std::find(me.begin(), me.end(), n1) == me.end())
1042                                         me.push_back(n1);
1043                                 if (std::find(me.begin(), me.end(), n2) == me.end())
1044                                         me.push_back(n2);
1045                         }
1046                 }
1047         } // need neighbor
1048
1049         { // need pointarea
1050                 int nf = mIndices.size()/3, nv = mPoints.size();
1051                 pointareas.clear();
1052                 pointareas.resize(nv);
1053                 cornerareas.clear();
1054                 cornerareas.resize(nf);
1055
1056                 for (int i = 0; i < nf; i++) {
1057                         // Edges
1058                         ntlVec3Gfx e[3] = { 
1059                                 mPoints[mIndices[i*3+2]].v - mPoints[mIndices[i*3+1]].v,
1060                                 mPoints[mIndices[i*3+0]].v - mPoints[mIndices[i*3+2]].v,
1061                                 mPoints[mIndices[i*3+1]].v - mPoints[mIndices[i*3+0]].v };
1062
1063                         // Compute corner weights
1064                         float area = 0.5f * norm( cross(e[0], e[1]));
1065                         float l2[3] = { normNoSqrt(e[0]), normNoSqrt(e[1]), normNoSqrt(e[2]) };
1066                         float ew[3] = { l2[0] * (l2[1] + l2[2] - l2[0]),
1067                                         l2[1] * (l2[2] + l2[0] - l2[1]),
1068                                         l2[2] * (l2[0] + l2[1] - l2[2]) };
1069                         if (ew[0] <= 0.0f) {
1070                                 cornerareas[i][1] = -0.25f * l2[2] * area /
1071                                                                 dot(e[0] , e[2]);
1072                                 cornerareas[i][2] = -0.25f * l2[1] * area /
1073                                                                 dot(e[0] , e[1]);
1074                                 cornerareas[i][0] = area - cornerareas[i][1] -
1075                                                                 cornerareas[i][2];
1076                         } else if (ew[1] <= 0.0f) {
1077                                 cornerareas[i][2] = -0.25f * l2[0] * area /
1078                                                                 dot(e[1] , e[0]);
1079                                 cornerareas[i][0] = -0.25f * l2[2] * area /
1080                                                                 dot(e[1] , e[2]);
1081                                 cornerareas[i][1] = area - cornerareas[i][2] -
1082                                                                 cornerareas[i][0];
1083                         } else if (ew[2] <= 0.0f) {
1084                                 cornerareas[i][0] = -0.25f * l2[1] * area /
1085                                                                 dot(e[2] , e[1]);
1086                                 cornerareas[i][1] = -0.25f * l2[0] * area /
1087                                                                 dot(e[2] , e[0]);
1088                                 cornerareas[i][2] = area - cornerareas[i][0] -
1089                                                                 cornerareas[i][1];
1090                         } else {
1091                                 float ewscale = 0.5f * area / (ew[0] + ew[1] + ew[2]);
1092                                 for (int j = 0; j < 3; j++)
1093                                         cornerareas[i][j] = ewscale * (ew[(j+1)%3] +
1094                                                                                          ew[(j+2)%3]);
1095                         }
1096
1097                         // NT important, check this...
1098 #ifndef WIN32
1099                         if(! finite(cornerareas[i][0]) ) cornerareas[i][0]=1e-6;
1100                         if(! finite(cornerareas[i][1]) ) cornerareas[i][1]=1e-6;
1101                         if(! finite(cornerareas[i][2]) ) cornerareas[i][2]=1e-6;
1102 #else // WIN32
1103                         // FIXME check as well...
1104                         if(! (cornerareas[i][0]>=0.0) ) cornerareas[i][0]=1e-6;
1105                         if(! (cornerareas[i][1]>=0.0) ) cornerareas[i][1]=1e-6;
1106                         if(! (cornerareas[i][2]>=0.0) ) cornerareas[i][2]=1e-6;
1107 #endif // WIN32
1108
1109                         pointareas[mIndices[i*3+0]] += cornerareas[i][0];
1110                         pointareas[mIndices[i*3+1]] += cornerareas[i][1];
1111                         pointareas[mIndices[i*3+2]] += cornerareas[i][2];
1112                 }
1113
1114         } // need pointarea
1115
1116         int nv = mPoints.size();
1117         if ((int)flags.size() != nv) flags.resize(nv);
1118         float invsigma2 = 1.0f / (sigma*sigma);
1119
1120         vector<ntlVec3Gfx> nflt(nv);
1121         for (int i = 0; i < nv; i++) {
1122                 if(diffuseVertexField( &mPoints[0].n, 2, i, invsigma2, nflt[i])) {
1123                         normalize(nflt[i]);
1124                 } else { nflt[i]=mPoints[i].n; }
1125         }
1126
1127         // copy results
1128         for (int i = 0; i < nv; i++) { mPoints[i].n = nflt[i]; }
1129 }
1130
1131