Cocos2d-x source code analysis of the overall framework

Source: Internet
Author: User

Just read the majority of cocos2d-x source code, feel benefited a lot, cocos2d-x code is not complex, strong readability, and some of the essence of the part can also be applied to work, complement each other. Now it seems that the best way to read the source code is the top-down method. First, understand the entire framework, and then focus on breaking through important and interesting modules. Nonsense, first look at the coscos2d-x framework is how, how to run.
Let's take a look at the main function in the test case testcpp, which is also the entrance to the entire Win32 program.

int APIENTRY _tWinMain(HINSTANCE hInstance,                       HINSTANCE hPrevInstance,                       LPTSTR    lpCmdLine,                       int       nCmdShow){    UNREFERENCED_PARAMETER(hPrevInstance);    UNREFERENCED_PARAMETER(lpCmdLine);// create the application instanceAppDelegate app;CCEGLView* eglView = CCEGLView::sharedOpenGLView();eglView->setViewName("TestCpp");eglView->setFrameSize(480, 320);return CCApplication::sharedApplication()->run();}

This entry has two very important classes cceglview and ccapplication, which are Singleton in the entire program.
Let's take a look at cceglview.
Cceglview is used to manage windows and draw. In cceglview: Create, you are familiar with the following:
1. The registerclass registration window, in which the very important message processing function cceglview: _ windowproc is defined throughout. The keyboard and mouse message response of windows in the game can be processed in this function.
2. initgl initializes the OpenGL engine.

    m_hDC = GetDC(m_hWnd);    SetupPixelFormat(m_hDC);    //SetupPalette();   m_hRC = wglCreateContext(m_hDC);   wglMakeCurrent(m_hDC, m_hRC);

Cceglview: The pixel format is set in initgl, And the rendercontext of OpenGL is created. The final rendering result of OpenGL is displayed on the DC of the window.
Let's take a look at ccapplication.
Ccapplication is the logic used to manage programs. The last sentence ccapplication: sharedapplication ()-> Run () starts to run at high speed. When I first started reading the code, I had a question:

CCApplication* CCApplication::sharedApplication(){    CC_ASSERT(sm_pSharedApplication);    return sm_pSharedApplication;}

Where is the sm_psharedapplication initialized in this function? Intelligent, you will soon find that there is actually an appdelegate app in front. appdelegate is a subclass of application, and the globally unique static variable is declared in the constructor of this subclass.

CCApplication::CCApplication(): m_hInstance(NULL), m_hAccelTable(NULL){m_hInstance    = GetModuleHandle(NULL);m_nAnimationInterval.QuadPart = 0;CC_ASSERT(! sm_pSharedApplication);sm_pSharedApplication = this;}

This also applies to the Singleton. Application: How does run () enable the entire program to 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;}

Skip the applicationdidfinishlaunching () Section (this part is related to the test case). We can see that two things are done in the while Main Loop:
1. Forward the window message to the previously defined cceglview: _ windowproc for processing.
2. process every m_nanimationinterval.quadpart, that is, a frame of the game.
The most important class ccdirector is the director class. This class is also a Singleton, responsible for managing the entire game scenario, updating logic, and drawing. Let's take a look.
Ccdirector: shareddirector ()-> what is done by mainloop of every frame of mainloop:
The frame of ccdirector often works:

void CCDisplayLinkDirector::mainLoop(void){    if (m_bPurgeDirecotorInNextLoop)    {        m_bPurgeDirecotorInNextLoop = false;        purgeDirector();    }    else if (! m_bInvalid)     {         drawScene();              // release the objects         CCPoolManager::sharedPoolManager()->pop();             }}

Drawscene is the most important thing for every frame of the director class,

void CCDirector::drawScene(void){    ......    if (! m_bPaused)    {        m_pScheduler->update(m_fDeltaTime);    }    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);    // draw the scene    if (m_pRunningScene)    {        m_pRunningScene->visit();    }    // swap buffers    if (m_pobOpenGLView)    {        m_pobOpenGLView->swapBuffers();    }}

After a closer look, the reader will find that this function has done two tasks ,:

1. Update the scheduler m_pscheduler, such as actions in the scenario. The following blog posts will detail the analysis.

2. Draw the object node in the scenario in a tree-like manner

So far, the overall framework of the cocos2d-x is very clear in front of us, followed by the anatomy of the sparrow ^_^

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.