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