Freestyle: Code cleanup, prepare for strict C++ flags
[blender.git] / source / blender / freestyle / intern / application / Controller.cpp
1 /*
2  * ***** BEGIN GPL LICENSE BLOCK *****
3  *
4  * This program is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU General Public License
6  * as published by the Free Software Foundation; either version 2
7  * of the License, or (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program; if not, write to the Free Software Foundation,
16  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
17  *
18  * ***** END GPL LICENSE BLOCK *****
19  */
20
21 /** \file blender/freestyle/intern/application/Controller.cpp
22  *  \ingroup freestyle
23  */
24
25 extern "C" {
26 #include <Python.h>
27 }
28
29 #include <string>
30 #include <fstream>
31 #include <float.h>
32
33 #include "AppView.h"
34 #include "AppCanvas.h"
35 #include "AppConfig.h"
36 #include "Controller.h"
37
38 #include "../image/Image.h"
39
40 #include "../scene_graph/NodeDrawingStyle.h"
41 #include "../scene_graph/NodeShape.h"
42 #include "../scene_graph/NodeTransform.h"
43 #include "../scene_graph/NodeSceneRenderLayer.h"
44 #include "../scene_graph/ScenePrettyPrinter.h"
45 #include "../scene_graph/VertexRep.h"
46
47 #include "../stroke/PSStrokeRenderer.h"
48 #include "../stroke/TextStrokeRenderer.h"
49 #include "../stroke/StrokeTesselator.h"
50 #include "../stroke/StyleModule.h"
51
52 #include "../system/StringUtils.h"
53 #include "../system/PythonInterpreter.h"
54
55 #include "../view_map/SteerableViewMap.h"
56 #include "../view_map/ViewMap.h"
57 #include "../view_map/ViewMapIO.h"
58 #include "../view_map/ViewMapTesselator.h"
59
60 #include "../winged_edge/Curvature.h"
61 #include "../winged_edge/WEdge.h"
62 #include "../winged_edge/WingedEdgeBuilder.h"
63 #include "../winged_edge/WXEdgeBuilder.h"
64
65 #include "../blender_interface/BlenderFileLoader.h"
66 #include "../blender_interface/BlenderStrokeRenderer.h"
67 #include "../blender_interface/BlenderStyleModule.h"
68
69 #include "BKE_global.h"
70 #include "BLI_utildefines.h"
71 #include "BLI_path_util.h"
72
73 #include "DNA_freestyle_types.h"
74
75 #include "FRS_freestyle.h"
76
77 namespace Freestyle {
78
79 Controller::Controller()
80 {
81         const string sep(Config::DIR_SEP.c_str());
82 #if 0
83         const string filename = Config::Path::getInstance()->getHomeDir() + sep + Config::OPTIONS_DIR + sep +
84                                 Config::OPTIONS_CURRENT_DIRS_FILE;
85         _current_dirs = new ConfigIO(filename, Config::APPLICATION_NAME + "CurrentDirs", true);
86 #endif
87
88         _RootNode = new NodeGroup;
89         _RootNode->addRef();
90
91         _SilhouetteNode = NULL;
92 #if 0
93         _ProjectedSilhouette = NULL;
94         _VisibleProjectedSilhouette = NULL;
95 #endif
96
97         _DebugNode = new NodeGroup;
98         _DebugNode->addRef();
99
100         _winged_edge = NULL;
101
102         _pView = NULL;
103         _pRenderMonitor = NULL;
104
105         _edgeTesselationNature = (Nature::SILHOUETTE | Nature::BORDER | Nature::CREASE);
106
107         _ProgressBar = new ProgressBar;
108         _SceneNumFaces = 0;
109         _minEdgeSize = DBL_MAX;
110         _EPSILON = 1.0e-6;
111         _bboxDiag = 0;
112
113         _ViewMap = 0;
114
115         _Canvas = 0;
116
117         _VisibilityAlgo = ViewMapBuilder::ray_casting_adaptive_traditional;
118         //_VisibilityAlgo = ViewMapBuilder::ray_casting;
119
120         _Canvas = new AppCanvas;
121
122         _inter = new PythonInterpreter();
123         _EnableViewMapCache = false;
124         _EnableQI = true;
125         _EnableFaceSmoothness = false;
126         _ComputeRidges = true;
127         _ComputeSteerableViewMap = false;
128         _ComputeSuggestive = true;
129         _ComputeMaterialBoundaries = true;
130         _sphereRadius = 1.0;
131         _creaseAngle = 134.43;
132         prevSceneHash = -1.0;
133
134         init_options();
135 }
136
137 Controller::~Controller()
138 {
139         if (NULL != _RootNode) {
140                 int ref = _RootNode->destroy();
141                 if (0 == ref)
142                         delete _RootNode;
143         }
144
145         if (NULL != _SilhouetteNode) {
146                 int ref = _SilhouetteNode->destroy();
147                 if (0 == ref)
148                         delete _SilhouetteNode;
149         }
150
151         if (NULL != _DebugNode) {
152                 int ref = _DebugNode->destroy();
153                 if (0 == ref)
154                         delete _DebugNode;
155         }
156
157         if (_winged_edge) {
158                 delete _winged_edge;
159                 _winged_edge = NULL;
160         }
161
162         if (0 != _ViewMap) {
163                 delete _ViewMap;
164                 _ViewMap = 0;
165         }
166
167         if (0 != _Canvas) {
168                 delete _Canvas;
169                 _Canvas = 0;
170         }
171
172         if (_inter) {
173                 delete _inter;
174                 _inter = NULL;
175         }
176
177         if (_ProgressBar) {
178                 delete _ProgressBar;
179                 _ProgressBar = NULL;
180         }
181
182         //delete _current_dirs;
183 }
184
185 void Controller::setView(AppView *iView)
186 {
187         if (NULL == iView)
188                 return;
189
190         _pView = iView;
191         _Canvas->setViewer(_pView);
192 }
193
194 void Controller::setRenderMonitor(RenderMonitor *iRenderMonitor)
195 {
196         _pRenderMonitor = iRenderMonitor;
197 }
198
199 void Controller::setPassDiffuse(float *buf, int width, int height)
200 {
201         AppCanvas *app_canvas = dynamic_cast<AppCanvas *>(_Canvas);
202         BLI_assert(app_canvas != 0);
203         app_canvas->setPassDiffuse(buf, width, height);
204 }
205
206 void Controller::setPassZ(float *buf, int width, int height)
207 {
208         AppCanvas *app_canvas = dynamic_cast<AppCanvas *>(_Canvas);
209         BLI_assert(app_canvas != 0);
210         app_canvas->setPassZ(buf, width, height);
211 }
212
213 void Controller::setContext(bContext *C)
214 {
215         PythonInterpreter *py_inter = dynamic_cast<PythonInterpreter*>(_inter);
216         py_inter->setContext(C);
217 }
218
219 bool Controller::hitViewMapCache()
220 {
221         if (!_EnableViewMapCache) {
222                 return false;
223         }
224         if (sceneHashFunc.match()) {
225                 return (NULL != _ViewMap);
226         }
227         sceneHashFunc.store();
228         return false;
229 }
230
231 int Controller::LoadMesh(Render *re, SceneRenderLayer *srl)
232 {
233         BlenderFileLoader loader(re, srl);
234
235         loader.setRenderMonitor(_pRenderMonitor);
236
237         _Chrono.start();
238
239         NodeGroup *blenderScene = loader.Load();
240
241         if (blenderScene == NULL) {
242                 if (G.debug & G_DEBUG_FREESTYLE) {
243                         cout << "Cannot load scene" << endl;
244                 }
245                 return 1;
246         }
247
248         if (blenderScene->numberOfChildren() < 1) {
249                 if (G.debug & G_DEBUG_FREESTYLE) {
250                         cout << "Empty scene" << endl;
251                 }
252                 blenderScene->destroy();
253                 delete blenderScene;
254                 return 1;
255         }
256
257         real duration = _Chrono.stop();
258         if (G.debug & G_DEBUG_FREESTYLE) {
259                 cout << "Scene loaded" << endl;
260                 printf("Mesh cleaning    : %lf\n", duration);
261                 printf("View map cache   : %s\n", _EnableViewMapCache ? "enabled" : "disabled");
262         }
263         _SceneNumFaces += loader.numFacesRead();
264
265         if (loader.minEdgeSize() < _minEdgeSize) {
266                 _minEdgeSize = loader.minEdgeSize();
267         }
268
269 #if 0  // DEBUG
270         ScenePrettyPrinter spp;
271         blenderScene->accept(spp);
272 #endif
273
274         _RootNode->AddChild(blenderScene);
275         _RootNode->UpdateBBox(); // FIXME: Correct that by making a Renderer to compute the bbox
276
277         _pView->setModel(_RootNode);
278         //_pView->FitBBox();
279
280         if (_pRenderMonitor->testBreak())
281                 return 0;
282
283         if (_EnableViewMapCache) {
284
285                 NodeCamera *cam;
286                 if (freestyle_proj[3][3] != 0.0)
287                         cam = new NodeOrthographicCamera;
288                 else
289                         cam = new NodePerspectiveCamera;
290                 double proj[16];
291                 for (int i = 0; i < 4; i++) {
292                         for (int j = 0; j < 4; j++) {
293                                 proj[i * 4 + j] = freestyle_proj[i][j];
294                         }
295                 }
296                 cam->setProjectionMatrix(proj);
297                 _RootNode->AddChild(cam);
298                 _RootNode->AddChild(new NodeSceneRenderLayer(*re->scene, *srl));
299
300                 sceneHashFunc.reset();
301                 //blenderScene->accept(sceneHashFunc);
302                 _RootNode->accept(sceneHashFunc);
303                 if (G.debug & G_DEBUG_FREESTYLE) {
304                         cout << "Scene hash       : " << sceneHashFunc.toString() << endl;
305                 }
306                 if (hitViewMapCache()) {
307                         ClearRootNode();
308                         return 0;
309                 }
310                 else {
311                         delete _ViewMap;
312                         _ViewMap = NULL;
313                 }
314         }
315
316         _Chrono.start();
317
318         WXEdgeBuilder wx_builder;
319         wx_builder.setRenderMonitor(_pRenderMonitor);
320         blenderScene->accept(wx_builder);
321         _winged_edge = wx_builder.getWingedEdge();
322
323         duration = _Chrono.stop();
324         if (G.debug & G_DEBUG_FREESTYLE) {
325                 printf("WEdge building   : %lf\n", duration);
326         }
327
328 #if 0
329         _pView->setDebug(_DebugNode);
330
331         // delete stuff
332         if (0 != ws_builder) {
333                 delete ws_builder;
334                 ws_builder = 0;
335         }
336
337         soc QFileInfo qfi(iFileName);
338         soc string basename((const char*)qfi.fileName().toAscii().data());
339         char cleaned[FILE_MAX];
340         BLI_strncpy(cleaned, iFileName, FILE_MAX);
341         BLI_cleanup_file(NULL, cleaned);
342         string basename = string(cleaned);
343 #endif
344
345         _ListOfModels.push_back("Blender_models");
346
347         _Scene3dBBox = _RootNode->bbox();
348
349         _bboxDiag = (_RootNode->bbox().getMax() - _RootNode->bbox().getMin()).norm();
350         if (G.debug & G_DEBUG_FREESTYLE) {
351                 cout << "Triangles nb     : " << _SceneNumFaces << " imported, " <<
352                         _winged_edge->getNumFaces() << " retained" << endl;
353                 cout << "Bounding Box     : " << _bboxDiag << endl;
354         }
355
356         ClearRootNode();
357
358         _SceneNumFaces = _winged_edge->getNumFaces();
359         if (_SceneNumFaces == 0) {
360                 DeleteWingedEdge();
361                 return 1;
362         }
363
364         return 0;
365 }
366
367 void Controller::CloseFile()
368 {
369         WShape::setCurrentId(0);
370         _ListOfModels.clear();
371
372         // We deallocate the memory:
373         ClearRootNode();
374         DeleteWingedEdge();
375         DeleteViewMap();
376
377         // clears the canvas
378         _Canvas->Clear();
379
380         // soc: reset passes
381         setPassDiffuse(NULL, 0, 0);
382         setPassZ(NULL, 0, 0);
383 }
384
385 void Controller::ClearRootNode()
386 {
387         _pView->DetachModel();
388         if (NULL != _RootNode) {
389                 int ref = _RootNode->destroy();
390                 if (0 == ref)
391                         _RootNode->addRef();
392                 _RootNode->clearBBox();
393         }
394 }
395
396 void Controller::DeleteWingedEdge()
397 {
398         if (_winged_edge) {
399                 delete _winged_edge;
400                 _winged_edge = NULL;
401         }
402
403         // clears the grid
404         _Grid.clear();
405         _Scene3dBBox.clear();
406         _SceneNumFaces = 0;
407         _minEdgeSize = DBL_MAX;
408 }
409
410 void Controller::DeleteViewMap(bool freeCache)
411 {
412         _pView->DetachSilhouette();
413         if (NULL != _SilhouetteNode) {
414                 int ref = _SilhouetteNode->destroy();
415                 if (0 == ref) {
416                         delete _SilhouetteNode;
417                         _SilhouetteNode = NULL;
418                 }
419         }
420
421 #if 0
422         if (NULL != _ProjectedSilhouette) {
423                 int ref = _ProjectedSilhouette->destroy();
424                 if (0 == ref) {
425                         delete _ProjectedSilhouette;
426                         _ProjectedSilhouette = NULL;
427                 }
428         }
429         if (NULL != _VisibleProjectedSilhouette) {
430                 int ref = _VisibleProjectedSilhouette->destroy();
431                 if (0 == ref) {
432                         delete _VisibleProjectedSilhouette;
433                         _VisibleProjectedSilhouette = NULL;
434                 }
435         }
436 #endif
437
438         _pView->DetachDebug();
439         if (NULL != _DebugNode) {
440                 int ref = _DebugNode->destroy();
441                 if (0 == ref)
442                         _DebugNode->addRef();
443         }
444
445         if (NULL != _ViewMap) {
446                 if (freeCache || !_EnableViewMapCache) {
447                         delete _ViewMap;
448                         _ViewMap = NULL;
449                         prevSceneHash = -1.0;
450                 }
451                 else {
452                         _ViewMap->Clean();
453                 }
454         }
455 }
456
457 void Controller::ComputeViewMap()
458 {
459         if (!_ListOfModels.size())
460                 return;
461
462         DeleteViewMap(true);
463
464         // retrieve the 3D viewpoint and transformations information
465         //----------------------------------------------------------
466         // Save the viewpoint context at the view level in order 
467         // to be able to restore it later:
468
469         // Restore the context of view:
470         // we need to perform all these operations while the 
471         // 3D context is on.
472         Vec3r vp(freestyle_viewpoint[0], freestyle_viewpoint[1], freestyle_viewpoint[2]);
473
474 #if 0
475         if (G.debug & G_DEBUG_FREESTYLE) {
476                 cout << "mv" << endl;
477         }
478 #endif
479         real mv[4][4];
480         for (int i = 0; i < 4; i++) {
481                 for (int j = 0; j < 4; j++) {
482                         mv[i][j] = freestyle_mv[i][j];
483 #if 0
484                         if (G.debug & G_DEBUG_FREESTYLE) {
485                                 cout << mv[i][j] << " ";
486                         }
487 #endif
488                 }
489 #if 0
490                 if (G.debug & G_DEBUG_FREESTYLE) {
491                         cout << endl;
492                 }
493 #endif
494         }
495
496 #if 0
497         if (G.debug & G_DEBUG_FREESTYLE) {
498                 cout << "\nproj" << endl;
499         }
500 #endif
501         real proj[4][4];
502         for (int i = 0; i < 4; i++) {
503                 for (int j = 0; j < 4; j++) {
504                         proj[i][j] = freestyle_proj[i][j];
505 #if 0
506                         if (G.debug & G_DEBUG_FREESTYLE) {
507                                 cout << proj[i][j] << " ";
508                         }
509 #endif
510                 }
511 #if 0
512                 if (G.debug & G_DEBUG_FREESTYLE) {
513                         cout << endl;
514                 }
515 #endif
516         }
517
518         int viewport[4];
519         for (int i = 0; i < 4; i++)
520                 viewport[i] = freestyle_viewport[i];
521
522 #if 0
523         if (G.debug & G_DEBUG_FREESTYLE) {
524                 cout << "\nfocal:" << _pView->GetFocalLength() << endl << endl;
525         }
526 #endif
527
528         // Flag the WXEdge structure for silhouette edge detection:
529         //----------------------------------------------------------
530
531         if (G.debug & G_DEBUG_FREESTYLE) {
532                 cout << "\n===  Detecting silhouette edges  ===" << endl;
533         }
534         _Chrono.start();
535
536         edgeDetector.setViewpoint(Vec3r(vp));
537         edgeDetector.enableOrthographicProjection(proj[3][3] != 0.0);
538         edgeDetector.enableRidgesAndValleysFlag(_ComputeRidges);
539         edgeDetector.enableSuggestiveContours(_ComputeSuggestive);
540         edgeDetector.enableMaterialBoundaries(_ComputeMaterialBoundaries);
541         edgeDetector.enableFaceSmoothness(_EnableFaceSmoothness);
542         edgeDetector.setCreaseAngle(_creaseAngle);
543         edgeDetector.setSphereRadius(_sphereRadius);
544         edgeDetector.setSuggestiveContourKrDerivativeEpsilon(_suggestiveContourKrDerivativeEpsilon);
545         edgeDetector.setRenderMonitor(_pRenderMonitor);
546         edgeDetector.processShapes(*_winged_edge);
547
548         real duration = _Chrono.stop();
549         if (G.debug & G_DEBUG_FREESTYLE) {
550                 printf("Feature lines    : %lf\n", duration);
551         }
552
553         if (_pRenderMonitor->testBreak())
554                 return;
555
556         // Builds the view map structure from the flagged WSEdge structure:
557         //----------------------------------------------------------
558         ViewMapBuilder vmBuilder;
559         vmBuilder.setEnableQI(_EnableQI);
560         vmBuilder.setViewpoint(Vec3r(vp));
561         vmBuilder.setTransform(mv, proj, viewport, _pView->GetFocalLength(), _pView->GetAspect(), _pView->GetFovyRadian());
562         vmBuilder.setFrustum(_pView->znear(), _pView->zfar());
563         vmBuilder.setGrid(&_Grid);
564         vmBuilder.setRenderMonitor(_pRenderMonitor);
565
566         // Builds a tesselated form of the silhouette for display purpose:
567         //---------------------------------------------------------------
568         ViewMapTesselator3D sTesselator3d;
569 #if 0
570         ViewMapTesselator2D sTesselator2d;
571         sTesselator2d.setNature(_edgeTesselationNature);
572 #endif
573         sTesselator3d.setNature(_edgeTesselationNature);
574
575         if (G.debug & G_DEBUG_FREESTYLE) {
576                 cout << "\n===  Building the view map  ===" << endl;
577         }
578         _Chrono.start();
579         // Build View Map
580         _ViewMap = vmBuilder.BuildViewMap(*_winged_edge, _VisibilityAlgo, _EPSILON, _Scene3dBBox, _SceneNumFaces);
581         _ViewMap->setScene3dBBox(_Scene3dBBox);
582
583         if (G.debug & G_DEBUG_FREESTYLE) {
584                 printf("ViewMap edge count : %i\n", _ViewMap->viewedges_size());
585         }
586
587         // Tesselate the 3D edges:
588         _SilhouetteNode = sTesselator3d.Tesselate(_ViewMap);
589         _SilhouetteNode->addRef();
590
591         // Tesselate 2D edges
592 #if 0
593         _ProjectedSilhouette = sTesselator2d.Tesselate(_ViewMap);
594         _ProjectedSilhouette->addRef();
595 #endif
596
597         duration = _Chrono.stop();
598         if (G.debug & G_DEBUG_FREESTYLE) {
599                 printf("ViewMap building : %lf\n", duration);
600         }
601
602         _pView->AddSilhouette(_SilhouetteNode);
603 #if 0
604         _pView->AddSilhouette(_WRoot);
605         _pView->Add2DSilhouette(_ProjectedSilhouette);
606         _pView->Add2DVisibleSilhouette(_VisibleProjectedSilhouette);
607 #endif
608         _pView->AddDebug(_DebugNode);
609
610         // Draw the steerable density map:
611         //--------------------------------
612         if (_ComputeSteerableViewMap) {
613                 ComputeSteerableViewMap();
614         }
615         // Reset Style modules modification flags
616         resetModified(true);
617
618         DeleteWingedEdge();
619 }
620
621 void Controller::ComputeSteerableViewMap()
622 {
623 #if 0  //soc
624         if ((!_Canvas) || (!_ViewMap))
625                 return;
626
627         // Build 4 nodes containing the edges in the 4 directions
628         NodeGroup *ng[Canvas::NB_STEERABLE_VIEWMAP];
629         unsigned i;
630         real c = 32.0f/255.0f; // see SteerableViewMap::readSteerableViewMapPixel() for information about this 32.
631         for (i = 0; i < Canvas::NB_STEERABLE_VIEWMAP; ++i) {
632                 ng[i] = new NodeGroup;
633         }
634         NodeShape *completeNS = new NodeShape;
635         completeNS->material().setDiffuse(c,c,c,1);
636         ng[Canvas::NB_STEERABLE_VIEWMAP-1]->AddChild(completeNS);
637         SteerableViewMap * svm = _Canvas->getSteerableViewMap();
638         svm->Reset();
639
640         ViewMap::fedges_container& fedges = _ViewMap->FEdges();
641         LineRep * fRep;
642         NodeShape *ns;
643         for (ViewMap::fedges_container::iterator f = fedges.begin(), fend = fedges.end();
644              f != fend;
645              ++f)
646         {
647                 if ((*f)->viewedge()->qi() != 0)
648                         continue;
649                 fRep = new LineRep((*f)->vertexA()->point2d(), (*f)->vertexB()->point2d());
650                 completeNS->AddRep(fRep); // add to the complete map anyway
651                 double *oweights = svm->AddFEdge(*f);
652                 for (i = 0; i < (Canvas::NB_STEERABLE_VIEWMAP - 1); ++i) {
653                         ns = new NodeShape;
654                         double wc = oweights[i]*c;
655                         if (oweights[i] == 0)
656                                 continue;
657                         ns->material().setDiffuse(wc, wc, wc, 1);
658                         ns->AddRep(fRep);
659                         ng[i]->AddChild(ns);
660                 }
661         }
662
663         GrayImage *img[Canvas::NB_STEERABLE_VIEWMAP];
664         //#ifdef WIN32
665         QGLBasicWidget offscreenBuffer(_pView, "SteerableViewMap", _pView->width(), _pView->height());
666         QPixmap pm;
667         QImage qimg;
668         for (i = 0; i < Canvas::NB_STEERABLE_VIEWMAP; ++i) {
669                 offscreenBuffer.AddNode(ng[i]);
670 #if 0
671                 img[i] = new GrayImage(_pView->width(), _pView->height());
672                 offscreenBuffer.readPixels(0,0,_pView->width(), _pView->height(), img[i]->getArray());
673 #endif
674                 pm = offscreenBuffer.renderPixmap(_pView->width(), _pView->height());
675
676                 if (pm.isNull()) {
677                         if (G.debug & G_DEBUG_FREESTYLE) {
678                                 cout << "BuildViewMap Warning: couldn't render the steerable ViewMap" << endl;
679                         }
680                 }
681                 //pm.save(QString("steerable") + QString::number(i) + QString(".bmp"), "BMP");
682                 // FIXME!! Lost of time !
683                 qimg = pm.toImage();
684                 // FIXME !! again!
685                 img[i] = new GrayImage(_pView->width(), _pView->height());
686                 for (unsigned int y = 0; y < img[i]->height(); ++y) {
687                         for (unsigned int x = 0; x < img[i]->width(); ++x) {
688                                 //img[i]->setPixel(x, y, (float)qGray(qimg.pixel(x, y)) / 255.0f);
689                                 img[i]->setPixel(x, y, (float)qGray(qimg.pixel(x, y)));
690                                 //float c = qGray(qimg.pixel(x, y));
691                                 //img[i]->setPixel(x, y, qGray(qimg.pixel(x, y)));
692                         }
693                 }
694                 offscreenBuffer.DetachNode(ng[i]);
695                 ng[i]->destroy();
696                 delete ng[i];
697                 // check
698 #if 0
699                 qimg = QImage(_pView->width(), _pView->height(), 32);
700                 for (unsigned int y = 0; y < img[i]->height(); ++y) {
701                         for (unsigned int x = 0; x < img[i]->width(); ++x) {
702                                 float v = img[i]->pixel(x, y);
703                                 qimg.setPixel(x, y, qRgb(v, v, v));
704                         }
705                 }
706                 qimg.save(QString("newsteerable") + QString::number(i) + QString(".bmp"), "BMP");
707 #endif
708         }
709
710
711         svm->buildImagesPyramids(img, false, 0, 1.0f);
712 #endif
713 }
714
715 void Controller::saveSteerableViewMapImages()
716 {
717         SteerableViewMap * svm = _Canvas->getSteerableViewMap();
718         if (!svm) {
719                 cerr << "the Steerable ViewMap has not been computed yet" << endl;
720                 return;
721         }
722         svm->saveSteerableViewMap();
723 }
724
725 void Controller::toggleVisibilityAlgo()
726 {
727         if (_VisibilityAlgo == ViewMapBuilder::ray_casting) {
728                 _VisibilityAlgo = ViewMapBuilder::ray_casting_fast;
729         }
730         else if (_VisibilityAlgo == ViewMapBuilder::ray_casting_fast) {
731                 _VisibilityAlgo = ViewMapBuilder::ray_casting_very_fast;
732         }
733         else {
734                 _VisibilityAlgo = ViewMapBuilder::ray_casting;
735         }
736 }
737
738 void Controller::setVisibilityAlgo(int algo)
739 {
740         switch (algo) {
741                 case FREESTYLE_ALGO_REGULAR:
742                         _VisibilityAlgo = ViewMapBuilder::ray_casting;
743                         break;
744                 case FREESTYLE_ALGO_FAST:
745                         _VisibilityAlgo = ViewMapBuilder::ray_casting_fast;
746                         break;
747                 case FREESTYLE_ALGO_VERYFAST:
748                         _VisibilityAlgo = ViewMapBuilder::ray_casting_very_fast;
749                         break;
750                 case FREESTYLE_ALGO_CULLED_ADAPTIVE_TRADITIONAL:
751                         _VisibilityAlgo = ViewMapBuilder::ray_casting_culled_adaptive_traditional;
752                         break;
753                 case FREESTYLE_ALGO_ADAPTIVE_TRADITIONAL:
754                         _VisibilityAlgo = ViewMapBuilder::ray_casting_adaptive_traditional;
755                         break;
756                 case FREESTYLE_ALGO_CULLED_ADAPTIVE_CUMULATIVE:
757                         _VisibilityAlgo = ViewMapBuilder::ray_casting_culled_adaptive_cumulative;
758                         break;
759                 case FREESTYLE_ALGO_ADAPTIVE_CUMULATIVE:
760                         _VisibilityAlgo = ViewMapBuilder::ray_casting_adaptive_cumulative;
761                         break;
762         }
763 }
764
765 int Controller::getVisibilityAlgo()
766 {
767         switch (_VisibilityAlgo) {
768                 case ViewMapBuilder::ray_casting:
769                         return FREESTYLE_ALGO_REGULAR;
770                 case ViewMapBuilder::ray_casting_fast:
771                         return FREESTYLE_ALGO_FAST;
772                 case ViewMapBuilder::ray_casting_very_fast:
773                         return FREESTYLE_ALGO_VERYFAST;
774                 case ViewMapBuilder::ray_casting_culled_adaptive_traditional:
775                         return FREESTYLE_ALGO_CULLED_ADAPTIVE_TRADITIONAL;
776                 case ViewMapBuilder::ray_casting_adaptive_traditional:
777                         return FREESTYLE_ALGO_ADAPTIVE_TRADITIONAL;
778                 case ViewMapBuilder::ray_casting_culled_adaptive_cumulative:
779                         return FREESTYLE_ALGO_CULLED_ADAPTIVE_CUMULATIVE;
780                 case ViewMapBuilder::ray_casting_adaptive_cumulative:
781                         return FREESTYLE_ALGO_ADAPTIVE_CUMULATIVE;
782         }
783
784         // ray_casting_adaptive_traditional is the most exact replacement
785         // for legacy code
786         return FREESTYLE_ALGO_ADAPTIVE_TRADITIONAL;
787 }
788
789 void Controller::setViewMapCache(bool iBool)
790 {
791         _EnableViewMapCache = iBool;
792 }
793
794 bool Controller::getViewMapCache() const
795 {
796         return _EnableViewMapCache;
797 }
798
799 void Controller::setQuantitativeInvisibility(bool iBool)
800 {
801         _EnableQI = iBool;
802 }
803
804 bool Controller::getQuantitativeInvisibility() const
805 {
806         return _EnableQI;
807 }
808
809 void Controller::setFaceSmoothness(bool iBool)
810 {
811         _EnableFaceSmoothness = iBool;
812 }
813
814 bool Controller::getFaceSmoothness() const
815 {
816         return _EnableFaceSmoothness;
817 }
818
819 void Controller::setComputeRidgesAndValleysFlag(bool iBool)
820 {
821         _ComputeRidges = iBool;
822 }
823
824 bool Controller::getComputeRidgesAndValleysFlag() const
825 {
826         return _ComputeRidges;
827 }
828
829 void Controller::setComputeSuggestiveContoursFlag(bool b)
830 {
831         _ComputeSuggestive = b;
832 }
833
834 bool Controller::getComputeSuggestiveContoursFlag() const
835 {
836         return _ComputeSuggestive;
837 }
838
839 void Controller::setComputeMaterialBoundariesFlag(bool b)
840 {
841         _ComputeMaterialBoundaries = b;
842 }
843
844 bool Controller::getComputeMaterialBoundariesFlag() const
845 {
846         return _ComputeMaterialBoundaries;
847 }
848
849 void Controller::setComputeSteerableViewMapFlag(bool iBool)
850 {
851         _ComputeSteerableViewMap = iBool;
852 }
853
854 bool Controller::getComputeSteerableViewMapFlag() const
855 {
856         return _ComputeSteerableViewMap;
857 }
858
859 void Controller::DrawStrokes()
860 {
861         if (_ViewMap == 0)
862                 return;
863
864         if (G.debug & G_DEBUG_FREESTYLE) {
865                 cout << "\n===  Stroke drawing  ===" << endl;
866         }
867         _Chrono.start();
868         _Canvas->Draw();
869         real d = _Chrono.stop();
870         if (G.debug & G_DEBUG_FREESTYLE) {
871                 cout << "Strokes generation  : " << d << endl;
872                 cout << "Stroke count  : " << _Canvas->getStrokeCount() << endl;
873         }
874         resetModified();
875         DeleteViewMap();
876 }
877
878 void Controller::ResetRenderCount()
879 {
880         _render_count = 0;
881 }
882
883 Render *Controller::RenderStrokes(Render *re, bool render)
884 {
885         int totmesh = 0;
886         _Chrono.start();
887         BlenderStrokeRenderer *blenderRenderer = new BlenderStrokeRenderer(re, ++_render_count);
888         if (render) {
889                 _Canvas->Render(blenderRenderer);
890                 totmesh = blenderRenderer->GenerateScene();
891         }
892         real d = _Chrono.stop();
893         if (G.debug & G_DEBUG_FREESTYLE) {
894                 cout << "Temporary scene generation: " << d << endl;
895         }
896         _Chrono.start();
897         Render *freestyle_render = blenderRenderer->RenderScene(re, render);
898         d = _Chrono.stop();
899         if (G.debug & G_DEBUG_FREESTYLE) {
900                 cout << "Stroke rendering  : " << d << endl;
901
902                 uintptr_t mem_in_use = MEM_get_memory_in_use();
903                 uintptr_t mmap_in_use = MEM_get_mapped_memory_in_use();
904                 uintptr_t peak_memory = MEM_get_peak_memory();
905
906                 float megs_used_memory = (mem_in_use - mmap_in_use) / (1024.0 * 1024.0);
907                 float mmap_used_memory = (mmap_in_use) / (1024.0 * 1024.0);
908                 float megs_peak_memory = (peak_memory) / (1024.0 * 1024.0);
909
910                 printf("%d objs, %d verts, %d faces, mem %.2fM (%.2fM, peak %.2fM)\n",
911                        totmesh, freestyle_render->i.totvert, freestyle_render->i.totface,
912                        megs_used_memory, mmap_used_memory, megs_peak_memory);
913         }
914         delete blenderRenderer;
915
916         return freestyle_render;
917 }
918
919 void Controller::InsertStyleModule(unsigned index, const char *iFileName)
920 {
921         if (!BLI_testextensie(iFileName, ".py")) {
922                 cerr << "Error: Cannot load \"" << string(iFileName) << "\", unknown extension" << endl;
923                 return;
924         }
925
926         StyleModule *sm = new StyleModule(iFileName, _inter);
927         _Canvas->InsertStyleModule(index, sm);
928 }
929
930 void Controller::InsertStyleModule(unsigned index, const char *iName, struct Text *iText)
931 {
932         StyleModule *sm = new BlenderStyleModule(iText, iName, _inter);
933         _Canvas->InsertStyleModule(index, sm);
934 }
935
936 void Controller::AddStyleModule(const char * /*iFileName*/)
937 {
938         //_pStyleWindow->Add(iFileName);
939 }
940
941 void Controller::RemoveStyleModule(unsigned index)
942 {
943         _Canvas->RemoveStyleModule(index);
944 }
945
946 void Controller::Clear()
947 {
948         _Canvas->Clear();
949 }
950
951 void Controller::ReloadStyleModule(unsigned index, const char * iFileName)
952 {
953         StyleModule *sm = new StyleModule(iFileName, _inter);
954         _Canvas->ReplaceStyleModule(index, sm);
955 }
956
957 void Controller::SwapStyleModules(unsigned i1, unsigned i2)
958 {
959         _Canvas->SwapStyleModules(i1, i2);
960 }
961
962 void Controller::toggleLayer(unsigned index, bool iDisplay)
963 {
964         _Canvas->setVisible(index, iDisplay);
965 }
966
967 void Controller::setModified(unsigned index, bool iMod)
968 {
969         //_pStyleWindow->setModified(index, iMod);
970         _Canvas->setModified(index, iMod);
971         updateCausalStyleModules(index + 1);
972 }
973
974 void Controller::updateCausalStyleModules(unsigned index)
975 {
976         vector<unsigned> vec;
977         _Canvas->causalStyleModules(vec, index);
978         for (vector<unsigned>::const_iterator it = vec.begin(); it != vec.end(); it++) {
979                 //_pStyleWindow->setModified(*it, true);
980                 _Canvas->setModified(*it, true);
981         }
982 }
983
984 void Controller::resetModified(bool iMod)
985 {
986         //_pStyleWindow->resetModified(iMod);
987         _Canvas->resetModified(iMod);
988 }
989
990 NodeGroup * Controller::BuildRep(vector<ViewEdge*>::iterator vedges_begin, vector<ViewEdge*>::iterator vedges_end)
991 {
992         ViewMapTesselator2D tesselator2D;
993         FrsMaterial mat;
994         mat.setDiffuse(1, 1, 0.3, 1);
995         tesselator2D.setFrsMaterial(mat);
996
997         return (tesselator2D.Tesselate(vedges_begin, vedges_end));
998 }
999
1000 void Controller::toggleEdgeTesselationNature(Nature::EdgeNature iNature)
1001 {
1002         _edgeTesselationNature ^= (iNature);
1003         ComputeViewMap();
1004 }
1005
1006 void Controller::setModelsDir(const string& /*dir*/)
1007 {
1008         //_current_dirs->setValue("models/dir", dir);
1009 }
1010
1011 string Controller::getModelsDir() const
1012 {
1013         string dir = ".";
1014         //_current_dirs->getValue("models/dir", dir);
1015         return dir;
1016 }
1017
1018 void Controller::setModulesDir(const string& /*dir*/)
1019 {
1020         //_current_dirs->setValue("modules/dir", dir);
1021 }
1022
1023 string Controller::getModulesDir() const
1024 {
1025         string dir = ".";
1026         //_current_dirs->getValue("modules/dir", dir);
1027         return dir;
1028 }
1029
1030 void Controller::resetInterpreter()
1031 {
1032         if (_inter)
1033                 _inter->reset();
1034 }
1035
1036
1037 void Controller::displayDensityCurves(int x, int y)
1038 {
1039         SteerableViewMap * svm = _Canvas->getSteerableViewMap();
1040         if (!svm)
1041                 return;
1042
1043         unsigned int i, j;
1044         typedef vector<Vec3r> densityCurve;
1045         vector<densityCurve> curves(svm->getNumberOfOrientations() + 1);
1046         vector<densityCurve> curvesDirection(svm->getNumberOfPyramidLevels());
1047
1048         // collect the curves values
1049         unsigned nbCurves = svm->getNumberOfOrientations() + 1;
1050         unsigned nbPoints = svm->getNumberOfPyramidLevels();
1051         if (!nbPoints)
1052                 return;
1053
1054         // build the density/nbLevels curves for each orientation
1055         for (i = 0; i < nbCurves; ++i) {
1056                 for (j = 0; j < nbPoints; ++j) {
1057                         curves[i].push_back(Vec3r(j, svm->readSteerableViewMapPixel(i, j, x, y), 0));
1058                 }
1059         }
1060         // build the density/nbOrientations curves for each level
1061         for (i = 0; i < nbPoints; ++i) {
1062                 for (j = 0; j < nbCurves; ++j) {
1063                         curvesDirection[i].push_back(Vec3r(j, svm->readSteerableViewMapPixel(j, i, x, y), 0));
1064                 }
1065         }
1066
1067         // display the curves
1068 #if 0
1069         for (i = 0; i < nbCurves; ++i)
1070                 _pDensityCurvesWindow->setOrientationCurve(i, Vec2d(0, 0), Vec2d(nbPoints, 1), curves[i], "scale", "density");
1071         for (i = 1; i <= 8; ++i)
1072                 _pDensityCurvesWindow->setLevelCurve(i, Vec2d(0, 0), Vec2d(nbCurves, 1), curvesDirection[i],
1073                                                      "orientation", "density");
1074         _pDensityCurvesWindow->show();
1075 #endif
1076 }
1077
1078 void Controller::init_options()
1079 {
1080         // from AppOptionsWindow.cpp
1081         // Default init options
1082
1083         Config::Path * cpath = Config::Path::getInstance();
1084
1085         // Directories
1086         ViewMapIO::Options::setModelsPath(cpath->getModelsPath());
1087         TextureManager::Options::setPatternsPath(cpath->getPatternsPath());
1088         TextureManager::Options::setBrushesPath(cpath->getModelsPath());
1089
1090         // ViewMap Format
1091         ViewMapIO::Options::rmFlags(ViewMapIO::Options::FLOAT_VECTORS);
1092         ViewMapIO::Options::rmFlags(ViewMapIO::Options::NO_OCCLUDERS);
1093         setComputeSteerableViewMapFlag(false);
1094
1095         // Visibility
1096         setQuantitativeInvisibility(true);
1097
1098         // soc: initialize canvas
1099         _Canvas->init();
1100
1101         // soc: initialize passes
1102         setPassDiffuse(NULL, 0, 0);
1103         setPassZ(NULL, 0, 0);
1104 }
1105
1106 } /* namespace Freestyle */