Two in one:
[blender.git] / source / blender / src / fluidsim.c
1 /**
2  * fluidsim.c
3  * 
4  * $Id$
5  *
6  * ***** BEGIN GPL/BL DUAL LICENSE BLOCK *****
7  *
8  * This program is free software; you can redistribute it and/or
9  * modify it under the terms of the GNU General Public License
10  * as published by the Free Software Foundation; either version 2
11  * of the License, or (at your option) any later version. The Blender
12  * Foundation also sells licenses for use in proprietary software under
13  * the Blender License.  See http://www.blender.org/BL/ for information
14  * about this.
15  *
16  * This program is distributed in the hope that it will be useful,
17  * but WITHOUT ANY WARRANTY; without even the implied warranty of
18  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
19  * GNU General Public License for more details.
20  *
21  * You should have received a copy of the GNU General Public License
22  * along with this program; if not, write to the Free Software Foundation,
23  * Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
24  *
25  * The Original Code is Copyright (C) Blender Foundation
26  * All rights reserved.
27  *
28  * The Original Code is: all of this file.
29  *
30  * Contributor(s): none yet.
31  *
32  * ***** END GPL/BL DUAL LICENSE BLOCK *****
33  */
34
35
36
37 #include <math.h>
38 #include <stdlib.h>
39 #include <string.h>
40
41
42 #include "MEM_guardedalloc.h"
43
44 /* types */
45 #include "DNA_curve_types.h"
46 #include "DNA_object_types.h"
47 #include "DNA_object_fluidsim.h"        
48 #include "DNA_key_types.h"
49 #include "DNA_mesh_types.h"
50 #include "DNA_meshdata_types.h"
51 #include "DNA_lattice_types.h"
52 #include "DNA_scene_types.h"
53 #include "DNA_camera_types.h"
54 #include "DNA_screen_types.h"
55 #include "DNA_space_types.h"
56 #include "DNA_ipo_types.h"
57 #include "DNA_key_types.h" 
58
59 #include "BLI_blenlib.h"
60 #include "BLI_arithb.h"
61 #include "MTC_matrixops.h"
62
63 #include "BKE_customdata.h"
64 #include "BKE_displist.h"
65 #include "BKE_effect.h"
66 #include "BKE_global.h"
67 #include "BKE_main.h"
68 #include "BKE_key.h"
69 #include "BKE_scene.h"
70 #include "BKE_object.h"
71 #include "BKE_softbody.h"
72 #include "BKE_utildefines.h"
73 #include "BKE_DerivedMesh.h"
74 #include "BKE_ipo.h"
75 #include "LBM_fluidsim.h"
76 // warning - double elbeem.h in intern/extern...
77 #include "elbeem.h"
78
79 #include "BLI_editVert.h"
80 #include "BIF_editdeform.h"
81 #include "BIF_gl.h"
82 #include "BIF_screen.h"
83 #include "BIF_space.h"
84 #include "BIF_cursors.h"
85 #include "BIF_interface.h"
86 #include "BSE_headerbuttons.h"
87
88 #include "mydevice.h"
89 #include "blendef.h"
90 #include "SDL.h"
91 #include "SDL_thread.h"
92 #include "SDL_mutex.h"
93 #include <sys/stat.h>
94
95 #ifdef WIN32    /* Windos */
96 //#include "BLI_winstuff.h"
97 #ifndef snprintf
98 #define snprintf _snprintf
99 #endif
100 #endif
101 // SDL redefines main for SDL_main, not needed here...
102 #undef main
103
104 #ifdef __APPLE__        /* MacOS X */
105 #undef main
106 #endif
107
108 // from DerivedMesh.c
109 void initElbeemMesh(struct Object *ob, int *numVertices, float **vertices, int *numTriangles, int **triangles, int useGlobalCoords);
110
111 /* from header info.c */
112 extern int start_progress_bar(void);
113 extern void end_progress_bar(void);
114 extern int progress_bar(float done, char *busy_info);
115
116 double fluidsimViscosityPreset[6] = {
117         -1.0,   /* unused */
118         -1.0,   /* manual */
119         1.0e-6, /* water */
120         5.0e-5, /* some (thick) oil */
121         2.0e-3, /* ca. honey */
122         -1.0    /* end */
123 };
124
125 char* fluidsimViscosityPresetString[6] = {
126         "UNUSED",       /* unused */
127         "UNUSED",       /* manual */
128         "  = 1.0 * 10^-6", /* water */
129         "  = 5.0 * 10^-5", /* some (thick) oil */
130         "  = 2.0 * 10^-3", /* ca. honey */
131         "INVALID"       /* end */
132 };
133
134 typedef struct {
135         DerivedMesh dm;
136
137         // similar to MeshDerivedMesh
138         struct Object *ob;      // pointer to parent object
139         float *extverts, *nors; // face normals, colors?
140         Mesh *fsmesh;   // mesh struct to display (either surface, or original one)
141         char meshFree;  // free the mesh afterwards? (boolean)
142 } fluidsimDerivedMesh;
143
144
145
146 /* enable/disable overall compilation */
147 #ifndef DISABLE_ELBEEM
148
149
150 /* ********************** fluid sim settings struct functions ********************** */
151
152 /* allocates and initializes general main data */
153 FluidsimSettings *fluidsimSettingsNew(struct Object *srcob)
154 {
155         //char blendDir[FILE_MAXDIR], blendFile[FILE_MAXFILE];
156         FluidsimSettings *fss;
157         
158         /* this call uses derivedMesh methods... */
159         if(srcob->type!=OB_MESH) return NULL;
160         
161         fss= MEM_callocN( sizeof(FluidsimSettings), "fluidsimsettings memory");
162         
163         fss->type = 0;
164         fss->show_advancedoptions = 0;
165
166         fss->resolutionxyz = 50;
167         fss->previewresxyz = 25;
168         fss->realsize = 0.03;
169         fss->guiDisplayMode = 2; // preview
170         fss->renderDisplayMode = 3; // render
171
172         fss->viscosityMode = 2; // default to water
173         fss->viscosityValue = 1.0;
174         fss->viscosityExponent = 6;
175         fss->gravx = 0.0;
176         fss->gravy = 0.0;
177         fss->gravz = -9.81;
178         fss->animStart = 0.0; 
179         fss->animEnd = 0.30;
180         fss->gstar = 0.005; // used as normgstar
181         fss->maxRefine = -1;
182         // maxRefine is set according to resolutionxyz during bake
183
184         // fluid/inflow settings
185         fss->iniVelx = 
186         fss->iniVely = 
187         fss->iniVelz = 0.0;
188
189         strcpy(fss->surfdataPath,""); // leave blank, init upon first bake
190         fss->orgMesh = (Mesh *)srcob->data;
191         fss->meshSurface = NULL;
192         fss->meshBB = NULL;
193         fss->meshSurfNormals = NULL;
194
195         // first init of bounding box
196         fss->bbStart[0] = 0.0;
197         fss->bbStart[1] = 0.0;
198         fss->bbStart[2] = 0.0;
199         fss->bbSize[0] = 1.0;
200         fss->bbSize[1] = 1.0;
201         fss->bbSize[2] = 1.0;
202         fluidsimGetAxisAlignedBB(srcob->data, srcob->obmat, fss->bbStart, fss->bbSize, &fss->meshBB);
203         
204         // todo - reuse default init from elbeem!
205         fss->typeFlags = 0;
206         fss->domainNovecgen = 0;
207         fss->volumeInitType = 1; // volume
208         fss->partSlipValue = 0.0;
209
210         fss->generateTracers = 0;
211         fss->generateParticles = 0.0;
212         fss->surfaceSmoothing = 1.0;
213         fss->surfaceSubdivs = 1.0;
214         fss->particleInfSize = 0.0;
215         fss->particleInfAlpha = 0.0;
216
217         return fss;
218 }
219
220 /* duplicate struct, analogous to free */
221 static Mesh *fluidsimCopyMesh(Mesh *me)
222 {
223         Mesh *dup = MEM_dupallocN(me);
224
225         CustomData_copy(&me->vdata, &dup->vdata, CD_MASK_MESH, CD_DUPLICATE, me->totvert);
226         CustomData_copy(&me->vdata, &dup->vdata, CD_MASK_MESH, CD_DUPLICATE, me->totvert);
227         CustomData_copy(&me->vdata, &dup->vdata, CD_MASK_MESH, CD_DUPLICATE, me->totvert);
228
229         return dup;
230 }
231
232 FluidsimSettings* fluidsimSettingsCopy(FluidsimSettings *fss)
233 {
234         FluidsimSettings *dupfss;
235
236         if(!fss) return NULL;
237         dupfss = MEM_dupallocN(fss);
238
239         if(fss->meshSurface)
240                 dupfss->meshSurface = fluidsimCopyMesh(fss->meshSurface);
241         if(fss->meshBB)
242                 dupfss->meshBB = fluidsimCopyMesh(fss->meshBB);
243
244         if(fss->meshSurfNormals) dupfss->meshSurfNormals = MEM_dupallocN(fss->meshSurfNormals);
245
246         return dupfss;
247 }
248
249 /* free struct */
250 static void fluidsimFreeMesh(Mesh *me)
251 {
252         CustomData_free(&me->vdata, me->totvert);
253         CustomData_free(&me->edata, me->totedge);
254         CustomData_free(&me->fdata, me->totface);
255
256         MEM_freeN(me);
257 }
258
259 void fluidsimSettingsFree(FluidsimSettings *fss)
260 {
261         if(fss->meshSurface) {
262                 fluidsimFreeMesh(fss->meshSurface);
263                 fss->meshSurface = NULL;
264         }
265         if(fss->meshBB) {
266                 fluidsimFreeMesh(fss->meshBB);
267                 fss->meshBB = NULL;
268         }
269
270         if(fss->meshSurfNormals){ MEM_freeN(fss->meshSurfNormals); fss->meshSurfNormals=NULL; } 
271
272         MEM_freeN(fss);
273 }
274
275
276 /* helper function */
277 void fluidsimGetGeometryObjFilename(struct Object *ob, char *dst) { //, char *srcname) {
278         //snprintf(dst,FILE_MAXFILE, "%s_cfgdata_%s.bobj.gz", srcname, ob->id.name);
279         snprintf(dst,FILE_MAXFILE, "fluidcfgdata_%s.bobj.gz", ob->id.name);
280 }
281
282
283
284
285 /* ******************************************************************************** */
286 /* ********************** fluid sim channel helper functions ********************** */
287 /* ******************************************************************************** */
288
289 // no. of entries for the two channel sizes
290 #define CHANNEL_FLOAT 1
291 #define CHANNEL_VEC   3
292
293 #define FS_FREE_ONECHANNEL(c,str) { \
294         if(c){ MEM_freeN(c); c=NULL; } \
295 } // end ONE CHANN, debug: fprintf(stderr,"freeing " str " \n"); 
296
297 #define FS_FREE_CHANNELS { \
298         FS_FREE_ONECHANNEL(timeAtIndex,"timeAtIndex");\
299         FS_FREE_ONECHANNEL(timeAtFrame,"timeAtFrame");\
300         FS_FREE_ONECHANNEL(channelDomainTime,"channelDomainTime"); \
301         FS_FREE_ONECHANNEL(channelDomainGravity,"channelDomainGravity");\
302         FS_FREE_ONECHANNEL(channelDomainViscosity,"channelDomainViscosity");\
303         for(i=0;i<256;i++) { \
304                 FS_FREE_ONECHANNEL(channelObjMove[i][0],"channelObjMove0"); \
305                 FS_FREE_ONECHANNEL(channelObjMove[i][1],"channelObjMove1"); \
306                 FS_FREE_ONECHANNEL(channelObjMove[i][2],"channelObjMove2"); \
307                 FS_FREE_ONECHANNEL(channelObjInivel[i],"channelObjInivel"); \
308                 FS_FREE_ONECHANNEL(channelObjActive[i],"channelObjActive"); \
309         }  \
310 } // end FS FREE CHANNELS
311
312
313 // simplify channels before printing
314 // for API this is done anyway upon init
315 #if 0
316 static void fluidsimPrintChannel(FILE *file, float *channel, int paramsize, char *str, int entries) 
317
318         int i,j; 
319         int channelSize = paramsize; 
320
321         if(entries==3) {
322                 elbeemSimplifyChannelVec3( channel, &channelSize); 
323         } else if(entries==1) {
324                 elbeemSimplifyChannelFloat( channel, &channelSize); 
325         } else {
326                 // invalid, cant happen?
327         }
328
329         fprintf(file, "      CHANNEL %s = \n", str); 
330         for(i=0; i<channelSize;i++) { 
331                 fprintf(file,"        ");  
332                 for(j=0;j<=entries;j++) {  // also print time value
333                         fprintf(file," %f ", channel[i*(entries+1)+j] ); 
334                         if(j==entries-1){ fprintf(file,"  "); }
335                 } 
336                 fprintf(file," \n");  
337         } 
338
339         fprintf(file,  "      ; \n" ); 
340 }
341 #endif
342
343 static void fluidsimInitChannel(float **setchannel, int size, float *time, 
344                 int *icuIds, float *defaults, Ipo* ipo, int entries) {
345         int i,j;
346         IpoCurve* icus[3];
347         char *cstr = NULL;
348         float *channel = NULL;
349         float aniFrlen = G.scene->r.framelen;
350         if((entries<1) || (entries>3)) {
351                 printf("fluidsimInitChannel::Error - invalid no. of entries: %d\n",entries);
352                 entries = 1;
353         }
354
355         cstr = "fluidsiminit_channelfloat";
356         if(entries>1) cstr = "fluidsiminit_channelvec";
357         channel = MEM_callocN( size* (entries+1)* sizeof(float), cstr );
358         
359         if(ipo) {
360                 for(j=0; j<entries; j++) icus[j]  = find_ipocurve(ipo, icuIds[j] );
361         } else {
362                 for(j=0; j<entries; j++) icus[j]  = NULL; 
363         }
364         
365         for(j=0; j<entries; j++) {
366                 if(icus[j]) { 
367                         for(i=1; i<=size; i++) {
368                                 calc_icu(icus[j], aniFrlen*((float)i) );
369                                 channel[(i-1)*(entries+1) + j] = icus[j]->curval;
370                         }
371                 }  else {
372                         for(i=1; i<=size; i++) { channel[(i-1)*(entries+1) + j] = defaults[j]; }
373                 }
374                 //printf("fluidsimInitChannel entry:%d , ",j); for(i=1; i<=size; i++) { printf(" val%d:%f ",i, channel[(i-1)*(entries+1) + j] ); } printf(" \n"); // DEBUG
375         }
376         // set time values
377         for(i=1; i<=size; i++) {
378                 channel[(i-1)*(entries+1) + entries] = time[i];
379         }
380
381         *setchannel = channel;
382 }
383
384 static void fluidsimInitMeshChannel(float **setchannel, int size, Object *obm, int vertices, float *time) {
385         float *channel = NULL;
386         int mallsize = size* (3*vertices+1);
387         int frame,i;
388         int numVerts=0, numTris=0;
389         int setsize = 3*vertices+1;
390
391         channel = MEM_callocN( mallsize* sizeof(float), "fluidsim_meshchannel" );
392
393         //fprintf(stderr,"\n\nfluidsimInitMeshChannel size%d verts%d mallsize%d \n\n\n",size,vertices,mallsize);
394         for(frame=1; frame<=size; frame++) {
395                 float *verts=NULL;
396                 int *tris=NULL;
397                 G.scene->r.cfra = frame;
398                 scene_update_for_newframe(G.scene, G.scene->lay);
399
400                 initElbeemMesh(obm, &numVerts, &verts, &numTris, &tris, 1);
401                 //fprintf(stderr,"\nfluidsimInitMeshChannel frame%d verts%d/%d \n\n",frame,vertices,numVerts);
402                 for(i=0; i<3*vertices;i++) {
403                         channel[(frame-1)*setsize + i] = verts[i];
404                         //fprintf(stdout," frame%d vert%d=%f \n",frame,i,verts[i]);
405                         //if(i%3==2) fprintf(stdout,"\n");
406                 }
407                 channel[(frame-1)*setsize + setsize-1] = time[frame];
408
409                 MEM_freeN(verts);
410                 MEM_freeN(tris);
411         }
412         *setchannel = channel;
413 }
414
415
416 /* ******************************************************************************** */
417 /* ********************** simulation thread             ************************* */
418 /* ******************************************************************************** */
419
420 SDL_mutex       *globalBakeLock=NULL;
421 int                     globalBakeState = 0; // 0 everything ok, -1 abort simulation, -2 sim error, 1 sim done
422 int                     globalBakeFrame = 0;
423
424 // run simulation in seperate thread
425 static int fluidsimSimulateThread(void *unused) { // *ptr) {
426         //char* fnameCfgPath = (char*)(ptr);
427         int ret=0;
428         
429         ret = elbeemSimulate();
430         SDL_mutexP(globalBakeLock);
431         if(globalBakeState==0) {
432                 if(ret==0) {
433                         // if no error, set to normal exit
434                         globalBakeState = 1;
435                 } else {
436                         // simulation failed, display error
437                         globalBakeState = -2;
438                 }
439         }
440         SDL_mutexV(globalBakeLock);
441         return ret;
442 }
443
444
445 int runSimulationCallback(void *data, int status, int frame) {
446         //elbeemSimulationSettings *settings = (elbeemSimulationSettings*)data;
447         //printf("elbeem blender cb s%d, f%d, domainid:%d \n", status,frame, settings->domainId ); // DEBUG
448         
449         if(!globalBakeLock) return FLUIDSIM_CBRET_ABORT;
450         if(status==FLUIDSIM_CBSTATUS_NEWFRAME) {
451                 SDL_mutexP(globalBakeLock);
452                 globalBakeFrame = frame-1;
453                 SDL_mutexV(globalBakeLock);
454         }
455         
456         //if((frameCounter==3) && (!frameStop)) { frameStop=1; return 1; }
457                 
458         SDL_mutexP(globalBakeLock);
459         if(globalBakeState!=0) {
460                 return FLUIDSIM_CBRET_ABORT;
461         }
462         SDL_mutexV(globalBakeLock);
463         return FLUIDSIM_CBRET_CONTINUE;
464 }
465
466
467 /* ******************************************************************************** */
468 /* ********************** write fluidsim config to file ************************* */
469 /* ******************************************************************************** */
470
471 void fluidsimBake(struct Object *ob)
472 {
473         FILE *fileCfg;
474         int i;
475         struct Object *fsDomain = NULL;
476         FluidsimSettings *domainSettings;
477         struct Object *obit = NULL; /* object iterator */
478         int origFrame = G.scene->r.cfra;
479         char debugStrBuffer[256];
480         int dirExist = 0;
481         int gridlevels = 0;
482         int simAborted = 0; // was the simulation aborted by user?
483         int  doExportOnly = 0;
484         char *exportEnvStr = "BLENDER_ELBEEMEXPORTONLY";
485         const char *strEnvName = "BLENDER_ELBEEMDEBUG"; // from blendercall.cpp
486         //char *channelNames[3] = { "translation","rotation","scale" };
487
488         char *suffixConfig = "fluidsim.cfg";
489         char *suffixSurface = "fluidsurface";
490         char newSurfdataPath[FILE_MAXDIR+FILE_MAXFILE]; // modified output settings
491         char targetDir[FILE_MAXDIR+FILE_MAXFILE];  // store & modify output settings
492         char targetFile[FILE_MAXDIR+FILE_MAXFILE]; // temp. store filename from targetDir for access
493         int  outStringsChanged = 0;             // modified? copy back before baking
494         int  haveSomeFluid = 0;                 // check if any fluid objects are set
495
496         // config vars, inited before either export or run...
497         double calcViscosity = 0.0;
498         int noFrames;
499         double aniFrameTime;
500         float aniFrlen;
501         int   channelObjCount;
502         float *bbStart = NULL;
503         float *bbSize = NULL;
504         float domainMat[4][4];
505         float invDomMat[4][4];
506         // channel data
507         int   allchannelSize; // fixed by no. of frames
508         int   startFrame = 1;  // dont use G.scene->r.sfra here, always start with frame 1
509         // easy frame -> sim time calc
510         float *timeAtFrame=NULL, *timeAtIndex=NULL;
511         // domain
512         float *channelDomainTime = NULL;
513         float *channelDomainViscosity = NULL; 
514         float *channelDomainGravity = NULL;
515         // objects (currently max. 256 objs)
516         float *channelObjMove[256][3]; // object movments , 0=trans, 1=rot, 2=scale
517         float *channelObjInivel[256];    // initial velocities
518         float *channelObjActive[256];    // obj active channel
519
520         if(getenv(strEnvName)) {
521                 int dlevel = atoi(getenv(strEnvName));
522                 elbeemSetDebugLevel(dlevel);
523                 snprintf(debugStrBuffer,256,"fluidsimBake::msg: Debug messages activated due to envvar '%s'\n",strEnvName); 
524                 elbeemDebugOut(debugStrBuffer);
525         }
526         if(getenv(exportEnvStr)) {
527                 doExportOnly = atoi(getenv(exportEnvStr));
528                 snprintf(debugStrBuffer,256,"fluidsimBake::msg: Exporting mode set to '%d' due to envvar '%s'\n",doExportOnly, exportEnvStr); 
529                 elbeemDebugOut(debugStrBuffer);
530         }
531
532         // make sure it corresponds to startFrame setting
533         // old: noFrames = G.scene->r.efra - G.scene->r.sfra +1;
534         noFrames = G.scene->r.efra - 0;
535         if(noFrames<=0) {
536                 pupmenu("Fluidsim Bake Error%t|No frames to export - check your animation range settings. Aborted%x0");
537                 return;
538         }
539
540         /* no object pointer, find in selected ones.. */
541         if(!ob) {
542                 Base *base;
543                 for(base=G.scene->base.first; base; base= base->next) {
544                         if ( ((base)->flag & SELECT) 
545                                         // ignore layer setting for now? && ((base)->lay & G.vd->lay) 
546                                  ) {
547                                 if((!ob)&&(base->object->fluidsimFlag & OB_FLUIDSIM_ENABLE)&&(base->object->type==OB_MESH)) {
548                                         if(base->object->fluidsimSettings->type == OB_FLUIDSIM_DOMAIN) {
549                                                 ob = base->object;
550                                         }
551                                 }
552                         }
553                 }
554                 // no domains found?
555                 if(!ob) return;
556         }
557
558         /* check if there's another domain... */
559         for(obit= G.main->object.first; obit; obit= obit->id.next) {
560                 if((obit->fluidsimFlag & OB_FLUIDSIM_ENABLE)&&(obit->type==OB_MESH)) {
561                         if(obit->fluidsimSettings->type == OB_FLUIDSIM_DOMAIN) {
562                                 if(obit != ob) {
563                                         //snprintf(debugStrBuffer,256,"fluidsimBake::warning - More than one domain!\n"); elbeemDebugOut(debugStrBuffer);
564                                         pupmenu("Fluidsim Bake Error%t|There should be only one domain object! Aborted%x0");
565                                         return;
566                                 }
567                         }
568                 }
569         }
570         /* these both have to be valid, otherwise we wouldnt be here */
571         /* dont use ob here after...*/
572         fsDomain = ob;
573         domainSettings = ob->fluidsimSettings;
574         ob = NULL;
575         /* rough check of settings... */
576         if(domainSettings->previewresxyz > domainSettings->resolutionxyz) {
577                 snprintf(debugStrBuffer,256,"fluidsimBake::warning - Preview (%d) >= Resolution (%d)... setting equal.\n", domainSettings->previewresxyz ,  domainSettings->resolutionxyz); 
578                 elbeemDebugOut(debugStrBuffer);
579                 domainSettings->previewresxyz = domainSettings->resolutionxyz;
580         }
581         // set adaptive coarsening according to resolutionxyz
582         // this should do as an approximation, with in/outflow
583         // doing this more accurate would be overkill
584         // perhaps add manual setting?
585         if(domainSettings->maxRefine <0) {
586                 if(domainSettings->resolutionxyz>128) {
587                         gridlevels = 2;
588                 } else
589                 if(domainSettings->resolutionxyz>64) {
590                         gridlevels = 1;
591                 } else {
592                         gridlevels = 0;
593                 }
594         } else {
595                 gridlevels = domainSettings->maxRefine;
596         }
597         snprintf(debugStrBuffer,256,"fluidsimBake::msg: Baking %s, refine: %d\n", fsDomain->id.name , gridlevels ); 
598         elbeemDebugOut(debugStrBuffer);
599         
600         // check if theres any fluid
601         // abort baking if not...
602         for(obit= G.main->object.first; obit; obit= obit->id.next) {
603                 if( (obit->fluidsimFlag & OB_FLUIDSIM_ENABLE) && 
604                                 (obit->type==OB_MESH) && (
605                           (obit->fluidsimSettings->type == OB_FLUIDSIM_FLUID) ||
606                           (obit->fluidsimSettings->type == OB_FLUIDSIM_INFLOW) )
607                                 ) {
608                         haveSomeFluid = 1;
609                 }
610         }
611         if(!haveSomeFluid) {
612                 pupmenu("Fluidsim Bake Error%t|No fluid objects in scene... Aborted%x0");
613                 return;
614         }
615
616         // prepare names...
617         strncpy(targetDir, domainSettings->surfdataPath, FILE_MAXDIR);
618         strncpy(newSurfdataPath, domainSettings->surfdataPath, FILE_MAXDIR);
619         BLI_convertstringcode(targetDir, G.sce, 0); // fixed #frame-no 
620
621         strcpy(targetFile, targetDir);
622         strcat(targetFile, suffixConfig);
623         if(!doExportOnly) { strcat(targetFile,".tmp"); }  // dont overwrite/delete original file
624         // make sure all directories exist
625         // as the bobjs use the same dir, this only needs to be checked
626         // for the cfg output
627         BLI_make_existing_file(targetFile);
628
629         // check selected directory
630         // simply try to open cfg file for writing to test validity of settings
631         fileCfg = fopen(targetFile, "w");
632         if(fileCfg) { 
633                 dirExist = 1; fclose(fileCfg); 
634                 // remove cfg dummy from  directory test
635                 if(!doExportOnly) { BLI_delete(targetFile, 0,0); }
636         }
637
638         if((strlen(targetDir)<1) || (!dirExist)) {
639                 char blendDir[FILE_MAXDIR+FILE_MAXFILE], blendFile[FILE_MAXDIR+FILE_MAXFILE];
640                 // invalid dir, reset to current/previous
641                 strcpy(blendDir, G.sce);
642                 BLI_splitdirstring(blendDir, blendFile);
643                 if(strlen(blendFile)>6){
644                         int len = strlen(blendFile);
645                         if( (blendFile[len-6]=='.')&& (blendFile[len-5]=='b')&& (blendFile[len-4]=='l')&&
646                                         (blendFile[len-3]=='e')&& (blendFile[len-2]=='n')&& (blendFile[len-1]=='d') ){
647                                 blendFile[len-6] = '\0';
648                         }
649                 }
650                 // todo... strip .blend ?
651                 snprintf(newSurfdataPath,FILE_MAXFILE+FILE_MAXDIR,"//fluidsimdata/%s_%s_", blendFile, fsDomain->id.name);
652
653                 snprintf(debugStrBuffer,256,"fluidsimBake::error - warning resetting output dir to '%s'\n", newSurfdataPath);
654                 elbeemDebugOut(debugStrBuffer);
655                 outStringsChanged=1;
656         }
657
658         // check if modified output dir is ok
659         if(outStringsChanged) {
660                 char dispmsg[FILE_MAXDIR+FILE_MAXFILE+256];
661                 int  selection=0;
662                 strcpy(dispmsg,"Output settings set to: '");
663                 strcat(dispmsg, newSurfdataPath);
664                 strcat(dispmsg, "'%t|Continue with changed settings%x1|Discard and abort%x0");
665
666                 // ask user if thats what he/she wants...
667                 selection = pupmenu(dispmsg);
668                 if(selection<1) return; // 0 from menu, or -1 aborted
669                 strcpy(targetDir, newSurfdataPath);
670                 strncpy(domainSettings->surfdataPath, newSurfdataPath, FILE_MAXDIR);
671                 BLI_convertstringcode(targetDir, G.sce, 0); // fixed #frame-no 
672         }
673         
674         // --------------------------------------------------------------------------------------------
675         // dump data for start frame 
676         // CHECK more reasonable to number frames according to blender?
677         // dump data for frame 0
678   G.scene->r.cfra = startFrame;
679   scene_update_for_newframe(G.scene, G.scene->lay);
680         
681         // init common export vars for both file export and run
682         for(i=0; i<256; i++) {
683                 channelObjMove[i][0] = channelObjMove[i][1] = channelObjMove[i][2] = NULL;
684                 channelObjInivel[i] = NULL;
685                 channelObjActive[i] = NULL;
686         }
687         allchannelSize = G.scene->r.efra; // always use till last frame
688         aniFrameTime = (domainSettings->animEnd - domainSettings->animStart)/(double)noFrames;
689         // blender specific - scale according to map old/new settings in anim panel:
690         aniFrlen = G.scene->r.framelen;
691         if(domainSettings->viscosityMode==1) {
692                 /* manual mode, visc=value/(10^-vexp) */
693                 calcViscosity = (1.0/pow(10.0,domainSettings->viscosityExponent)) * domainSettings->viscosityValue;
694         } else {
695                 calcViscosity = fluidsimViscosityPreset[ domainSettings->viscosityMode ];
696         }
697
698         bbStart = fsDomain->fluidsimSettings->bbStart; 
699         bbSize = fsDomain->fluidsimSettings->bbSize;
700         fluidsimGetAxisAlignedBB(fsDomain->data, fsDomain->obmat, bbStart, bbSize, &domainSettings->meshBB);
701
702         // always init
703         { int timeIcu[1] = { FLUIDSIM_TIME };
704                 float timeDef[1] = { 1. };
705                 int gravIcu[3] = { FLUIDSIM_GRAV_X, FLUIDSIM_GRAV_Y, FLUIDSIM_GRAV_Z };
706                 float gravDef[3];
707                 int viscIcu[1] = { FLUIDSIM_VISC };
708                 float viscDef[1] = { 1. };
709
710                 gravDef[0] = domainSettings->gravx;
711                 gravDef[1] = domainSettings->gravy;
712                 gravDef[2] = domainSettings->gravz;
713
714                 // time channel is a bit special, init by hand...
715                 timeAtIndex = MEM_callocN( (allchannelSize+1)*1*sizeof(float), "fluidsiminit_timeatindex");
716                 for(i=0; i<=G.scene->r.efra; i++) {
717                         timeAtIndex[i] = (float)(i-startFrame);
718                 }
719                 fluidsimInitChannel( &channelDomainTime, allchannelSize, timeAtIndex, timeIcu,timeDef, domainSettings->ipo, CHANNEL_FLOAT ); // NDEB
720                 // time channel is a multiplicator for aniFrameTime
721                 if(channelDomainTime) {
722                         for(i=0; i<allchannelSize; i++) { 
723                                 channelDomainTime[i*2+0] = aniFrameTime * channelDomainTime[i*2+0]; 
724                                 if(channelDomainTime[i*2+0]<0.) channelDomainTime[i*2+0] = 0.;
725                         }
726                 }
727                 timeAtFrame = MEM_callocN( (allchannelSize+1)*1*sizeof(float), "fluidsiminit_timeatframe");
728                 timeAtFrame[0] = timeAtFrame[1] = domainSettings->animStart; // start at index 1
729                 if(channelDomainTime) {
730                         for(i=2; i<=allchannelSize; i++) {
731                                 timeAtFrame[i] = timeAtFrame[i-1]+channelDomainTime[(i-1)*2+0];
732                         }
733                 } else {
734                         for(i=2; i<=allchannelSize; i++) { timeAtFrame[i] = timeAtFrame[i-1]+aniFrameTime; }
735                 }
736
737                 fluidsimInitChannel( &channelDomainViscosity, allchannelSize, timeAtFrame, viscIcu,viscDef, domainSettings->ipo, CHANNEL_FLOAT ); // NDEB
738                 if(channelDomainViscosity) {
739                         for(i=0; i<allchannelSize; i++) { channelDomainViscosity[i*2+0] = calcViscosity * channelDomainViscosity[i*2+0]; }
740                 }
741                 fluidsimInitChannel( &channelDomainGravity, allchannelSize, timeAtFrame, gravIcu,gravDef, domainSettings->ipo, CHANNEL_VEC );
742         } // domain channel init
743         
744         // init obj movement channels
745         channelObjCount=0;
746         for(obit= G.main->object.first; obit; obit= obit->id.next) {
747                 //{ snprintf(debugStrBuffer,256,"DEBUG object name=%s, type=%d ...\n", obit->id.name, obit->type); elbeemDebugOut(debugStrBuffer); } // DEBUG
748                 if( (obit->fluidsimFlag & OB_FLUIDSIM_ENABLE) && 
749                                 (obit->type==OB_MESH) &&
750                                 (obit->fluidsimSettings->type != OB_FLUIDSIM_DOMAIN) &&  // if has to match 3 places! // CHECKMATCH
751                                 (obit->fluidsimSettings->type != OB_FLUIDSIM_PARTICLE) ) {
752
753                         //  cant use fluidsimInitChannel for obj channels right now, due
754                         //  to the special DXXX channels, and the rotation specialities
755                         IpoCurve *icuex[3][3];
756                         //IpoCurve *par_icuex[3][3];
757                         int icuIds[3][3] = { 
758                                 {OB_LOC_X,  OB_LOC_Y,  OB_LOC_Z},
759                                 {OB_ROT_X,  OB_ROT_Y,  OB_ROT_Z},
760                                 {OB_SIZE_X, OB_SIZE_Y, OB_SIZE_Z} 
761                         };
762                         // relative ipos
763                         IpoCurve *icudex[3][3];
764                         //IpoCurve *par_icudex[3][3];
765                         int icudIds[3][3] = { 
766                                 {OB_DLOC_X,  OB_DLOC_Y,  OB_DLOC_Z},
767                                 {OB_DROT_X,  OB_DROT_Y,  OB_DROT_Z},
768                                 {OB_DSIZE_X, OB_DSIZE_Y, OB_DSIZE_Z} 
769                         };
770                         int j,k;
771                         float vals[3] = {0.0,0.0,0.0}; 
772                         int o = channelObjCount;
773                         int   inivelIcu[3] =  { FLUIDSIM_VEL_X, FLUIDSIM_VEL_Y, FLUIDSIM_VEL_Z };
774                         float inivelDefs[3];
775                         int   activeIcu[1] =  { FLUIDSIM_ACTIVE };
776                         float activeDefs[1] = { 1 }; // default to on
777
778                         inivelDefs[0] = obit->fluidsimSettings->iniVelx;
779                         inivelDefs[1] = obit->fluidsimSettings->iniVely;
780                         inivelDefs[2] = obit->fluidsimSettings->iniVelz;
781
782                         // check & init loc,rot,size
783                         for(j=0; j<3; j++) {
784                                 for(k=0; k<3; k++) {
785                                         icuex[j][k]  = find_ipocurve(obit->ipo, icuIds[j][k] );
786                                         icudex[j][k] = find_ipocurve(obit->ipo, icudIds[j][k] );
787                                         //if(obit->parent) {
788                                                 //par_icuex[j][k]  = find_ipocurve(obit->parent->ipo, icuIds[j][k] );
789                                                 //par_icudex[j][k] = find_ipocurve(obit->parent->ipo, icudIds[j][k] );
790                                         //}
791                                 }
792                         }
793
794                         for(j=0; j<3; j++) {
795                                 channelObjMove[o][j] = MEM_callocN( allchannelSize*4*sizeof(float), "fluidsiminit_objmovchannel");
796                                 for(i=1; i<=allchannelSize; i++) {
797
798                                         for(k=0; k<3; k++) {
799                                                 if(icuex[j][k]) { 
800                                                         // IPO exists, use it ...
801                                                         calc_icu(icuex[j][k], aniFrlen*((float)i) );
802                                                         vals[k] = icuex[j][k]->curval; 
803                                                         if(obit->parent) {
804                                                                 // add parent transform, multiply scaling, add trafo&rot
805                                                                 //calc_icu(par_icuex[j][k], aniFrlen*((float)i) );
806                                                                 //if(j==2) { vals[k] *= par_icuex[j][k]->curval; }
807                                                                 //else { vals[k] += par_icuex[j][k]->curval; }
808                                                         }
809                                                 } else {
810                                                         // use defaults from static values
811                                                         float setval=0.0;
812                                                         if(j==0) { 
813                                                                 setval = obit->loc[k];
814                                                                 if(obit->parent){ setval += obit->parent->loc[k]; }
815                                                         } else if(j==1) { 
816                                                                 setval = ( 180.0*obit->rot[k] )/( 10.0*M_PI );
817                                                                 if(obit->parent){ setval = ( 180.0*(obit->rot[k]+obit->parent->rot[k]) )/( 10.0*M_PI ); }
818                                                         } else { 
819                                                                 setval = obit->size[k]; 
820                                                                 if(obit->parent){ setval *= obit->parent->size[k]; }
821                                                         }
822                                                         vals[k] = setval;
823                                                 }
824                                                 if(icudex[j][k]) { 
825                                                         calc_icu(icudex[j][k], aniFrlen*((float)i) );
826                                                         //vals[k] += icudex[j][k]->curval; 
827                                                         // add transform, multiply scaling, add trafo&rot
828                                                         if(j==2) { vals[k] *= icudex[j][k]->curval; }
829                                                         else { vals[k] += icudex[j][k]->curval; }
830                                                         if(obit->parent) {
831                                                                 // add parent transform, multiply scaling, add trafo&rot
832                                                                 //calc_icu(par_icuex[j][k], aniFrlen*((float)i) );
833                                                                 //if(j==2) { vals[k] *= par_icudex[j][k]->curval; }
834                                                                 //else { vals[k] += par_icudex[j][k]->curval; }
835                                                         }
836                                                 } 
837                                         } // k
838
839                                         for(k=0; k<3; k++) {
840                                                 float set = vals[k];
841                                                 if(j==1) { // rot is downscaled by 10 for ipo !?
842                                                         set = 360.0 - (10.0*set);
843                                                 }
844                                                 channelObjMove[o][j][(i-1)*4 + k] = set;
845                                         } // k
846                                         channelObjMove[o][j][(i-1)*4 + 3] = timeAtFrame[i];
847                                 }
848                         }
849
850                         fluidsimInitChannel( &channelObjInivel[o], allchannelSize, timeAtFrame, inivelIcu,inivelDefs, obit->fluidsimSettings->ipo, CHANNEL_VEC );
851                         fluidsimInitChannel( &channelObjActive[o], allchannelSize, timeAtFrame, activeIcu,activeDefs, obit->fluidsimSettings->ipo, CHANNEL_FLOAT );
852
853                         channelObjCount++;
854
855                 }
856         }
857
858         // init trafo matrix
859         MTC_Mat4CpyMat4(domainMat, fsDomain->obmat);
860         if(!Mat4Invert(invDomMat, domainMat)) {
861                 snprintf(debugStrBuffer,256,"fluidsimBake::error - Invalid obj matrix?\n"); 
862                 elbeemDebugOut(debugStrBuffer);
863                 // FIXME add fatal msg
864                 FS_FREE_CHANNELS;
865                 return;
866         }
867
868
869         // --------------------------------------------------------------------------------------------
870         // start writing / exporting
871         strcpy(targetFile, targetDir);
872         strcat(targetFile, suffixConfig);
873         if(!doExportOnly) { strcat(targetFile,".tmp"); }  // dont overwrite/delete original file
874         // make sure these directories exist as well
875         if(outStringsChanged) {
876                 BLI_make_existing_file(targetFile);
877         }
878
879         if(!doExportOnly) {
880                 SDL_Thread *simthr = NULL;
881
882                 // perform simulation with El'Beem api and SDL threads
883                 elbeemSimulationSettings fsset;
884                 elbeemResetSettings(&fsset);
885                 fsset.version = 1;
886
887                 // setup global settings
888                 for(i=0 ; i<3; i++) fsset.geoStart[i] = bbStart[i];
889                 for(i=0 ; i<3; i++) fsset.geoSize[i] = bbSize[i];
890                 // simulate with 50^3
891                 fsset.resolutionxyz = (int)domainSettings->resolutionxyz;
892                 fsset.previewresxyz = (int)domainSettings->previewresxyz;
893                 // 10cm water domain
894                 fsset.realsize = domainSettings->realsize;
895                 fsset.viscosity = calcViscosity;
896                 // earth gravity
897                 fsset.gravity[0] = domainSettings->gravx;
898                 fsset.gravity[1] = domainSettings->gravy;
899                 fsset.gravity[2] = domainSettings->gravz;
900                 // simulate 5 frames, each 0.03 seconds, output to ./apitest_XXX.bobj.gz
901                 fsset.animStart = domainSettings->animStart;
902                 fsset.aniFrameTime = aniFrameTime;
903                 fsset.noOfFrames = noFrames - 1; // is otherwise subtracted in parser
904                 strcpy(targetFile, targetDir);
905                 strcat(targetFile, suffixSurface);
906                 // defaults for compressibility and adaptive grids
907                 fsset.gstar = domainSettings->gstar;
908                 fsset.maxRefine = domainSettings->maxRefine; // check <-> gridlevels
909                 fsset.generateParticles = domainSettings->generateParticles; 
910                 fsset.numTracerParticles = domainSettings->generateTracers; 
911                 fsset.surfaceSmoothing = domainSettings->surfaceSmoothing; 
912                 fsset.surfaceSubdivs = domainSettings->surfaceSubdivs; 
913                 fsset.farFieldSize = domainSettings->farFieldSize; 
914                 strcpy( fsset.outputPath, targetFile);
915
916                 // domain channels
917                 fsset.channelSizeFrameTime = 
918                 fsset.channelSizeViscosity = 
919                 fsset.channelSizeGravity =  allchannelSize;
920                 fsset.channelFrameTime = channelDomainTime;
921                 fsset.channelViscosity = channelDomainViscosity;
922                 fsset.channelGravity = channelDomainGravity;
923
924                 fsset.runsimCallback = &runSimulationCallback;
925                 fsset.runsimUserData = &fsset;
926
927                 if(     (domainSettings->typeFlags&OB_FSBND_NOSLIP))   fsset.domainobsType = FLUIDSIM_OBSTACLE_NOSLIP;
928                 else if((domainSettings->typeFlags&OB_FSBND_PARTSLIP)) fsset.domainobsType = FLUIDSIM_OBSTACLE_PARTSLIP;
929                 else if((domainSettings->typeFlags&OB_FSBND_FREESLIP)) fsset.domainobsType = FLUIDSIM_OBSTACLE_FREESLIP;
930                 fsset.domainobsPartslip = domainSettings->partSlipValue;
931                 fsset.generateVertexVectors = (domainSettings->domainNovecgen==0);
932
933                 // init blender trafo matrix
934                 // fprintf(stderr,"elbeemInit - mpTrafo:\n");
935                 { int j; 
936                 for(i=0; i<4; i++) {
937                         for(j=0; j<4; j++) {
938                                 fsset.surfaceTrafo[i*4+j] = invDomMat[j][i];
939                                 // fprintf(stderr,"elbeemInit - mpTrafo %d %d = %f (%d) \n", i,j, fsset.surfaceTrafo[i*4+j] , (i*4+j) );
940                         }
941                 } }
942
943           // init solver with settings
944                 elbeemInit();
945                 elbeemAddDomain(&fsset);
946                 
947                 // init objects
948                 channelObjCount = 0;
949                 for(obit= G.main->object.first; obit; obit= obit->id.next) {
950                         //{ snprintf(debugStrBuffer,256,"DEBUG object name=%s, type=%d ...\n", obit->id.name, obit->type); elbeemDebugOut(debugStrBuffer); } // DEBUG
951                         if( (obit->fluidsimFlag & OB_FLUIDSIM_ENABLE) &&  // if has to match 3 places! // CHECKMATCH
952                                         (obit->type==OB_MESH) &&
953                                         (obit->fluidsimSettings->type != OB_FLUIDSIM_DOMAIN) &&
954                                         (obit->fluidsimSettings->type != OB_FLUIDSIM_PARTICLE)
955                                 ) {
956                                 float *verts=NULL;
957                                 int *tris=NULL;
958                                 int numVerts=0, numTris=0;
959                                 int o = channelObjCount;
960                                 int     deform = (obit->fluidsimSettings->domainNovecgen); // misused value
961                                 // todo - use blenderInitElbeemMesh
962                                 elbeemMesh fsmesh;
963                                 elbeemResetMesh( &fsmesh );
964                                 fsmesh.type = obit->fluidsimSettings->type;;
965                                 // get name of object for debugging solver
966                                 fsmesh.name = obit->id.name; 
967
968                                 initElbeemMesh(obit, &numVerts, &verts, &numTris, &tris, 0);
969                                 fsmesh.numVertices   = numVerts;
970                                 fsmesh.numTriangles  = numTris;
971                                 fsmesh.vertices      = verts;
972                                 fsmesh.triangles     = tris;
973
974                                 fsmesh.channelSizeTranslation  = 
975                                 fsmesh.channelSizeRotation     = 
976                                 fsmesh.channelSizeScale        = 
977                                 fsmesh.channelSizeInitialVel   = 
978                                 fsmesh.channelSizeActive       = allchannelSize;
979
980                                 fsmesh.channelTranslation      = channelObjMove[o][0];
981                                 fsmesh.channelRotation         = channelObjMove[o][1];
982                                 fsmesh.channelScale            = channelObjMove[o][2];
983                                 fsmesh.channelActive           = channelObjActive[o];
984                                 if( (fsmesh.type == OB_FLUIDSIM_FLUID) ||
985                                                 (fsmesh.type == OB_FLUIDSIM_INFLOW) ) {
986                                         fsmesh.channelInitialVel       = channelObjInivel[o];
987                                   fsmesh.localInivelCoords = ((obit->fluidsimSettings->typeFlags&OB_FSINFLOW_LOCALCOORD)?1:0);
988                                 } 
989
990                                 if(     (obit->fluidsimSettings->typeFlags&OB_FSBND_NOSLIP))   fsmesh.obstacleType = FLUIDSIM_OBSTACLE_NOSLIP;
991                                 else if((obit->fluidsimSettings->typeFlags&OB_FSBND_PARTSLIP)) fsmesh.obstacleType = FLUIDSIM_OBSTACLE_PARTSLIP;
992                                 else if((obit->fluidsimSettings->typeFlags&OB_FSBND_FREESLIP)) fsmesh.obstacleType = FLUIDSIM_OBSTACLE_FREESLIP;
993                                 fsmesh.obstaclePartslip = obit->fluidsimSettings->partSlipValue;
994                                 fsmesh.volumeInitType = obit->fluidsimSettings->volumeInitType;
995                                 fsmesh.obstacleImpactFactor = obit->fluidsimSettings->surfaceSmoothing; // misused value
996
997                                 // animated meshes
998                                 if(deform) {
999                                         fsmesh.channelSizeVertices = allchannelSize;
1000                                         fluidsimInitMeshChannel( &fsmesh.channelVertices, allchannelSize, obit, numVerts, timeAtFrame);
1001                                         G.scene->r.cfra = startFrame;
1002                                         scene_update_for_newframe(G.scene, G.scene->lay);
1003                                         // remove channels
1004                                         fsmesh.channelTranslation      = 
1005                                         fsmesh.channelRotation         = 
1006                                         fsmesh.channelScale            = NULL; 
1007                                 } 
1008
1009                                 elbeemAddMesh(&fsmesh);
1010
1011                                 if(verts) MEM_freeN(verts);
1012                                 if(tris) MEM_freeN(tris);
1013                                 if(fsmesh.channelVertices) MEM_freeN(fsmesh.channelVertices);
1014                                 channelObjCount++;
1015                         } // valid mesh
1016                 } // objects
1017                 //domainSettings->type = OB_FLUIDSIM_DOMAIN; // enable for bake display again
1018                 //fsDomain->fluidsimFlag = OB_FLUIDSIM_ENABLE; // disable during bake
1019                 
1020                 globalBakeLock = SDL_CreateMutex();
1021                 // set to neutral, -1 means user abort, -2 means init error
1022                 globalBakeState = 0;
1023                 globalBakeFrame = 0;
1024                 simthr = SDL_CreateThread(fluidsimSimulateThread, targetFile);
1025
1026                 if(!simthr) {
1027                         snprintf(debugStrBuffer,256,"fluidsimBake::error: Unable to create thread... running without one.\n"); 
1028                         elbeemDebugOut(debugStrBuffer);
1029                         set_timecursor(0);
1030                         elbeemSimulate();
1031                 } else {
1032                         int done = 0;
1033                         unsigned short event=0;
1034                         short val;
1035                         float noFramesf = (float)noFrames;
1036                         float percentdone = 0.0;
1037                         int lastRedraw = -1;
1038                         
1039                         start_progress_bar();
1040
1041                         while(done==0) {            
1042                                 char busy_mess[80];
1043                                 
1044                                 waitcursor(1);
1045                                 
1046                                 // lukep we add progress bar as an interim mesure
1047                                 percentdone = globalBakeFrame / noFramesf;
1048                                 sprintf(busy_mess, "baking fluids %d / %d       |||", globalBakeFrame, (int) noFramesf);
1049                                 progress_bar(percentdone, busy_mess );
1050                                 
1051                                 SDL_Delay(2000); // longer delay to prevent frequent redrawing
1052                                 SDL_mutexP(globalBakeLock);
1053                                 if(globalBakeState != 0) done = 1; // 1=ok, <0=error/abort
1054                                 SDL_mutexV(globalBakeLock);
1055
1056                                 while(qtest()) {
1057                                         event = extern_qread(&val);
1058                                         if(event == ESCKEY) {
1059                                                 // abort...
1060                                                 SDL_mutexP(globalBakeLock);
1061                                                 done = -1;
1062                                                 globalBakeFrame = 0;
1063                                                 globalBakeState = -1;
1064                                                 simAborted = 1;
1065                                                 SDL_mutexV(globalBakeLock);
1066                                                 break;
1067                                         }
1068                                 } 
1069
1070                                 // redraw the 3D for showing progress once in a while...
1071                                 if(lastRedraw!=globalBakeFrame) {
1072                                         ScrArea *sa;
1073                                         G.scene->r.cfra = startFrame+globalBakeFrame;
1074                                         lastRedraw = globalBakeFrame;
1075                                         update_for_newframe_muted();
1076                                         sa= G.curscreen->areabase.first;
1077                                         while(sa) {
1078                                                 if(sa->spacetype == SPACE_VIEW3D) { scrarea_do_windraw(sa); }
1079                                                 sa= sa->next;   
1080                                         } 
1081                                         screen_swapbuffers();
1082                                 } // redraw
1083                         }
1084                         SDL_WaitThread(simthr,NULL);
1085                         end_progress_bar();
1086                 }
1087                 SDL_DestroyMutex(globalBakeLock);
1088                 globalBakeLock = NULL;
1089         } // El'Beem API init, thread creation 
1090         // --------------------------------------------------------------------------------------------
1091         else
1092         { // write config file to be run with command line simulator
1093                 pupmenu("Fluidsim Bake Message%t|Config file export not supported.%x0");
1094         } // config file export done!
1095
1096         // --------------------------------------------------------------------------------------------
1097         FS_FREE_CHANNELS;
1098
1099         // go back to "current" blender time
1100         waitcursor(0);
1101   G.scene->r.cfra = origFrame;
1102   scene_update_for_newframe(G.scene, G.scene->lay);
1103         allqueue(REDRAWVIEW3D, 0);
1104         allqueue(REDRAWBUTSOBJECT, 0);
1105
1106         if(!simAborted) {
1107                 char fsmessage[512];
1108                 char elbeemerr[256];
1109                 strcpy(fsmessage,"Fluidsim Bake Error: ");
1110                 // check if some error occurred
1111                 if(globalBakeState==-2) {
1112                         strcat(fsmessage,"Failed to initialize [Msg: ");
1113
1114                         elbeemGetErrorString(elbeemerr);
1115                         strcat(fsmessage,elbeemerr);
1116
1117                         strcat(fsmessage,"] |OK%x0");
1118                         pupmenu(fsmessage);
1119                 } // init error
1120         }
1121 }
1122
1123
1124 #else /* DISABLE_ELBEEM */
1125
1126 /* compile dummy functions for disabled fluid sim */
1127
1128 FluidsimSettings *fluidsimSettingsNew(struct Object *srcob) {
1129         return NULL;
1130 }
1131
1132 void fluidsimSettingsFree(FluidsimSettings *fss) {
1133 }
1134
1135 FluidsimSettings* fluidsimSettingsCopy(FluidsimSettings *fss) {
1136         return NULL;
1137 }
1138
1139 /* only compile dummy functions */
1140 void fluidsimBake(struct Object *ob) {
1141 }
1142
1143 #endif /* DISABLE_ELBEEM */
1144