scene.C
Go to the documentation of this file.
1 /*---------------------------------------------------------------------------*\
2  ========= |
3  \\ / F ield | OpenFOAM: The Open Source CFD Toolbox
4  \\ / O peration |
5  \\ / A nd | Copyright (C) 2015 OpenFOAM Foundation
6  \\/ M anipulation | Copyright (C) 2015 OpenCFD Ltd.
7 -------------------------------------------------------------------------------
8 License
9  This file is part of OpenFOAM.
10 
11  OpenFOAM is free software: you can redistribute it and/or modify it
12  under the terms of the GNU General Public License as published by
13  the Free Software Foundation, either version 3 of the License, or
14  (at your option) any later version.
15 
16  OpenFOAM is distributed in the hope that it will be useful, but WITHOUT
17  ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
18  FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
19  for more details.
20 
21  You should have received a copy of the GNU General Public License
22  along with OpenFOAM. If not, see <http://www.gnu.org/licenses/>.
23 
24 \*---------------------------------------------------------------------------*/
25 
26 // OpenFOAM includes
27 #include "scene.H"
28 #include "Constant.H"
29 
30 // VTK includes
31 #include "vtkCamera.h"
32 #include "vtkCubeSource.h"
33 #include "vtkLightKit.h"
34 #include "vtkPolyDataMapper.h"
35 #include "vtkPNGWriter.h"
36 #include "vtkRenderer.h"
37 #include "vtkRendererCollection.h"
38 #include "vtkRenderWindow.h"
39 #include "vtkWindowToImageFilter.h"
40 
41 // * * * * * * * * * * * * Static Member Functions * * * * * * * * * * * * * //
42 
43 namespace Foam
44 {
45  template<>
47  {
48  "static",
49  "flightPath"
50  };
51 }
52 
54 
55 
56 // * * * * * * * * * * * * * Private Member Functions * * * * * * * * * * * //
57 
59 {
60  if (dict.readIfPresent("nFrameTotal", nFrameTotal_))
61  {
62  if (nFrameTotal_ < 1)
63  {
65  << "nFrameTotal must be 1 or greater"
66  << exit(FatalIOError);
67  }
68  }
69 
70  if (dict.readIfPresent("startPosition", position_))
71  {
72  if ((position_ < 0) || (position_ > 1))
73  {
75  << "startPosition must be in the range 0-1"
76  << exit(FatalIOError);
77  }
78  }
79 
80 
81  dict.lookup("parallelProjection") >> parallelProjection_;
82 
83  if (nFrameTotal_ > 1)
84  {
85  scalar endPosition = dict.lookupOrDefault<scalar>("endPosition", 1);
86  if ((endPosition < 0) || (endPosition > 1))
87  {
89  << "endPosition must be in the range 0-1"
90  << exit(FatalIOError);
91  }
92  dPosition_ = (endPosition - position_)/scalar(nFrameTotal_ - 1);
93  }
94 
95  mode_ = modeTypeNames_.read(dict.lookup("mode"));
96 
97  word coeffsName = modeTypeNames_[mode_] + word("Coeffs");
98  const dictionary& coeffs = dict.subDict(coeffsName);
99 
100  switch (mode_)
101  {
102  case mtStatic:
103  {
104  clipBox_ = boundBox(coeffs.lookup("clipBox"));
105  const vector lookDir(vector(coeffs.lookup("lookDir")));
106  cameraPosition_.reset(new Constant<point>("position", -lookDir));
107  const vector focalPoint(coeffs.lookup("focalPoint"));
108  cameraFocalPoint_.reset
109  (
110  new Constant<point>("focalPoint", focalPoint)
111  );
112  const vector up(coeffs.lookup("up"));
113  cameraUp_.reset(new Constant<point>("up", up));
114  break;
115  }
116  case mtFlightPath:
117  {
118  cameraPosition_.reset
119  (
120  DataEntry<vector>::New("position", coeffs).ptr()
121  );
122  cameraFocalPoint_.reset
123  (
124  DataEntry<point>::New("focalPoint", coeffs).ptr()
125  );
126  cameraUp_.reset(DataEntry<vector>::New("up", coeffs).ptr());
127  break;
128  }
129  default:
130  {
132  << "Unhandled enumeration " << modeTypeNames_[mode_]
133  << abort(FatalError);
134  }
135  }
136 
137  if (dict.found("zoom"))
138  {
139  cameraZoom_.reset(DataEntry<scalar>::New("zoom", dict).ptr());
140  }
141  else
142  {
143  cameraZoom_.reset(new Constant<scalar>("zoom", 1.0));
144  }
145 
146  if (dict.found("viewAngle"))
147  {
148  cameraViewAngle_.reset(DataEntry<scalar>::New("viewAngle", dict).ptr());
149  }
150  else
151  {
152  cameraViewAngle_.reset(new Constant<scalar>("viewAngle", 35.0));
153  }
154 }
155 
156 
158 {
159  const wordList colours = dict.toc();
160  forAll(colours, i)
161  {
162  const word& c = colours[i];
163  colours_.insert(c, DataEntry<vector>::New(c, dict).ptr());
164  }
165 }
166 
167 
168 void Foam::scene::initialise(vtkRenderer* renderer, const word& outputName)
169 {
170  currentFrameI_ = 0;
171 
172  outputName_ = outputName;
173 
174  // Set the background
175  const vector backgroundColour = colours_["background"]->value(position());
176  renderer->SetBackground
177  (
178  backgroundColour.x(),
179  backgroundColour.y(),
180  backgroundColour.z()
181  );
182 
183  // Apply gradient background if "background2" defined
184  if (colours_.found("background2"))
185  {
186  renderer->GradientBackgroundOn();
187  vector backgroundColour2 = colours_["background2"]->value(position());
188 
189  renderer->SetBackground2
190  (
191  backgroundColour2.x(),
192  backgroundColour2.y(),
193  backgroundColour2.z()
194  );
195  }
196 
197  // Depth peeling
198  renderer->SetUseDepthPeeling(true);
199  renderer->SetMaximumNumberOfPeels(4);
200  renderer->SetOcclusionRatio(0);
201 
202  // Set the camera
203  vtkSmartPointer<vtkCamera> camera = vtkSmartPointer<vtkCamera>::New();
204  camera->SetParallelProjection(parallelProjection_);
205  renderer->SetActiveCamera(camera);
206 
207  setCamera(renderer, true);
208 
209  // Initialise the extents
210  if (mode_ == mtStatic)
211  {
212  const point& min = clipBox_.min();
213  const point& max = clipBox_.max();
214  vtkSmartPointer<vtkCubeSource> clipBox =
216  clipBox->SetXLength(max.x() - min.x());
217  clipBox->SetYLength(max.y() - min.y());
218  clipBox->SetZLength(max.z() - min.z());
219  clipBox->SetCenter
220  (
221  min.x() + 0.5*(max.x() - min.x()),
222  min.y() + 0.5*(max.y() - min.y()),
223  min.z() + 0.5*(max.z() - min.z())
224  );
225  vtkSmartPointer<vtkPolyDataMapper> clipMapper =
227  clipMapper->SetInputConnection(clipBox->GetOutputPort());
228 
229  vtkSmartPointer<vtkActor> clipActor = vtkSmartPointer<vtkActor>::New();
230  clipActor->SetMapper(clipMapper);
231  clipActor->VisibilityOn();
232  renderer->AddActor(clipActor);
233 
234  renderer->ResetCamera();
235 
236  clipActor->VisibilityOff();
237  }
238 }
239 
240 
241 void Foam::scene::setCamera(vtkRenderer* renderer, const bool override) const
242 {
243  if (mode_ == mtFlightPath || override)
244  {
245  vtkCamera* camera = renderer->GetActiveCamera();
246 
247  if (!parallelProjection_)
248  {
249  camera->SetViewAngle(cameraViewAngle_->value(position()));
250  }
251 
252  const vector up = cameraUp_->value(position());
253  const vector pos = cameraPosition_->value(position());
254  const point focalPoint = cameraFocalPoint_->value(position());
255 
256  camera->SetViewUp(up.x(), up.y(), up.z());
257  camera->SetPosition(pos.x(), pos.y(), pos.z());
258  camera->SetFocalPoint(focalPoint.x(), focalPoint.y(), focalPoint.z());
259  camera->Modified();
260 
261  vtkSmartPointer<vtkLightKit> lightKit =
263  lightKit->AddLightsToRenderer(renderer);
264  }
265 }
266 
267 
269 {
270  string str = Foam::name(currentFrameI_);
271  str.insert(0, 4 - str.length(), '0');
272 
273  return str;
274 }
275 
276 
277 // * * * * * * * * * * * * * * * * Constructors * * * * * * * * * * * * * * //
278 
280 :
281  obr_(obr),
282  name_(name),
283  colours_(),
284  mode_(mtStatic),
285  cameraPosition_(NULL),
286  cameraFocalPoint_(NULL),
287  cameraUp_(NULL),
288  cameraZoom_(NULL),
289  cameraViewAngle_(NULL),
290  clipBox_(),
291  parallelProjection_(true),
292  nFrameTotal_(1),
293  position_(0),
294  dPosition_(0),
295  currentFrameI_(0),
296  outputName_("unknown")
297 {}
298 
299 
300 // * * * * * * * * * * * * * * * * Destructor * * * * * * * * * * * * * * * //
301 
303 {}
304 
305 
306 // * * * * * * * * * * * * * * * Member Functions * * * * * * * * * * * * * //
307 
310 {
311  return colours_;
312 }
313 
314 
316 {
317  return currentFrameI_;
318 }
319 
320 
321 Foam::scalar Foam::scene::position() const
322 {
323  return position_;
324 }
325 
326 
328 {
329  readCamera(dict.subDict("camera"));
330  readColours(dict.subDict("colours"));
331 }
332 
333 
334 bool Foam::scene::loop(vtkRenderer* renderer)
335 {
336  static bool initialised = false;
337 
338  setCamera(renderer, false);
339 
340  if (!initialised)
341  {
342  initialised = true;
343  return true;
344  }
345 
346  // Save image from last iteration
347  saveImage(renderer->GetRenderWindow());
348 
349  currentFrameI_++;
350 
351  position_ += currentFrameI_*dPosition_;
352 
353  if (currentFrameI_ < nFrameTotal_)
354  {
355  return true;
356  }
357  else
358  {
359  return false;
360  }
361 }
362 
363 
364 void Foam::scene::saveImage(vtkRenderWindow* renderWindow) const
365 {
366  if (!renderWindow)
367  {
368  return;
369  }
370 
371  fileName prefix("postProcessing"/name_/obr_.time().timeName());
372  mkDir(prefix);
373 
374  renderWindow->Render();
375 
376  // Set up off-screen rendering
377  vtkSmartPointer<vtkWindowToImageFilter> windowToImageFilter =
379 
380  windowToImageFilter->SetInput(renderWindow);
381 
383  // windowToImageFilter->SetInputBufferTypeToRGBA();
384  windowToImageFilter->SetInputBufferTypeToRGB();
385 
386 // windowToImageFilter->ReadFrontBufferOff();
387  windowToImageFilter->Update();
388 
389  // Save the image
390  vtkSmartPointer<vtkPNGWriter> writer = vtkSmartPointer<vtkPNGWriter>::New();
391  fileName fName(prefix/outputName_ + '.' + frameIndexStr() + ".png");
392  writer->SetFileName(fName.c_str());
393  writer->SetInputConnection(windowToImageFilter->GetOutputPort());
394 
395  Info<< " Generating image: " << fName << endl;
396 
397  writer->Write();
398 }
399 
400 
401 // ************************************************************************* //
Foam::scene::frameIndexStr
string frameIndexStr() const
Definition: scene.C:268
Foam::scene::modeTypeNames_
NamedEnum< modeType, 2 > modeTypeNames_
Definition: scene.H:67
Foam::scene::scene
scene(const scene &)
Disallow default bitwise copy construct.
Foam::scene::cameraViewAngle_
autoPtr< DataEntry< scalar > > cameraViewAngle_
View angle.
Definition: scene.H:122
Foam::scene::~scene
virtual ~scene()
Destructor.
Definition: scene.C:302
Foam::scene::cameraFocalPoint_
autoPtr< DataEntry< point > > cameraFocalPoint_
Focal point.
Definition: scene.H:113
Foam::word
A class for handling words, derived from string.
Definition: word.H:59
Foam::compressible::New
autoPtr< BasicCompressibleTurbulenceModel > New(const volScalarField &rho, const volVectorField &U, const surfaceScalarField &phi, const typename BasicCompressibleTurbulenceModel::transportModel &transport, const word &propertiesName)
Definition: turbulentFluidThermoModel.C:36
Foam::fileName
A class for handling file names.
Definition: fileName.H:69
Foam::scene::nFrameTotal_
label nFrameTotal_
Number of frames.
Definition: scene.H:134
Foam::scene::position_
scalar position_
Position [0-1].
Definition: scene.H:137
forAll
#define forAll(list, i)
Loop across all elements in list.
Definition: UList.H:406
Foam::scene::parallelProjection_
bool parallelProjection_
Parallel projection flag.
Definition: scene.H:131
Foam::scene::readCamera
void readCamera(const dictionary &dict)
Read camera properties.
Definition: scene.C:58
Foam::scene::mode_
modeType mode_
Mode.
Definition: scene.H:107
Foam::dictionary::lookup
ITstream & lookup(const word &, bool recursive=false, bool patternMatch=true) const
Find and return an entry data stream.
Definition: dictionary.C:449
Foam::FatalIOError
IOerror FatalIOError
Foam::endl
Ostream & endl(Ostream &os)
Add newline and flush stream.
Definition: Ostream.H:251
Foam::dimensioned::value
const Type & value() const
Return const reference to value.
Definition: dimensionedType.C:261
Foam::string
A class for handling character strings derived from std::string.
Definition: string.H:74
Foam::scene::position
scalar position() const
Return the current position (in range 0-1)
Definition: scene.C:321
scene.H
Foam::scene::initialise
void initialise(vtkRenderer *renderer, const word &outputName)
Definition: scene.C:168
Foam::Constant
Templated basic entry that holds a constant value.
Definition: Constant.H:51
Foam::scene::colours
const HashPtrTable< DataEntry< vector >, word > & colours() const
Return the colours.
Definition: scene.C:309
Foam::objectRegistry
Registry of regIOobjects.
Definition: objectRegistry.H:50
modeTypeNames_
const Foam::NamedEnum< Foam::scene::modeType, 2 > modeTypeNames_
Definition: scene.C:53
Foam::scene::readColours
void readColours(const dictionary &dict)
Read solour properties.
Definition: scene.C:157
Foam::scene::cameraPosition_
autoPtr< DataEntry< point > > cameraPosition_
Position.
Definition: scene.H:110
Foam::scene::setCamera
void setCamera(vtkRenderer *renderer, const bool override) const
Definition: scene.C:241
camera
Foam::label
intWM_LABEL_SIZE_t label
A label is an int32_t or int64_t as specified by the pre-processor macro WM_LABEL_SIZE.
Definition: label.H:59
Foam::Info
messageStream Info
Foam::scene::mtStatic
@ mtStatic
Definition: scene.H:65
Foam::scene::read
void read(const dictionary &dict)
Definition: scene.C:327
Foam::scene::loop
bool loop(vtkRenderer *renderer)
Main control loop.
Definition: scene.C:334
dict
dictionary dict
Definition: searchingEngine.H:14
Foam::Vector::x
const Cmpt & x() const
Definition: VectorI.H:65
Foam::FatalError
error FatalError
Foam::dictionary
A list of keyword definitions, which are a keyword followed by any number of values (e....
Definition: dictionary.H:137
Foam::scene::frameIndex
label frameIndex() const
Return the current frame index.
Definition: scene.C:315
Foam::writer
Base class for graphics format writing. Entry points are.
Definition: writer.H:78
Foam
Namespace for OpenFOAM.
Definition: combustionModel.C:30
Foam::Vector::z
const Cmpt & z() const
Definition: VectorI.H:77
Foam::abort
errorManip< error > abort(error &err)
Definition: errorManip.H:131
Foam::vector
Vector< scalar > vector
A scalar version of the templated Vector.
Definition: vector.H:49
Foam::scene::cameraUp_
autoPtr< DataEntry< vector > > cameraUp_
Up direction.
Definition: scene.H:116
Foam::exit
errorManipArg< error, int > exit(error &err, const int errNo=1)
Definition: errorManip.H:124
Foam::max
dimensioned< Type > max(const dimensioned< Type > &, const dimensioned< Type > &)
Foam::scene::dPosition_
scalar dPosition_
Change in position per frame.
Definition: scene.H:140
Foam::NamedEnum::read
Enum read(Istream &) const
Read a word from Istream and return the corresponding.
Definition: NamedEnum.C:61
FatalErrorInFunction
#define FatalErrorInFunction
Report an error message using Foam::FatalError.
Definition: error.H:318
Foam::scene::mtFlightPath
@ mtFlightPath
Definition: scene.H:65
Foam::scene::saveImage
void saveImage(vtkRenderWindow *renderWindow) const
Save image to file.
Definition: scene.C:364
Foam::HashPtrTable
A HashTable specialization for hashing pointers.
Definition: HashPtrTable.H:50
Foam::Vector< scalar >
Foam::List
A 1D array of objects of type <T>, where the size of the vector is known and used for subscript bound...
Definition: HashTable.H:59
Foam::scene::clipBox_
boundBox clipBox_
Clipping box.
Definition: scene.H:128
Foam::scene::cameraZoom_
autoPtr< DataEntry< scalar > > cameraZoom_
Zoom level.
Definition: scene.H:119
Foam::boundBox
A bounding box defined in terms of the points at its extremities.
Definition: boundBox.H:55
Foam::constant::universal::c
const dimensionedScalar c
Speed of light in a vacuum.
Constant.H
Foam::Vector::y
const Cmpt & y() const
Definition: VectorI.H:71
FatalIOErrorInFunction
#define FatalIOErrorInFunction(ios)
Report an error message using Foam::FatalIOError.
Definition: error.H:330
Foam::dictionary::toc
wordList toc() const
Return the table of contents.
Definition: dictionary.C:697
Foam::dictionary::subDict
const dictionary & subDict(const word &) const
Find and return a sub-dictionary.
Definition: dictionary.C:631
Foam::mkDir
bool mkDir(const fileName &, mode_t=0777)
Make a directory and return an error if it could not be created.
Definition: POSIX.C:419
Foam::DataEntry
Top level data entry class for use in dictionaries. Provides a mechanism to specify a variable as a c...
Definition: DataEntry.H:52
Foam::min
dimensioned< Type > min(const dimensioned< Type > &, const dimensioned< Type > &)
Foam::name
word name(const complex &)
Return a string representation of a complex.
Definition: complex.C:47
Foam::NamedEnum
Initialise the NamedEnum HashTable from the static list of names.
Definition: NamedEnum.H:52
Foam::pos
dimensionedScalar pos(const dimensionedScalar &ds)
Definition: dimensionedScalar.C:190