Beispiel #1
0
bool App::onEvent(const GEvent& e) {
    if (viewer != NULL) {
        if (viewer->onEvent(e, this)) {
            // Viewer consumed the event
            return true;
        }
    }

    switch (e.type) {
    case GEventType::FILE_DROP:
        {
            Array<G3D::String> fileArray;
            window()->getDroppedFilenames(fileArray);
            setViewer(fileArray[0]);
            return true;
        }

    case GEventType::KEY_DOWN:
        if (e.key.keysym.sym == GKey::F5) { 
            Shader::reloadAll();
            return true;
        } else if (e.key.keysym.sym == GKey::F3) {
            showDebugText = ! showDebugText;
            return true;
        } else if (e.key.keysym.sym == GKey::F8) {
            Array<shared_ptr<Texture> > output;
            renderCubeMap(renderDevice, output, m_debugCamera, shared_ptr<Texture>(), 2048);

            const CubeMapConvention::CubeMapInfo& cubeMapInfo = Texture::cubeMapInfo(CubeMapConvention::DIRECTX);
            for (int f = 0; f < 6; ++f) {
                const CubeMapConvention::CubeMapInfo::Face& faceInfo = cubeMapInfo.face[f];

                shared_ptr<Image> temp = Image::fromPixelTransferBuffer(output[f]->toPixelTransferBuffer(ImageFormat::RGB8()));
                temp->flipVertical();
                temp->rotateCW(toRadians(90.0) * (-faceInfo.rotations));
                if (faceInfo.flipY) { temp->flipVertical();   }
                if (faceInfo.flipX) { temp->flipHorizontal(); }
                temp->save(format("cube-%s.png", faceInfo.suffix.c_str()));
            }
            return true;
        } else if (e.key.keysym.sym == 'v') {
            // Event viewer
            if (isNull(dynamic_cast<EventViewer*>(viewer))) {
                setViewer("<events>");
                return true;
            }
        }
        break;
        
    default:;
    }

    // Must call after processing events to prevent default .ArticulatedModel.Any file-drop functionality
    if (GApp::onEvent(e)) {
        return true;
    }
    
    return false;    
}
Beispiel #2
0
bool App::onEvent(const GEvent& e) {
    /** Explicitly not calling the base class' onEvent method because we do not want
        all of GApp's events (e.g its .am.any dropping)
    if (GApp::onEvent(e)) {
        return true;
    }
    */

    if (viewer != NULL) {
        if (viewer->onEvent(e, this)) {
            // Viewer consumed the event
            return true;
        }
    }

    switch (e.type) {
    case GEventType::FILE_DROP:
        {
            Array<std::string> fileArray;
            window()->getDroppedFilenames(fileArray);
            setViewer(fileArray[0]);
            return true;
        }

    case GEventType::KEY_DOWN:
        if (e.key.keysym.sym == GKey::F3) {
            showDebugText = ! showDebugText;
            return true;
        } else if (e.key.keysym.sym == GKey::F8) {
            Array<shared_ptr<Texture> > output;
            renderCubeMap(renderDevice, output, m_debugCamera, shared_ptr<Texture>(), 2048);

            const Texture::CubeMapInfo& cubeMapInfo = Texture::cubeMapInfo(CubeMapConvention::DIRECTX);
            for (int f = 0; f < 6; ++f) {
                const Texture::CubeMapInfo::Face& faceInfo = cubeMapInfo.face[f];

                shared_ptr<Image> temp = Image::fromPixelTransferBuffer(output[f]->toPixelTransferBuffer(ImageFormat::RGB8()));
                temp->flipVertical();
                temp->rotateCW(toRadians(90.0) * (-faceInfo.rotations));
                if (faceInfo.flipY) { temp->flipVertical();   }
                if (faceInfo.flipX) { temp->flipHorizontal(); }
                temp->save(format("cube-%s.png", faceInfo.suffix.c_str()));
            }
            return true;
        } else if (e.key.keysym.sym == 'v') {
            // Event viewer
            if (isNull(dynamic_cast<EventViewer*>(viewer))) {
                setViewer("<events>");
                return true;
            }
        }
        break;
        
    default:;
    }
    
    return false;    
}
Beispiel #3
0
void App::onInit() {
    setScene(Scene::create());
    logPrintf("App::onInit()\n");
    createDeveloperHUD();
    showRenderingStats = false;

    developerWindow->cameraControlWindow->setVisible(false);
    developerWindow->setVisible(false);
    developerWindow->videoRecordDialog->setCaptureGui(false);

    m_debugCamera->filmSettings().setAntialiasingEnabled(true);
    if (filename != "") {
        window()->setCaption(filenameBaseExt(filename) + " - G3D Viewer");
    }

    lighting = shared_ptr<LocalLightingEnvironment>(new LocalLightingEnvironment());
    lighting->lightArray.clear();
    // The spot light is designed to just barely fit the 3D models.  Note that it has no attenuation
    lighting->lightArray.append(Light::spotTarget("Light", Point3(20, 200, 20), Point3::zero(), 8 * units::degrees(), Power3(25.0f), 1, 0, 0, true, 8192));
    lighting->environmentMapArray.append(ScaledTexture(Texture::fromFile(System::findDataFile("uffizi/uffizi*.jpg"), ImageFormat::SRGB8(), Texture::DIM_CUBE_MAP, Texture::Settings::cubeMap()), 0.65f));
    lighting->ambientOcclusionSettings.numSamples   = 24; // High-quality AO
    lighting->ambientOcclusionSettings.radius       = 1.6f * units::meters();
    lighting->ambientOcclusionSettings.intensity    = 1.0f;
    lighting->ambientOcclusionSettings.bias         = 0.002f * units::meters();
    m_debugCamera->setFarPlaneZ(-1000);
    m_debugCamera->setNearPlaneZ(-0.05f);

    // Don't clip to the near plane
    glDisable(GL_DEPTH_CLAMP);	
    colorClear = Color3::white() * 0.9f;
    //modelController = ThirdPersonManipulator::create();

    setViewer(filename);
    logPrintf("Done App::onInit()\n");
}
Beispiel #4
0
void onDraw()
{
  /*setViewer O(1)*/
  setMatrixMode(PROJECTION);
  initMatrix();
  setViewer(vertex(eyex, eyey, eyez), vertex(lookx, looky, lookz), vertex(upx, upy, upz));
  setFrustum(10, 10*MAX_H/MAX_W, 4, 25);

  /*createPolygons O(1)*/
  initScene();
  setMatrixMode(MODELVIEW); 
  initMatrix();
  blockWithHole(-5.0,0.0,0.0);
  blockColoured(barx, bary, 0.0);

 
  /*calcData*/
  /*
    For each polygon,
      Go to next triangle if current polygon doesn't face viewer O(1)
      Calculate pixel values of vertices of the triangle O(1)
      clip triangle  //unless you model your scene such that no part ever goes outside the viewport (commentception) O(1)
      For each triangle, O(m*n)
        Add x,y,z position of scan conversion pixels to temp per-polygon table (indexed on y position with min and max x values)
        Also store a min and max x for y=0, y=MAX_Y-1. Add the x,y values for the points in between to the temp table
        Copy temp table to data table with the points between min and max x values filled (in case of conlict, min z value only) O(m*n)
  */

  /*drawPixels*/
  if(q4) innerclipTriangles();
  renderScene();
  glDrawPixels(MAX_W, MAX_H, GL_RGBA, GL_BYTE, data);
  glFlush();
}
Beispiel #5
0
void App::onInit() {
    GApp::onInit();


	renderDevice->setSwapBuffersAutomatically(true);
    logPrintf("App::onInit()\n");
    createDeveloperHUD();
    showRenderingStats = false;

    developerWindow->cameraControlWindow->setVisible(false);
    developerWindow->setVisible(false);
    developerWindow->videoRecordDialog->setCaptureGui(false);

    m_debugCamera->filmSettings().setBloomStrength(0.20f);
    m_debugCamera->filmSettings().setBloomRadiusFraction(0.017f);
    m_debugCamera->filmSettings().setAntialiasingEnabled(true);
    m_debugCamera->filmSettings().setCelluloidToneCurve();

    if (! filename.empty()) {
        window()->setCaption(filenameBaseExt(filename) + " - G3D Viewer");
    }

    lighting = shared_ptr<LightingEnvironment>(new LightingEnvironment());
    lighting->lightArray.clear();
    // The spot light is designed to just barely fit the 3D models.  Note that it has no attenuation
    lighting->lightArray.append(Light::spotTarget("Light", Point3(40, 120, 80), Point3::zero(), 10 * units::degrees(), Power3(50.0f), 1, 0, 0, true, 8192));
    lighting->lightArray.last()->shadowMap()->setBias(0.1f);

    Texture::Encoding e;
    e.readMultiplyFirst = Color4(Color3(0.5f));
    e.format = ImageFormat::RGB32F();

    lighting->environmentMapArray.append(Texture::fromFile(System::findDataFile("uffizi/uffizi-*.exr"), e, Texture::DIM_CUBE_MAP));
    lighting->ambientOcclusionSettings.numSamples   = 24;
    lighting->ambientOcclusionSettings.radius       = 0.75f * units::meters();
    lighting->ambientOcclusionSettings.intensity    = 2.0f;
    lighting->ambientOcclusionSettings.bias         = 0.06f * units::meters();
    lighting->ambientOcclusionSettings.useDepthPeelBuffer = true;

    m_debugCamera->setFarPlaneZ(-finf());
    m_debugCamera->setNearPlaneZ(-0.05f);

    // Don't clip to the near plane
    glDisable(GL_DEPTH_CLAMP);	
    colorClear = Color3::white() * 0.9f;

    //modelController = ThirdPersonManipulator::create();
    m_gbufferSpecification.encoding[GBuffer::Field::CS_POSITION_CHANGE].format = NULL;
    gbuffer()->setSpecification(m_gbufferSpecification);

    setViewer(filename);
    developerWindow->sceneEditorWindow->setVisible(false);
    logPrintf("Done App::onInit()\n");
}
Beispiel #6
0
void App::onInit() {
    showRenderingStats = false;
    window()->setCaption(filenameBaseExt(filename) + " - G3D Viewer");

    sky = Sky::fromFile(System::findDataFile("sky"));
    skyParameters = SkyParameters( G3D::toSeconds(10, 00, 00, AM) );
    lighting = Lighting::fromSky( sky, skyParameters, Color3::white() );
    lighting->ambientTop = Color3::white() * 0.3f;
    lighting->ambientBottom = Color3::white() * 0.1f;
	
    colorClear = Color3::white();
    //modelController = ThirdPersonManipulator::create();

    setViewer(filename);
}
int Tools::qt_metacall(QMetaObject::Call _c, int _id, void **_a)
{
    _id = QObject::qt_metacall(_c, _id, _a);
    if (_id < 0)
        return _id;
    if (_c == QMetaObject::InvokeMetaMethod) {
        if (_id < 38)
            qt_static_metacall(this, _c, _id, _a);
        _id -= 38;
    } else if (_c == QMetaObject::RegisterMethodArgumentMetaType) {
        if (_id < 38)
            *reinterpret_cast<int*>(_a[0]) = -1;
        _id -= 38;
    }
#ifndef QT_NO_PROPERTIES
      else if (_c == QMetaObject::ReadProperty) {
        void *_v = _a[0];
        switch (_id) {
        case 0: *reinterpret_cast< ImageViewer**>(_v) = getViewer(); break;
        }
        _id -= 1;
    } else if (_c == QMetaObject::WriteProperty) {
        void *_v = _a[0];
        switch (_id) {
        case 0: setViewer(*reinterpret_cast< ImageViewer**>(_v)); break;
        }
        _id -= 1;
    } else if (_c == QMetaObject::ResetProperty) {
        _id -= 1;
    } else if (_c == QMetaObject::QueryPropertyDesignable) {
        _id -= 1;
    } else if (_c == QMetaObject::QueryPropertyScriptable) {
        _id -= 1;
    } else if (_c == QMetaObject::QueryPropertyStored) {
        _id -= 1;
    } else if (_c == QMetaObject::QueryPropertyEditable) {
        _id -= 1;
    } else if (_c == QMetaObject::QueryPropertyUser) {
        _id -= 1;
    } else if (_c == QMetaObject::RegisterPropertyMetaType) {
        if (_id < 1)
            *reinterpret_cast<int*>(_a[0]) = -1;
        _id -= 1;
    }
#endif // QT_NO_PROPERTIES
    return _id;
}
void onDraw()
{
  /*setViewer O(1)*/
  setMatrixMode(PROJECTION);
  initMatrix();
  setViewer(vertex(eyex, eyey, eyez), vertex(lookx, looky, lookz), vertex(upx, upy, upz));
  setFrustum(10, 10*MAX_H/MAX_W, 4, 25);

  /*createPolygons O(1)*/
  initScene();
  setMatrixMode(MODELVIEW); 
  initMatrix();
  if(!Aisclippingwindow)
	drawA(Ax, Ay, Az);
  drawB(Bx, By, Bz);

  /*drawPixels*/
  renderScene();
  glDrawPixels(MAX_W, MAX_H, GL_RGBA, GL_BYTE, data);
  glFlush();
}
Beispiel #9
0
bool App::onEvent(const GEvent& e) {
    if (GApp::onEvent(e)) {
        return true;
    }

    switch (e.type) {
    case GEventType::FILE_DROP:
        {
            Array<std::string> fileArray;
            window()->getDroppedFilenames(fileArray);
            setViewer(fileArray[0]);
            return true;
        }
        
    default:;
    }
    
    if (viewer != NULL) {
        return viewer->onEvent(e, this);
    } else {
        return false;
    }
}
Beispiel #10
0
int main( int argc, char **argv )
{
    // use an ArgumentParser object to manage the program arguments.
    osg::ArgumentParser arguments(&argc,argv);
    
    // set up the usage document, in case we need to print out how to use this program.
    arguments.getApplicationUsage()->setApplicationName(arguments.getApplicationName());
    arguments.getApplicationUsage()->setDescription(arguments.getApplicationName()+" is the application for presenting 3D interactive slide shows.");
    arguments.getApplicationUsage()->setCommandLineUsage(arguments.getApplicationName()+" [options] filename ...");
    arguments.getApplicationUsage()->addCommandLineOption("-h or --help","Display this information");
    arguments.getApplicationUsage()->addCommandLineOption("-a","Turn auto stepping on by default");
    arguments.getApplicationUsage()->addCommandLineOption("-d <float>","Time duration in seconds between layers/slides");
    arguments.getApplicationUsage()->addCommandLineOption("-s <float> <float> <float>","width, height, distance and of the screen away from the viewer");
    arguments.getApplicationUsage()->addCommandLineOption("--viewer","Start Present3D as the viewer version.");
    arguments.getApplicationUsage()->addCommandLineOption("--authoring","Start Present3D as the authoring version, license required.");
    arguments.getApplicationUsage()->addCommandLineOption("--master","Start Present3D as the master version, license required.");
    arguments.getApplicationUsage()->addCommandLineOption("--slave","Start Present3D as the slave version, license required.");
    arguments.getApplicationUsage()->addCommandLineOption("--publishing","Start Present3D as the publishing version, license required.");
    arguments.getApplicationUsage()->addCommandLineOption("--timeDelayOnNewSlideWithMovies","Set the time delay on new slide with movies, done to allow movie threads to get in sync with rendering thread.");
    arguments.getApplicationUsage()->addCommandLineOption("--targetFrameRate","Set the target frame rate, defaults to 80Hz.");
    arguments.getApplicationUsage()->addCommandLineOption("--version","Report the Present3D version.");
    arguments.getApplicationUsage()->addCommandLineOption("--print <filename>","Print out slides to a series of image files.");
    arguments.getApplicationUsage()->addCommandLineOption("--html <filename>","Print out slides to a series of html & image files.");
    arguments.getApplicationUsage()->addCommandLineOption("--loop","Switch on looping of presentation.");
    arguments.getApplicationUsage()->addCommandLineOption("--devices","Print the Video input capability via QuickTime and exit.");

    // add alias from xml to p3d to provide backwards compatibility for old p3d files.
    osgDB::Registry::instance()->addFileExtensionAlias("xml","p3d");

    // if user requests devices video capability.
    if (arguments.read("-devices") || arguments.read("--devices"))
    {
        // Force load QuickTime plugin, probe video capability, exit
        osgDB::readImageFile("devices.live");
        return 1;
    }


    // read any env vars from presentations before we create viewer to make sure the viewer
    // utilises these env vars
    if (p3d::readEnvVars(arguments))
    {
        osg::DisplaySettings::instance()->readEnvironmentalVariables();
    }

    // set up any logins required for http access
    std::string url, username, password;
    while(arguments.read("--login",url, username, password))
    {
        if (!osgDB::Registry::instance()->getAuthenticationMap())
        {
            osgDB::Registry::instance()->setAuthenticationMap(new osgDB::AuthenticationMap);
            osgDB::Registry::instance()->getAuthenticationMap()->addAuthenticationDetails(
                url,
                new osgDB::AuthenticationDetails(username, password)
            );
        }
    }



#ifdef USE_SDL
    SDLIntegration sdlIntegration;
    
    osg::notify(osg::INFO)<<"USE_SDL"<<std::endl;
#endif    
    
    bool doSetViewer = true;
    std::string configurationFile;

    // check env vars for configuration file
    const char* str = getenv("PRESENT3D_CONFIG_FILE");
    if (!str) str = getenv("OSG_CONFIG_FILE");
    if (str) configurationFile = str;

    // check command line parameters for configuration file.
    while (arguments.read("-c",configurationFile)) {}

    osg::Vec4 clearColor(0.0f,0.0f,0.0f,0.0f);
    
    while (arguments.read("--clear-color",clearColor[0],clearColor[1],clearColor[2],clearColor[3])) {}

    std::string filename;
    if (arguments.read("--spell-check",filename))
    {
        p3d::SpellChecker spellChecker;
        spellChecker.checkP3dXml(filename);
        return 1;
    }

    if (arguments.read("--strip-text",filename))
    {
        p3d::XmlPatcher patcher;
        // patcher.stripP3dXml(filename, osg::notify(osg::NOTICE));

        osg::ref_ptr<osgDB::XmlNode> newNode = patcher.simplifyP3dXml(filename);
        if (newNode.valid())
        {
            newNode->write(std::cout);
        }
        return 1;
    }

    std::string lhs_filename, rhs_filename;
    if (arguments.read("--merge",lhs_filename, rhs_filename))
    {
        p3d::XmlPatcher patcher;
        osg::ref_ptr<osgDB::XmlNode> newNode = patcher.mergeP3dXml(lhs_filename, rhs_filename);
        if (newNode.valid())
        {
            newNode->write(std::cout);
        }
        return 1;
    }


    // construct the viewer.
    osgViewer::Viewer viewer(arguments);
    
    // set clear colour to black by default.
    viewer.getCamera()->setClearColor(clearColor);

    if (!configurationFile.empty())
    {
        viewer.readConfiguration(configurationFile);
        doSetViewer = false;
    }

    const char* p3dDevice = getenv("P3D_DEVICE");
    if (p3dDevice)
    {
        osgDB::StringList devices;
        osgDB::split(p3dDevice, devices);
        for(osgDB::StringList::iterator i = devices.begin(); i != devices.end(); ++i)
        {
            addDeviceTo(viewer, *i);
        }
    }


    std::string device;
    while (arguments.read("--device", device))
    {
        addDeviceTo(viewer, device);
        
    }

    if (arguments.read("--http-control"))
    {
    
        std::string server_address = "localhost";
        std::string server_port = "8080";
        std::string document_root = "htdocs";

        while (arguments.read("--http-server-address", server_address)) {}
        while (arguments.read("--http-server-port", server_port)) {}
        while (arguments.read("--http-document-root", document_root)) {}

        osg::ref_ptr<osgDB::Options> device_options = new osgDB::Options("documentRegisteredHandlers");

        osg::ref_ptr<osgGA::Device> rest_http_device = osgDB::readFile<osgGA::Device>(server_address+":"+server_port+"/"+document_root+".resthttp", device_options.get());
        if (rest_http_device.valid())
        {
            viewer.addDevice(rest_http_device.get());
        }
    }
    
    // set up stereo masks
    viewer.getCamera()->setCullMask(0xffffffff);
    viewer.getCamera()->setCullMaskLeft(0x00000001);
    viewer.getCamera()->setCullMaskRight(0x00000002);   

    // set up the camera manipulators.
    {
        osg::ref_ptr<osgGA::KeySwitchMatrixManipulator> keyswitchManipulator = new osgGA::KeySwitchMatrixManipulator;

        keyswitchManipulator->addMatrixManipulator( '1', "Trackball", new osgGA::TrackballManipulator() );
        keyswitchManipulator->addMatrixManipulator( '2', "Flight", new osgGA::FlightManipulator() );
        keyswitchManipulator->addMatrixManipulator( '3', "Drive", new osgGA::DriveManipulator() );
        keyswitchManipulator->addMatrixManipulator( '4', "Terrain", new osgGA::TerrainManipulator() );

        std::string pathfile;
        char keyForAnimationPath = '5';
        while (arguments.read("-p",pathfile))
        {
            osgGA::AnimationPathManipulator* apm = new osgGA::AnimationPathManipulator(pathfile);
            if (apm || !apm->valid()) 
            {
                unsigned int num = keyswitchManipulator->getNumMatrixManipulators();
                keyswitchManipulator->addMatrixManipulator( keyForAnimationPath, "Path", apm );
                keyswitchManipulator->selectMatrixManipulator(num);
                ++keyForAnimationPath;
            }
        }

        viewer.setCameraManipulator( keyswitchManipulator.get() );
    }

    // add the state manipulator
    osg::ref_ptr<osgGA::StateSetManipulator> ssManipulator = new osgGA::StateSetManipulator(viewer.getCamera()->getOrCreateStateSet());
    ssManipulator->setKeyEventToggleTexturing('e');
    viewer.addEventHandler( ssManipulator.get() );

    // add the state manipulator
    viewer.addEventHandler( new osgViewer::StatsHandler() );

    viewer.addEventHandler( new osgViewer::WindowSizeHandler() );

    // neeed to address.
    // viewer.getScene()->getUpdateVisitor()->setTraversalMode(osg::NodeVisitor::TRAVERSE_ACTIVE_CHILDREN);


    const char* p3dCursor = getenv("P3D_CURSOR");
    std::string cursorFileName( p3dCursor ? p3dCursor : "");
    while (arguments.read("--cursor",cursorFileName)) {}


    while (arguments.read("--set-viewer")) { doSetViewer = true; }
    
    while (arguments.read("--no-set-viewer")) { doSetViewer = false; }
    

    // cluster related entries.
    int socketNumber=8100;
    while (arguments.read("-n",socketNumber)) {}

    float camera_fov=-1.0f;
    while (arguments.read("-f",camera_fov)) {}

    float camera_offset=45.0f;
    while (arguments.read("-o",camera_offset)) {}


    std::string exportName;
    while (arguments.read("--print",exportName)) {}

    while (arguments.read("--html",exportName)) {}

    // read any time delay argument.
    float timeDelayBetweenSlides = 1.0f;
    while (arguments.read("-d",timeDelayBetweenSlides)) {}

    bool autoSteppingActive = false;
    while (arguments.read("-a")) autoSteppingActive = true;

    bool loopPresentation = false;
    while (arguments.read("--loop")) loopPresentation = true;

    {
        // set update hte default traversal mode settings for update visitor
        // default to osg::NodeVisitor::TRAVERSE_ACTIVE_CHILDREN.
        osg::NodeVisitor::TraversalMode updateTraversalMode = osg::NodeVisitor::TRAVERSE_ACTIVE_CHILDREN; // viewer.getUpdateVisitor()->getTraversalMode();

        const char* p3dUpdateStr = getenv("P3D_UPDATE");
        if (p3dUpdateStr)
        {
            std::string updateStr(p3dUpdateStr);
            if (updateStr=="active" || updateStr=="Active" || updateStr=="ACTIVE") updateTraversalMode = osg::NodeVisitor::TRAVERSE_ACTIVE_CHILDREN;
            else if (updateStr=="all" || updateStr=="All" || updateStr=="ALL") updateTraversalMode = osg::NodeVisitor::TRAVERSE_ALL_CHILDREN;
        }

        while(arguments.read("--update-active")) updateTraversalMode = osg::NodeVisitor::TRAVERSE_ACTIVE_CHILDREN;
        while(arguments.read("--update-all")) updateTraversalMode = osg::NodeVisitor::TRAVERSE_ALL_CHILDREN;

        viewer.getUpdateVisitor()->setTraversalMode(updateTraversalMode);
    }

    
    // register the slide event handler - which moves the presentation from slide to slide, layer to layer.
    osg::ref_ptr<osgPresentation::SlideEventHandler> seh = new osgPresentation::SlideEventHandler(&viewer);
    viewer.addEventHandler(seh.get());

    seh->setAutoSteppingActive(autoSteppingActive);
    seh->setTimeDelayBetweenSlides(timeDelayBetweenSlides);
    seh->setLoopPresentation(loopPresentation);

    double targetFrameRate = 80.0;
    while (arguments.read("--targetFrameRate",targetFrameRate)) {}


    // set the time delay
    float timeDelayOnNewSlideWithMovies = 0.4f;
    while (arguments.read("--timeDelayOnNewSlideWithMovies",timeDelayOnNewSlideWithMovies)) {}
    seh->setTimeDelayOnNewSlideWithMovies(timeDelayOnNewSlideWithMovies);

    // set up optimizer options
    unsigned int optimizer_options = osgUtil::Optimizer::DEFAULT_OPTIMIZATIONS;
    bool relase_and_compile = false;
    while (arguments.read("--release-and-compile")) 
    {
        relase_and_compile = true;
    }
    seh->setReleaseAndCompileOnEachNewSlide(relase_and_compile);
    if (relase_and_compile)
    {
        // make sure that imagery stays around after being applied to textures.
        viewer.getDatabasePager()->setUnrefImageDataAfterApplyPolicy(true,false);
        optimizer_options &= ~osgUtil::Optimizer::OPTIMIZE_TEXTURE_SETTINGS;
    }
// 
//     osgDB::Registry::instance()->getOrCreateDatabasePager()->setUnrefImageDataAfterApplyPolicy(true,false);
//     optimizer_options &= ~osgUtil::Optimizer::OPTIMIZE_TEXTURE_SETTINGS;
//     osg::Texture::getTextureObjectManager()->setExpiryDelay(0.0f);
//     osgDB::Registry::instance()->getOrCreateDatabasePager()->setExpiryDelay(1.0f);

    // register the handler for modifying the point size
    osg::ref_ptr<PointsEventHandler> peh = new PointsEventHandler;
    viewer.addEventHandler(peh.get());

    // add the screen capture handler
    std::string screenCaptureFilename = "screen_shot.jpg";
    while(arguments.read("--screenshot", screenCaptureFilename)) {}
    osg::ref_ptr<osgViewer::ScreenCaptureHandler::WriteToFile> writeFile = new osgViewer::ScreenCaptureHandler::WriteToFile(
        osgDB::getNameLessExtension(screenCaptureFilename),
        osgDB::getFileExtension(screenCaptureFilename) );
    osg::ref_ptr<osgViewer::ScreenCaptureHandler> screenCaptureHandler = new osgViewer::ScreenCaptureHandler(writeFile.get());
    screenCaptureHandler->setKeyEventTakeScreenShot('m');//osgGA::GUIEventAdapter::KEY_Print);
    screenCaptureHandler->setKeyEventToggleContinuousCapture('M');
    viewer.addEventHandler(screenCaptureHandler.get());

    // osg::DisplaySettings::instance()->setSplitStereoAutoAjustAspectRatio(false);

    float width = osg::DisplaySettings::instance()->getScreenWidth();
    float height = osg::DisplaySettings::instance()->getScreenHeight();
    float distance = osg::DisplaySettings::instance()->getScreenDistance();
    while (arguments.read("-s", width, height, distance)) 
    {
        osg::DisplaySettings::instance()->setScreenDistance(distance);
        osg::DisplaySettings::instance()->setScreenHeight(height);
        osg::DisplaySettings::instance()->setScreenWidth(width);
    }

    std::string outputFileName;
    while(arguments.read("--output",outputFileName)) {}


    // get details on keyboard and mouse bindings used by the viewer.
    viewer.getUsage(*arguments.getApplicationUsage());

    // if user request help write it out to cout.
    if (arguments.read("-h") || arguments.read("--help"))
    {
        arguments.getApplicationUsage()->write(osg::notify(osg::NOTICE));
        return 1;
    }

    P3DApplicationType P3DApplicationType = VIEWER;

    str = getenv("PRESENT3D_TYPE");
    if (str)
    {
        if (strcmp(str,"viewer")==0) P3DApplicationType = VIEWER;
        else if (strcmp(str,"master")==0) P3DApplicationType = MASTER;
        else if (strcmp(str,"slave")==0) P3DApplicationType = SLAVE;
    }
        
    while (arguments.read("--viewer")) { P3DApplicationType = VIEWER; }
    while (arguments.read("--master")) { P3DApplicationType = MASTER; }
    while (arguments.read("--slave")) { P3DApplicationType = SLAVE; }
    
    while (arguments.read("--version"))
    {
        std::string appTypeName = "invalid";
        switch(P3DApplicationType)
        {
            case(VIEWER): appTypeName = "viewer"; break;
            case(MASTER): appTypeName = "master"; break;
            case(SLAVE): appTypeName = "slave"; break;
        }

        osg::notify(osg::NOTICE)<<std::endl;
        osg::notify(osg::NOTICE)<<"Present3D "<<appTypeName<<" version : "<<s_version<<std::endl;
        osg::notify(osg::NOTICE)<<std::endl;

        return 0;
    }

    // any option left unread are converted into errors to write out later.
    //arguments.reportRemainingOptionsAsUnrecognized();

    // report any errors if they have ocured when parsing the program aguments.
    if (arguments.errors())
    {
        arguments.writeErrorMessages(osg::notify(osg::INFO));
        return 1;
    }


    // read files name from arguments.
    p3d::FileNameList xmlFiles, normalFiles;
    if (!p3d::getFileNames(arguments, xmlFiles, normalFiles))
    {
        osg::notify(osg::NOTICE)<<std::endl;
        osg::notify(osg::NOTICE)<<"No file specified, please specify and file to load."<<std::endl;
        osg::notify(osg::NOTICE)<<std::endl;
        return 1;
    }



    bool viewerInitialized = false;
    if (!xmlFiles.empty())
    {
        osg::ref_ptr<osg::Node> holdingModel = p3d::readHoldingSlide(xmlFiles.front());

        if (holdingModel.valid())
        {
            viewer.setSceneData(holdingModel.get());

            seh->selectSlide(0);

            if (!viewerInitialized)
            {
                // pass the global stateset to the point event handler so that it can
                // alter the point size of all points in the scene.
                peh->setStateSet(viewer.getCamera()->getOrCreateStateSet());

                // create the windows and run the threads.
                viewer.realize();

                if (doSetViewer) setViewer(viewer, width, height, distance);

                viewerInitialized = true;
            }

            seh->home();

            // render a frame
            viewer.frame();
        }
    }

    osg::Timer timer;
    osg::Timer_t start_tick = timer.tick();


    osg::ref_ptr<osgDB::ReaderWriter::Options> cacheAllOption = new osgDB::ReaderWriter::Options;
    cacheAllOption->setObjectCacheHint(osgDB::ReaderWriter::Options::CACHE_ALL);
    osgDB::Registry::instance()->setOptions(cacheAllOption.get());

    // read the scene from the list of file specified commandline args.
    osg::ref_ptr<osg::Node> loadedModel = p3d::readShowFiles(arguments,cacheAllOption.get()); // osgDB::readNodeFiles(arguments, cacheAllOption.get());


    osgDB::Registry::instance()->setOptions( 0 );


    // if no model has been successfully loaded report failure.
    if (!loadedModel) 
    {
        osg::notify(osg::INFO) << arguments.getApplicationName() <<": No data loaded" << std::endl;
        return 1;
    }

    osg::Timer_t end_tick = timer.tick();

    osg::notify(osg::INFO) << "Time to load = "<<timer.delta_s(start_tick,end_tick)<<std::endl;


    if (loadedModel->getNumDescriptions()>0)
    {
        for(unsigned int i=0; i<loadedModel->getNumDescriptions(); ++i)
        {
            const std::string& desc = loadedModel->getDescription(i);
            if (desc=="loop") 
            {
                osg::notify(osg::NOTICE)<<"Enabling looping"<<std::endl;
                seh->setLoopPresentation(true);
            }
            else if (desc=="auto") 
            {
                osg::notify(osg::NOTICE)<<"Enabling auto run"<<std::endl;
                seh->setAutoSteppingActive(true);
            }
        }
    }


    processLoadedModel(loadedModel, optimizer_options, cursorFileName);

    // set the scene to render
    viewer.setSceneData(loadedModel.get());

    if (!viewerInitialized)
    {
        // pass the global stateset to the point event handler so that it can
        // alter the point size of all points in the scene.
        peh->setStateSet(viewer.getCamera()->getOrCreateStateSet());

        // create the windows and run the threads.
        viewer.realize();

        if (doSetViewer) setViewer(viewer, width, height, distance);

        viewerInitialized = true;
    }


    

    // pass the model to the slide event handler so it knows which to manipulate.
    seh->set(loadedModel.get());
    seh->selectSlide(0);

    seh->home();

    if (!outputFileName.empty())
    {
        osgDB::writeNodeFile(*loadedModel,outputFileName);
        return 0;
    }
    

    if (!cursorFileName.empty())
    {
        // have to add a frame in here to avoid problems with X11 threading issue on switching off the cursor
        // not yet sure why it makes a difference, but it at least fixes the crash that would otherwise occur
        // under X11.
        viewer.frame();

        // switch off the cursor
        osgViewer::Viewer::Windows windows;
        viewer.getWindows(windows);
        for(osgViewer::Viewer::Windows::iterator itr = windows.begin();
            itr != windows.end();
            ++itr)
        {
            (*itr)->useCursor(false);
        }
    }

    osg::Timer_t startOfFrameTick = osg::Timer::instance()->tick();
    double targetFrameTime = 1.0/targetFrameRate;
    
    if (exportName.empty())
    {
        // objects for managing the broadcasting and recieving of camera packets.
        CameraPacket cp;
        Broadcaster  bc;
        Receiver     rc;
        bc.setPort(static_cast<short int>(socketNumber));
        rc.setPort(static_cast<short int>(socketNumber));

        bool masterKilled = false;
        DataConverter scratchPad(1024);

        while( !viewer.done() && !masterKilled)
        {
            // wait for all cull and draw threads to complete.
            viewer.advance();

            osg::Timer_t currentTick = osg::Timer::instance()->tick();
            double deltaTime = osg::Timer::instance()->delta_s(startOfFrameTick, currentTick);


            if (deltaTime<targetFrameTime)
            {
                OpenThreads::Thread::microSleep(static_cast<unsigned int>((targetFrameTime-deltaTime)*1000000.0));
            }

            startOfFrameTick =  osg::Timer::instance()->tick();

#if 0            
            if (kmcb)
            {
                double time = kmcb->getTime();
                viewer.getFrameStamp()->setReferenceTime(time);
            }
#endif

#ifdef USE_SDL
            sdlIntegration.update(viewer);
#endif

            if (P3DApplicationType==MASTER)
            {
                // take camera zero as the guide.
                osg::Matrix modelview(viewer.getCamera()->getViewMatrix());
                
                cp.setPacket(modelview,viewer.getFrameStamp());
                
                // cp.readEventQueue(viewer);

                scratchPad.reset();
                scratchPad.write(cp);

                scratchPad.reset();
                scratchPad.read(cp);

                bc.setBuffer(scratchPad.startPtr(), scratchPad.numBytes());
                
                std::cout << "bc.sync()"<<scratchPad.numBytes()<<std::endl;

                bc.sync();
            }
            else if (P3DApplicationType==SLAVE)
            {
                rc.setBuffer(scratchPad.startPtr(), scratchPad.numBytes());

                rc.sync();
                
                scratchPad.reset();
                scratchPad.read(cp);
    
                // cp.writeEventQueue(viewer);

                if (cp.getMasterKilled()) 
                {
                    std::cout << "Received master killed."<<std::endl;
                    // break out of while (!done) loop since we've now want to shut down.
                    masterKilled = true;
                }
            }

            // update the scene by traversing it with the the update visitor which will
            // call all node update callbacks and animations.
            viewer.eventTraversal();

            if (seh->getRequestReload())
            {
                OSG_INFO<<"Reload requested"<<std::endl;
                seh->setRequestReload(false);
                int previous_ActiveSlide = seh->getActiveSlide();
                int previous_ActiveLayer = seh->getActiveLayer();

                // reset time so any event key generate

                loadedModel = p3d::readShowFiles(arguments,cacheAllOption.get());
                processLoadedModel(loadedModel, optimizer_options, cursorFileName);

                if (!loadedModel)
                {
                    return 0;
                }

                viewer.setSceneData(loadedModel.get());
                seh->set(loadedModel.get());
                seh->selectSlide(previous_ActiveSlide, previous_ActiveLayer);

                continue;
                
            }

            // update the scene by traversing it with the the update visitor which will
            // call all node update callbacks and animations.
            viewer.updateTraversal();

            if (P3DApplicationType==SLAVE)
            {
                osg::Matrix modelview;
                cp.getModelView(modelview,camera_offset);

                viewer.getCamera()->setViewMatrix(modelview);
            }

            // fire off the cull and draw traversals of the scene.
            if(!masterKilled)
                viewer.renderingTraversals();
        }
    }
    else
    {
        ExportHTML::write(seh.get(), viewer, exportName);
    }
    
    return 0;
}
Tools::Tools(ImageViewer* iv, QObject* parent) :
    QObject(parent)
{
    setViewer(iv);
}
Beispiel #12
0
ViewerWindow::ViewerWindow( ViewerWidget* viewer )
{
    setViewer( viewer );

    createMenus();
}
Beispiel #13
0
void ViewerConfiguration::buildViewerConfigurationControls(void)
	{
	/* Build the graphical user interface: */
	const GLMotif::StyleSheet& ss=*getUiStyleSheet();
	
	dialogWindow=new GLMotif::PopupWindow("ViewerConfigurationDialog",getWidgetManager(),"Viewer Configuration");
	dialogWindow->setHideButton(true);
	dialogWindow->setResizableFlags(true,false);
	
	GLMotif::RowColumn* viewerConfiguration=new GLMotif::RowColumn("ViewerConfiguration",dialogWindow,false);
	viewerConfiguration->setOrientation(GLMotif::RowColumn::VERTICAL);
	viewerConfiguration->setPacking(GLMotif::RowColumn::PACK_TIGHT);
	viewerConfiguration->setNumMinorWidgets(2);
	
	/* Create a drop-down menu to select a viewer: */
	new GLMotif::Label("ViewerLabel",viewerConfiguration,"Viewer");
	viewerMenu=new GLMotif::DropdownBox("ViewerMenu",viewerConfiguration);
	int mainViewerIndex=0;
	for(int viewerIndex=0;viewerIndex<getNumViewers();++viewerIndex)
		{
		Viewer* viewer=getViewer(viewerIndex);
		viewerMenu->addItem(viewer->getName());
		if(viewer==getMainViewer())
			mainViewerIndex=viewerIndex;
		}
	viewerMenu->setSelectedItem(mainViewerIndex);
	viewerMenu->getValueChangedCallbacks().add(this,&ViewerConfiguration::viewerMenuCallback);
	
	/* Calculate an appropriate slider range and granularity: */
	Scalar sliderRange=Scalar(18)*factory->configUnit.getInchFactor(); // Slider range is at least 18"
	Scalar sliderRangeFactor=Math::pow(Scalar(10),Math::floor(Math::log10(sliderRange)));
	sliderRange=Math::ceil(sliderRange/sliderRangeFactor)*sliderRangeFactor;
	Scalar sliderStep=Scalar(0.01)*factory->configUnit.getInchFactor(); // Slider granularity is at most 0.01"
	int sliderStepDigits=int(Math::floor(Math::log10(sliderStep)));
	Scalar sliderStepFactor=Math::pow(Scalar(10),Scalar(sliderStepDigits));
	sliderStep=Math::floor(sliderStep/sliderStepFactor)*sliderStepFactor;
	sliderStepDigits=sliderStepDigits<0?-sliderStepDigits:0;
	
	/* Create three sliders to set the mono eye position: */
	new GLMotif::Label("MonoEyePosLabel",viewerConfiguration,"Mono Eye");
	
	GLMotif::RowColumn* monoEyePosBox=new GLMotif::RowColumn("MonoEyePosBox",viewerConfiguration,false);
	monoEyePosBox->setPacking(GLMotif::RowColumn::PACK_GRID);
	for(int i=0;i<3;++i)
		{
		char epsName[14]="EyePosSlider ";
		epsName[12]=char(i+'0');
		eyePosSliders[0][i]=new GLMotif::TextFieldSlider(epsName,monoEyePosBox,7,ss.fontHeight*10.0f);
		eyePosSliders[0][i]->getTextField()->setFieldWidth(6);
		eyePosSliders[0][i]->getTextField()->setPrecision(sliderStepDigits);
		eyePosSliders[0][i]->getTextField()->setFloatFormat(GLMotif::TextField::FIXED);
		eyePosSliders[0][i]->setSliderMapping(GLMotif::TextFieldSlider::LINEAR);
		eyePosSliders[0][i]->setValueType(GLMotif::TextFieldSlider::FLOAT);
		eyePosSliders[0][i]->setValueRange(-sliderRange,sliderRange,sliderStep);
		eyePosSliders[0][i]->getValueChangedCallbacks().add(this,&ViewerConfiguration::eyePosSliderCallback,i);
		}
	monoEyePosBox->manageChild();
	
	/* Create a slider to set the eye separation distance: */
	new GLMotif::Label("EyeDistLabel",viewerConfiguration,"Eye Distance");
	
	eyeDistanceSlider=new GLMotif::TextFieldSlider("EyeDistanceSlider",viewerConfiguration,7,ss.fontHeight*10.0f);
	eyeDistanceSlider->getTextField()->setFieldWidth(6);
	eyeDistanceSlider->getTextField()->setPrecision(sliderStepDigits);
	eyeDistanceSlider->getTextField()->setFloatFormat(GLMotif::TextField::FIXED);
	eyeDistanceSlider->setSliderMapping(GLMotif::TextFieldSlider::LINEAR);
	eyeDistanceSlider->setValueType(GLMotif::TextFieldSlider::FLOAT);
	eyeDistanceSlider->setValueRange(sliderStep*Scalar(10),sliderRange,sliderStep);
	eyeDistanceSlider->getValueChangedCallbacks().add(this,&ViewerConfiguration::eyeDistanceSliderCallback);
	
	/* Create two triples of sliders to set the left and right eye positions: */
	for(int eyeIndex=1;eyeIndex<3;++eyeIndex)
		{
		/* Create a separator: */
		new GLMotif::Blind(eyeIndex==1?"Blind1":"Blind2",viewerConfiguration);
		new GLMotif::Separator(eyeIndex==1?"Separator1":"Separator2",viewerConfiguration,GLMotif::Separator::HORIZONTAL,ss.fontHeight,GLMotif::Separator::LOWERED);
		
		/* Create three sliders to set the left or right eye position: */
		new GLMotif::Label(eyeIndex==1?"LeftEyePosLabel":"RightEyePosLabel",viewerConfiguration,eyeIndex==1?"Left Eye":"Right Eye");
		
		GLMotif::RowColumn* eyePosBox=new GLMotif::RowColumn(eyeIndex==1?"LeftEyePosBox":"RightEyePosBox",viewerConfiguration,false);
		eyePosBox->setPacking(GLMotif::RowColumn::PACK_GRID);
		for(int i=0;i<3;++i)
			{
			char epsName[14]="EyePosSlider ";
			epsName[12]=char(eyeIndex*3+i+'0');
			eyePosSliders[eyeIndex][i]=new GLMotif::TextFieldSlider(epsName,eyePosBox,7,ss.fontHeight*10.0f);
			eyePosSliders[eyeIndex][i]->getTextField()->setFieldWidth(6);
			eyePosSliders[eyeIndex][i]->getTextField()->setPrecision(sliderStepDigits);
			eyePosSliders[eyeIndex][i]->getTextField()->setFloatFormat(GLMotif::TextField::FIXED);
			eyePosSliders[eyeIndex][i]->setSliderMapping(GLMotif::TextFieldSlider::LINEAR);
			eyePosSliders[eyeIndex][i]->setValueType(GLMotif::TextFieldSlider::FLOAT);
			eyePosSliders[eyeIndex][i]->setValueRange(-sliderRange,sliderRange,sliderStep);
			eyePosSliders[eyeIndex][i]->getValueChangedCallbacks().add(this,&ViewerConfiguration::eyePosSliderCallback,eyeIndex*3+i);
			}
		eyePosBox->manageChild();
		}
	
	viewerConfiguration->manageChild();
	
	/* Initialize vislet state and GUI: */
	setViewer(getViewer(mainViewerIndex));
	}
Beispiel #14
0
void ViewerConfiguration::viewerMenuCallback(GLMotif::DropdownBox::ValueChangedCallbackData* cbData)
	{
	/* Select a new viewer: */
	setViewer(cbData->newSelectedItem!=0?findViewer(cbData->getItem()):0);
	}