campvisapplication.cpp 13.1 KB
Newer Older
1
2
// ================================================================================================
// 
schultezub's avatar
schultezub committed
3
// This file is part of the CAMPVis Software Framework.
4
// 
5
// If not explicitly stated otherwise: Copyright (C) 2012-2014, all rights reserved,
schultezub's avatar
schultezub committed
6
//      Christian Schulte zu Berge <christian.szb@in.tum.de>
7
//      Chair for Computer Aided Medical Procedures
8
9
//      Technische Universitaet Muenchen
//      Boltzmannstr. 3, 85748 Garching b. Muenchen, Germany
10
// 
schultezub's avatar
schultezub committed
11
// For a full list of authors and contributors, please refer to the file "AUTHORS.txt".
12
// 
13
14
15
16
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file 
// except in compliance with the License. You may obtain a copy of the License at
// 
// http://www.apache.org/licenses/LICENSE-2.0
17
// 
18
19
20
21
// Unless required by applicable law or agreed to in writing, software distributed under the 
// License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 
// either express or implied. See the License for the specific language governing permissions 
// and limitations under the License.
22
23
24
// 
// ================================================================================================

schultezub's avatar
schultezub committed
25
#include "campvisapplication.h"
26
27
28

#include "tgt/assert.h"
#include "tgt/exception.h"
29
#include "tgt/glcanvas.h"
30
#include "tgt/glcontextmanager.h"
31
#include "tgt/gpucapabilities.h"
32
#include "tgt/shadermanager.h"
33
#include "tgt/texturereadertga.h"
34
35
36
#include "tgt/qt/qtapplication.h"
#include "tgt/qt/qtthreadedcanvas.h"

schultezub's avatar
schultezub committed
37
#include "application/campvispainter.h"
38
#include "application/gui/properties/propertywidgetfactory.h"
39
#include "application/gui/mainwindow.h"
Jakob Weiss's avatar
Jakob Weiss committed
40
#include "application/gui/mdi/mdidockablewindow.h"
41

42
#include "core/tools/job.h"
43
#include "core/tools/opengljobprocessor.h"
44
#include "core/tools/simplejobprocessor.h"
45
#include "core/tools/stringutils.h"
46
#include "core/tools/quadrenderer.h"
47
#include "core/pipeline/abstractpipeline.h"
48
#include "core/datastructures/imagerepresentationconverter.h"
49
#include "core/pipeline/visualizationprocessor.h"
50

51
#include "modules/pipelinefactory.h"
52
#include "qtjobprocessor.h"
53

54
#ifdef CAMPVIS_HAS_SCRIPTING
55
#include "scripting/gen_pipelineregistration.h"
56
57
#endif

schultezub's avatar
schultezub committed
58
namespace campvis {
59

60
    const std::string CampVisApplication::loggerCat_ = "CAMPVis.application.CampVisApplication";
61

62
    CampVisApplication::CampVisApplication(int& argc, char** argv) 
63
64
        : QApplication(argc, argv)
        , _localContext(0)
65
        , _mainWindow(0)
66
        , _errorTexture(nullptr)
67
        , _luaVmState(nullptr)
68
69
70
71
        , _initialized(false)
        , _argc(argc)
        , _argv(argv)
    {
72
73
        // Make Xlib and GLX thread safe under X11
        QApplication::setAttribute(Qt::AA_X11InitThreads);
74

75
76
        sigslot::signal_manager::init();
        sigslot::signal_manager::getRef().start();
77
        _mainWindow = new MainWindow(this);
78
        tgt::GlContextManager::init();
79
80

        OpenGLJobProcessor::init();
81
        SimpleJobProcessor::init();
82
        QtJobProcessor::init();
83
84
    }

85
86
    CampVisApplication::~CampVisApplication() {
        tgtAssert(_initialized == false, "Destructing initialized CampVisApplication, deinitialize first!");
87
88

        // delete everything in the right order:
89
90
91
        for (std::vector<PipelineRecord>::iterator it = _pipelines.begin(); it != _pipelines.end(); ++it) {
            delete it->_painter;
            delete it->_pipeline;
92
        }
93
94
95
        for (std::vector<DataContainer*>::iterator it = _dataContainers.begin(); it != _dataContainers.end(); ++it) {
            delete *it;
        }
96
97
98

        sigslot::signal_manager::getRef().stop();
        sigslot::signal_manager::deinit();
99
100
    }

101
102
    void CampVisApplication::init() {
        tgtAssert(_initialized == false, "Tried to initialize CampVisApplication twice.");
103
104
105
106
107
108
109

        // Init TGT
        tgt::InitFeature::Features featureset = tgt::InitFeature::ALL;
        tgt::init(featureset);
        LogMgr.getConsoleLog()->addCat("", true);

        // create a local OpenGL context and init GL
110
        _localContext = new QtThreadedCanvas("", tgt::ivec2(16, 16));
111

112
        tgt::GLContextScopedLock lock(_localContext);
113
        tgt::GlContextManager::getRef().registerContextAndInitGlew(_localContext);
114

115
        tgt::initGL(featureset);
116
        ShdrMgr.setDefaultGlslVersion("330");
117
118
        LGL_ERROR;

119
        QuadRenderer::init();
120
        
121
122
        if (_argc > 0) {
            // ugly hack
schultezub's avatar
schultezub committed
123
            std::string basePath(_argv[0]);
124
125
126
127
128
            basePath = tgt::FileSystem::parentDir(basePath);
            ShdrMgr.addPath(basePath);
            ShdrMgr.addPath(basePath + "/core/glsl");

            basePath = tgt::FileSystem::parentDir(tgt::FileSystem::parentDir(basePath));
schultezub's avatar
schultezub committed
129
130
131
            ShdrMgr.addPath(basePath);
            ShdrMgr.addPath(basePath + "/core/glsl");

132
133
134
135
136
137
#ifdef CAMPVIS_SOURCE_DIR
            {
                std::string sourcePath = CAMPVIS_SOURCE_DIR;
                ShdrMgr.addPath(sourcePath);
                ShdrMgr.addPath(sourcePath + "/core/glsl");
            }
schultezub's avatar
schultezub committed
138
#endif
139
140
        }

141
142
        _mainWindow->init();

143
144
145
146
147
148
149
150
151
152
        // ensure matching OpenGL specs
        LINFO("Using Graphics Hardware " << GpuCaps.getVendorAsString() << " " << GpuCaps.getGlRendererString() << " on " << GpuCaps.getOSVersionString());
        LINFO("Supported OpenGL " << GpuCaps.getGlVersion() << ", GLSL " << GpuCaps.getShaderVersion());
        if (GpuCaps.getGlVersion() < tgt::GpuCapabilities::GlVersion::TGT_GL_VERSION_3_3) {
            LERROR("Your system does not support OpenGL 3.3, which is mandatory. CAMPVis will probably not work as intended.");
        }
        if (GpuCaps.getShaderVersion() < tgt::GpuCapabilities::GlVersion::SHADER_VERSION_330) {
            LERROR("Your system does not support GLSL Shader Version 3.30, which is mandatory. CAMPVis will probably not work as intended.");
        }

153
154
        GLJobProc.start();
        GLJobProc.registerContext(_localContext);
155

156
157
        // load textureData from file
        tgt::TextureReaderTga trt;
158
        _errorTexture = trt.loadTexture(ShdrMgr.completePath("application/data/no_input.tga"), tgt::Texture::LINEAR);
159

160
161
162
163

#ifdef CAMPVIS_HAS_SCRIPTING
        // create and store Lua VM for this very pipeline
        _luaVmState = new LuaVmState();
164
        _luaVmState->redirectLuaPrint();
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182

        // Let Lua know where CAMPVis modules are located
        if (! _luaVmState->execString("package.cpath = '" CAMPVIS_LUA_MODS_PATH "'"))
            LERROR("Error setting up Lua VM.");

        // Load CAMPVis' core Lua module to have SWIG glue for AutoEvaluationPipeline available
        if (! _luaVmState->execString("require(\"campvis\")"))
            LERROR("Error setting up Lua VM.");
        if (! _luaVmState->execString("require(\"tgt\")"))
            LERROR("Error setting up Lua VM.");

        if (! _luaVmState->execString("pipelines = {}"))
            LERROR("Error setting up Lua VM.");

        if (! _luaVmState->execString("inspect = require 'inspect'"))
            LERROR("Error setting up Lua VM.");
#endif

183
184
185
186
187
188
189
        // parse argument list and create pipelines
        QStringList pipelinesToAdd = this->arguments();
        for (int i = 1; i < pipelinesToAdd.size(); ++i) {
            DataContainer* dc = createAndAddDataContainer("DataContainer #" + StringUtils::toString(_dataContainers.size() + 1));
            AbstractPipeline* p = PipelineFactory::getRef().createPipeline(pipelinesToAdd[i].toStdString(), dc);
            if (p != 0)
                addPipeline(pipelinesToAdd[i].toStdString(), p);
190
191
192
193
194
        }

        _initialized = true;
    }

195
196
    void CampVisApplication::deinit() {
        tgtAssert(_initialized, "Tried to deinitialize uninitialized CampVisApplication.");
197

198
199
        GLJobProc.stop();

200
201
        {
            // Deinit everything OpenGL related using the local context.
202
            tgt::GLContextScopedLock lock(_localContext);
203

204
205
            delete _errorTexture;

206
207
208
209
            // Deinit pipeline and painter first
            for (std::vector<PipelineRecord>::iterator it = _pipelines.begin(); it != _pipelines.end(); ++it) {
                it->_pipeline->deinit();
                it->_painter->deinit();
210
211
            }

212
            _mainWindow->deinit();
213
214
            QuadRenderer::deinit();

215
216
            // deinit OpenGL and tgt
            tgt::deinitGL();
217
218
        }

219
        tgt::GlContextManager::deinit();
220
221
        tgt::deinit();

222
223
224
225
226
227
228
        OpenGLJobProcessor::deinit();
        SimpleJobProcessor::deinit();

        PropertyWidgetFactory::deinit();
        ImageRepresentationConverter::deinit();
        PipelineFactory::deinit();

229
        // MainWindow dtor needs a valid CampVisApplication, so we need to call it here instead of during destruction.
schultezub's avatar
schultezub committed
230
231
        delete _mainWindow;

232
233
234
        _initialized = false;
    }

235
236
    int CampVisApplication::run() {
        tgtAssert(_initialized, "Tried to run uninitialized CampVisApplication.");
237
238

        // disconnect OpenGL context from this thread so that the other threads can acquire an OpenGL context.
239
        tgt::GlContextManager::getRef().releaseCurrentContext();
240

241
242
        _mainWindow->show();

243
244
245
246
247
248
        // Start QApplication
        int toReturn = QApplication::exec();

        return toReturn;
    }

249
    void CampVisApplication::addPipeline(const std::string& name, AbstractPipeline* pipeline) {
250
251
        tgtAssert(pipeline != 0, "Pipeline must not be 0.");

252
        // create canvas and painter for the pipeline and connect all together
253
        tgt::QtThreadedCanvas* canvas = new tgt::QtThreadedCanvas("CAMPVis", tgt::ivec2(512, 512));
254
        GLJobProc.registerContext(canvas);
255
256
        canvas->init();

257
        CampVisPainter* painter = new CampVisPainter(canvas, pipeline);
258
        canvas->setPainter(painter, false);
259
        pipeline->setCanvas(canvas);
260
        painter->setErrorTexture(_errorTexture);
261

262
        PipelineRecord pr = { pipeline, painter };
263
        _pipelines.push_back(pr);
264

Jakob Weiss's avatar
Jakob Weiss committed
265
        _pipelineWindows[pipeline] = _mainWindow->addVisualizationPipelineWidget(name, canvas);
266

267
268
269
270
271
272
        // initialize context (GLEW) and pipeline in OpenGL thread)
        GLJobProc.enqueueJob(
            canvas, 
            makeJobOnHeap<CampVisApplication, tgt::GLCanvas*, AbstractPipeline*>(this, &CampVisApplication::initGlContextAndPipeline, canvas, pipeline), 
            OpenGLJobProcessor::SerialJob);

273
#ifdef CAMPVIS_HAS_SCRIPTING
274
275
        if (! _luaVmState->injectObjectPointerToTable(pipeline, "campvis::AutoEvaluationPipeline *", "pipelines", static_cast<int>(_pipelines.size())))
        //if (! _luaVmState->injectObjectPointerToTableField(pipeline, "campvis::AutoEvaluationPipeline *", "pipelines", name))
276
277
            LERROR("Could not inject the pipeline into the Lua VM.");

278
        _luaVmState->execString("inspect(pipelines)");
279
280
#endif

281
        s_PipelinesChanged.emitSignal();
282
283
284
285
286
287
288
289
290
291
    }

    void CampVisApplication::initGlContextAndPipeline(tgt::GLCanvas* canvas, AbstractPipeline* pipeline) {
        tgt::GlContextManager::getRef().registerContextAndInitGlew(canvas);

        pipeline->init();
        LGL_ERROR;
        canvas->getPainter()->init();
        LGL_ERROR;

292
293
294
295
296
        // enable pipeline and invalidate all processors
        pipeline->setEnabled(true);
        for (std::vector<AbstractProcessor*>::const_iterator it = pipeline->getProcessors().begin(); it != pipeline->getProcessors().end(); ++it) {
            (*it)->invalidate(AbstractProcessor::INVALID_RESULT);
        }
297
298
    }

299
300
301
302
303
304
    void CampVisApplication::registerDockWidget(Qt::DockWidgetArea area, QDockWidget* dock) {
        tgtAssert(dock != 0, "Dock widget must not be 0.");

        _mainWindow->addDockWidget(area, dock);
    }

305
306
307
    DataContainer* CampVisApplication::createAndAddDataContainer(const std::string& name) {
        DataContainer* dc = new DataContainer(name);
        _dataContainers.push_back(dc);
308
        s_DataContainersChanged.emitSignal();
309
        return dc;
310
311
    }

312
313
314
315
316
317
318
319
320
321
322
    void CampVisApplication::rebuildAllShadersFromFiles() {
        // rebuilding all shaders has to be done from OpenGL context, use the local one.
        GLJobProc.enqueueJob(_localContext, makeJobOnHeap(this, &CampVisApplication::triggerShaderRebuild), OpenGLJobProcessor::SerialJob);
    }

    void CampVisApplication::triggerShaderRebuild() {

        if (! ShdrMgr.rebuildAllShadersFromFile()) {
            LERROR("Could not rebuild all shaders from file.");
            return;
        }
323
324
325
        else {
            LINFO("Rebuilding shaders from file successful.");
        }
326

327
328
        for (std::vector<PipelineRecord>::iterator it = _pipelines.begin(); it != _pipelines.end(); ++it) {
            for (std::vector<AbstractProcessor*>::const_iterator pit = it->_pipeline->getProcessors().begin(); pit != it->_pipeline->getProcessors().end(); ++pit) {
329
330
331
332
333
334
335
                if (VisualizationProcessor* tester = dynamic_cast<VisualizationProcessor*>(*pit)) {
                	tester->invalidate(AbstractProcessor::INVALID_RESULT);
                }
            }
        }
    }

336
337
338
339
#ifdef CAMPVIS_HAS_SCRIPTING
    LuaVmState* CampVisApplication::getLuaVmState() {
        return _luaVmState;
    }
340

341
#endif
342

343
}