コード例 #1
0
std::string LLUrlEntryAgent::getLabel(const std::string &url, const LLUrlLabelCallback &cb)
{
	if (!gCacheName)
	{
		// probably at the login screen, use short string for layout
		return LLTrans::getString("LoadingData");
	}

	std::string agent_id_string = getIDStringFromUrl(url);
	if (agent_id_string.empty())
	{
		// something went wrong, just give raw url
		return unescapeUrl(url);
	}

	LLUUID agent_id(agent_id_string);
	if (agent_id.isNull())
	{
		return LLTrans::getString("AvatarNameNobody");
	}

	LLAvatarName av_name;
	if (LLAvatarNameCache::get(agent_id, &av_name))
	{
		std::string label = av_name.getCompleteName();

		// handle suffixes like /mute or /offerteleport
		label = localize_slapp_label(url, label);
		return label;
	}
	else
	{
		LLAvatarNameCache::get(agent_id,
			boost::bind(&LLUrlEntryAgent::onAvatarNameCache,
				this, _1, _2));
		addObserver(agent_id_string, url, cb);
		return LLTrans::getString("LoadingData");
	}
}
コード例 #2
0
std::string LLUrlEntryParcel::getLabel(const std::string &url, const LLUrlLabelCallback &cb)
{
	LLSD path_array = LLURI(url).pathArray();
	S32 path_parts = path_array.size();

	if (path_parts < 3) // no parcel id
	{
		llwarns << "Failed to parse url [" << url << "]" << llendl;
		return url;
	}

	std::string parcel_id_string = unescapeUrl(path_array[2]); // parcel id

	// Add an observer to call LLUrlLabelCallback when we have parcel name.
	addObserver(parcel_id_string, url, cb);

	LLUUID parcel_id(parcel_id_string);

	sendParcelInfoRequest(parcel_id);

	return unescapeUrl(url);
}
コード例 #3
0
ファイル: MainMenuState.cpp プロジェクト: Ioni14/quoridor
void MainMenuState::makeChoiceSummary()
{
    int choice = State::promptInteger();
    switch (choice) {
        case 1:
            {
                auto newState = std::make_unique<GameState>(m_app, std::move(m_players), m_boardSize);
                auto newView = std::make_shared<GameView>(*newState);
                newState->addObserver(newView);
                m_app.setState(std::move(newState));
                m_app.setView(newView);
                m_app.applyNewState();
                return;
            }
            break;
        case 2:
            m_subState = SUB_STATE::BOARD_SIZE;
            break;
        case -1:
        default:
            m_error << "Veuillez taper 1 ou 2.";
    }
}
コード例 #4
0
std::string LLUrlEntryAgentName::getLabel(const std::string &url, const LLUrlLabelCallback &cb)
{
	if (!gCacheName)
	{
		// probably at the login screen, use short string for layout
		return LLTrans::getString("LoadingData");
	}

	std::string agent_id_string = getIDStringFromUrl(url);
	if (agent_id_string.empty())
	{
		// something went wrong, just give raw url
		return unescapeUrl(url);
	}

	LLUUID agent_id(agent_id_string);
	if (agent_id.isNull())
	{
		return LLTrans::getString("AvatarNameNobody");
	}

	LLAvatarName av_name;
	if (LLAvatarNameCache::get(agent_id, &av_name))
	{
		return getName(av_name);
	}
	else
	{
		if (mAvatarNameCacheConnection.connected())
		{
			mAvatarNameCacheConnection.disconnect();
		}
		mAvatarNameCacheConnection = LLAvatarNameCache::get(agent_id, boost::bind(&LLUrlEntryAgentName::onAvatarNameCache, this, _1, _2));
		addObserver(agent_id_string, url, cb);
		return LLTrans::getString("LoadingData");
	}
}
コード例 #5
0
ファイル: GameObject.cpp プロジェクト: aaronmjacobs/tgil
void GameObject::setPhysicsComponent(SPtr<PhysicsComponent> physicsComponent) {
   this->physicsComponent = physicsComponent;
   physicsComponent->init();
   addObserver(physicsComponent);
}
コード例 #6
0
MainLayerStoreFrame::MainLayerStoreFrame(enumStore flag)
{
	mFlag = flag;
	mContentLayer = NULL;

	mBg = CCScale9Sprite::create("shangdian_bg.jpg");
	addChild(mBg);
	float h = mWinSize.height - BaseSprite::create("zhuangtailan_jinqian.png")->getContentSize().height
		- MainLayerBase::getCurrentMainBase()->getFooter()->getFooterSize().height;
	mBg->setContentSize(CCSize(mBg->getContentSize().width, h));
	mBg->setPosition(ccp(mWinSize.width/2,mBg->getContentSize().height/2));

	//创建按钮
	{
		CCMenuItemImage* shenbingItem = CCMenuItemImage::create(
			"shangdian_shenbin_dengdai.png",
			"shangdian_shenbin_anxia.png",
			"shangdian_shenbin_select.png",
			this,SEL_MenuHandler(&MainLayerStoreFrame::menuItemClicked));
// 		CCMenuItemImage* daojuItem = CCMenuItemImage::create(
// 			"shangdian_daoju_dengdai.png",
// 			"shangdian_daoju_anxia.png",
// 			"shangdian_daoju_select.png",
// 			this,SEL_MenuHandler(&MainLayerStoreFrame::menuItemClicked));
		CCMenuItemImage* libaoItem = CCMenuItemImage::create(
			"shangdian_libao_dengdai.png",
			"shangdian_libao_anxia.png",
			"shangdian_libao_select.png", 
			this,SEL_MenuHandler(&MainLayerStoreFrame::menuItemClicked));
		CCMenuItemImage* chongzhiItem = CCMenuItemImage::create(
			"shangdian_chongzhi_dengdai.png",
			"shangdian_chongzhi_anxia.png",
			"shangdian_chongzhi_select.png", 
			this,SEL_MenuHandler(&MainLayerStoreFrame::menuItemClicked));


		mMenu = CCMenu::create(shenbingItem, libaoItem, chongzhiItem, NULL);
//		mMenu->addChild(daojuItem);
		mBg->addChild(mMenu,1);
		mMenu->setPosition(CCPointZero);


		shenbingItem->setPosition(ccp(mBg->getContentSize().width/2-shenbingItem->getContentSize().width - 20, mBg->getContentSize().height-144));
		shenbingItem->setTag(TAG_ITEM_ShenBing);

//		daojuItem->setPosition(ccp(259,shenbingItem->getPositionY()));
//		daojuItem->setTag(TAG_ITEM_DAOJU);

		libaoItem->setPosition(ccp(mBg->getContentSize().width/2,shenbingItem->getPositionY()));
		libaoItem->setTag(TAG_ITEM_LiBao);

		chongzhiItem->setPosition(ccp(mBg->getContentSize().width/2+chongzhiItem->getContentSize().width + 20,shenbingItem->getPositionY()));
		chongzhiItem->setTag(TAG_ITEM_CHONGZHI);

	}

	//
	if(MarketManager::getManager()->itemCount() == 0)
	{
		//
		mMenu->setEnabled(false);

		//加载市场数据
		addObserver(SEL_CallFuncO(&MainLayerStoreFrame::getMarketInfoCallBack),MSG_getMarketInfoRsp);
		CmdHelper::getHelper()->cmdGetMarketInfo();
	}
	else
	{
		mFooterLayer = MainLayerBase::getCurrentMainBase();
		if (mFlag == store_ShenBing)
			menuItemClicked(mMenu->getChildByTag(TAG_ITEM_ShenBing));
		else if (mFlag == store_DaoJu)
			CCLOG("TAG_ITEM_DAOJU");
//			menuItemClicked(mMenu->getChildByTag(TAG_ITEM_DAOJU));
		else if (mFlag == store_LiBao)
			menuItemClicked(mMenu->getChildByTag(TAG_ITEM_LiBao));
		else if (mFlag == store_ChongZhi)
			menuItemClicked(mMenu->getChildByTag(TAG_ITEM_CHONGZHI));
	}
	
}
コード例 #7
0
void MailListTile::selectDelete(CCObject* obj)
{
	addObserver(callfuncO_selector(MailListTile::clickDeleteOK), MSG_DeleteEmailRsp);
	CmdHelper::getHelper()->cmdDeleteEmail(m_sSystemMail.email_id);
	
}
void BountyMissionObjectiveImplementation::addObserverToCreature(unsigned int observerType, CreatureObject* creature) {
	ManagedReference<MissionObserver*> observer = new MissionObserver(_this.getReferenceUnsafeStaticCast());
	addObserver(observer, true);

	creature->registerObserver(observerType, observer);
}
コード例 #9
0
ファイル: db.cpp プロジェクト: wpjunior/mongo
ExitCode _initAndListen(int listenPort) {
    Client::initThread("initandlisten");

    initWireSpec();
    auto serviceContext = getGlobalServiceContext();

    serviceContext->setFastClockSource(FastClockSourceFactory::create(Milliseconds(10)));
    auto opObserverRegistry = stdx::make_unique<OpObserverRegistry>();
    opObserverRegistry->addObserver(stdx::make_unique<OpObserverShardingImpl>());
    opObserverRegistry->addObserver(stdx::make_unique<UUIDCatalogObserver>());

    if (serverGlobalParams.clusterRole == ClusterRole::ShardServer) {
        opObserverRegistry->addObserver(stdx::make_unique<ShardServerOpObserver>());
    } else if (serverGlobalParams.clusterRole == ClusterRole::ConfigServer) {
        opObserverRegistry->addObserver(stdx::make_unique<ConfigServerOpObserver>());
    }
    setupFreeMonitoringOpObserver(opObserverRegistry.get());


    serviceContext->setOpObserver(std::move(opObserverRegistry));

    DBDirectClientFactory::get(serviceContext).registerImplementation([](OperationContext* opCtx) {
        return std::unique_ptr<DBClientBase>(new DBDirectClient(opCtx));
    });

    const repl::ReplSettings& replSettings =
        repl::ReplicationCoordinator::get(serviceContext)->getSettings();

    {
        ProcessId pid = ProcessId::getCurrent();
        LogstreamBuilder l = log(LogComponent::kControl);
        l << "MongoDB starting : pid=" << pid << " port=" << serverGlobalParams.port
          << " dbpath=" << storageGlobalParams.dbpath;

        const bool is32bit = sizeof(int*) == 4;
        l << (is32bit ? " 32" : " 64") << "-bit host=" << getHostNameCached() << endl;
    }

    DEV log(LogComponent::kControl) << "DEBUG build (which is slower)" << endl;

#if defined(_WIN32)
    VersionInfoInterface::instance().logTargetMinOS();
#endif

    logProcessDetails();

    serviceContext->setServiceEntryPoint(
        stdx::make_unique<ServiceEntryPointMongod>(serviceContext));

    if (!storageGlobalParams.repair) {
        auto tl =
            transport::TransportLayerManager::createWithConfig(&serverGlobalParams, serviceContext);
        auto res = tl->setup();
        if (!res.isOK()) {
            error() << "Failed to set up listener: " << res;
            return EXIT_NET_ERROR;
        }
        serviceContext->setTransportLayer(std::move(tl));
    }

    // Set up the periodic runner for background job execution. This is required to be running
    // before the storage engine is initialized.
    auto runner = makePeriodicRunner(serviceContext);
    runner->startup();
    serviceContext->setPeriodicRunner(std::move(runner));

    initializeStorageEngine(serviceContext, StorageEngineInitFlags::kNone);

#ifdef MONGO_CONFIG_WIREDTIGER_ENABLED
    if (EncryptionHooks::get(serviceContext)->restartRequired()) {
        exitCleanly(EXIT_CLEAN);
    }
#endif

    // Warn if we detect configurations for multiple registered storage engines in the same
    // configuration file/environment.
    if (serverGlobalParams.parsedOpts.hasField("storage")) {
        BSONElement storageElement = serverGlobalParams.parsedOpts.getField("storage");
        invariant(storageElement.isABSONObj());
        for (auto&& e : storageElement.Obj()) {
            // Ignore if field name under "storage" matches current storage engine.
            if (storageGlobalParams.engine == e.fieldName()) {
                continue;
            }

            // Warn if field name matches non-active registered storage engine.
            if (isRegisteredStorageEngine(serviceContext, e.fieldName())) {
                warning() << "Detected configuration for non-active storage engine "
                          << e.fieldName() << " when current storage engine is "
                          << storageGlobalParams.engine;
            }
        }
    }

    // Disallow running a storage engine that doesn't support capped collections with --profile
    if (!serviceContext->getStorageEngine()->supportsCappedCollections() &&
        serverGlobalParams.defaultProfile != 0) {
        log() << "Running " << storageGlobalParams.engine << " with profiling is not supported. "
              << "Make sure you are not using --profile.";
        exitCleanly(EXIT_BADOPTIONS);
    }

    // Disallow running WiredTiger with --nojournal in a replica set
    if (storageGlobalParams.engine == "wiredTiger" && !storageGlobalParams.dur &&
        replSettings.usingReplSets()) {
        log() << "Running wiredTiger without journaling in a replica set is not "
              << "supported. Make sure you are not using --nojournal and that "
              << "storage.journal.enabled is not set to 'false'.";
        exitCleanly(EXIT_BADOPTIONS);
    }

    logMongodStartupWarnings(storageGlobalParams, serverGlobalParams, serviceContext);

#ifdef MONGO_CONFIG_SSL
    if (sslGlobalParams.sslAllowInvalidCertificates &&
        ((serverGlobalParams.clusterAuthMode.load() == ServerGlobalParams::ClusterAuthMode_x509) ||
         sequenceContains(saslGlobalParams.authenticationMechanisms, "MONGODB-X509"))) {
        log() << "** WARNING: While invalid X509 certificates may be used to" << startupWarningsLog;
        log() << "**          connect to this server, they will not be considered"
              << startupWarningsLog;
        log() << "**          permissible for authentication." << startupWarningsLog;
        log() << startupWarningsLog;
    }
#endif

    {
        std::stringstream ss;
        ss << endl;
        ss << "*********************************************************************" << endl;
        ss << " ERROR: dbpath (" << storageGlobalParams.dbpath << ") does not exist." << endl;
        ss << " Create this directory or give existing directory in --dbpath." << endl;
        ss << " See http://dochub.mongodb.org/core/startingandstoppingmongo" << endl;
        ss << "*********************************************************************" << endl;
        uassert(10296, ss.str().c_str(), boost::filesystem::exists(storageGlobalParams.dbpath));
    }

    initializeSNMP();

    if (!storageGlobalParams.readOnly) {
        boost::filesystem::remove_all(storageGlobalParams.dbpath + "/_tmp/");
    }

    if (mongodGlobalParams.scriptingEnabled) {
        ScriptEngine::setup();
    }

    auto startupOpCtx = serviceContext->makeOperationContext(&cc());

    bool canCallFCVSetIfCleanStartup =
        !storageGlobalParams.readOnly && (storageGlobalParams.engine != "devnull");
    if (canCallFCVSetIfCleanStartup && !replSettings.usingReplSets()) {
        Lock::GlobalWrite lk(startupOpCtx.get());
        FeatureCompatibilityVersion::setIfCleanStartup(startupOpCtx.get(),
                                                       repl::StorageInterface::get(serviceContext));
    }

    auto swNonLocalDatabases = repairDatabasesAndCheckVersion(startupOpCtx.get());
    if (!swNonLocalDatabases.isOK()) {
        // SERVER-31611 introduced a return value to `repairDatabasesAndCheckVersion`. Previously,
        // a failing condition would fassert. SERVER-31611 covers a case where the binary (3.6) is
        // refusing to start up because it refuses acknowledgement of FCV 3.2 and requires the
        // user to start up with an older binary. Thus shutting down the server must leave the
        // datafiles in a state that the older binary can start up. This requires going through a
        // clean shutdown.
        //
        // The invariant is *not* a statement that `repairDatabasesAndCheckVersion` must return
        // `MustDowngrade`. Instead, it is meant as a guardrail to protect future developers from
        // accidentally buying into this behavior. New errors that are returned from the method
        // may or may not want to go through a clean shutdown, and they likely won't want the
        // program to return an exit code of `EXIT_NEED_DOWNGRADE`.
        severe(LogComponent::kControl) << "** IMPORTANT: "
                                       << swNonLocalDatabases.getStatus().reason();
        invariant(swNonLocalDatabases == ErrorCodes::MustDowngrade);
        exitCleanly(EXIT_NEED_DOWNGRADE);
    }

    // Assert that the in-memory featureCompatibilityVersion parameter has been explicitly set. If
    // we are part of a replica set and are started up with no data files, we do not set the
    // featureCompatibilityVersion until a primary is chosen. For this case, we expect the in-memory
    // featureCompatibilityVersion parameter to still be uninitialized until after startup.
    if (canCallFCVSetIfCleanStartup &&
        (!replSettings.usingReplSets() || swNonLocalDatabases.getValue())) {
        invariant(serverGlobalParams.featureCompatibility.isVersionInitialized());
    }

    if (storageGlobalParams.upgrade) {
        log() << "finished checking dbs";
        exitCleanly(EXIT_CLEAN);
    }

    // Start up health log writer thread.
    HealthLog::get(startupOpCtx.get()).startup();

    auto const globalAuthzManager = AuthorizationManager::get(serviceContext);
    uassertStatusOK(globalAuthzManager->initialize(startupOpCtx.get()));

    // This is for security on certain platforms (nonce generation)
    srand((unsigned)(curTimeMicros64()) ^ (unsigned(uintptr_t(&startupOpCtx))));

    if (globalAuthzManager->shouldValidateAuthSchemaOnStartup()) {
        Status status = verifySystemIndexes(startupOpCtx.get());
        if (!status.isOK()) {
            log() << redact(status);
            if (status == ErrorCodes::AuthSchemaIncompatible) {
                exitCleanly(EXIT_NEED_UPGRADE);
            } else if (status == ErrorCodes::NotMaster) {
                // Try creating the indexes if we become master.  If we do not become master,
                // the master will create the indexes and we will replicate them.
            } else {
                quickExit(EXIT_FAILURE);
            }
        }

        // SERVER-14090: Verify that auth schema version is schemaVersion26Final.
        int foundSchemaVersion;
        status =
            globalAuthzManager->getAuthorizationVersion(startupOpCtx.get(), &foundSchemaVersion);
        if (!status.isOK()) {
            log() << "Auth schema version is incompatible: "
                  << "User and role management commands require auth data to have "
                  << "at least schema version " << AuthorizationManager::schemaVersion26Final
                  << " but startup could not verify schema version: " << status;
            log() << "To manually repair the 'authSchema' document in the admin.system.version "
                     "collection, start up with --setParameter "
                     "startupAuthSchemaValidation=false to disable validation.";
            exitCleanly(EXIT_NEED_UPGRADE);
        }

        if (foundSchemaVersion <= AuthorizationManager::schemaVersion26Final) {
            log() << "This server is using MONGODB-CR, an authentication mechanism which "
                  << "has been removed from MongoDB 4.0. In order to upgrade the auth schema, "
                  << "first downgrade MongoDB binaries to version 3.6 and then run the "
                  << "authSchemaUpgrade command. "
                  << "See http://dochub.mongodb.org/core/3.0-upgrade-to-scram-sha-1";
            exitCleanly(EXIT_NEED_UPGRADE);
        }
    } else if (globalAuthzManager->isAuthEnabled()) {
        error() << "Auth must be disabled when starting without auth schema validation";
        exitCleanly(EXIT_BADOPTIONS);
    } else {
        // If authSchemaValidation is disabled and server is running without auth,
        // warn the user and continue startup without authSchema metadata checks.
        log() << startupWarningsLog;
        log() << "** WARNING: Startup auth schema validation checks are disabled for the "
                 "database."
              << startupWarningsLog;
        log() << "**          This mode should only be used to manually repair corrupted auth "
                 "data."
              << startupWarningsLog;
    }

    // This function may take the global lock.
    auto shardingInitialized = ShardingInitializationMongoD::get(startupOpCtx.get())
                                   ->initializeShardingAwarenessIfNeeded(startupOpCtx.get());
    if (shardingInitialized) {
        waitForShardRegistryReload(startupOpCtx.get()).transitional_ignore();
    }

    auto storageEngine = serviceContext->getStorageEngine();
    invariant(storageEngine);
    BackupCursorHooks::initialize(serviceContext, storageEngine);

    if (!storageGlobalParams.readOnly) {

        if (storageEngine->supportsCappedCollections()) {
            logStartup(startupOpCtx.get());
        }

        startMongoDFTDC();

        startFreeMonitoring(serviceContext);

        restartInProgressIndexesFromLastShutdown(startupOpCtx.get());

        if (serverGlobalParams.clusterRole == ClusterRole::ShardServer) {
            // Note: For replica sets, ShardingStateRecovery happens on transition to primary.
            if (!repl::ReplicationCoordinator::get(startupOpCtx.get())->isReplEnabled()) {
                if (ShardingState::get(startupOpCtx.get())->enabled()) {
                    uassertStatusOK(ShardingStateRecovery::recover(startupOpCtx.get()));
                }
            }
        } else if (serverGlobalParams.clusterRole == ClusterRole::ConfigServer) {
            initializeGlobalShardingStateForMongoD(startupOpCtx.get(),
                                                   ConnectionString::forLocal(),
                                                   kDistLockProcessIdForConfigServer);

            Balancer::create(startupOpCtx->getServiceContext());

            ShardingCatalogManager::create(
                startupOpCtx->getServiceContext(),
                makeShardingTaskExecutor(executor::makeNetworkInterface("AddShard-TaskExecutor")));

            Grid::get(startupOpCtx.get())->setShardingInitialized();
        } else if (replSettings.usingReplSets()) {  // standalone replica set
            auto keysCollectionClient = stdx::make_unique<KeysCollectionClientDirect>();
            auto keyManager = std::make_shared<KeysCollectionManager>(
                KeysCollectionManager::kKeyManagerPurposeString,
                std::move(keysCollectionClient),
                Seconds(KeysRotationIntervalSec));
            keyManager->startMonitoring(startupOpCtx->getServiceContext());

            LogicalTimeValidator::set(startupOpCtx->getServiceContext(),
                                      stdx::make_unique<LogicalTimeValidator>(keyManager));
        }

        repl::ReplicationCoordinator::get(startupOpCtx.get())->startup(startupOpCtx.get());
        const unsigned long long missingRepl =
            checkIfReplMissingFromCommandLine(startupOpCtx.get());
        if (missingRepl) {
            log() << startupWarningsLog;
            log() << "** WARNING: mongod started without --replSet yet " << missingRepl
                  << " documents are present in local.system.replset." << startupWarningsLog;
            log() << "**          Database contents may appear inconsistent with the oplog and may "
                     "appear to not contain"
                  << startupWarningsLog;
            log() << "**          writes that were visible when this node was running as part of a "
                     "replica set."
                  << startupWarningsLog;
            log() << "**          Restart with --replSet unless you are doing maintenance and no "
                     "other clients are connected."
                  << startupWarningsLog;
            log() << "**          The TTL collection monitor will not start because of this."
                  << startupWarningsLog;
            log() << "**         ";
            log() << " For more info see http://dochub.mongodb.org/core/ttlcollections";
            log() << startupWarningsLog;
        } else {
            startTTLBackgroundJob();
        }

        if (replSettings.usingReplSets() || !internalValidateFeaturesAsMaster) {
            serverGlobalParams.validateFeaturesAsMaster.store(false);
        }
    }

    startClientCursorMonitor();

    PeriodicTask::startRunningPeriodicTasks();

    SessionKiller::set(serviceContext,
                       std::make_shared<SessionKiller>(serviceContext, killSessionsLocal));

    // Start up a background task to periodically check for and kill expired transactions; and a
    // background task to periodically check for and decrease cache pressure by decreasing the
    // target size setting for the storage engine's window of available snapshots.
    //
    // Only do this on storage engines supporting snapshot reads, which hold resources we wish to
    // release periodically in order to avoid storage cache pressure build up.
    if (storageEngine->supportsReadConcernSnapshot()) {
        startPeriodicThreadToAbortExpiredTransactions(serviceContext);
        startPeriodicThreadToDecreaseSnapshotHistoryCachePressure(serviceContext);
    }

    // Set up the logical session cache
    LogicalSessionCacheServer kind = LogicalSessionCacheServer::kStandalone;
    if (serverGlobalParams.clusterRole == ClusterRole::ShardServer) {
        kind = LogicalSessionCacheServer::kSharded;
    } else if (serverGlobalParams.clusterRole == ClusterRole::ConfigServer) {
        kind = LogicalSessionCacheServer::kConfigServer;
    } else if (replSettings.usingReplSets()) {
        kind = LogicalSessionCacheServer::kReplicaSet;
    }

    auto sessionCache = makeLogicalSessionCacheD(kind);
    LogicalSessionCache::set(serviceContext, std::move(sessionCache));

    // MessageServer::run will return when exit code closes its socket and we don't need the
    // operation context anymore
    startupOpCtx.reset();

    auto start = serviceContext->getServiceExecutor()->start();
    if (!start.isOK()) {
        error() << "Failed to start the service executor: " << start;
        return EXIT_NET_ERROR;
    }

    start = serviceContext->getServiceEntryPoint()->start();
    if (!start.isOK()) {
        error() << "Failed to start the service entry point: " << start;
        return EXIT_NET_ERROR;
    }

    if (!storageGlobalParams.repair) {
        start = serviceContext->getTransportLayer()->start();
        if (!start.isOK()) {
            error() << "Failed to start the listener: " << start.toString();
            return EXIT_NET_ERROR;
        }
    }

    serviceContext->notifyStartupComplete();

#ifndef _WIN32
    mongo::signalForkSuccess();
#else
    if (ntservice::shouldStartService()) {
        ntservice::reportStatus(SERVICE_RUNNING);
        log() << "Service running";
    }
#endif

    if (MONGO_FAIL_POINT(shutdownAtStartup)) {
        log() << "starting clean exit via failpoint";
        exitCleanly(EXIT_CLEAN);
    }

    MONGO_IDLE_THREAD_BLOCK;
    return waitForShutdown();
}
コード例 #10
0
ファイル: GameState.cpp プロジェクト: John-Chan/crush
void GameState::addMapBody(const Map::Node& n)
{
    switch (n.type)
    {
    case Category::Block:
        addBlock(n.position, n.size);
        break;
    case Category::Solid:
    {
        auto node = std::make_unique<Node>();
        node->setPosition(n.position);
        node->setCollisionBody(m_collisionWorld.addBody(CollisionWorld::Body::Solid, n.size));
        m_scene.addNode(node, Scene::Solid);
    }
        break;
    case Category::Water:
    {
        auto node = std::make_unique<Node>();
        node->setPosition(n.position);
        auto drawable = static_cast<WaterDrawable*>(m_mapController.getDrawable(MapController::MapDrawable::Water));
        drawable->setSize(n.size);
        node->setDrawable(drawable);
        node->setCollisionBody(m_collisionWorld.addBody(CollisionWorld::Body::Water, n.size));
        node->addObserver(m_particleController);
        m_scene.addNode(node, Scene::Water);
    }
        break;
    case Category::Item:
    {
        auto node = std::make_unique<Node>();
        node->setPosition(n.position);
        node->setCategory(Category::Item);
        node->setDrawable(m_mapController.getDrawable(MapController::MapDrawable::Item));
        node->setCollisionBody(m_collisionWorld.addBody(CollisionWorld::Body::Item, n.size));
        node->addObserver(m_particleController);
        node->addObserver(m_audioController);

        auto light = m_scene.addLight(sf::Vector3f(0.34f, 0.96f, 1.f), 400.f);
        if (light)
        {
            light->setDepth(50.f);
            node->setLight(light);
        }
        node->setBlendMode(sf::BlendAdd);
        m_scene.addNode(node, Scene::DynamicFront);
    }
        break;
    case Category::Light:
    {
        auto node = std::make_unique<Node>();
        node->setCategory(Category::Light);
        //TODO magix0r numb0rz
        auto light = m_scene.addLight(colourToVec3(n.colour), 700.f);
        light->setDepth(50.f);
        node->setLight(light);
        node->setPosition(n.position + (n.size / 2.f));
        node->addObserver(*light);
        node->setDrawable(&lightDrawable);
        node->setBlendMode(sf::BlendAlpha);

        //if (n.anchorOffset) //TODO make not broken (see contraint solve())
        //{
        //    //we want a constraint on this light
        //    node->setCollisionBody(m_collisionWorld.addBody(CollisionWorld::Body::Type::FreeForm, { lightDrawable.getRadius(), lightDrawable.getRadius() }));

        //    auto anchorNode = std::make_unique<Node>();
        //    anchorNode->setPosition(n.position);
        //    anchorNode->move(0.f, -n.anchorOffset);
        //    anchorNode->setCollisionBody(m_collisionWorld.addBody(CollisionWorld::Body::Type::Anchor, { lightDrawable.getRadius(), lightDrawable.getRadius() }));
        //    anchorNode->setDrawable(&c1);

        //    m_collisionWorld.addConstraint(anchorNode->getCollisionBody(), node->getCollisionBody(), n.anchorOffset);
        //    m_scene.addNode(anchorNode);
        //}

        m_scene.addNode(node, Scene::Background);
        break;
    }

    case Category::HatDropped:
    {
        auto node = std::make_unique<Node>();
        node->setPosition(n.position);
        node->setDrawable(m_mapController.getDrawable(MapController::MapDrawable::Hat));
        node->setCollisionBody(m_collisionWorld.addBody(CollisionWorld::Body::Type::FreeForm, n.size));
        node->setCategory(n.type);
        auto light = m_scene.addLight(sf::Vector3f(1.f, 0.9f, 0.f), 200.f);
        light->setDepth(50.f);
        node->setLight(light);

        node->addObserver(m_particleController);
        node->addObserver(m_audioController);
        node->addObserver(m_mapController);
        node->addObserver(m_scoreBoard);
        node->addObserver(m_players[0]);
        node->addObserver(m_players[1]);

        m_scene.addNode(node, Scene::DynamicFront);
        break;
    }
    case Category::Bat:
    case Category::Bird:
    {
        auto node = std::make_unique<Node>();
        node->setPosition(n.position);
        node->setCategory(n.type);
        node->setDrawable(m_mapController.getDrawable((n.type == Category::Bat) ? MapController::MapDrawable::Bat : MapController::MapDrawable::Bird));
        m_scene.addNode(node, Scene::FrontDetail);
        break;
    }
    default: break;
    }
}
void EntertainerMissionObjectiveImplementation::activate() {
	Locker _lock(_this.getReferenceUnsafeStaticCast());

	ManagedReference<MissionObject* > mission = this->mission.get();

	MissionObjectiveImplementation::activate();

	if (hasObservers()) {
		return;
	}

	if (mission == NULL)
		return;

	ManagedReference<ZoneServer*> zoneServer = Core::lookupObject<ZoneServer>("ZoneServer");

	if (locationActiveArea == NULL) {
		locationActiveArea = ( zoneServer->createObject(STRING_HASHCODE("object/active_area.iff"), 1)).castTo<ActiveArea*>();
	}

	if (!locationActiveArea->isInQuadTree()) {
		String planetName = mission->getStartPlanet();

		Zone* zone = zoneServer->getZone(planetName);

		Locker locker(locationActiveArea);

		locationActiveArea->initializePosition(mission->getStartPositionX(), 0, mission->getStartPositionY());
		locationActiveArea->setRadius(32.f);

		if (zone != NULL) {
			zone->transferObject(locationActiveArea, -1, true);
		} else {
			error("Failed to insert entertainer location to zone.");
			abort();
			return;
		}
	}

	Locker locationLocker(locationActiveArea);

	ManagedReference<MissionObserver*> observer1 = new MissionObserver(_this.getReferenceUnsafeStaticCast());
	addObserver(observer1, true);
	locationActiveArea->registerObserver(ObserverEventType::ENTEREDAREA, observer1);

	ManagedReference<MissionObserver*> observer2 = new MissionObserver(_this.getReferenceUnsafeStaticCast());
	addObserver(observer2, true);
	locationActiveArea->registerObserver(ObserverEventType::EXITEDAREA, observer2);

	locationLocker.release();

	WaypointObject* waypoint = mission->getWaypointToMission();

	if (waypoint == NULL) {
		Locker mlocker(mission);
		waypoint = mission->createWaypoint();
	}

	Locker wplocker(waypoint);

	waypoint->setPlanetCRC(mission->getStartPlanetCRC());
	waypoint->setPosition(mission->getStartPositionX(), 0, mission->getStartPositionY());
	waypoint->setActive(true);

	mission->updateMissionLocation();
}
void DestroyMissionObjectiveImplementation::spawnLair() {
	ManagedReference<MissionObject* > mission = this->mission.get();

	ManagedReference<MissionSpawnActiveArea* > spawnActiveArea = this->spawnActiveArea;

	if (spawnActiveArea == NULL)
		return;

	if (lairObject != NULL && lairObject->getZone() != NULL)
		return;

	Zone* zone = spawnActiveArea->getZone();

	Locker locker(spawnActiveArea);

	spawnActiveArea->destroyObjectFromWorld(true);

	Vector3 pos = findValidSpawnPosition(zone);

	ManagedReference<WaypointObject*> waypoint = mission->getWaypointToMission();

	if (waypoint == NULL) {
		waypoint = mission->createWaypoint();
	}

	waypoint->setPosition(pos.getX(), 0, pos.getY());
	mission->updateMissionLocation();

	mission->setStartPosition(pos.getX(), pos.getY());

	//TODO: find correct string id
	ManagedReference<CreatureObject*> player = getPlayerOwner();

	if (player != NULL) {
		player->sendSystemMessage("Transmission Received: Mission Target has been located.  Mission waypoint has been updated to exact location");
	}

	LairTemplate* lair = CreatureTemplateManager::instance()->getLairTemplate(lairTemplate.hashCode());

	if (lair == NULL) {
		error("incorrect lair template in destroy mission objective " + lairTemplate);
		abort();
		return;
	}

	if (lairObject == NULL) {
		String buildingToSpawn = lair->getMissionBuilding(difficulty);

	 	if (buildingToSpawn.isEmpty()) {
	 		error("error spawning " + buildingToSpawn);
	 		abort();
	 		return;
	 	}

		lairObject = zone->getZoneServer()->createObject(buildingToSpawn.hashCode(), 0).castTo<LairObject*>();

	 	if (lairObject == NULL) {
	 		error("error spawning " + buildingToSpawn);
	 		abort();
	 		return;
	 	}

	 	Locker locker(lairObject);

	 	lairObject->setFaction(lair->getFaction());
	 	lairObject->setPvpStatusBitmask(CreatureFlag::ATTACKABLE);
	 	lairObject->setOptionsBitmask(0, false);
	 	lairObject->setMaxCondition(difficultyLevel * (900 + System::random(200)));
	 	lairObject->setConditionDamage(0, false);
	 	lairObject->initializePosition(pos.getX(), pos.getZ(), pos.getY());
	 	lairObject->setDespawnOnNoPlayersInRange(false);

		ManagedReference<MissionObserver*> observer = new MissionObserver(_this.get());
		addObserver(observer, true);

		lairObject->registerObserver(ObserverEventType::OBJECTDESTRUCTION, observer);

	 	ManagedReference<DestroyMissionLairObserver*> lairObserver = new DestroyMissionLairObserver();
	 	lairObserver->deploy();
	 	lairObserver->setLairTemplate(lair);
	 	lairObserver->setDifficulty(difficulty);
	 	lairObserver->setObserverType(ObserverType::LAIR);
	 	lairObserver->setSize(mission->getSize());

	 	lairObject->registerObserver(ObserverEventType::OBJECTDESTRUCTION, lairObserver);
	 	lairObject->registerObserver(ObserverEventType::DAMAGERECEIVED, lairObserver);
	 	lairObject->registerObserver(ObserverEventType::AIMESSAGE, lairObserver);
	 	lairObject->registerObserver(ObserverEventType::OBJECTREMOVEDFROMZONE, lairObserver);

		zone->transferObject(lairObject, -1, true);

		lairObserver->checkForNewSpawns(lairObject, NULL, true);
	}

	if (lairObject != NULL && lairObject->getZone() == NULL) {
		zone->transferObject(lairObject, -1, true);
	}
}
コード例 #13
0
ファイル: controller.cpp プロジェクト: maurisvh/SpaceInvaders
 void Controller::registerGame(model::Game *game) {
     addObserver(game);
 }
コード例 #14
0
ファイル: GameObject.cpp プロジェクト: aaronmjacobs/tgil
void GameObject::setAudioComponent(SPtr<AudioComponent> audioComponent) {
   this->audioComponent = audioComponent;
   addObserver(audioComponent);
}
コード例 #15
0
ファイル: HCommonObject.cpp プロジェクト: hyizsg/mytest1st
void HCommonObject::addObserver(SEL_CallFuncO sel, int cmdid)
{
    addObserver(sel, itoa(cmdid));
}
コード例 #16
0
ファイル: HCommonObject.cpp プロジェクト: hyizsg/mytest1st
void HCommonObject::addObserver(const char *cmdstr)
{
    addObserver(callfuncO_selector(HCommonObject::notifyActionMsg), cmdstr);
}
コード例 #17
0
ファイル: HCommonObject.cpp プロジェクト: hyizsg/mytest1st
void HCommonObject:: addObserver(int cmdid)
{
    addObserver(itoa(cmdid));
}
コード例 #18
0
FileTransferModule_Impl::FileTransferModule_Impl()
    :m_pFileTransferDialog(0)
{
    TransferFileEntityManager::getInstance()->startup();
    addObserver(this, BIND_CALLBACK_2(FileTransferModule_Impl::MKOForFileTransferModuleCallback));
}
コード例 #19
0
ファイル: TanSuoLayer.cpp プロジェクト: longguai/game-DarkWar
void TanSuoLayer::menuItemClicked_TanSuo(CCObject *pSender)
{
	int tag = ((CCMenuItem*)pSender)->getTag();

	if (tag == Tag_MenuItem_YiJianTanSuo)
	{
		if (m_bIsJieFeng)
		{
			string infoStr = LFStrings::getValue("XuYaoJieFeng");
			UnblockWarnDialog* pDlg = UnblockWarnDialog::create(infoStr);
			CCDirector::sharedDirector()->getRunningScene()->addChild(pDlg, 300);
			return;
		}
		if (MyselfManager::getManager()->getMyZhuJueData()->getVipLevel() < 3)
		{
			FXToast *layer = FXToast::create(LFStrings::getValue("XunBao_VipNeed"));
			CCDirector::sharedDirector()->getRunningScene()->addChild(layer);
			return;
		}

		m_bDiscoverAll = true;
		addObserver(callfuncO_selector(TanSuoLayer::rsp_tansuo), MSG_discoverRsp);
		mCmdHlp->cmdDiscover(m_bDiscoverAll);
	}
	else if (tag == Tag_MenuItem_TanSuo)
	{
		m_bDiscoverAll = false;
		addObserver(callfuncO_selector(TanSuoLayer::rsp_tansuo), MSG_discoverRsp);
		mCmdHlp->cmdDiscover(m_bDiscoverAll);
	}
	else if (tag == Tag_MenuItem_JieFen)
	{
		if (mDestroyCount >= m_nMaxCountDestroy)
		{
			m_bIsJieFeng = true;
			m_nSelectProId = -1;
			if (! EquipmentManager::getManager()->isSpareEnoughToSaveEquip(1))
			{
				EquipBagNotEnoughDialog *layer = new EquipBagNotEnoughDialog;
				layer->showGoToFenJieDialog();
			}


			CCSize visSize = CCDirector::sharedDirector()->getWinSize();
			BaseSprite* dialog = BaseSprite::create("juqing_duihuakuang.png");
			dialog->setPosition(ccp(visSize.width/2, visSize.height/2));
			//label 提示
			{
				/*CCLabelTTF* label = CCLabelTTF::create(LFStrings::getValue("XunBao_XuanZeHeroTiShi").c_str(), 
				fontStr_kaiti, m_nFontSize, CCSize(425, 0), kCCTextAlignmentLeft);
				label->setAnchorPoint(ccp(0.5, 1));
				label->setPosition(ccp(dialog->getContentSize().width/2, 250));
				dialog->addChild(label, 1);*/

				CCLabelTTF *title = CCLabelTTF::create(LFStrings::getValue("JieChuFengYin").c_str(),fontStr_kaiti,m_nFontSize);
				title->setAnchorPoint(ccp(0.5,1));
				title->setPosition(ccp(dialog->getContentSize().width/2, 250));
				dialog->addChild(title, 1);


				CCLabelTTF *chuanqi = CCLabelTTF::create(LFStrings::getValue("ChuanQiZhuangBei").c_str(),fontStr_kaiti,m_nFontSize);
				chuanqi->setAnchorPoint(ccp(0.5,1));
				chuanqi->setPosition(ccp(title->getPositionX() - title->getContentSize().width / 2 + m_nFontSize * 7 + chuanqi->getContentSize().width / 2, 250));
				dialog->addChild(chuanqi, 1);
				chuanqi->setColor(ccc3(235,106,12));
			}
			{
				m_lMenuItemList.clear();
				//mHeros = MyselfManager::getManager()->getTeamActors_ZhenShen(Actor_All, LF_UnLock);
				mHeros = MyselfManager::getManager()->getTeamActors_ZhenShen(Actor_ShangZheng, LF_UnLock);
				//tabel view
				CCTableView *tabelView = CCTableView::create(this, CCSizeMake(560, 158));
				tabelView->setDirection(kCCScrollViewDirectionHorizontal);
				tabelView->setPosition(ccp(41, 44));
				tabelView->setDelegate(this);
				dialog->addChild(tabelView);
				tabelView->reloadData();
			}
			//确认 取消按键  
			CCMenu* menu = CCMenu::create();
			menu->setPosition(CCPointZero);
			menu->setTag(0);
			//
			{
				LFAlert* lfAlert = new LFAlert();
				lfAlert->setTag(TAG_AwardDisplayer_Layer);
				lfAlert->setBaseContainer(dialog,menu);
				lfAlert->setZoneCanotTouch();
				CCDirector::sharedDirector()->getRunningScene()->addChild(lfAlert,128, TAG_AwardDisplayer_Layer);
				lfAlert->release();
			}
			return;
		}
		else
		{
			MessageDisplay* layer = MessageDisplay::create("ERROR!");
			CCDirector::sharedDirector()->getRunningScene()->addChild(layer);
			return;
		}
	}
}
コード例 #20
0
ファイル: Brave.cpp プロジェクト: shvanceinfo/GameResource
// on "init" you need to initialize your instance
bool Brave::init()
{
	//////////////////////////////
	// 1. super init first
	if (!Layer::init())
	{
		return false;
	}

	SpriteFrameCache::getInstance()->addSpriteFramesWithFile("ui.plist", "ui.pvr.ccz");
	SpriteFrameCache::getInstance()->addSpriteFramesWithFile("role.plist", "role.pvr.ccz");

	Size visibleSize = Director::getInstance()->getVisibleSize();
	Vec2 origin = Director::getInstance()->getVisibleOrigin();

// 	Sprite * background = Sprite::create("background.png");
// 	background->setPosition(origin + visibleSize / 2);
// 	this->addChild(background);
	

// 	player = Player::create(Player::PlayerType::PLAYER);
// 	player->setPosition(origin.x + player->getContentSize().width / 2, origin.y + visibleSize.height / 2);
// 	this->addChild(player);
// 
// 	enemy1 = Player::create(Player::PlayerType::ENEMY1);
// 	enemy1->setPosition(origin.x + visibleSize.width - player->getContentSize().width / 2, origin.y + visibleSize.height / 2);
// 	this->addChild(enemy1);
// 
// 	enemy2 = Player::create(Player::PlayerType::ENEMY2);
// 	enemy2->setPosition(VisibleRect::right().x - player->getContentSize().width / 2, VisibleRect::top().y / 2);
// 	this->addChild(enemy2);

	//player->playAnimationForever(1);
	//enemy1->playAnimationForever(1);
	//enemy2->playAnimationForever(1);

// 	_listener_touch = EventListenerTouchOneByOne::create();
// 	_listener_touch->onTouchBegan = CC_CALLBACK_2(Brave::onTouchBegan, this);
// 	_eventDispatcher->addEventListenerWithSceneGraphPriority(_listener_touch, this);
// 
// 	//auto fsm = fsm::FSM::create("idle", [](){cocos2d::log("enter idle"); });
// 
// 	_listener_contact = EventListenerPhysicsContact::create();
// 	_listener_contact->onContactBegin = CC_CALLBACK_1(Brave::onContactBegin, this);
// 	_listener_contact->onContactSeperate = CC_CALLBACK_1(Brave::onContactSeperate, this);
// 	_eventDispatcher->addEventListenerWithFixedPriority(_listener_contact, 10);
// 
// 	NotificationCenter::getInstance()->addObserver(this, callfuncO_selector(Brave::clickEnemy), "clickEnemy", nullptr);


// 	process = Progress::create("player-progress-bg.png", "player-progress-fill.png");
// 	process->setPosition(VisibleRect::left().x + process->getContentSize().width /2, VisibleRect::top().y - process->getContentSize().height / 2);
// 	this->addChild(process);
// 
// 	auto pauseItem = CustomTool::createMenuItemImage("pause1.png", "pause2.png",CC_CALLBACK_1(Brave::onTouchPause,this));
// 	pauseItem->setPosition(VisibleRect::right().x - pauseItem->getContentSize().width / 2, VisibleRect::top().y - pauseItem->getContentSize().height / 2);
// 
// 	auto debugItem = MenuItemImage::create("CloseNormal.png", "CloseSelected.png", CC_CALLBACK_1(Brave::toggleDebug, this));
// 	debugItem->setScale(2.0);
// 	debugItem->setPosition(Vec2(VisibleRect::right().x - debugItem->getContentSize().width - pauseItem->getContentSize().width,
// 		VisibleRect::top().y - debugItem->getContentSize().height));
// 
// 	//_menu = Menu::create(pauseItem, NULL);
// 	_menu = Menu::create(pauseItem, debugItem, NULL);
// 
// 	_menu->setPosition(0, 0);
// 	this->addChild(_menu);
	initLevel();
	addRoles();
	addUI();
	addListener();
	addObserver();

	//this->schedule(schedule_selector(Brave::enemyMove), 1);
	this->schedule(schedule_selector(Brave::enemyMove, 3));
	this->scheduleUpdate();
    return true;
}