Exemple #1
0
GLWindow::WindowPos GLWindow::getRootWindowPos(void) const
	{
	return WindowPos(DisplayWidth(context->getDisplay(),screen),DisplayHeight(context->getDisplay(),screen));
	}
GLWindow::WindowPos GLWindow::getRootWindowPos(void) const
	{
	return WindowPos(DisplayWidth(display,screen),DisplayHeight(display,screen));
	}
Int32 MainApplication::run(int argc, char **argv)
{
    //Get the date/time run
    _DateTimeRun = boost::posix_time::second_clock::local_time();

    //Get the path to the command
    BoostPath CommandPath(argv[0]);
    if(!CommandPath.is_complete() && !CommandPath.has_root_directory())
    {
        CommandPath = boost::filesystem::complete(CommandPath);
    }
    CommandPath.normalize();

    //Parse the Program arguments
    boost::program_options::variables_map OptionsVariableMap;
    try
    {
        boost::program_options::store(boost::program_options::command_line_parser(argc, argv).
                                      options(_OptionsDescription).
#ifdef __APPLE__
                                      extra_parser(procSerialNumParser).
#endif
                                      positional(_PositionalOptions).run(), OptionsVariableMap);

        boost::program_options::notify(OptionsVariableMap);
    }
    catch(boost::program_options::error& e)
    {
        std::cout << "Error parsing command line: " << e.what() << std::endl;
        printCommandLineHelp();
    }

    //Check for the help argument
    if(OptionsVariableMap.count("help"))
    {
        printCommandLineHelp();
        return 1;
    }
    
    //Setup the Logging
    LogLevel KELogLevel(LOG_NOTICE);
    if(OptionsVariableMap.count("log-level"))
    {
        KELogLevel = OptionsVariableMap["log-level"].as<LogLevel>();
    }

    _LogFilePath = getLoggingDir()
                 / BoostPath(boost::posix_time::to_iso_string(_DateTimeRun) + ".log");  //ISO date/time format
    if(OptionsVariableMap.count("log-file"))
    {
        _LogFilePath = BoostPath(OptionsVariableMap["log-file"].as<std::string>());
    }
    if(OptionsVariableMap.count("disable-log"))
    {
        _EnableLogging = false;
    }
    if(OptionsVariableMap.count("disable-file-log"))
    {
        _LogToFile = false;
    }

    initializeLogging(_LogFilePath);
    osgLogP->setLogLevel(KELogLevel, true);
    osgLogP->setHeaderElem((LOG_TYPE_HEADER | LOG_FUNCNAME_HEADER), true);

    //Check if the last run crashed
    if(didCrashLastExecution())
    {
        handleCrashLastExecution();
    }

    //Create a file to indicate if a crash occurs
    createCrashIndicationFile();

    // Set up Settings
    //Check for the settings file
    if(OptionsVariableMap.count("settings-file"))
    {
        setSettingsLoadFile(BoostPath(OptionsVariableMap["settings-file"].as<std::string>()));
    }
    else
    {
        //Use default location
        setSettingsLoadFile(getUserAppDataDir()
                          / BoostPath("KEDefaultSettings.xml"));
    }
    loadSettings(getSettingsLoadFile());

    //Cleanup the Logging Directory
    cleanupLoggingDir();

    //If the settings aren't being overriden by the command-line options
    //then set the logging with the settings values
    if(!OptionsVariableMap.count("log-level"))
    {
        osgLogP->setLogLevel(static_cast<LogLevel>(getSettings().get<UInt8>("logging.level")), true);
    }
    osgLogP->setHeaderElem(getSettings().get<UInt32>("logging.header_elements"), true);

    //Initialize OpenSG
    initOpenSG(argc,argv);

    //Log information about the Engine
    {
        PLOG << "Starting Kabala Engine:" << std::endl;
        OSG::indentLog(4,PLOG);
        PLOG << "Arguments: ";
        for(UInt32 i(0) ; i<argc ; ++i)
        {
            PLOG << argv[i] << " ";
        }
        PLOG << std::endl;

        OSG::indentLog(4,PLOG);
        PLOG << "System:" << std::endl;
        OSG::indentLog(8,PLOG);
        PLOG << "Operating System: " << getPlatformName() << std::endl;
        OSG::indentLog(8,PLOG);
        PLOG << "Processor: " << getPlatformProcessors() << std::endl;
        OSG::indentLog(8,PLOG);
        PLOG << "RAM: " << getPlatformRAM() << std::endl;
        OSG::indentLog(4,PLOG);
        PLOG << "Time: " << to_simple_string(_DateTimeRun) << std::endl;
        OSG::indentLog(4,PLOG);
        PLOG << "Version: " << getKabalaEngineVersion() << std::endl;
        OSG::indentLog(8,PLOG);
        PLOG << "Revision: " << getKabalaEngineBuildRepositoryRevision() << std::endl;
        OSG::indentLog(8,PLOG);
        PLOG << "Build Type: " << getKabalaEngineBuildType() << std::endl;
        OSG::indentLog(4,PLOG);
        PLOG << "Working Directory: " << boost::filesystem::current_path().string() << std::endl;
        OSG::indentLog(4,PLOG);
        PLOG << "Executable Directory: " << CommandPath.parent_path().string() << std::endl;
        OSG::indentLog(4,PLOG);
        PLOG << "Settings File: " << getSettingsLoadFile().string() << std::endl;

        OSG::indentLog(4,PLOG);
        PLOG << "Logging: " << (_EnableLogging ? "Enabled" : "Disabled" ) << std::endl;
        if(_EnableLogging)
        {
            OSG::indentLog(8,PLOG);
            PLOG << "Log File: " << (_LogToFile ? _LogFilePath.string() : "Disabled" ) << std::endl;
        }
    }

    //Check if the Data Directory exists
    if(!boost::filesystem::exists(getSettings().get<BoostPath>("basic.data.directory")))
    {
        BoostPath DataDirPath(getSettings().get<BoostPath>("basic.data.directory"));
        DataDirPath = boost::filesystem::complete(DataDirPath);
        DataDirPath.normalize();
        SWARNING << "Could not find Application Data directory: \""
                 << DataDirPath.string()
                 << "\" specified in the Settings file because the directory doesn't exist." << std::endl;

        //Try to find the data directory in a few locations
        std::vector<BoostPath> PathsToTry;

#ifdef __APPLE__
        PathsToTry.push_back(CommandPath.parent_path() /
                             BoostPath("../Resources") /
                             EngineAppDataDirectory);       //Path to try for OS X Bundles
        PathsToTry.push_back(CommandPath.parent_path() /
                             BoostPath("../Resources/share") /
                             EngineAppDataDirectory);       //Path to try for OS X Bundles
#endif

        PathsToTry.push_back(BoostPath("/usr/local/share") / EngineAppDataDirectory);
        PathsToTry.push_back(BoostPath("/usr/share") / EngineAppDataDirectory);
        PathsToTry.push_back(CommandPath.parent_path() / EngineAppDataDirectory);
        PathsToTry.push_back(CommandPath.parent_path() / BoostPath("..") / EngineAppDataDirectory);
        PathsToTry.push_back(CommandPath.parent_path() / BoostPath("../share") / EngineAppDataDirectory);

        for(UInt32 i(0) ; i<PathsToTry.size() ; ++i)
        {
            SNOTICE << "Looking for Data directory in: "
                << PathsToTry[i].string() << std::endl;
            if(boost::filesystem::exists(PathsToTry[i]))
            {
                PNOTICE << "FOUND" << std::endl;
                PathsToTry[i].normalize();
                getSettings().put("basic.data.directory",PathsToTry[i]);
                break;
            }
            else
            {
                PNOTICE << "NOT FOUND" << std::endl;
            }
        }
    }

    if(!boost::filesystem::exists(getSettings().get<BoostPath>("basic.data.directory")))
    {
        SWARNING << "Could not find Application Data directory: \""
                 << getSettings().get<BoostPath>("basic.data.directory").string()
                 << "\" because the directory doesn't exist." << std::endl;
    }
    else
    {
        SLOG << "Using Application Data directory: \""
                 << getSettings().get<BoostPath>("basic.data.directory").string()
                 << "\"" << std::endl;
    }

    // Set up Window
    WindowEventProducerUnrecPtr MainWindow(createNativeWindow());
    setMainWindow(MainWindow);
    setName(getMainWindow(),"__KABALA_ENGINE_WINDOW_EVENT_PRODUCER");

    //If Fullscreen option -> Fullscreen
    if(OptionsVariableMap.count("fullscreen"))
    {
        getMainWindow()->setFullscreen(true);
    }
    //If no-fullscreen     -> not Fullscreen
    else if(OptionsVariableMap.count("no-fullscreen"))
    {
        getMainWindow()->setFullscreen(false);
    }
    //else                 -> use the value in the settings
    else
    {
        getMainWindow()->setFullscreen(getSettings().get<bool>("basic.window.fullscreen"));
    }

    getMainWindow()->initWindow();

    _WindowClosingConnection = getMainWindow()->connectWindowClosing(boost::bind(&MainApplication::handleWindowClosing, this, _1));
    _WindowClosedConnection = getMainWindow()->connectWindowClosed(boost::bind(&MainApplication::handleWindowClosed, this, _1));

    // Initialize the LookAndFeelManager to enable default settings
    KELookAndFeel::the()->init();


    //Open Window
    Vec2f WindowSize(getSettings().get<Vec2f>("basic.window.size"));
    if(getSettings().get<Vec2f>("basic.window.size").x() <= 1.0f )
    {
        WindowSize[0] = getMainWindow()->getDesktopSize().x() * getSettings().get<Vec2f>("basic.window.size").x();
    }
    if(getSettings().get<Vec2f>("basic.window.size").y() <= 1.0f )
    {
        WindowSize[1] = getMainWindow()->getDesktopSize().y() * getSettings().get<Vec2f>("basic.window.size").y();
    }
    Pnt2f WindowPos(getSettings().get<Pnt2f>("basic.window.position"));
    if(getSettings().get<Pnt2f>("basic.window.position").x() < 0.0f )
    {
        WindowPos[0] = (getMainWindow()->getDesktopSize().x() - WindowSize.x()) * 0.5f;
    }
    if(getSettings().get<Pnt2f>("basic.window.position").y() < 0.0f )
    {
        WindowPos[1] = (getMainWindow()->getDesktopSize().y() - WindowSize.y()) * 0.5f;
    }

    getMainWindow()->openWindow(WindowPos,
                                WindowSize,
                                "Kabala Engine");

        
    //Store a pointer to the application thread
    //_ApplicationThread = dynamic_cast<OSG::Thread *>(OSG::ThreadManager::getAppThread());
    
    //Create the rendering thread
    //_RenderThread = OSG::dynamic_pointer_cast<OSG::Thread>(OSG::ThreadManager::the()->getThread("__KABALA_ENGINE_RENDER_THREAD", true));
    
    //Create the loading thread
    //_LoadingThread = OSG::dynamic_pointer_cast<OSG::Thread>(OSG::ThreadManager::the()->getThread("__KABALA_ENGINE_LOADING_THREAD", true));

    //Draw the loading thread
    activateLoadingScreen();

    //Load the Project file, if given
    if(OptionsVariableMap.count("project-file"))
    {
        loadProject(BoostPath(OptionsVariableMap["project-file"].as<std::string>()));
    }
    else if(getSettings().get<bool>("basic.load_most_recent_project"))
    {
        boost::optional<BoostPath> LastOpenedProjectFile = getSettings().get_optional<BoostPath>("basic.last_opened_project");
        if(LastOpenedProjectFile)
        {
            loadProject(LastOpenedProjectFile.get());
            commitChanges();
        }
    }

    if(getProject() == NULL)
    {
        //Project Failed to load, or file didn't exist
        ProjectRecPtr NewProject = createDefaultProject();
        setProject(NewProject);
    }

    //Detach the loading screen
    detachLoadingScreen();

#ifdef BUILD_WITH_WORLD_BUILDER
    if(OptionsVariableMap.count("builder"))
    {
        attachBuilder();
    }
    else 
#endif
        if(OptionsVariableMap.count("play"))
    {
        attachPlayer();
        if(OptionsVariableMap.count("debug"))
        {
            dynamic_cast<ApplicationPlayer*>(getPlayerMode())->enableDebug(true);
        }
    }
    else
    {
#ifdef BUILD_WITH_WORLD_BUILDER
        if(getSettings().get<std::string>("basic.initial_mode").compare(std::string("builder")) == 0)
        {
            attachBuilder();
        }
        else
#endif
            if(getSettings().get<std::string>("basic.initial_mode").compare(std::string("play")) == 0)
        {
            attachPlayer();
            if(OptionsVariableMap.count("debug") || getSettings().get<bool>("player.debugger.initially_active"))
            {
                dynamic_cast<ApplicationPlayer*>(getPlayerMode())->enableDebug(true);
            }
        }
        else
        {
            attachStartScreen();
        }
    }
    
    //Start the render thread on aspect 1
    //_RenderThread->runFunction(MainApplication::mainRenderLoop, 1, NULL);
    
    //Start the loading thread on aspect 2
    //_LoadingThread->runFunction(MainApplication::mainLoadingLoop, 2, NULL);

    //Main Loop
    getMainWindow()->mainLoop();

    //Exited Main Loop
    //Save Settings
    saveSettings(getSettingsLoadFile());
    
    SLOG << "Stopping Kabala Engine" << std::endl;
    OSG::indentLog(4,PLOG);
    PLOG << "Time: " << to_simple_string(boost::posix_time::second_clock::local_time()) << std::endl;

    //OSG exit
    OSG::osgExit();

    //Uninitialize logging
    uninitializeLogging();

    //Create a file to indicate if a crash occurs
    removeCrashIndicationFile();

    return 0;
}