svn merge -r39765:39781 https://svn.blender.org/svnroot/bf-blender/trunk/blender
[blender.git] / source / blender / modifiers / intern / MOD_fluidsim_util.c
1 /*
2 * $Id$
3 *
4 * ***** BEGIN GPL LICENSE BLOCK *****
5 *
6 * This program is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU General Public License
8 * as published by the Free Software Foundation; either version 2
9 * of the License, or (at your option) any later version.
10 *
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14 * GNU General Public License for more details.
15 *
16 * You should have received a copy of the GNU General Public License
17 * along with this program; if not, write to the Free Software  Foundation,
18 * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
19 *
20 * The Original Code is Copyright (C) 2005 by the Blender Foundation.
21 * All rights reserved.
22 *
23 * Contributor(s): Daniel Dunbar
24 *                 Ton Roosendaal,
25 *                 Ben Batt,
26 *                 Brecht Van Lommel,
27 *                 Campbell Barton
28 *
29 * ***** END GPL LICENSE BLOCK *****
30 *
31 */
32
33 /** \file blender/modifiers/intern/MOD_fluidsim_util.c
34  *  \ingroup modifiers
35  */
36
37
38 #include <stddef.h>
39 #include <zlib.h>
40
41 #include "DNA_object_types.h"
42 #include "DNA_scene_types.h"
43 #include "DNA_mesh_types.h"
44 #include "DNA_meshdata_types.h"
45 #include "DNA_object_types.h"
46 #include "DNA_object_fluidsim.h"
47
48 #include "BLI_blenlib.h"
49 #include "BLI_math.h"
50 #include "BLI_utildefines.h"
51
52 #include "BKE_main.h"
53 #include "BKE_fluidsim.h" /* ensure definitions here match */
54 #include "BKE_cdderivedmesh.h"
55 #include "BKE_mesh.h"
56 #include "BKE_utildefines.h"
57 #include "BKE_global.h" /* G.main->name only */
58
59 #include "MOD_fluidsim_util.h"
60 #include "MOD_modifiertypes.h"
61
62 #include "MEM_guardedalloc.h"
63
64 // headers for fluidsim bobj meshes
65 #include "LBM_fluidsim.h"
66
67 void fluidsim_init(FluidsimModifierData *fluidmd)
68 {
69 #ifndef DISABLE_ELBEEM
70         if(fluidmd)
71         {
72                 FluidsimSettings *fss = MEM_callocN(sizeof(FluidsimSettings), "fluidsimsettings");
73                 
74                 fluidmd->fss = fss;
75                 
76                 if(!fss)
77                         return;
78                 
79                 fss->fmd = fluidmd;
80                 fss->type = OB_FLUIDSIM_ENABLE;
81                 fss->show_advancedoptions = 0;
82
83                 fss->resolutionxyz = 65;
84                 fss->previewresxyz = 45;
85                 fss->realsize = 0.5;
86                 fss->guiDisplayMode = 2; // preview
87                 fss->renderDisplayMode = 3; // render
88
89                 fss->viscosityMode = 2; // default to water
90                 fss->viscosityValue = 1.0;
91                 fss->viscosityExponent = 6;
92                 
93                 fss->grav[0] = 0.0;
94                 fss->grav[1] = 0.0;
95                 fss->grav[2] = -9.81;
96
97                 fss->animStart = 0.0; 
98                 fss->animEnd = 4.0;
99                 fss->gstar = 0.005; // used as normgstar
100                 fss->maxRefine = -1;
101                 // maxRefine is set according to resolutionxyz during bake
102
103                 // fluid/inflow settings
104                 // fss->iniVel --> automatically set to 0
105
106                 /*  elubie: changed this to default to the same dir as the render output
107                 to prevent saving to C:\ on Windows */
108                 BLI_strncpy(fss->surfdataPath, btempdir, FILE_MAX);
109
110                 // first init of bounding box
111                 // no bounding box needed
112                 
113                 // todo - reuse default init from elbeem!
114                 fss->typeFlags = OB_FSBND_PARTSLIP | OB_FSSG_NOOBS;
115                 fss->domainNovecgen = 0;
116                 fss->volumeInitType = 1; // volume
117                 fss->partSlipValue = 0.2;
118
119                 fss->generateTracers = 0;
120                 fss->generateParticles = 0.0;
121                 fss->surfaceSmoothing = 1.0;
122                 fss->surfaceSubdivs = 0.0;
123                 fss->particleInfSize = 0.0;
124                 fss->particleInfAlpha = 0.0;
125         
126                 // init fluid control settings
127                 fss->attractforceStrength = 0.2;
128                 fss->attractforceRadius = 0.75;
129                 fss->velocityforceStrength = 0.2;
130                 fss->velocityforceRadius = 0.75;
131                 fss->cpsTimeStart = fss->animStart;
132                 fss->cpsTimeEnd = fss->animEnd;
133                 fss->cpsQuality = 10.0; // 1.0 / 10.0 => means 0.1 width
134                 
135                 /*
136                 BAD TODO: this is done in buttons_object.c in the moment 
137                 Mesh *mesh = ob->data;
138                 // calculate bounding box
139                 fluid_get_bb(mesh->mvert, mesh->totvert, ob->obmat, fss->bbStart, fss->bbSize); 
140                 */
141                 
142                 fss->meshVelocities = NULL;
143                 
144                 fss->lastgoodframe = -1;
145                 
146                 fss->flag |= OB_FLUIDSIM_ACTIVE;
147
148         }
149 #else
150         (void)fluidmd; /* unused */
151 #endif
152         return;
153 }
154
155 void fluidsim_free(FluidsimModifierData *fluidmd)
156 {
157 #ifndef DISABLE_ELBEEM
158         if(fluidmd)
159         {
160                 if(fluidmd->fss->meshVelocities)
161                 {
162                         MEM_freeN(fluidmd->fss->meshVelocities);
163                         fluidmd->fss->meshVelocities = NULL;
164                 }
165                 MEM_freeN(fluidmd->fss);
166         }
167 #else
168         (void)fluidmd; /* unused */
169 #endif
170         
171         return;
172 }
173
174 #ifndef DISABLE_ELBEEM
175 /* read .bobj.gz file into a fluidsimDerivedMesh struct */
176 static DerivedMesh *fluidsim_read_obj(const char *filename)
177 {
178         int wri = 0,i;
179         int gotBytes;
180         gzFile gzf;
181         int numverts = 0, numfaces = 0;
182         DerivedMesh *dm = NULL;
183         MFace *mf;
184         MVert *mv;
185         short *normals, *no_s;
186         float no[3];
187
188         // ------------------------------------------------
189         // get numverts + numfaces first
190         // ------------------------------------------------
191         gzf = gzopen(filename, "rb");
192         if (!gzf)
193         {
194                 return NULL;
195         }
196
197         // read numverts
198         gotBytes = gzread(gzf, &wri, sizeof(wri));
199         numverts = wri;
200
201         // skip verts
202         gotBytes = gzseek(gzf, numverts * 3 * sizeof(float), SEEK_CUR) != -1;
203
204
205         // read number of normals
206         if(gotBytes)
207                 gotBytes = gzread(gzf, &wri, sizeof(wri));
208
209         // skip normals
210         gotBytes = gzseek(gzf, numverts * 3 * sizeof(float), SEEK_CUR) != -1;
211
212         /* get no. of triangles */
213         if(gotBytes)
214                 gotBytes = gzread(gzf, &wri, sizeof(wri));
215         numfaces = wri;
216
217         gzclose( gzf );
218         // ------------------------------------------------
219
220         if(!numfaces || !numverts || !gotBytes)
221                 return NULL;
222
223         gzf = gzopen(filename, "rb");
224         if (!gzf)
225         {
226                 return NULL;
227         }
228
229         dm = CDDM_new(numverts, 0, numfaces, 0, 0);
230
231         if(!dm)
232         {
233                 gzclose( gzf );
234                 return NULL;
235         }
236
237         // read numverts
238         gotBytes = gzread(gzf, &wri, sizeof(wri));
239
240         // read vertex position from file
241         mv = CDDM_get_verts(dm);
242
243         for(i=0; i<numverts; i++, mv++)
244                 gotBytes = gzread(gzf, mv->co, sizeof(float) * 3);
245
246         // should be the same as numverts
247         gotBytes = gzread(gzf, &wri, sizeof(wri));
248         if(wri != numverts)
249         {
250                 if(dm)
251                         dm->release(dm);
252                 gzclose( gzf );
253                 return NULL;
254         }
255
256         normals = MEM_callocN(sizeof(short) * numverts * 3, "fluid_tmp_normals" );
257         if(!normals)
258         {
259                 if(dm)
260                         dm->release(dm);
261                 gzclose( gzf );
262                 return NULL;
263         }
264
265         // read normals from file (but don't save them yet)
266         for(i=numverts, no_s= normals; i>0; i--, no_s += 3)
267         {
268                 gotBytes = gzread(gzf, no, sizeof(float) * 3);
269                 normal_float_to_short_v3(no_s, no);
270         }
271
272         /* read no. of triangles */
273         gotBytes = gzread(gzf, &wri, sizeof(wri));
274
275         if(wri!=numfaces) {
276                 printf("Fluidsim: error in reading data from file.\n");
277                 if(dm)
278                         dm->release(dm);
279                 gzclose( gzf );
280                 MEM_freeN(normals);
281                 return NULL;
282         }
283
284         // read triangles from file
285         mf = CDDM_get_tessfaces(dm);
286         for(i=numfaces; i>0; i--, mf++)
287         {
288                 int face[3];
289
290                 gotBytes = gzread(gzf, face, sizeof(int) * 3);
291
292                 // check if 3rd vertex has index 0 (not allowed in blender)
293                 if(face[2])
294                 {
295                         mf->v1 = face[0];
296                         mf->v2 = face[1];
297                         mf->v3 = face[2];
298                 }
299                 else
300                 {
301                         mf->v1 = face[1];
302                         mf->v2 = face[2];
303                         mf->v3 = face[0];
304                 }
305                 mf->v4 = 0;
306
307                 test_index_face(mf, NULL, 0, 3);
308         }
309
310         gzclose( gzf );
311
312         CDDM_calc_edges(dm);
313
314         CDDM_apply_vert_normals(dm, (short (*)[3])normals);
315         MEM_freeN(normals);
316
317         // CDDM_calc_normals(result);
318
319         return dm;
320 }
321
322
323 void fluid_get_bb(MVert *mvert, int totvert, float obmat[][4],
324                  /*RET*/ float start[3], /*RET*/ float size[3] )
325 {
326         float bbsx=0.0, bbsy=0.0, bbsz=0.0;
327         float bbex=1.0, bbey=1.0, bbez=1.0;
328         int i;
329         float vec[3];
330
331         if(totvert == 0) {
332                 zero_v3(start);
333                 zero_v3(size);
334                 return;
335         }
336
337         copy_v3_v3(vec, mvert[0].co);
338         mul_m4_v3(obmat, vec);
339         bbsx = vec[0]; bbsy = vec[1]; bbsz = vec[2];
340         bbex = vec[0]; bbey = vec[1]; bbez = vec[2];
341
342         for(i = 1; i < totvert; i++) {
343                 copy_v3_v3(vec, mvert[i].co);
344                 mul_m4_v3(obmat, vec);
345
346                 if(vec[0] < bbsx){ bbsx= vec[0]; }
347                 if(vec[1] < bbsy){ bbsy= vec[1]; }
348                 if(vec[2] < bbsz){ bbsz= vec[2]; }
349                 if(vec[0] > bbex){ bbex= vec[0]; }
350                 if(vec[1] > bbey){ bbey= vec[1]; }
351                 if(vec[2] > bbez){ bbez= vec[2]; }
352         }
353
354         // return values...
355         if(start) {
356                 start[0] = bbsx;
357                 start[1] = bbsy;
358                 start[2] = bbsz;
359         }
360         if(size) {
361                 size[0] = bbex-bbsx;
362                 size[1] = bbey-bbsy;
363                 size[2] = bbez-bbsz;
364         }
365 }
366
367 //-------------------------------------------------------------------------------
368 // old interface
369 //-------------------------------------------------------------------------------
370
371 void fluid_estimate_memory(Object *ob, FluidsimSettings *fss, char *value)
372 {
373         Mesh *mesh;
374
375         value[0]= '\0';
376
377         if(ob->type == OB_MESH) {
378                 /* use mesh bounding box and object scaling */
379                 mesh= ob->data;
380
381                 fluid_get_bb(mesh->mvert, mesh->totvert, ob->obmat, fss->bbStart, fss->bbSize);
382                 elbeemEstimateMemreq(fss->resolutionxyz, fss->bbSize[0],fss->bbSize[1],fss->bbSize[2], fss->maxRefine, value);
383         }
384 }
385
386
387 /* read zipped fluidsim velocities into the co's of the fluidsimsettings normals struct */
388 static void fluidsim_read_vel_cache(FluidsimModifierData *fluidmd, DerivedMesh *dm, char *filename)
389 {
390         int wri, i, j;
391         float wrf;
392         gzFile gzf;
393         FluidsimSettings *fss = fluidmd->fss;
394         int len = strlen(filename);
395         int totvert = dm->getNumVerts(dm);
396         FluidVertexVelocity *velarray = NULL;
397
398         // mesh and vverts have to be valid from loading...
399
400         if(fss->meshVelocities)
401                 MEM_freeN(fss->meshVelocities);
402
403         if(len<7)
404         {
405                 return;
406         }
407
408         if(fss->domainNovecgen>0) return;
409
410         fss->meshVelocities = MEM_callocN(sizeof(FluidVertexVelocity)*dm->getNumVerts(dm), "Fluidsim_velocities");
411         fss->totvert = totvert;
412
413         velarray = fss->meshVelocities;
414
415         // .bobj.gz , correct filename
416         // 87654321
417         filename[len-6] = 'v';
418         filename[len-5] = 'e';
419         filename[len-4] = 'l';
420
421         gzf = gzopen(filename, "rb");
422         if (!gzf)
423         {
424                 MEM_freeN(fss->meshVelocities);
425                 fss->meshVelocities = NULL;
426                 return;
427         }
428
429         gzread(gzf, &wri, sizeof( wri ));
430         if(wri != totvert)
431         {
432                 MEM_freeN(fss->meshVelocities);
433                 fss->meshVelocities = NULL;
434                 return;
435         }
436
437         for(i=0; i<totvert;i++)
438         {
439                 for(j=0; j<3; j++)
440                 {
441                         gzread(gzf, &wrf, sizeof( wrf ));
442                         velarray[i].vel[j] = wrf;
443                 }
444         }
445
446         gzclose(gzf);
447 }
448
449 static DerivedMesh *fluidsim_read_cache(DerivedMesh *orgdm, FluidsimModifierData *fluidmd, int framenr, int useRenderParams)
450 {
451         int displaymode = 0;
452         int curFrame = framenr - 1 /*scene->r.sfra*/; /* start with 0 at start frame */
453         char targetDir[FILE_MAXFILE+FILE_MAXDIR], targetFile[FILE_MAXFILE+FILE_MAXDIR];
454         FluidsimSettings *fss = fluidmd->fss;
455         DerivedMesh *dm = NULL;
456         MFace *mface;
457         int numfaces;
458         int mat_nr, flag, i;
459
460         if(!useRenderParams) {
461                 displaymode = fss->guiDisplayMode;
462         } else {
463                 displaymode = fss->renderDisplayMode;
464         }
465
466         BLI_strncpy(targetDir, fss->surfdataPath, sizeof(targetDir));
467
468         // use preview or final mesh?
469         if(displaymode==1)
470         {
471                 // just display original object
472                 return NULL;
473         }
474         else if(displaymode==2)
475         {
476                 strcat(targetDir,"fluidsurface_preview_####");
477         }
478         else
479         { // 3
480                 strcat(targetDir,"fluidsurface_final_####");
481         }
482
483         BLI_path_abs(targetDir, G.main->name);
484         BLI_path_frame(targetDir, curFrame, 0); // fixed #frame-no
485
486         BLI_snprintf(targetFile, sizeof(targetFile), "%s.bobj.gz", targetDir);
487
488         dm = fluidsim_read_obj(targetFile);
489
490         if(!dm)
491         {
492                 // switch, abort background rendering when fluidsim mesh is missing
493                 const char *strEnvName2 = "BLENDER_ELBEEMBOBJABORT"; // from blendercall.cpp
494
495                 if(G.background==1) {
496                         if(getenv(strEnvName2)) {
497                                 int elevel = atoi(getenv(strEnvName2));
498                                 if(elevel>0) {
499                                         printf("Env. var %s set, fluid sim mesh '%s' not found, aborting render...\n",strEnvName2, targetFile);
500                                         exit(1);
501                                 }
502                         }
503                 }
504
505                 // display org. object upon failure which is in dm
506                 return NULL;
507         }
508
509         // assign material + flags to new dm
510         mface = orgdm->getTessFaceArray(orgdm);
511         mat_nr = mface[0].mat_nr;
512         flag = mface[0].flag;
513
514         mface = dm->getTessFaceArray(dm);
515         numfaces = dm->getNumTessFaces(dm);
516         for(i=0; i<numfaces; i++)
517         {
518                 mface[i].mat_nr = mat_nr;
519                 mface[i].flag = flag;
520         }
521
522         // load vertex velocities, if they exist...
523         // TODO? use generate flag as loading flag as well?
524         // warning, needs original .bobj.gz mesh loading filename
525         if(displaymode==3)
526         {
527                 fluidsim_read_vel_cache(fluidmd, dm, targetFile);
528         }
529         else
530         {
531                 if(fss->meshVelocities)
532                         MEM_freeN(fss->meshVelocities);
533
534                 fss->meshVelocities = NULL;
535         }
536
537         return dm;
538 }
539 #endif // DISABLE_ELBEEM
540
541 DerivedMesh *fluidsimModifier_do(FluidsimModifierData *fluidmd, Scene *scene,
542                                                 Object *UNUSED(ob),
543                                                 DerivedMesh *dm,
544                                                 int useRenderParams, int UNUSED(isFinalCalc))
545 {
546 #ifndef DISABLE_ELBEEM
547         DerivedMesh *result = NULL;
548         int framenr;
549         FluidsimSettings *fss = NULL;
550
551         framenr= (int)scene->r.cfra;
552         
553         // only handle fluidsim domains
554         if(fluidmd && fluidmd->fss && (fluidmd->fss->type != OB_FLUIDSIM_DOMAIN))
555                 return dm;
556         
557         // sanity check
558         if(!fluidmd || (fluidmd && !fluidmd->fss))
559                 return dm;
560         
561         fss = fluidmd->fss;
562         
563         // timescale not supported yet
564         // clmd->sim_parms->timescale= timescale;
565
566         // support reversing of baked fluid frames here
567         if((fss->flag & OB_FLUIDSIM_REVERSE) && (fss->lastgoodframe >= 0))
568         {
569                 framenr = fss->lastgoodframe - framenr + 1;
570                 CLAMP(framenr, 1, fss->lastgoodframe);
571         }
572         
573         /* try to read from cache */
574         /* if the frame is there, fine, otherwise don't do anything */
575         if((result = fluidsim_read_cache(dm, fluidmd, framenr, useRenderParams)))
576                 return result;
577         
578         return dm;
579 #else
580         /* unused */
581         (void)fluidmd;
582         (void)scene;
583         (void)dm;
584         (void)useRenderParams;
585         return NULL;
586 #endif
587 }