Пример #1
0
LUA_STRING CCCrypto::encryptXXTEALua(const char* plaintext,
                                     int plaintextLength,
                                     const char* key,
                                     int keyLength)
{
    CCLuaStack* stack = CCLuaEngine::defaultEngine()->getLuaStack();
    stack->clean();

    int resultLength;
    unsigned char* result = encryptXXTEA((unsigned char*)plaintext, plaintextLength, (unsigned char*)key, keyLength, &resultLength);
    
    if (resultLength <= 0)
    {
        lua_pushnil(stack->getLuaState());
    }
    else
    {
        lua_pushlstring(stack->getLuaState(), (const char*)result, resultLength);
        free(result);
    }
    return 1;
}
Пример #2
0
bool AppDelegate::applicationDidFinishLaunching()
{
    // initialize director
    CCDirector *pDirector = CCDirector::sharedDirector();
    pDirector->setOpenGLView(CCEGLView::sharedOpenGLView());

    pDirector->setDisplayStats(true);
    pDirector->setAnimationInterval(1.0 / 60);
	CCEGLView::sharedOpenGLView()->setDesignResolutionSize(960, 640, kResolutionShowAll);

    // register lua engine
    CCLuaEngine* pEngine = CCLuaEngine::defaultEngine();
    CCScriptEngineManager::sharedManager()->setScriptEngine(pEngine);

    CCLuaStack *pStack = pEngine->getLuaStack();
    lua_State *tolua_s = pStack->getLuaState();
    tolua_extensions_ccb_open(tolua_s);
#if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS || CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID || CC_TARGET_PLATFORM == CC_PLATFORM_WIN32)
    pStack = pEngine->getLuaStack();
    tolua_s = pStack->getLuaState();
    tolua_web_socket_open(tolua_s);
#endif
    
#if (CC_TARGET_PLATFORM == CC_PLATFORM_BLACKBERRY)
    CCFileUtils::sharedFileUtils()->addSearchPath("script");
#endif

	CCFileUtils::sharedFileUtils()->addSearchPath("luaScript");

	//cocoswidget lua binding open api
	tolua_Lua_cocos2dx_widget_open(tolua_s);

    std::string path = CCFileUtils::sharedFileUtils()->fullPathForFilename("main.lua");
    pEngine->executeScriptFile(path.c_str());
	pEngine->executeGlobalFunction("main");

    return true;
}
 virtual void onMessage(WebSocket* ws, const WebSocket::Data& data)
 {
     LuaWebSocket* luaWs = dynamic_cast<LuaWebSocket*>(ws);
     if (NULL != luaWs) {
         if (data.isBinary) {
             int nHandler = luaWs->getScriptHandler(LuaWebSocket::kWebSocketScriptHandlerMessage);
             if (-1 != nHandler) {
                 CCLuaStack *pStack = CCLuaEngine::defaultEngine()->getLuaStack();
                 pStack->pushFunctionByHandler(nHandler);
                 pStack->pushString(data.bytes, (int)data.len);
                 pStack->pushInt((int)data.len);
                 pStack->executeFunction(2);
             }
         }
         else{
             
             int nHandler = luaWs->getScriptHandler(LuaWebSocket::kWebSocketScriptHandlerMessage);
             if (-1 != nHandler) {
                 CCScriptEngineManager::sharedManager()->getScriptEngine()->executeEvent(nHandler,data.bytes);
             }
         }
     }
 }
Пример #4
0
bool AppDelegate::applicationDidFinishLaunching()
{
    // initialize director
    CCDirector *pDirector = CCDirector::sharedDirector();
    pDirector->setOpenGLView(CCEGLView::sharedOpenGLView());

    // 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);

    // register lua engine
    CCLuaEngine* pEngine = CCLuaEngine::defaultEngine();
    CCScriptEngineManager::sharedManager()->setScriptEngine(pEngine);

    CCLuaStack *pStack = pEngine->getLuaStack();
    lua_State *tolua_s = pStack->getLuaState();
    tolua_extensions_ccb_open(tolua_s);
#if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS || CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID || CC_TARGET_PLATFORM == CC_PLATFORM_WIN32)
    pStack = pEngine->getLuaStack();
    tolua_s = pStack->getLuaState();
    tolua_web_socket_open(tolua_s);
#endif
    
#if (CC_TARGET_PLATFORM == CC_PLATFORM_BLACKBERRY)
    CCFileUtils::sharedFileUtils()->addSearchPath("script");
#endif

	std::string lua_entry = "lua/mainapp.lua";
	initLuaGlobalVariables(lua_entry);
	std::string path = CCFileUtils::sharedFileUtils()->fullPathForFilename(lua_entry.c_str());
	pEngine->executeScriptFile(path.c_str());

    return true;
}
void LuaArmatureWrapper::frameEventCallback(CCBone* bone, const char* frameEventName, int orginFrameIndex, int currentFrameIndex)
{
    if (0 != m_lHandler)
    {
        CCLuaEngine* pEngine = CCLuaEngine::defaultEngine();
        CCLuaStack* pStack = pEngine->getLuaStack();
        
        pStack->pushCCObject(bone, "CCBone");
        pStack->pushString(frameEventName);
        pStack->pushInt(orginFrameIndex);
        pStack->pushInt(currentFrameIndex);
        pStack->executeFunctionByHandler(m_lHandler, 4);
        pStack->clean();
    }
}
void LuaArmatureWrapper::movementEventCallback(CCArmature* armature, MovementEventType type,const char* movementID)
{
    if (0 != m_lHandler)
    {
        CCLuaEngine* pEngine = CCLuaEngine::defaultEngine();
        CCLuaStack* pStack = pEngine->getLuaStack();
        
        pStack->pushCCObject(armature, "CCArmature");
        pStack->pushInt(type);
        pStack->pushString(movementID);
        pStack->executeFunctionByHandler(m_lHandler, 3);
        pStack->clean();
    }
}
Пример #7
0
void CWidgetLayout::executeTouchCancelledAfterLongClickHandler(CCObject* pSender, CCTouch *pTouch, float fDuration)
{
    if( m_pTouchCancelledAfterLongClickListener && m_pTouchCancelledAfterLongClickHandler )
    {
		(m_pTouchCancelledAfterLongClickListener->*m_pTouchCancelledAfterLongClickHandler)(pSender, pTouch, fDuration);
    }
#if USING_LUA
	else if( m_pTouchCancelledAfterLongClickScriptHandler != 0 )
	{
		CCLuaEngine* pEngine = CCLuaEngine::defaultEngine();
		CCLuaStack* pStack = pEngine->getLuaStack();

		pStack->pushCCObject(pSender, "CCObject");
		pStack->pushCCObject(pTouch, "CCTouch");
		pStack->pushFloat(fDuration);

		int nRet = pStack->executeFunctionByHandler(m_pTouchCancelledAfterLongClickScriptHandler, 3);
		pStack->clean();
	}
#endif
}
Пример #8
0
void CWidget::executeTouchCancelledHandler(CCTouch* pTouch, float fDuration)
{
    if( m_pTouchCancelledListener && m_pTouchCancelledHandler )
    {
        if( !(m_pTouchCancelledListener->*m_pTouchCancelledHandler)(m_pThisObject, pTouch, fDuration) )
        {
            return;
        }
    }
#if USING_LUA
	else if( m_nTouchCancelledScriptHandler != 0 )
	{
		CCLuaEngine* pEngine = CCLuaEngine::defaultEngine();
		CCLuaStack* pStack = pEngine->getLuaStack();

		pStack->pushCCObject(m_pThisObject, "CCObject");
		pStack->pushCCObject(pTouch, "CCTouch");
		pStack->pushFloat(fDuration);
		
		CCArray* pRetArray = new CCArray();
		pRetArray->initWithCapacity(1);

		int nRet = pStack->executeFunctionReturnArray(m_nTouchCancelledScriptHandler, 3, 1, pRetArray);
		CCAssert(pRetArray->count() > 0, "return count = 0");

		CCBool* pBool = (CCBool*) pRetArray->objectAtIndex(0);
		bool bContinue = pBool->getValue();
		delete pRetArray;
		pStack->clean();

		if(!bContinue)
		{
			return;
		}
	}
#endif
	this->onTouchCancelled(pTouch, fDuration);
    return;
}
Пример #9
0
bool AppDelegate::applicationDidFinishLaunching()
{
    // initialize director
    CCDirector *pDirector = CCDirector::sharedDirector();
    pDirector->setOpenGLView(CCEGLView::sharedOpenGLView());
    pDirector->setProjection(kCCDirectorProjection2D);
    
    // set FPS. the default value is 1.0/60 if you don't call this
    pDirector->setAnimationInterval(1.0 / 60);
    
    // register lua engine
    CCLuaEngine *pEngine = CCLuaEngine::defaultEngine();
    CCScriptEngineManager::sharedManager()->setScriptEngine(pEngine);    
    
    CCLuaStack *pStack = pEngine->getLuaStack();
    lua_State* L = pStack->getLuaState();
    
    // load lua extensions
    luaopen_lua_extensions(L);
    // load cocos2dx_extensions luabinding
    luaopen_cocos2dx_extensions_luabinding(L);
    // load cocos2dx_extra luabinding
    luaopen_cocos2dx_extra_luabinding(L);
    // load precompiled framework
    luaopen_framework_precompiled(L);
    
#if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS || CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID)
    string path = CCFileUtils::sharedFileUtils()->fullPathForFilename("scripts/main.lua");
#else
    string path = CCFileUtils::sharedFileUtils()->fullPathForFilename(getStartupScriptFilename().c_str());
#endif
    int pos;
    while ((pos = path.find_first_of("\\")) != std::string::npos)
    {
        path.replace(pos, 1, "/");
    }
    size_t p = path.find_last_of("/\\");
    if (p != path.npos)
    {
        const string dir = path.substr(0, p);
        pStack->addSearchPath(dir.c_str());
        
        p = dir.find_last_of("/\\");
        if (p != dir.npos)
        {
            pStack->addSearchPath(dir.substr(0, p).c_str());
        }
    }
    
    string env = "__LUA_STARTUP_FILE__=\"";
    env.append(path);
    env.append("\"");
    pEngine->executeString(env.c_str());
    
    CCLOG("------------------------------------------------");
    CCLOG("LOAD LUA FILE: %s", path.c_str());
    CCLOG("------------------------------------------------");
    pEngine->executeScriptFile(path.c_str());
    
    return true;
}
Пример #10
0
int UiPlayer::run(void)
{
    const char *QUICK_COCOS2DX_ROOT = getenv("QUICK_COCOS2DX_ROOT");
    SimulatorConfig::sharedDefaults()->setQuickCocos2dxRootPath(QUICK_COCOS2DX_ROOT);

    loadProjectConfig();

    HWND hwndConsole = NULL;
    if (m_project.isShowConsole())
    {
        AllocConsole();
        freopen("CONOUT$", "wt", stdout);
        freopen("CONOUT$", "wt", stderr);

        // disable close console
        hwndConsole = GetConsoleWindow();
        if (hwndConsole != NULL)
        {
            HMENU hMenu = GetSystemMenu(hwndConsole, FALSE);
            if (hMenu != NULL) DeleteMenu(hMenu, SC_CLOSE, MF_BYCOMMAND);

            ShowWindow(hwndConsole, SW_SHOW);
            BringWindowToTop(hwndConsole);
        }
    }

    if (m_project.isWriteDebugLogToFile())
    {
        const string debugLogFilePath = m_project.getDebugLogFilePath();
        m_writeDebugLogFile = fopen(debugLogFilePath.c_str(), "w");
        if (!m_writeDebugLogFile)
        {
            CCLOG("Cannot create debug log file %s", debugLogFilePath.c_str());
        }
    }

    do
    {
        m_exit = TRUE;

        // create the application instance
        m_app = new AppDelegate();
        m_app->setProjectConfig(m_project);

        // set environments
        SetCurrentDirectoryA(m_project.getProjectDir().c_str());
        CCFileUtils::sharedFileUtils()->setSearchRootPath(m_project.getProjectDir().c_str());
        CCFileUtils::sharedFileUtils()->setWritablePath(m_project.getWritableRealPath().c_str());

        // create opengl view
        CCEGLView* eglView = CCEGLView::sharedOpenGLView();
        eglView->setMenuResource(MAKEINTRESOURCE(IDC_LUAHOSTWIN32));
        eglView->setWndProc(WindowProc);
        eglView->setFrameSize(m_project.getFrameSize().width, m_project.getFrameSize().height);
        eglView->setFrameZoomFactor(m_project.getFrameScale());

        // make window actived
        m_hwnd = eglView->getHWnd();
        BringWindowToTop(m_hwnd);
        SetWindowTextA(m_hwnd, "ui-player");

        // restore window position
        const CCPoint windowOffset = m_project.getWindowOffset();
        if (windowOffset.x != 0 || windowOffset.y != 0)
        {
            eglView->moveWindow(windowOffset.x, windowOffset.y);
        }

        // set icon
        HICON icon = LoadIcon(GetModuleHandle(NULL), MAKEINTRESOURCE(IDI_LUAHOSTWIN32));
        SendMessage(m_hwnd, WM_SETICON, ICON_BIG, (LPARAM)icon);

        if (hwndConsole)
        {
            SendMessage(hwndConsole, WM_SETICON, ICON_BIG, (LPARAM)icon);
        }

        // update menu
        createViewMenu();
        updateMenu();

        // run game
        CCLuaStack *stack = CCLuaEngine::defaultEngine()->getLuaStack();
        const vector<string> arr = m_project.getPackagePathArray();
        for (vector<string>::const_iterator it = arr.begin(); it != arr.end(); ++it)
        {
            stack->addSearchPath(it->c_str());
        }

        m_app->run();

        // cleanup
        CCScriptEngineManager::sharedManager()->removeScriptEngine();
        CCScriptEngineManager::purgeSharedManager();
        CocosDenshion::SimpleAudioEngine::end();

        delete m_app;
        m_app = NULL;
    } while (!m_exit);

    FreeConsole();
    if (m_writeDebugLogFile) fclose(m_writeDebugLogFile);
    return 0;
}
Пример #11
0
void LUA_EXECUTE_COMMAND(int nCommand)
{
    if( nCommand == 12 )    //百度Android
    {
#if (AGENT_SDK_CODE == 12)
        JniMethodInfo methodInfo;
        if( JniHelper::getStaticMethodInfo(methodInfo, "com/haowan123/kof/bd/GameBox", "dkAccountManager", "()V") )
        {
            methodInfo.env->CallStaticVoidMethod(methodInfo.classID, methodInfo.methodID );
        }
        else
        {
            CCLOG("GameBox::openDKAccountManager method missed!");
        }
#endif
    }
    else if( nCommand == 2 ) //360Android
    {
#if (AGENT_SDK_CODE == 2)
        JniMethodInfo methodInfo;
        if( JniHelper::getStaticMethodInfo(methodInfo, "com/haowan123/kof/qh/GameBox", "doSdkAccountManager", "()V") )
        {
            methodInfo.env->CallStaticVoidMethod(methodInfo.classID, methodInfo.methodID );
        }
        else
        {
            CCLOG("GameBox::doSdkAccountManager method missed!");
        }
#endif
    }

    if( nCommand == 84 )
    {

        CCScriptEngineProtocol *pEngine = CCScriptEngineManager::sharedManager()->getScriptEngine();
        if( pEngine == NULL )
            return;
        CCLuaEngine *pLuaEngine = dynamic_cast<CCLuaEngine *>(pEngine);
        if( pLuaEngine == NULL )
            return;
        CCLuaStack *pLuaStack = pLuaEngine->getLuaStack();
        if( pLuaStack == NULL )
            return;

        lua_State *L = pLuaStack->getLuaState();

        lua_getglobal(L, "g_resetAll");
        lua_call(L, 0, 1);
        lua_pop(L, 1);
        CCLOG("LLLLLLLL");
        
//        CCScriptEngineManager::sharedManager()->removeScriptEngine();
//        CCLOG("84-2");
//        CCLuaEngine *pEngine = CCLuaEngine::defaultEngine();
//        CCLOG("84-3");
//        CCScriptEngineManager::sharedManager()->setScriptEngine(pEngine);
//        CCLOG("84-4");
//        ptola::script::CLuaClassSupport::initialize(pEngine);
        //        CCLOG("84-5");
        CCDirector *pDirector = CCDirector::sharedDirector();
        CCLOG("84-1");
        int nLevelLimit = CCUserDefault::sharedUserDefault()->getIntegerForKey("LevelResource", 0);

        CCLOG("84-6");

        pDirector->popToRootScene();

        CCLOG("84-7");
        CCScene *pUpdateScene = CGameUpdateScene::scene(nLevelLimit);
        CCLOG("84-8 %d", pUpdateScene);
        pDirector->pushScene(pUpdateScene);

        CCLOG("84-9");
        pDirector->setShowBundleVersion(true);
        CCLOG("84-10");
    }
    CCLOG("EXECUTE_LUA_COMMAND: %d", nCommand);
    
    return;
}
Пример #12
0
bool AppDelegate::applicationDidFinishLaunching()
{
    // initialize director
    CCDirector *pDirector = CCDirector::sharedDirector();
    pDirector->setOpenGLView(CCEGLView::sharedOpenGLView());
    pDirector->setProjection(kCCDirectorProjection2D);

    // set FPS. the default value is 1.0/60 if you don't call this
    pDirector->setAnimationInterval(1.0 / 60);

    // register lua engine
    CCLuaEngine *pEngine = CCLuaEngine::defaultEngine();
    CCScriptEngineManager::sharedManager()->setScriptEngine(pEngine);

    CCLuaStack *pStack = pEngine->getLuaStack();

	lua_State* L = pStack->getLuaState();
    
	tolua_ChessRule_luabinding_open(L);

#if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS || CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID)
    // load framework
    pStack->loadChunksFromZIP("res/framework_precompiled.zip");

    // set script path
    string path = CCFileUtils::sharedFileUtils()->fullPathForFilename("scripts/main.lua");
#else
    // load framework
    if (m_projectConfig.isLoadPrecompiledFramework())
    {
        const string precompiledFrameworkPath = SimulatorConfig::sharedDefaults()->getPrecompiledFrameworkPath();
        pStack->loadChunksFromZIP(precompiledFrameworkPath.c_str());
    }

    // set script path
    string path = CCFileUtils::sharedFileUtils()->fullPathForFilename(m_projectConfig.getScriptFileRealPath().c_str());
#endif

    size_t pos;
    while ((pos = path.find_first_of("\\")) != std::string::npos)
    {
        path.replace(pos, 1, "/");
    }
    size_t p = path.find_last_of("/\\");
    if (p != path.npos)
    {
        const string dir = path.substr(0, p);
        pStack->addSearchPath(dir.c_str());

        p = dir.find_last_of("/\\");
        if (p != dir.npos)
        {
            pStack->addSearchPath(dir.substr(0, p).c_str());
        }
    }

    string env = "__LUA_STARTUP_FILE__=\"";
    env.append(path);
    env.append("\"");
    pEngine->executeString(env.c_str());

    CCLOG("------------------------------------------------");
    CCLOG("LOAD LUA FILE: %s", path.c_str());
    CCLOG("------------------------------------------------");
    pEngine->executeScriptFile(path.c_str());

    return true;
}
Пример #13
0
bool GameScriptManger::LoadScript(const char* szPath)
{
	XFUNC_START();
	do 
	{
		if(!m_pLs)
		{
			CCLuaEngine* pEngine = CCLuaEngine::defaultEngine();
			if(!pEngine)
				break;
			CCLuaStack* pLuaState = pEngine->getLuaStack();
			if(!pLuaState)
				break;
			m_pLs = pLuaState->getLuaState();

			tolua_GameScript_Open(m_pLs);
			int nTop = lua_gettop(m_pLs);
			if(szPath && szPath[0])
			{
				// 设置自己的Lua table 名词
				cocos2d::CCString* pstrFileContent = cocos2d::CCString::createWithContentsOfFile(szPath);
				if (!pstrFileContent)
				{
					break;
				}

				if(!m_bySetGlobal)
				{
					lua_pushnumber(m_pLs, g_wChannelNum);
					lua_setglobal(m_pLs, "g_wChannelNum");
					lua_pushnumber(m_pLs, g_wCharge);
					lua_setglobal(m_pLs, "g_wCharge");
#if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID )
					lua_pushnumber(m_pLs, 2);
					lua_setglobal(m_pLs, "g_TargType");
#elif (CC_TARGET_PLATFORM == CC_PLATFORM_IOS || CC_TARGET_PLATFORM == CC_PLATFORM_MAC)
					lua_pushnumber(m_pLs, 1);
					lua_setglobal(m_pLs, "g_TargType");
#else
					lua_pushnumber(m_pLs, 3);
					lua_setglobal(m_pLs, "g_TargType");
#endif

				}

				int nRes = luaL_dostring(m_pLs, pstrFileContent->getCString());
				if(nRes)
				{
					CCLOG("GameScriptManger::LoadScript luaL_dofile [%s] Faild, Error Info is [%s]",
						szPath, lua_tostring(m_pLs, -1));
					lua_pop(m_pLs,1);	// error info
					break;
				}
			}
		}
		int nEnd = 0;
		const char* sztableName = GetLuaTableName();
		lua_getglobal(m_pLs, "GameScript");
		if(lua_istable(m_pLs, -1))
		{
			// 测试代码
			/*lua_pushnumber(m_pLs, 111.1);
			lua_setfield(m_pLs, -2, "tCtrl");
			lua_pushstring(m_pLs, "I am panel");
			lua_setfield(m_pLs, -2, "tPanel");*/
			//测试结束

			// 调用Onload函数
			lua_getfield(m_pLs, -1, "OnLoad");
			if(lua_isfunction(m_pLs, -1))
			{
				int nRes = lua_pcall(m_pLs, 0, 1, 0);
				if(nRes)
				{
					CCLOG("GameScriptManger::LoadScript call OnLoad Faild, Error info is[%s]!!!",
						lua_tostring(m_pLs, -1));
					lua_pop(m_pLs,1);	// error
					lua_pop(m_pLs,1);	// table
					break;
				}
				// get return value
				if (!lua_isnumber(m_pLs, -1))
				{
					lua_pop(m_pLs, 1);	// error
					lua_pop(m_pLs, 1);	// table
					break;
				}
				nEnd = lua_tointeger(m_pLs, -1);
				lua_pop(m_pLs, 1);
			}
		}
		lua_pop(m_pLs,1);	// table
#ifdef X_SDK_SWITCH
		if(!m_bySetGlobal)
		{
			lua_pushnumber(m_pLs, 1);
			lua_setglobal(m_pLs, "g_IsSDKVersion");
		}
#endif
		m_bySetGlobal = 0xFF;
		if(nEnd)
		{			
			return true;
		}
		return false;
	} while (0);
	CCLOG("GameScriptManger::LoadScript Faild!");
	XFUNC_END_RETURN(bool, res, false);
}
Пример #14
0
bool AppDelegate::applicationDidFinishLaunching()
{
    // initialize director
    CCDirector *pDirector = CCDirector::sharedDirector();
    pDirector->setOpenGLView(CCEGLView::sharedOpenGLView());
    pDirector->setProjection(kCCDirectorProjection2D);

    // set FPS. the default value is 1.0/60 if you don't call this
    pDirector->setAnimationInterval(1.0 / 60);

    // register lua engine
    CCLuaEngine *pEngine = CCLuaEngine::defaultEngine();
    CCScriptEngineManager::sharedManager()->setScriptEngine(pEngine);

    CCLuaStack *pStack = pEngine->getLuaStack();
    lua_State* L = pStack->getLuaState();

    // load lua extensions
    luaopen_lua_extensions(L);
    // load cocos2dx_extra luabinding
    luaopen_cocos2dx_extra_luabinding(L);

    // thrid_party
    luaopen_third_party_luabinding(L);

#if USE_PROXY
    // CCBReader
    tolua_extensions_ccb_open(L);
#endif//USE_PROXY

    // load framework
    if (m_projectConfig.isLoadPrecompiledFramework())
    {
        const string precompiledFrameworkPath = SimulatorConfig::sharedDefaults()->getPrecompiledFrameworkPath();
        pStack->loadChunksFromZip(precompiledFrameworkPath.c_str());
    }

    // load script
    string path = CCFileUtils::sharedFileUtils()->fullPathForFilename(m_projectConfig.getScriptFileRealPath().c_str());
    int pos;
    while ((pos = path.find_first_of("\\")) != std::string::npos)
    {
        path.replace(pos, 1, "/");
    }
    size_t p = path.find_last_of("/\\");
    if (p != path.npos)
    {
        const string dir = path.substr(0, p);
        pStack->addSearchPath(dir.c_str());

        p = dir.find_last_of("/\\");
        if (p != dir.npos)
        {
            pStack->addSearchPath(dir.substr(0, p).c_str());
        }
    }

    string env = "__LUA_STARTUP_FILE__=\"";
    env.append(path);
    env.append("\"");
    pEngine->executeString(env.c_str());

    CCLOG("------------------------------------------------");
    CCLOG("LOAD LUA FILE: %s", path.c_str());
    CCLOG("------------------------------------------------");
    pEngine->executeScriptFile(path.c_str());

    return true;
}
Пример #15
0
void CCHTTPRequest::update(float dt)
{
    if (m_state == kCCHTTPRequestStateInProgress)
    {
#if CC_LUA_ENGINE_ENABLED > 0
        if (m_listener)
        {
            CCLuaValueDict dict;

            dict["name"] = CCLuaValue::stringValue("inprogress");
            dict["dltotal"] = CCLuaValue::floatValue((float)m_dltotal);
            dict["dlnow"] = CCLuaValue::floatValue((float)m_dlnow);
            dict["ultotal"] = CCLuaValue::floatValue((float)m_ultotal);
            dict["ulnow"] = CCLuaValue::floatValue((float)m_ulnow);
            dict["request"] = CCLuaValue::ccobjectValue(this, "CCHTTPRequest");
            CCLuaStack *stack = CCLuaEngine::defaultEngine()->getLuaStack();
            stack->clean();
            stack->pushCCLuaValueDict(dict);
            stack->executeFunctionByHandler(m_listener, 1);
        }
#endif
        return;
    }
    CCDirector::sharedDirector()->getScheduler()->unscheduleAllForTarget(this);
    if (m_curlState != kCCHTTPRequestCURLStateIdle)
    {
        CCDirector::sharedDirector()->getScheduler()->scheduleSelector(schedule_selector(CCHTTPRequest::checkCURLState), this, 0, false);
    }

    if (m_state == kCCHTTPRequestStateCompleted)
    {
        CCLOG("CCHTTPRequest[0x%04x] - request completed", m_id);
        if (m_delegate) m_delegate->requestFinished(this);
    }
    else
    {
        CCLOG("CCHTTPRequest[0x%04x] - request failed", m_id);
        if (m_delegate) m_delegate->requestFailed(this);
    }

#if CC_LUA_ENGINE_ENABLED > 0
    if (m_listener)
    {
        CCLuaValueDict dict;

        switch (m_state)
        {
            case kCCHTTPRequestStateCompleted:
                dict["name"] = CCLuaValue::stringValue("completed");
                break;

            case kCCHTTPRequestStateCancelled:
                dict["name"] = CCLuaValue::stringValue("cancelled");
                break;

            case kCCHTTPRequestStateFailed:
                dict["name"] = CCLuaValue::stringValue("failed");
                break;

            default:
                dict["name"] = CCLuaValue::stringValue("unknown");
        }
        dict["request"] = CCLuaValue::ccobjectValue(this, "CCHTTPRequest");
        CCLuaStack *stack = CCLuaEngine::defaultEngine()->getLuaStack();
        stack->clean();
        stack->pushCCLuaValueDict(dict);
        stack->executeFunctionByHandler(m_listener, 1);
    }
#endif
}
Пример #16
0
bool AppDelegate::applicationDidFinishLaunching()
{
//#if CC_TARGET_PLATFORM == CC_PLATFORM_IOS
//	//Lua版本、JS版本请参考并在lua侧或js侧调用,同时请在该applicationFinishLaunching接口调用dataeye.h中的接口注入接口
//    //添加DataEye需要配置的appID和channelId
//    //APPID 是一组32位的代码,可以在g.dataeye.com创建游戏后获得.
//    //“937042C1192B1833CD8DF4895B281674”的部分要按照实际情况设置,一定要记得替换哦
//    //DC_AFTER_LOGIN模式适用于有账号体系的游戏,后面必须要调用DCAccount login,否则不会上报数据。
//    //DEFAULT模式适用于不存在账号体系的游戏(如单机),SDK会用设备ID作为用户的ID
//    //请选择合适于自己游戏的上报模式
//    DCAgent::setReportMode(DC_AFTER_LOGIN);
//    DCAgent::setDebugMode(true);
//    DCAgent::onStart("937042C1192B1833CD8DF4895B281674", "DataEye");
//#endif
    // initialize director
    CCDirector *pDirector = CCDirector::sharedDirector();
    pDirector->setOpenGLView(CCEGLView::sharedOpenGLView());
    pDirector->setProjection(kCCDirectorProjection2D);

	/////.........COPY 3 FILES FIRST. //////////////////
	string Srcfile = CCFileUtils::sharedFileUtils()->getSearchPaths()[0] + "res_phone/";//game.dat"; //game.dat
	string cachePath = CCFileUtils::sharedFileUtils()->getWritablePath() + "res_iphone/";
	string lockPath = cachePath + ".lock";
			fstream _file;
     _file.open(lockPath.c_str(),ios::in);
	 CCLog("Srcfile:%s",Srcfile.c_str());
	 CCLog("cachePath:%s",cachePath.c_str());
	 CCLog("lockPath:%s",lockPath.c_str());
	if (!_file)
	{

	if ( CheckDir(cachePath.c_str()) )
	{
		
		CCLog("create :%s success!",cachePath.c_str());
		MyCopyFile(Srcfile + "game.dat",cachePath + "game.dat");
		MyCopyFile(Srcfile + "framework_precompiled.zip",cachePath + "framework_precompiled.zip");
		ofstream fout;
		fout.open(cachePath+".lock",ios::app);
		fout<<" "<<endl;
	}
	else
	{
		CCLog("create :%s failed!",cachePath.c_str());
	}
	}
	else
	{
		CCLog(".lock exists!");
	}
		
    
    
    // set FPS. the default value is 1.0/60 if you don't call this
    pDirector->setAnimationInterval(1.0 / 60);
    
    // register lua engine
    CCLuaEngine *pEngine = CCLuaEngine::defaultEngine();
    CCScriptEngineManager::sharedManager()->setScriptEngine(pEngine);
    
    CCLuaStack *pStack = pEngine->getLuaStack();
    
    #if CC_TARGET_PLATFORM == CC_PLATFORM_IOS || CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID 
        lua_State *tolua_s = pStack->getLuaState(); 
    #endif
    
#if defined(ENCRYPT_RESOURCE_ENABLED) && ENCRYPT_RESOURCE_ENABLED == 1
    std::string pathBase = "res_phone/";
#else
    std::string pathBase = "res/";
#endif
    
#if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS || CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID)
    // load framework
    pathBase = "res_phone/";
    std::string pre_zip = "framework_precompiled.zip";
    pre_zip = pathBase+pre_zip;
    
    CCLog("cpp loadChunksFromZIP begin-- ");
    pStack->loadChunksFromZIP(pre_zip.c_str());
    CCLog("cpp loadChunksFromZIP end-- ");
    // set script path
    string path = CCFileUtils::sharedFileUtils()->fullPathForFilename("scripts/main.lua");
#endif
    
    size_t pos;
    while ((pos = path.find_first_of("\\")) != std::string::npos)
    {
        path.replace(pos, 1, "/");
    }
    size_t p = path.find_last_of("/\\");
    if (p != path.npos)
    {
        const string dir = path.substr(0, p);
        pStack->addSearchPath(dir.c_str());
        
        p = dir.find_last_of("/\\");
        if (p != dir.npos)
        {
            pStack->addSearchPath(dir.substr(0, p).c_str());
        }
    }
    
    string env = "__LUA_STARTUP_FILE__=\"";
    env.append(path);
    env.append("\"");
    
    pStack->setXXTEAKeyAndSign("CFgrrwCFewrf", 12);
    
#if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS || CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID)
    
#if 0
    std::string rootDir = CCFileUtils::sharedFileUtils()->getWritablePath();
#else
    std::string rootDir =  CCFileUtils::sharedFileUtils()->getWritablePath();
#endif
    std::string dataPath =   cachePath + "game.dat";
    CCLog("LOAD MAIN.LUA dataPath=%s",dataPath.c_str());
    CCLog("LOAD MAIN.LUA begin--");
    bool runCompliedScript = true;                         ////////////////////////------------------USE COMPILED RESOURCE??
    if (runCompliedScript) {
        
        if(pStack->loadChunksFromZIP(dataPath.c_str()))
        {
            CCLog("LOAD MAIN.LUA end2--");
            pEngine->executeString("require \"main\"");
            CCLog("LOAD MAIN.LUA end3--");
        }
    }
    else
    {

    CCLog("LOAD MAIN.LUA end5--");
    
    pEngine->executeString("print(\"blah\")");
    pEngine->executeString("CCLuaLog(\"blah\")");
    std::string dataPath = rootDir+pathBase + "scripts/main.lua";
    CCLog("dataPath:%s",dataPath.c_str());
        if(pStack->executeScriptFile(dataPath.c_str()))
        {

    CCLog("LOAD MAIN.LUA end6--");
            pEngine->executeString("require \"main\"");
        }
    }
    CCLog("LOAD MAIN.LUA end7--");
    pEngine->executeString(env.c_str());
    CCLog("LOAD MAIN.LUA end4--");
    CCLog("LOAD MAIN.LUA end4--");
#else
    
	string dataPath = CCFileUtils::sharedFileUtils()->getWritablePath();
	dataPath += "res"DIRECTORY_SEPARATOR"game2.dat";
	if(pStack->loadChunksFromZip(dataPath.c_str()))
	{
		pEngine->executeString("require \"main\"");
	}
	else
	{
        CCLOG("------------------------------------------------");
        CCLOG("LOAD LUA FILE: %s", path.c_str());
        CCLOG("------------------------------------------------");
        pEngine->executeScriptFile(path.c_str());
	}
#endif
    return true;
}
Пример #17
0
bool AppDelegate::applicationDidFinishLaunching()
{
    // initialize director
    CCDirector *pDirector = CCDirector::sharedDirector();
    pDirector->setOpenGLView(CCEGLView::sharedOpenGLView());
    
    CCEGLView::sharedOpenGLView()->setDesignResolutionSize(480, 800, kResolutionShowAll);

    // turn on display FPS
    pDirector->setDisplayStats(false);

    // set FPS. the default value is 1.0/60 if you don't call this
    pDirector->setAnimationInterval(1.0 / 60);

    // register lua engine
    CCLuaEngine* pEngine = CCLuaEngine::defaultEngine();
    lua_State *state = pEngine->getLuaStack()->getLuaState();
    tolua_MyExt_open(state);

    CCScriptEngineManager::sharedManager()->setScriptEngine(pEngine);

	//加载cjson
	CCLuaStack *pStack = pEngine->getLuaStack(); 
    lua_State* L = pStack->getLuaState(); 
    luaopen_lua_extensions(L); 


#if (CC_TARGET_PLATFORM != CC_PLATFORM_WIN32 && ANALYTICS_UMENG == 1)
	loadAnalyticsPlugin();
    g_pAnalytics->setDebugMode(false);
    g_pAnalytics->startSession(s_strAppKey.c_str());
    g_pAnalytics->setCaptureUncaughtException(true);

    AnalyticsUmeng* pUmeng = dynamic_cast<AnalyticsUmeng*>(g_pAnalytics);
    //AnalyticsFlurry* pFlurry = dynamic_cast<AnalyticsFlurry*>(g_pAnalytics);
    if (pUmeng != NULL)
    {
        pUmeng->updateOnlineConfig();
        pUmeng->setDefaultReportPolicy(AnalyticsUmeng::REALTIME);
    }
	/*
    if (pFlurry != NULL)
    {
        pFlurry->setReportLocation(true);
        pFlurry->logPageView();
        // const char* sdkVersion = pFlurry->getSDKVersion();
        pFlurry->setVersionName("1.1");
        pFlurry->setAge(20);
        pFlurry->setGender(AnalyticsFlurry::MALE);
        pFlurry->setUserId("123456");
        pFlurry->setUseHttps(false);
    }*/
#endif

CCLog("before to load lua file");
CCLog("platform ");

#if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID)
    CCLog("before android add search path");
	//pEngine->addSearchPath((CCFileUtils::sharedFileUtils()->getWritablePath() + "script/").c_str());
	//CCFileUtils::sharedFileUtils()->addSearchPath((CCFileUtils::sharedFileUtils()->getWritablePath() + "script/").c_str());
	
    CCString* pstrFileContent = CCString::createWithContentsOfFile("Entry");
	
    CCLOG("%s","read script from phone memory");
    
    pEngine->executeString(pstrFileContent->getCString());
    
#elif (CC_TARGET_PLATFORM == CC_PLATFORM_IOS || CC_TARGET_PLATFORM == CC_PLATFORM_MAC)
    
    CCLuaStack *pStack = pEngine->getLuaStack();
    lua_State *tolua_s = pStack->getLuaState();
    tolua_AppstorePurchase_open(tolua_s);
    
    std::string path = CCFileUtils::sharedFileUtils()->fullPathForFilename("Entry");
    pEngine->addSearchPath(path.substr(0, path.find_last_of("/")).c_str());
	CCString* pstrFileContent = CCString::createWithContentsOfFile("Entry");
	pEngine->executeString(pstrFileContent->getCString());
#else
    std::string path = CCFileUtils::sharedFileUtils()->fullPathForFilename("Entry");
    pEngine->addSearchPath(path.substr(0, path.find_last_of("/")).c_str());

	CCString* pstrFileContent = CCString::createWithContentsOfFile("Entry");
	const char * res = pstrFileContent->getCString();

	int len = strlen(res);
	int remain_len = len % 8;
	int desSize = len+1;
	if(remain_len>0){
		desSize += 8 - remain_len;
	}
	unsigned char* des = (unsigned char*)malloc(desSize*sizeof(unsigned char));

	//加密脚本
	file_encrypt(res,des,desSize);
	pEngine->executeString(file_decrypt(des,desSize));//解密脚本

	//unsigned long desSize = 0;
	//unsigned char * enc = CCFileUtils::sharedFileUtils()->getFileData(path.c_str(), "rb", &desSize);
	//char * res = file_decrypt(enc,desSize);
	//CCLOG(res);
	//pEngine->executeString(res);//解密脚本
#endif 

    return true;
}
Пример #18
0
int LuaHostWin32::run(void)
{
    loadProjectConfig();

    AllocConsole();
    freopen("CONOUT$", "wt", stdout);
    freopen("CONOUT$", "wt", stderr);

    // disable close console
    HWND hwndConsole = GetConsoleWindow();
    if (hwndConsole != NULL)
    {
        HMENU hMenu = GetSystemMenu(hwndConsole, FALSE);
        if (hMenu != NULL) DeleteMenu(hMenu, SC_CLOSE, MF_BYCOMMAND);
    }

    do
    {
        m_exit = TRUE;

        if (m_project.isShowConsole())
        {
            ShowWindow(hwndConsole, SW_SHOW);
            BringWindowToTop(hwndConsole);
        }
        else
        {
            ShowWindow(hwndConsole, SW_HIDE);
        }

        // create the application instance
        m_app = new AppDelegate();
        m_app->setStartupScriptFilename(m_project.getScriptFilePath());

        // set environments
        SetCurrentDirectoryA(m_project.getProjectDir().c_str());
        vector<string> searchPaths;
        searchPaths.push_back(m_project.getProjectDir());
        CCFileUtils::sharedFileUtils()->setSearchPaths(searchPaths);

        // create opengl view
        CCEGLView* eglView = CCEGLView::sharedOpenGLView();    
        eglView->setMenuResource(MAKEINTRESOURCE(IDC_LUAHOSTWIN32));
        eglView->setWndProc(WindowProc);
        eglView->setFrameSize(m_project.getFrameSize().width, m_project.getFrameSize().height);
        eglView->setFrameZoomFactor(m_project.getFrameScale());

        // make window actived
        m_hwnd = eglView->getHWnd();
        BringWindowToTop(m_hwnd);

        // restore window position
        const CCPoint windowOffset = m_project.getWindowOffset();
        if (windowOffset.x >= 0 || windowOffset.y >= 0)
        {
            eglView->moveWindow(windowOffset.x, windowOffset.y);
        }

        // set icon
        HICON icon = LoadIcon(GetModuleHandle(NULL), MAKEINTRESOURCE(IDI_LUAHOSTWIN32));
        SendMessage(m_hwnd, WM_SETICON, ICON_BIG, (LPARAM)icon);
        SendMessage(hwndConsole, WM_SETICON, ICON_BIG, (LPARAM)icon);

        // run game
        CCLuaStack *stack = CCLuaEngine::defaultEngine()->getLuaStack();
        const vector<string> arr = m_project.getPackagePathArray();
        for (vector<string>::const_iterator it = arr.begin(); it != arr.end(); ++it)
        {
            stack->addSearchPath(it->c_str());
        }

        m_app->run();

        // cleanup
        CCScriptEngineManager::sharedManager()->removeScriptEngine();
        CCScriptEngineManager::purgeSharedManager();
        CocosDenshion::SimpleAudioEngine::end();

        delete m_app;
        m_app = NULL;
    } while (!m_exit);

    FreeConsole();
    return 0;
}