cocos2d-x入口類

來源:互聯網
上載者:User

上一篇文章中有一個在棧中建立的執行個體——AppDelegate,這個類的初始化使cocos2d-x的程式可以運行起來。因為它是繼承於CCApplication類,而啟動並執行run方法就是在此類中實現的。

class CC_DLL CCApplication : public CCApplicationProtocol{public:    CCApplication();    virtual ~CCApplication();    /**    @brief    Run the message loop.    */    virtual int run();    /**    @brief    Get current applicaiton instance.    @return Current application instance pointer.    */    static CCApplication* sharedApplication();    /* override functions */    virtual void setAnimationInterval(double interval);    virtual ccLanguageType getCurrentLanguage();        /**     @brief Get target platform     */    virtual TargetPlatform getTargetPlatform();    /**     *  Sets the Resource root path.     *  @deprecated Please use CCFileUtils::sharedFileUtils()->setSearchPaths() instead.     */    CC_DEPRECATED_ATTRIBUTE void setResourceRootPath(const std::string& rootResDir);    /**      *  Gets the Resource root path.     *  @deprecated Please use CCFileUtils::sharedFileUtils()->getSearchPaths() instead.      */    CC_DEPRECATED_ATTRIBUTE const std::string& getResourceRootPath(void);    void setStartupScriptFilename(const std::string& startupScriptFile);    const std::string& getStartupScriptFilename(void)    {        return m_startupScriptFilename;    }protected:    HINSTANCE           m_hInstance;    HACCEL              m_hAccelTable;    LARGE_INTEGER       m_nAnimationInterval;    std::string         m_resourceRootPath;    std::string         m_startupScriptFilename;    static CCApplication * sm_pSharedApplication;};NS_CC_END#endif    // __CC_APPLICATION_WIN32_H__
可以看到,CCApplication是繼承自於CCApplicationProtocol,CCApplicationProtocol是個純虛類,生命了程式啟動,切到後台,後台喚醒等函數。

class CC_DLL CCApplicationProtocol{public:    virtual ~CCApplicationProtocol() {}    /**    @brief    Implement CCDirector and CCScene init code here.    @return true    Initialize success, app continue.    @return false   Initialize failed, app terminate.    *///遊戲第一次運行時被調用,用於初始情境和載入情境    virtual bool applicationDidFinishLaunching() = 0;    /**    @brief  The function be called when the application enter background    @param  the pointer of the application    *///當遊戲進入後台時被調用。    virtual void applicationDidEnterBackground() = 0;    /**    @brief  The function be called when the application enter foreground    @param  the pointer of the application    *///從後台被喚醒時調用。    virtual void applicationWillEnterForeground() = 0;    /**    @brief    Callback by CCDirector for limit FPS.    @interval       The time, expressed in seconds, between current frame and next.     *///設定幀數    virtual void setAnimationInterval(double interval) = 0;    /**    @brief Get current language config    @return Current language config    *///擷取語言    virtual ccLanguageType getCurrentLanguage() = 0;        /**     @brief Get target platform     *///擷取啟動並執行平台    virtual TargetPlatform getTargetPlatform() = 0;};

而CCApplication只實現了setAnimationInterval,getCurrentLanguage和getTargetPlatform三個函數,另外三個交給CCApplication的子類,也就是AppDelegate來實現。如下代碼所示:

class  AppDelegate : private cocos2d::CCApplication{public:    AppDelegate();    virtual ~AppDelegate();    /**    @brief    Implement CCDirector and CCScene init code here.    @return true    Initialize success, app continue.    @return false   Initialize failed, app terminate.    */    virtual bool applicationDidFinishLaunching();    /**    @brief  The function be called when the application enter background    @param  the pointer of the application    */    virtual void applicationDidEnterBackground();    /**    @brief  The function be called when the application enter foreground    @param  the pointer of the application    */    virtual void applicationWillEnterForeground();};

bool AppDelegate::applicationDidFinishLaunching() {    // initialize director    CCDirector* pDirector = CCDirector::sharedDirector();    CCEGLView* pEGLView = CCEGLView::sharedOpenGLView();    pDirector->setOpenGLView(pEGLView);    // turn on display FPS    pDirector->setDisplayStats(true);    // set FPS. the default value is 1.0/60 if you don't call this    pDirector->setAnimationInterval(1.0 / 60);    // create a scene. it's an autorelease object    CCScene *pScene = HelloWorld::scene();    // run    pDirector->runWithScene(pScene);    return true;}// This function will be called when the app is inactive. When comes a phone call,it's be invoked toovoid AppDelegate::applicationDidEnterBackground() {    CCDirector::sharedDirector()->stopAnimation();    // if you use SimpleAudioEngine, it must be pause    // SimpleAudioEngine::sharedEngine()->pauseBackgroundMusic();}// this function will be called when the app is active againvoid AppDelegate::applicationWillEnterForeground() {    CCDirector::sharedDirector()->startAnimation();    // if you use SimpleAudioEngine, it must resume here    // SimpleAudioEngine::sharedEngine()->resumeBackgroundMusic();}
其實現很簡單。在applicationDidFinishLaunching函數中先初始化導演,設定是否顯示FPS,設定幀率,建立情境,載入和運行情境。applicationDidEnterBackground則讓導演停止渲染,applicationWillEnterForeground則讓導演繼續渲染。


上面說到applicationDidFinishLaunching在程式一啟動就會被調用,而在main函數中只是建立了一個AppDelegate的執行個體,而AppDelegate的執行個體並沒有主動調用該方法,那麼它的調用肯定是在它的父類在調用run函數時啟動。

int CCApplication::run(){    PVRFrameEnableControlWindow(false);    // Main message loop:    MSG msg;    LARGE_INTEGER nFreq;    LARGE_INTEGER nLast;    LARGE_INTEGER nNow;    QueryPerformanceFrequency(&nFreq);    QueryPerformanceCounter(&nLast);    // Initialize instance and cocos2d.    if (!applicationDidFinishLaunching())    {        return 0;    }    CCEGLView* pMainWnd = CCEGLView::sharedOpenGLView();    pMainWnd->centerWindow();    ShowWindow(pMainWnd->getHWnd(), SW_SHOW);    while (1)    {        if (! PeekMessage(&msg, NULL, 0, 0, PM_REMOVE))        {            // Get current time tick.            QueryPerformanceCounter(&nNow);            // If it's the time to draw next frame, draw it, else sleep a while.            if (nNow.QuadPart - nLast.QuadPart > m_nAnimationInterval.QuadPart)            {                nLast.QuadPart = nNow.QuadPart;                CCDirector::sharedDirector()->mainLoop();            }            else            {                Sleep(0);            }            continue;        }        if (WM_QUIT == msg.message)        {            // Quit message loop.            break;        }        // Deal with windows message.        if (! m_hAccelTable || ! TranslateAccelerator(msg.hwnd, m_hAccelTable, &msg))        {            TranslateMessage(&msg);            DispatchMessage(&msg);        }    }    return (int) msg.wParam;}
這個函數的主要邏輯是先調用子類的applicationDidFinishLaunching函數,執行建立情境等操作,然後設定視窗,最後將整個擁有權交給導演類的主迴圈,也就是死迴圈中的mainLoop函數的調用,當然在調用前還要判斷當前的幀率與上一幀的幀率之差是否大於設定的幀率,否則不調用。


總結:從上面的過程可以看出CCApplication類是整個程式的起始控制類,裡面執行了讓遊戲真正跑起來的主迴圈,其次還定義了整個程式的執行環境。像設定幀率,擷取當前的運行平台等。另外,由於CCApplication是個單例共用類,可以在程式中隨時擷取當前的平台資訊,設定/擷取資源的根路徑等操作。


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.