1 /******************************************************************************
3 * El'Beem - Free Surface Fluid Simulation with the Lattice Boltzmann Method
4 * Copyright 2003-2006 Nils Thuerey
6 * Basic interface for all simulation modules
8 *****************************************************************************/
10 #include "simulation_object.h"
11 #include "solver_interface.h"
12 #include "ntl_bsptree.h"
14 #include "ntl_world.h"
15 #include "solver_interface.h"
16 #include "particletracer.h"
25 //! lbm factory functions
26 LbmSolverInterface* createSolver();
29 /******************************************************************************
31 *****************************************************************************/
32 SimulationObject::SimulationObject() :
34 mGeoStart(-100.0), mGeoEnd(100.0),
35 mpGiTree(NULL), mpGiObjects(NULL),
38 mDebugType( 1 /* =FLUIDDISPNothing*/ ),
39 mpLbm(NULL), mpParam( NULL ),
40 mShowSurface(true), mShowParticles(false),
42 mpElbeemSettings( NULL )
45 mpParam = new Parametrizer();
46 //for(int i=0; i<MAX_DEBDISPSET; i++) { mDebDispSet[i].type = (i); mDebDispSet[i].on = false; mDebDispSet[i].scale = 1.0; }
53 /******************************************************************************
55 *****************************************************************************/
56 SimulationObject::~SimulationObject()
58 if(mpGiTree) delete mpGiTree;
59 if(mpElbeemSettings) delete mpElbeemSettings;
60 if(mpLbm) delete mpLbm;
61 if(mpParam) delete mpParam;
62 debMsgStd("SimulationObject",DM_MSG,"El'Beem Done!\n",10);
67 /*****************************************************************************/
68 /*! init tree for certain geometry init */
69 /*****************************************************************************/
70 void SimulationObject::initGeoTree() {
71 // unused!! overriden by solver interface
73 errFatal("SimulationObject::initGeoTree error","Requires globals!", SIMWORLD_INITERROR);
76 ntlScene *scene = mpGlob->getSimScene();
77 mpGiObjects = scene->getObjects();
79 if(mpGiTree != NULL) delete mpGiTree;
80 char treeFlag = (1<<(mGeoInitId+4));
81 mpGiTree = new ntlTree( 20, 4, // warning - fixed values for depth & maxtriangles here...
83 // unused!! overriden by solver interface
86 /*****************************************************************************/
87 /*! destroy tree etc. when geometry init done */
88 /*****************************************************************************/
89 void SimulationObject::freeGeoTree() {
90 if(mpGiTree != NULL) delete mpGiTree;
95 // copy & remember settings for later use
96 void SimulationObject::copyElbeemSettings(elbeemSimulationSettings *settings) {
97 mpElbeemSettings = new elbeemSimulationSettings;
98 *mpElbeemSettings = *settings;
100 mGeoInitId = settings->domainId+1;
101 debMsgStd("SimulationObject",DM_MSG,"mGeoInitId="<<mGeoInitId<<", domainId="<<settings->domainId, 8);
104 /******************************************************************************
105 * simluation interface: initialize simulation using the given configuration file
106 *****************************************************************************/
107 extern int glob_mpnum;
108 int SimulationObject::initializeLbmSimulation(ntlRenderGlobals *glob)
110 if(! isSimworldOk() ) return 1;
117 mpAttrs->setAllUsed();
122 mGeoInitId = mpAttrs->readInt("geoinitid", mGeoInitId,"LbmSolverInterface", "mGeoInitId", false);
123 //mDimension, mSolverType are deprecated
124 string mSolverType("");
125 mSolverType = mpAttrs->readString("solver", mSolverType, "SimulationObject","mSolverType", false );
127 mpLbm = createSolver();
128 /* check lbm pointer */
130 errFatal("SimulationObject::initializeLbmSimulation","Unable to init LBM solver! ", SIMWORLD_INITERROR);
133 debMsgStd("SimulationObject::initialized",DM_MSG,"IdStr:"<<mpLbm->getIdString() <<" LBM solver! ", 2);
135 mpParts = new ParticleTracer();
137 // for non-param simulations
138 mpLbm->setParametrizer( mpParam );
139 mpParam->setAttrList( getAttributeList() );
140 // not needed.. done in solver_init: mpParam->setSize ... in solver_interface
141 mpParam->parseAttrList();
143 mpLbm->setAttrList( getAttributeList() );
144 mpLbm->setSwsAttrList( getSwsAttributeList() );
145 mpLbm->parseAttrList();
146 mpParts->parseAttrList( getAttributeList() );
148 if(! isSimworldOk() ) return 3;
149 mpParts->setName( getName() + "_part" );
150 mpParts->initialize( glob );
151 if(! isSimworldOk() ) return 4;
153 // init material settings
154 string matMc("default");
155 matMc = mpAttrs->readString("material_surf", matMc, "SimulationObject","matMc", false );
156 mShowSurface = mpAttrs->readInt("showsurface", mShowSurface, "SimulationObject","mShowSurface", false );
157 mShowParticles = mpAttrs->readInt("showparticles", mShowParticles, "SimulationObject","mShowParticles", false );
159 checkBoundingBox( mGeoStart, mGeoEnd, "SimulationObject::initializeSimulation" );
160 mpLbm->setLbmInitId( mGeoInitId );
161 mpLbm->setGeoStart( mGeoStart );
162 mpLbm->setGeoEnd( mGeoEnd );
163 mpLbm->setRenderGlobals( mpGlob );
164 mpLbm->setName( getName() + "_lbm" );
165 mpLbm->setParticleTracer( mpParts );
166 if(mpElbeemSettings) {
167 // set further settings from API struct init
168 if(mpElbeemSettings->outputPath) this->mOutFilename = string(mpElbeemSettings->outputPath);
169 mpLbm->initDomainTrafo( mpElbeemSettings->surfaceTrafo );
170 mpLbm->setSmoothing(1.0 * mpElbeemSettings->surfaceSmoothing, 1.0 * mpElbeemSettings->surfaceSmoothing);
171 mpLbm->setIsoSubdivs(mpElbeemSettings->surfaceSubdivs);
172 mpLbm->setSizeX(mpElbeemSettings->resolutionxyz);
173 mpLbm->setSizeY(mpElbeemSettings->resolutionxyz);
174 mpLbm->setSizeZ(mpElbeemSettings->resolutionxyz);
175 mpLbm->setPreviewSize(mpElbeemSettings->previewresxyz);
176 mpLbm->setRefinementDesired(mpElbeemSettings->maxRefine);
177 mpLbm->setGenerateParticles(mpElbeemSettings->generateParticles);
178 // set initial particles
179 mpParts->setNumInitialParticles(mpElbeemSettings->numTracerParticles);
181 string dinitType = string("no");
182 if (mpElbeemSettings->domainobsType==FLUIDSIM_OBSTACLE_PARTSLIP) dinitType = string("part");
183 else if(mpElbeemSettings->domainobsType==FLUIDSIM_OBSTACLE_FREESLIP) dinitType = string("free");
184 else /*if(mpElbeemSettings->domainobsType==FLUIDSIM_OBSTACLE_NOSLIP)*/ dinitType = string("no");
185 mpLbm->setDomainBound(dinitType);
186 mpLbm->setDomainPartSlip(mpElbeemSettings->domainobsPartslip);
187 mpLbm->setDumpVelocities(mpElbeemSettings->generateVertexVectors);
188 mpLbm->setFarFieldSize(mpElbeemSettings->farFieldSize);
189 debMsgStd("SimulationObject::initialize",DM_MSG,"Added domain bound: "<<dinitType<<" ps="<<mpElbeemSettings->domainobsPartslip<<" vv"<<mpElbeemSettings->generateVertexVectors<<","<<mpLbm->getDumpVelocities(), 9 );
191 debMsgStd("SimulationObject::initialize",DM_MSG,"Set ElbeemSettings values "<<mpLbm->getGenerateParticles(),10);
194 if(! mpLbm->initializeSolverMemory() ) { errMsg("SimulationObject::initialize","initializeSolverMemory failed"); mPanic=true; return 10; }
195 if(checkCallerStatus(FLUIDSIM_CBSTATUS_STEP, 0)) { errMsg("SimulationObject::initialize","initializeSolverMemory status"); mPanic=true; return 11; }
196 if(! mpLbm->initializeSolverGrids() ) { errMsg("SimulationObject::initialize","initializeSolverGrids failed"); mPanic=true; return 12; }
197 if(checkCallerStatus(FLUIDSIM_CBSTATUS_STEP, 0)) { errMsg("SimulationObject::initialize","initializeSolverGrids status"); mPanic=true; return 13; }
198 if(! mpLbm->initializeSolverPostinit() ) { errMsg("SimulationObject::initialize","initializeSolverPostin failed"); mPanic=true; return 14; }
199 if(checkCallerStatus(FLUIDSIM_CBSTATUS_STEP, 0)) { errMsg("SimulationObject::initialize","initializeSolverPostin status"); mPanic=true; return 15; }
201 // print cell type stats
202 bool printStats = true;
203 if(glob_mpnum>0) printStats=false; // skip in this case
205 const int jmax = sizeof(CellFlagType)*8;
208 for(int j=0; j<jmax ; j++) flagCount[j] = 0;
210 LbmSolverInterface::CellIdentifier cid = mpLbm->getFirstCell();
211 for(; mpLbm->noEndCell( cid );
212 mpLbm->advanceCell( cid ) ) {
213 int flag = mpLbm->getCellFlag(cid,0);
214 int flag2 = mpLbm->getCellFlag(cid,1);
218 for(int j=0; j<jmax ; j++) {
219 if( flag&(1<<j) ) flagCount[j]++;
223 mpLbm->deleteCellIterator( &cid );
226 debugOutNnl("SimulationObject::initializeLbmSimulation celltype stats: " <<charNl, 5);
227 debugOutNnl("no. of cells = "<<totalCells<<", "<<charNl ,5);
228 for(int j=0; j<jmax ; j++) {
229 std::ostringstream out;
231 out<<"\t" << flagCount[j] <<" x "<< convertCellFlagType2String( (CellFlagType)(1<<j) ) <<", " << charNl;
232 debugOutNnl(out.str(), 5);
235 // compute dist. of empty/bnd - fluid - if
236 // cfEmpty = (1<<0), cfBnd = (1<< 2), cfFluid = (1<<10), cfInter = (1<<11),
238 std::ostringstream out;
239 out.precision(2); out.width(4);
240 int totNum = flagCount[1]+flagCount[2]+flagCount[7]+flagCount[8];
241 double ebFrac = (double)(flagCount[1]+flagCount[2]) / totNum;
242 double flFrac = (double)(flagCount[7]) / totNum;
243 double ifFrac = (double)(flagCount[8]) / totNum;
245 out<<"\tFractions: [empty/bnd - fluid - interface - ext. if] = [" << ebFrac<<" - " << flFrac<<" - " << ifFrac<<"] "<< charNl;
248 debMsgStd("SimulationObject::initializeLbmSimulation",DM_MSG,"celltype Warning: Diffinits="<<diffInits<<"!" , 5);
250 debugOutNnl(out.str(), 5);
254 // might be modified by mpLbm
255 //mpParts->setStart( mGeoStart );? mpParts->setEnd( mGeoEnd );?
256 mpParts->setStart( mpLbm->getGeoStart() );
257 mpParts->setEnd( mpLbm->getGeoEnd() );
258 mpParts->setCastShadows( false );
259 mpParts->setReceiveShadows( false );
260 mpParts->searchMaterial( glob->getMaterials() );
262 // this has to be inited here - before, the values might be unknown
263 IsoSurface *surf = mpLbm->getSurfaceGeoObj();
265 surf->setName( "final" ); // final surface mesh
266 // warning - this might cause overwriting effects for multiple sims and geom dump...
267 surf->setCastShadows( true );
268 surf->setReceiveShadows( false );
269 surf->searchMaterial( glob->getMaterials() );
270 if(mShowSurface) mObjects.push_back( surf );
274 mShowParticles=1; // for e.g. dumping
275 #endif // ELBEEM_PLUGIN
276 if((mpLbm->getGenerateParticles()>0.0)||(mpParts->getNumInitialParticles()>0)) {
278 mpParts->setDumpParts(true);
280 //debMsgStd("SimulationObject::init",DM_NOTIFY,"Using envvar ELBEEM_DUMPPARTICLE to set mShowParticles, DEBUG!",1);
281 //} // DEBUG ENABLE!!!!!!!!!!
283 mObjects.push_back(mpParts);
286 // add objects to display for debugging (e.g. levelset particles)
287 vector<ntlGeometryObject *> debugObjs = mpLbm->getDebugObjects();
288 for(size_t i=0;i<debugObjs.size(); i++) {
289 debugObjs[i]->setCastShadows( false );
290 debugObjs[i]->setReceiveShadows( false );
291 debugObjs[i]->searchMaterial( glob->getMaterials() );
292 mObjects.push_back( debugObjs[i] );
293 debMsgStd("SimulationObject::init",DM_NOTIFY,"Added debug obj "<<debugObjs[i]->getName(), 10 );
298 /*! set current frame */
299 void SimulationObject::setFrameNum(int num) {
300 // advance parametrizer
301 mpParam->setFrameNum(num);
304 /******************************************************************************
305 * simluation interface: advance simulation another step (whatever delta time that might be)
306 *****************************************************************************/
307 void SimulationObject::step( void )
309 if(mpParam->getCurrentAniFrameTime()>0.0) {
310 // dont advance for stopped time
312 mTime += mpParam->getTimestep();
313 //if(mTime>0.001) { errMsg("DEBUG!!!!!!!!","quit mlsu..."); xit(1); } // PROFILE DEBUG TEST!
315 if(mpLbm->getPanic()) mPanic = true;
317 checkCallerStatus(FLUIDSIM_CBSTATUS_STEP, 0);
318 //if((mpElbeemSettings)&&(mpElbeemSettings->runsimCallback)) {
319 //int ret = (mpElbeemSettings->runsimCallback)(mpElbeemSettings->runsimUserData, FLUIDSIM_CBSTATUS_STEP, 0);
320 //errMsg("runSimulationCallback cbtest1"," "<<this->getName()<<" ret="<<ret);
322 //debMsgStd("SimulationObject::step",DM_MSG," Sim '"<<mName<<"' stepped to "<<mTime<<" (stept="<<(mpParam->getTimestep())<<", framet="<<getFrameTime()<<") ", 10);
324 /*! prepare visualization of simulation for e.g. raytracing */
325 void SimulationObject::prepareVisualization( void ) {
327 mpLbm->prepareVisualization();
331 /******************************************************************************/
332 /* get current start simulation time */
333 double SimulationObject::getStartTime( void ) {
334 //return mpParam->calculateAniStart();
335 return mpParam->getAniStart();
337 /* get time for a single animation frame */
338 double SimulationObject::getFrameTime( int frame ) {
339 return mpParam->getAniFrameTime(frame);
341 /* get time for a single time step */
342 double SimulationObject::getTimestep( void ) {
343 return mpParam->getTimestep();
347 /******************************************************************************
348 * return a pointer to the geometry object of this simulation
349 *****************************************************************************/
350 //ntlGeometryObject *SimulationObject::getGeometry() { return mpMC; }
351 vector<ntlGeometryObject *>::iterator
352 SimulationObject::getObjectsBegin()
354 return mObjects.begin();
356 vector<ntlGeometryObject *>::iterator
357 SimulationObject::getObjectsEnd()
359 return mObjects.end();
366 /******************************************************************************
367 * GUI - display debug info
368 *****************************************************************************/
370 void SimulationObject::drawDebugDisplay() {
372 if(!getVisible()) return;
374 //if( mDebugType > (MAX_DEBDISPSET-1) ){ errFatal("SimulationObject::drawDebugDisplay","Invalid debug type!", SIMWORLD_GENERICERROR); return; }
375 //mDebDispSet[ mDebugType ].on = true;
376 //errorOut( mDebugType <<"//"<< mDebDispSet[mDebugType].type );
377 mpLbm->debugDisplay( mDebugType );
379 //::lbmMarkedCellDisplay<>( mpLbm );
380 mpLbm->lbmMarkedCellDisplay();
384 /* GUI - display interactive info */
385 void SimulationObject::drawInteractiveDisplay()
388 if(!getVisible()) return;
390 // in debugDisplayNode if dispset is on is ignored...
391 mpLbm->debugDisplayNode( FLUIDDISPGrid, mSelectedCid );
397 /*******************************************************************************/
398 // GUI - handle mouse movement for selection
399 /*******************************************************************************/
400 void SimulationObject::setMousePos(int x,int y, ntlVec3Gfx org, ntlVec3Gfx dir)
403 // assume 2D sim is in XY plane...
405 double zplane = (mGeoEnd[2]-mGeoStart[2])*0.5;
406 double zt = (zplane-org[2]) / dir[2];
409 org[1]+ dir[1] * zt, 0.0);
411 mSelectedCid = mpLbm->getCellAt( pos );
412 //errMsg("SMP ", mName<< x<<" "<<y<<" - "<<dir );
413 x = y = 0; // remove warning
417 void SimulationObject::setMouseClick()
420 //::debugPrintNodeInfo<>( mpLbm, mSelectedCid, mpLbm->getNodeInfoString() );
421 mpLbm->debugPrintNodeInfo( mSelectedCid );
425 /*! notify object that dump is in progress (e.g. for field dump) */
426 void SimulationObject::notifyShaderOfDump(int dumptype, int frameNr,char *frameNrStr,string outfilename) {
429 mpLbm->notifySolverOfDump(dumptype, frameNr,frameNrStr,outfilename);
430 checkCallerStatus(FLUIDSIM_CBSTATUS_NEWFRAME, frameNr);
433 /*! check status (e.g. stop/abort) from calling program, returns !=0 if sth. happened... */
434 int SimulationObject::checkCallerStatus(int status, int frame) {
437 if((mpElbeemSettings)&&(mpElbeemSettings->runsimCallback)) {
438 ret = (mpElbeemSettings->runsimCallback)(mpElbeemSettings->runsimUserData, status,frame);
439 if(ret!=FLUIDSIM_CBRET_CONTINUE) {
440 if(ret==FLUIDSIM_CBRET_STOP) {
441 debMsgStd("SimulationObject::notifySolverOfDump",DM_NOTIFY,"Got stop signal from caller",1);
442 setElbeemState( SIMWORLD_STOP );
444 else if(ret==FLUIDSIM_CBRET_ABORT) {
445 errFatal("SimulationObject::notifySolverOfDump","Got abort signal from caller, aborting...", SIMWORLD_GENERICERROR );
449 errMsg("SimulationObject::notifySolverOfDump","Invalid callback return value: "<<ret<<", ignoring... ");
454 //debMsgStd("SimulationObject::checkCallerStatus",DM_MSG, "s="<<status<<",f="<<frame<<" "<<this->getName()<<" ret="<<ret);
455 if(isSimworldOk()) return 0;