Dali::Adaptor& Adaptor::Get()
{
  DALI_ASSERT_ALWAYS( IsAvailable() && "Adaptor not instantiated" );
  return gThreadLocalAdaptor->mAdaptor;
}
bool
CombatAction::IsAvailable() const
{
	CombatAction* pThis = (CombatAction*) this;

	if (rval < 0) {
		pThis->rval = (int) Random(0, 100);

		if (rval > probability)
		pThis->status = SKIPPED;
	}

	if (status != PENDING)
	return false;

	if (min_rank > 0 || max_rank < 100) {
		Player* player = Player::GetCurrentPlayer();

		if (player->Rank() < min_rank || player->Rank() > max_rank)
		return false;
	}

	Campaign* campaign = Campaign::GetCampaign();
	if (campaign) {
		if (campaign->GetTime() < start_after) {
			return false;
		}

		if (campaign->GetTime() > start_before) {
			pThis->status = FAILED; // too late!
			return false;
		}

		// check requirements against actions in current campaign:
		ListIter<CombatActionReq> iter = pThis->requirements;
		while (++iter) {
			CombatActionReq* r  = iter.value();
			bool             ok = false;

			if (r->action > 0) {
				ListIter<CombatAction> action = campaign->GetActions();
				while (++action) {
					CombatAction* a = action.value();

					if (a->Identity() == r->action) {
						if (r->not) {
							if (a->Status() == r->stat)
							return false;
						}
						else {
							if (a->Status() != r->stat)
							return false;
						}
					}
				}
			}

			// group-based requirement
			else if (r->group_type > 0) {
				if (r->c1) {
					CombatGroup* group = r->c1->FindGroup(r->group_type, r->group_id);

					if (group) {
						int test = 0;
						int comp = 0;

						if (r->intel) {
							test = group->IntelLevel();
							comp = r->intel;
						}

						else {
							test = group->CalcValue();
							comp = r->score;
						}

						switch (r->comp) {
						case CombatActionReq::LT:  ok = (test <  comp); break;
						case CombatActionReq::LE:  ok = (test <= comp); break;
						case CombatActionReq::GT:  ok = (test >  comp); break;
						case CombatActionReq::GE:  ok = (test >= comp); break;
						case CombatActionReq::EQ:  ok = (test == comp); break;
						}
					}

					if (!ok)
					return false;
				}
			}

			// score-based requirement
			else {
				int test = 0;

				if (r->comp <= CombatActionReq::EQ) {  // absolute
					if (r->c1) {
						int test = r->c1->Score();

						switch (r->comp) {
						case CombatActionReq::LT:  ok = (test <  r->score); break;
						case CombatActionReq::LE:  ok = (test <= r->score); break;
						case CombatActionReq::GT:  ok = (test >  r->score); break;
						case CombatActionReq::GE:  ok = (test >= r->score); break;
						case CombatActionReq::EQ:  ok = (test == r->score); break;
						}
					}
				}

				else {                                 // relative
					if (r->c1 && r->c2) {
						int test = r->c1->Score() - r->c2->Score();

						switch (r->comp) {
						case CombatActionReq::RLT: ok = (test <  r->score); break;
						case CombatActionReq::RLE: ok = (test <= r->score); break;
						case CombatActionReq::RGT: ok = (test >  r->score); break;
						case CombatActionReq::RGE: ok = (test >= r->score); break;
						case CombatActionReq::REQ: ok = (test == r->score); break;
						}
					}
				}

				if (!ok)
				return false;
			}

			if (delay > 0) {
				pThis->start_after = (int) campaign->GetTime() + delay;
				pThis->delay       = 0;
				return IsAvailable();
			}
		}
	}

	return true;
}
bool Slash::isAvailable(const Player *player) const{
    return IsAvailable(player, this) && BasicCard::isAvailable(player);
}
Example #4
0
bool Crisp::isAvailable(const Player *player) const{
    return IsAvailable(player);
}
Example #5
0
const T* CRecentImp<T, S>::GetItem( int nIndex ) const
{
	if(!IsAvailable() || nIndex<0 || nIndex>=*m_pnUserItemCount)return NULL;
	return &m_puUserItemData[nIndex];
}
Example #6
0
  const RCP<const FactoryBase> FactoryManager<Scalar, LocalOrdinal, GlobalOrdinal, Node, LocalMatOps>::GetDefaultFactory(const std::string & varName) const {
    if (IsAvailable(varName, defaultFactoryTable_)) {

      return defaultFactoryTable_[varName];

    } else {

      if (varName == "A")             return SetAndReturnDefaultFactory(varName, rcp(new RAPFactory()));
      if (varName == "RAP Pattern")   return GetFactory("A");
      if (varName == "AP Pattern")    return GetFactory("A");
      if (varName == "P") {
        RCP<Factory> factory = rcp(new SaPFactory());
        factory->SetFactory("P", GetFactory("Ptent")); // GetFactory("Ptent"): Use the same factory instance for both "P" and "Nullspace"
        return SetAndReturnDefaultFactory(varName, factory);
      }

      if (varName == "R")             return SetAndReturnDefaultFactory(varName, rcp(new TransPFactory()));
#if defined(HAVE_MUELU_ZOLTAN) && defined(HAVE_MPI)
      if (varName == "Partition")     {
        return SetAndReturnDefaultFactory(varName, rcp(new ZoltanInterface()));
      }
#endif //ifdef HAVE_MPI

      if (varName == "Importer") {
#ifdef HAVE_MPI
        return SetAndReturnDefaultFactory(varName, rcp(new RepartitionFactory()));
#else
        return SetAndReturnDefaultFactory(varName, NoFactory::getRCP());
#endif
      }
      if (varName == "number of partitions") {
        return GetFactory("Importer");
      }
      //JJH FIXME is this going to bite me in the backside?
//       if (varName == "Coordinates") {
//         return SetAndReturnDefaultFactory(varName, rcp(new MueLu::MultiVectorTransferFactory<SC,LO,GO,NO,LMO>(varName,"R")));
//       }

      if (varName == "Nullspace") {
        RCP<Factory> factory = rcp(new NullspaceFactory());
        factory->SetFactory("Nullspace", GetFactory("Ptent")); // GetFactory("Ptent"): Use the same factory instance for both "P" and "Nullspace"
        return SetAndReturnDefaultFactory(varName, factory);
      }

      if (varName == "Graph")               return SetAndReturnDefaultFactory(varName, rcp(new CoalesceDropFactory()));
      if (varName == "UnAmalgamationInfo")  return SetAndReturnDefaultFactory(varName, rcp(new AmalgamationFactory())); //GetFactory("Graph"));
      if (varName == "Aggregates")          return SetAndReturnDefaultFactory(varName, rcp(new CoupledAggregationFactory()));
      if (varName == "CoarseMap")           return SetAndReturnDefaultFactory(varName, rcp(new CoarseMapFactory()));
      if (varName == "DofsPerNode")         return GetFactory("Graph");
      if (varName == "Filtering")           return GetFactory("Graph");

      // Same factory for both Pre and Post Smoother. Factory for key "Smoother" can be set by users.
      if (varName == "PreSmoother")         return GetFactory("Smoother");
      if (varName == "PostSmoother")        return GetFactory("Smoother");

#ifdef HAVE_MUELU_EXPERIMENTAL
      if (varName == "Ppattern") {
        RCP<PatternFactory> PpFact = rcp(new PatternFactory);
        PpFact->SetFactory("P", GetFactory("Ptent"));
        return SetAndReturnDefaultFactory(varName, PpFact);
      }
      if (varName == "Constraint")          return SetAndReturnDefaultFactory(varName, rcp(new ConstraintFactory()));
#endif

      //if (varName == "Smoother")    return SetAndReturnDefaultFactory(varName, rcp(new SmootherFactory(rcp(new GaussSeidelSmoother()))));
      if (varName == "Smoother") {
        Teuchos::ParameterList smootherParamList;
        smootherParamList.set("relaxation: type", "Symmetric Gauss-Seidel");
        smootherParamList.set("relaxation: sweeps", (LO) 1);
        smootherParamList.set("relaxation: damping factor", (Scalar) 1.0); //FIXME once Ifpack2's parameter list validator is fixed, change this back to Scalar
        return SetAndReturnDefaultFactory(varName, rcp( new SmootherFactory(rcp(new TrilinosSmoother("RELAXATION", smootherParamList)))));
      }

      if (varName == "CoarseSolver")  return SetAndReturnDefaultFactory(varName, rcp(new SmootherFactory(rcp(new DirectSolver()),Teuchos::null)));

      if (varName == "Ptent") return SetAndReturnDefaultFactory(varName, rcp(new TentativePFactory())); // Use the same factory instance for both "P" and "Nullspace"

      TEUCHOS_TEST_FOR_EXCEPTION(true, MueLu::Exceptions::RuntimeError, "MueLu::FactoryManager::GetDefaultFactory(): No default factory available for building '"+varName+"'.");
    }

  }
bool Analeptic::isAvailable(const Player *player) const{
    return IsAvailable(player, this) && BasicCard::isAvailable(player);
}
Example #8
0
CItemElem*	CPocketController::GetAt( int nPocket, int nIndex )
{
    if( !IsAvailable( nPocket, FALSE ) )
        return NULL;
    return m_apPocket[nPocket]->GetAt( nIndex );
}
Example #9
0
CPocket*	CPocketController::GetPocket( int nPocket )
{
    if( IsAvailable( nPocket, FALSE ) )
        return m_apPocket[nPocket];
    return NULL;
}
Example #10
0
// static
void Disassembler::StaticInitialize()
{
    LIMITED_METHOD_CONTRACT;

#if USE_COREDISTOOLS_DISASSEMBLER
    _ASSERTE(!IsAvailable());

    // TODO: The 'coredistools' library will eventually be part of a NuGet package, need to be able to load
    // that using appropriate search paths
    LPCWSTR libraryName = MAKEDLLNAME(W("coredistools"));
    HMODULE libraryHandle = CLRLoadLibrary(libraryName);
    do
    {
        if (libraryHandle == nullptr)
        {
        #ifdef _DEBUG
            wprintf(W("LoadLibrary failed for '%s': error %u\n"), libraryName, GetLastError());
        #endif // _DEBUG
            break;
        }

        External_InitDisasm =
            reinterpret_cast<decltype(External_InitDisasm)>(GetProcAddress(libraryHandle, "InitDisasm"));
        if (External_InitDisasm == nullptr)
        {
        #ifdef _DEBUG
            wprintf(
                W("GetProcAddress failed for library '%s', function 'InitDisasm': error %u\n"),
                libraryName,
                GetLastError());
        #endif // _DEBUG
            break;
        }

        External_DisasmInstruction =
            reinterpret_cast<decltype(External_DisasmInstruction)>(GetProcAddress(libraryHandle, "DisasmInstruction"));
        if (External_DisasmInstruction == nullptr)
        {
        #ifdef _DEBUG
            wprintf(
                W("GetProcAddress failed for library '%s', function 'DisasmInstruction': error %u\n"),
                libraryName,
                GetLastError());
        #endif // _DEBUG
            break;
        }

        External_FinishDisasm =
            reinterpret_cast<decltype(External_FinishDisasm)>(GetProcAddress(libraryHandle, "FinishDisasm"));
        if (External_FinishDisasm == nullptr)
        {
        #ifdef _DEBUG
            wprintf(
                W("GetProcAddress failed for library '%s', function 'FinishDisasm': error %u\n"),
                libraryName,
                GetLastError());
        #endif // _DEBUG
            break;
        }

        // Set this last to indicate successful load of the library and all exports
        s_libraryHandle = libraryHandle;
        _ASSERTE(IsAvailable());
        return;
    } while (false);

    CLRFreeLibrary(libraryHandle);
    _ASSERTE(!IsAvailable());
#endif // USE_COREDISTOOLS_DISASSEMBLER
}
void CNpcMagicProcess::MagicPacket(char *pBuf, int len)
{
	int index = 0, send_index = 0, magicid = 0, sid = -1, tid = -1, data1 = 0, data2 = 0, data3 = 0, data4 = 0, data5 = 0, data6 = 0;
	char send_buff[128];
	_MAGIC_TABLE* pTable = NULL;
	
	BYTE command = GetByte( pBuf, index );		// Get the magic status.  
	if( command == MAGIC_FAIL ) {			    // Client indicates that magic failed. Just send back packet.
		SetByte( send_buff, AG_MAGIC_ATTACK_RESULT, send_index );
		SetString( send_buff, pBuf, len-1, send_index );	// len ==> include WIZ_MAGIC_PROCESS command byte. 
		//g_pMain->Send_Region( send_buff, send_index, m_pSrcUser->m_pUserData->m_bZone, m_pSrcUser->m_RegionX, m_pSrcUser->m_RegionZ );
		m_bMagicState = NONE;
		return;
	}

	magicid = GetDWORD( pBuf, index );        // Get ID of magic.
	sid = GetShort( pBuf, index );			  // Get ID of source.
	tid = GetShort( pBuf, index );            // Get ID of target.

	data1 = GetShort( pBuf, index );          // ( Remember, you don't definately need this. )
	data2 = GetShort( pBuf, index );		  // ( Only use it when you really feel it's needed. )
	data3 = GetShort( pBuf, index );
	data4 = GetShort( pBuf, index );
	data5 = GetShort( pBuf, index );
	data6 = GetShort( pBuf, index );          // Get data1 ~ data6 (No, I don't know what the hell 'data' is.) 

	pTable = IsAvailable( magicid, tid, command );     // If magic was successful.......
	if( !pTable ) return;

	if( command == MAGIC_EFFECTING )     // Is target another player? 
	{
		//if (tid < -1 || tid >= MAX_USER) return;	

		switch( pTable->bType[0] ) {
		case 1:
			ExecuteType1( pTable->iNum, tid, data1, data2, data3 );
			break;
		case 2:
			ExecuteType2( pTable->iNum, tid, data1, data2, data3 );	
			break;
		case 3:
			ExecuteType3( pTable->iNum, tid, data1, data2, data3, pTable->bMoral );
			break;
		case 4:
			ExecuteType4( pTable->iNum, tid );
			break;
		case 5:
			ExecuteType5( pTable->iNum );
			break;
		case 6:
			ExecuteType6( pTable->iNum );
			break;
		case 7:
			ExecuteType7( pTable->iNum );
			break;
		case 8:
			ExecuteType8( pTable->iNum, tid, sid, data1, data2, data3 );
			break;
		case 9:
			ExecuteType9( pTable->iNum );
			break;
		case 10:
			ExecuteType10( pTable->iNum );
			break;
		}

		switch( pTable->bType[1] ) {
		case 1:
			ExecuteType1( pTable->iNum, tid, data4, data5, data6 );
			break;
		case 2:
			ExecuteType2( pTable->iNum, tid, data1, data2, data3 );	
			break;
		case 3:
			ExecuteType3( pTable->iNum, tid, data1, data2, data3, pTable->bMoral );
			break;
		case 4:
			ExecuteType4( pTable->iNum, tid );
			break;
		case 5:
			ExecuteType5( pTable->iNum );
			break;
		case 6:
			ExecuteType6( pTable->iNum );
			break;
		case 7:
			ExecuteType7( pTable->iNum );
			break;
		case 8:
			ExecuteType8( pTable->iNum, tid, sid, data1, data2, data3 );
			break;
		case 9:
			ExecuteType9( pTable->iNum );
			break;
		case 10:
			ExecuteType10( pTable->iNum );
			break;	
		}
	}
	else if( command == MAGIC_CASTING ) {
		SetByte( send_buff, AG_MAGIC_ATTACK_RESULT, send_index );
		SetString( send_buff, pBuf, len-1, send_index );	// len ==> include WIZ_MAGIC_PROCESS command byte. 
		m_pSrcNpc->SendAll(send_buff, send_index);
	}
}
Example #12
0
NonLegacyRenderer::NonLegacyRenderer() :
	m_previous_window_size( -1, -1 ),
	m_last_vertex_count( 0 ),
	m_last_index_count( 0 ),
	m_vbo_sync_type( INVALIDATE_ALL ),
	m_vbo_synced( false ),
	m_cull( false ),
	m_use_fbo( false ) {
	if( IsAvailable() ) {
		auto load_result = m_shader.loadFromMemory(
			"#version 130\n"
			"uniform vec2 viewport_parameters;\n"
			"in vec2 vertex;\n"
			"in vec4 color;\n"
			"in vec2 texture_coordinate;\n"
			"out vec4 vertex_color;\n"
			"out vec2 vertex_texture_coordinate;\n"
			"void main() {\n"
			"\tmat4 mvp_matrix = mat4(1.f);\n"
			"\tmvp_matrix[3][0] = -1.f;\n"
			"\tmvp_matrix[3][1] = 1.f;\n"
			"\tmvp_matrix[0][0] = viewport_parameters.x;\n"
			"\tmvp_matrix[1][1] = viewport_parameters.y;\n"
			"\tmvp_matrix[2][2] = -1.f;\n"
			"\tgl_Position = mvp_matrix * vec4(vertex.xy, 1.f, 1.f);\n"
			"\tvertex_color = color;\n"
			"\tvertex_texture_coordinate = texture_coordinate;\n"
			"}\n",
			"#version 130\n"
			"uniform sampler2D texture0;\n"
			"in vec4 vertex_color;\n"
			"in vec2 vertex_texture_coordinate;\n"
			"out vec4 fragment_color;\n"
			"void main() {\n"
			"\tfragment_color = vertex_color * texture(texture0, vertex_texture_coordinate);\n"
			"}\n"
		);

		if( !load_result ) {
			shader_supported = false;

#if defined( SFGUI_DEBUG )
			std::cerr << "Non-legacy renderer unavailable.\n";
#endif

			return;
		}

		m_vertex_location = GetAttributeLocation( m_shader, "vertex" );
		m_color_location = GetAttributeLocation( m_shader, "color" );
		m_texture_coordinate_location = GetAttributeLocation( m_shader, "texture_coordinate" );

		CheckGLError( GLEXT_glGenBuffers( 1, &m_vertex_vbo ) );
		CheckGLError( GLEXT_glGenBuffers( 1, &m_color_vbo ) );
		CheckGLError( GLEXT_glGenBuffers( 1, &m_texture_vbo ) );
		CheckGLError( GLEXT_glGenBuffers( 1, &m_index_vbo ) );
	}
	else {
#if defined( SFGUI_DEBUG )
		std::cerr << "Non-legacy renderer unavailable.\n";
#endif
	}
}
Example #13
0
void Disassembler::StaticInitialize()
{
    LIMITED_METHOD_CONTRACT;

#if USE_COREDISTOOLS_DISASSEMBLER
    _ASSERTE(!IsAvailable());

    HMODULE libraryHandle = nullptr;
    PathString libPath;
    DWORD result = WszGetModuleFileName(nullptr, libPath);
    if (result == 0) {
#ifdef _DEBUG
        wprintf(
            W("GetModuleFileName failed, function 'DisasmInstruction': error %u\n"),
            GetLastError());
#endif // _DEBUG
        return;
    }

#if defined(FEATURE_PAL)
    WCHAR delim = W('/');
#else
    WCHAR delim = W('\\');
#endif
    LPCWSTR libFileName = MAKEDLLNAME(W("coredistools"));
    PathString::Iterator iter = libPath.End();
    if (libPath.FindBack(iter, delim)) {
        libPath.Truncate(++iter);
        libPath.Append(libFileName);
    }
    else {
        _ASSERTE(!"unreachable");
    }

    LPCWSTR libraryName = libPath.GetUnicode();
    libraryHandle = CLRLoadLibrary(libraryName);
    do
    {
        if (libraryHandle == nullptr)
        {
        #ifdef _DEBUG
            wprintf(W("LoadLibrary failed for '%s': error %u\n"), libraryName, GetLastError());
        #endif // _DEBUG
            break;
        }

        External_InitDisasm =
            reinterpret_cast<decltype(External_InitDisasm)>(GetProcAddress(libraryHandle, "InitDisasm"));
        if (External_InitDisasm == nullptr)
        {
        #ifdef _DEBUG
            wprintf(
                W("GetProcAddress failed for library '%s', function 'InitDisasm': error %u\n"),
                libraryName,
                GetLastError());
        #endif // _DEBUG
            break;
        }

        External_DisasmInstruction =
            reinterpret_cast<decltype(External_DisasmInstruction)>(GetProcAddress(libraryHandle, "DisasmInstruction"));
        if (External_DisasmInstruction == nullptr)
        {
        #ifdef _DEBUG
            wprintf(
                W("GetProcAddress failed for library '%s', function 'DisasmInstruction': error %u\n"),
                libraryName,
                GetLastError());
        #endif // _DEBUG
            break;
        }

        External_FinishDisasm =
            reinterpret_cast<decltype(External_FinishDisasm)>(GetProcAddress(libraryHandle, "FinishDisasm"));
        if (External_FinishDisasm == nullptr)
        {
        #ifdef _DEBUG
            wprintf(
                W("GetProcAddress failed for library '%s', function 'FinishDisasm': error %u\n"),
                libraryName,
                GetLastError());
        #endif // _DEBUG
            break;
        }

        // Set this last to indicate successful load of the library and all exports
        s_libraryHandle = libraryHandle;
        _ASSERTE(IsAvailable());
        return;
    } while (false);

    _ASSERTE(!IsAvailable());
    
#endif // USE_COREDISTOOLS_DISASSEMBLER
}
Example #14
0
bool Analeptic::isAvailable() const{
    return IsAvailable();
}
bool Slash::isAvailable() const{
    return IsAvailable();
}
Example #16
0
CItemElem*	CPocketController::GetAtId( int nPocket, int nItem, BOOL bExpiration )
{
    if( !IsAvailable( nPocket, bExpiration ) )
        return NULL;
    return m_apPocket[nPocket]->GetAtId( nItem );
}
  void RebalanceTransferFactory<Scalar, LocalOrdinal, GlobalOrdinal, Node, LocalMatOps>::Build(Level& fineLevel, Level& coarseLevel) const {
    FactoryMonitor m(*this, "Build", coarseLevel);

    const ParameterList& pL = GetParameterList();

    int implicit   = !pL.get<bool>("repartition: rebalance P and R");
    int writeStart = pL.get<int> ("write start");
    int writeEnd   = pL.get<int> ("write end");

    if (writeStart == 0 && fineLevel.GetLevelID() == 0 && writeStart <= writeEnd && IsAvailable(fineLevel, "Coordinates")) {
      std::string fileName = "coordinates_level_0.m";
      RCP<MultiVector> fineCoords = fineLevel.Get< RCP<MultiVector> >("Coordinates");
      if (fineCoords != Teuchos::null)
        Utils::Write(fileName, *fineCoords);
    }

    RCP<const Import> importer = Get<RCP<const Import> >(coarseLevel, "Importer");
    if (implicit) {
      // Save the importer, we'll need it for solve
      coarseLevel.Set("Importer", importer, NoFactory::get());
    }

    RCP<ParameterList> params = rcp(new ParameterList());;
    params->set("printLoadBalancingInfo", true);
    params->set("printCommInfo",          true);

    std::string transferType = pL.get<std::string>("type");
    if (transferType == "Interpolation") {
      RCP<Matrix> originalP = Get< RCP<Matrix> >(coarseLevel, "P");

      {
        // This line must be after the Get call
        SubFactoryMonitor m1(*this, "Rebalancing prolongator", coarseLevel);

        if (implicit || importer.is_null()) {
          GetOStream(Runtime0) << "Using original prolongator" << std::endl;
          Set(coarseLevel, "P", originalP);

        } else {
          // P is the transfer operator from the coarse grid to the fine grid.
          // P must transfer the data from the newly reordered coarse A to the
          // (unchanged) fine A.  This means that the domain map (coarse) of P
          // must be changed according to the new partition. The range map
          // (fine) is kept unchanged.
          //
          // The domain map of P must match the range map of R.  See also note
          // below about domain/range map of R and its implications for P.
          //
          // To change the domain map of P, P needs to be fillCompleted again
          // with the new domain map.  To achieve this, P is copied into a new
          // matrix that is not fill-completed.  The doImport() operation is
          // just used here to make a copy of P: the importer is trivial and
          // there is no data movement involved.  The reordering actually
          // happens during the fillComplete() with domainMap == importer->getTargetMap().
          RCP<Matrix> rebalancedP = originalP;
          RCP<const CrsMatrixWrap> crsOp = rcp_dynamic_cast<const CrsMatrixWrap>(originalP);
          TEUCHOS_TEST_FOR_EXCEPTION(crsOp == Teuchos::null, Exceptions::BadCast, "Cast from Xpetra::Matrix to Xpetra::CrsMatrixWrap failed");

          RCP<CrsMatrix> rebalancedP2 = crsOp->getCrsMatrix();
          TEUCHOS_TEST_FOR_EXCEPTION(rebalancedP2 == Teuchos::null, std::runtime_error, "Xpetra::CrsMatrixWrap doesn't have a CrsMatrix");

          {
            SubFactoryMonitor subM(*this, "Rebalancing prolongator -- fast map replacement", coarseLevel);

            RCP<const Import> newImporter = ImportFactory::Build(importer->getTargetMap(), rebalancedP->getColMap());
            rebalancedP2->replaceDomainMapAndImporter(importer->getTargetMap(), newImporter);
          }

          ///////////////////////// EXPERIMENTAL
          // TODO FIXME somehow we have to transfer the striding information of the permuted domain/range maps.
          // That is probably something for an external permutation factory
          //   if (originalP->IsView("stridedMaps"))
          //     rebalancedP->CreateView("stridedMaps", originalP);
          ///////////////////////// EXPERIMENTAL

          Set(coarseLevel, "P", rebalancedP);

          if (IsPrint(Statistics1))
            GetOStream(Statistics1) << PerfUtils::PrintMatrixInfo(*rebalancedP, "P (rebalanced)", params);
        }
      }

      if (importer.is_null()) {
        if (IsAvailable(coarseLevel, "Nullspace"))
          Set(coarseLevel, "Nullspace", Get<RCP<MultiVector> >(coarseLevel, "Nullspace"));

        if (pL.isParameter("Coordinates") && pL.get< RCP<const FactoryBase> >("Coordinates") != Teuchos::null)
          if (IsAvailable(coarseLevel, "Coordinates"))
            Set(coarseLevel, "Coordinates", Get< RCP<MultiVector> >(coarseLevel, "Coordinates"));

        return;
      }

      if (pL.isParameter("Coordinates") &&
          pL.get< RCP<const FactoryBase> >("Coordinates") != Teuchos::null &&
          IsAvailable(coarseLevel, "Coordinates")) {
        RCP<MultiVector> coords = Get<RCP<MultiVector> >(coarseLevel, "Coordinates");

        // This line must be after the Get call
        SubFactoryMonitor subM(*this, "Rebalancing coordinates", coarseLevel);

        LO nodeNumElts = coords->getMap()->getNodeNumElements();

        // If a process has no matrix rows, then we can't calculate blocksize using the formula below.
        LO myBlkSize = 0, blkSize = 0;
        if (nodeNumElts > 0)
          myBlkSize = importer->getSourceMap()->getNodeNumElements() / nodeNumElts;
        maxAll(coords->getMap()->getComm(), myBlkSize, blkSize);

        RCP<const Import> coordImporter;
        if (blkSize == 1) {
          coordImporter = importer;

        } else {
          // NOTE: there is an implicit assumption here: we assume that dof any node are enumerated consequently
          // Proper fix would require using decomposition similar to how we construct importer in the
          // RepartitionFactory
          RCP<const Map> origMap   = coords->getMap();
          GO             indexBase = origMap->getIndexBase();

          ArrayView<const GO> OEntries   = importer->getTargetMap()->getNodeElementList();
          LO                  numEntries = OEntries.size()/blkSize;
          ArrayRCP<GO> Entries(numEntries);
          for (LO i = 0; i < numEntries; i++)
            Entries[i] = (OEntries[i*blkSize]-indexBase)/blkSize + indexBase;

          RCP<const Map> targetMap = MapFactory::Build(origMap->lib(), origMap->getGlobalNumElements(), Entries(), indexBase, origMap->getComm());
          coordImporter = ImportFactory::Build(origMap, targetMap);
        }

        RCP<MultiVector> permutedCoords  = MultiVectorFactory::Build(coordImporter->getTargetMap(), coords->getNumVectors());
        permutedCoords->doImport(*coords, *coordImporter, Xpetra::INSERT);

        if (pL.get<bool>("useSubcomm") == true)
          permutedCoords->replaceMap(permutedCoords->getMap()->removeEmptyProcesses());

        Set(coarseLevel, "Coordinates", permutedCoords);

        std::string fileName = "rebalanced_coordinates_level_" + toString(coarseLevel.GetLevelID()) + ".m";
        if (writeStart <= coarseLevel.GetLevelID() && coarseLevel.GetLevelID() <= writeEnd && permutedCoords->getMap() != Teuchos::null)
          Utils::Write(fileName, *permutedCoords);
      }

      if (IsAvailable(coarseLevel, "Nullspace")) {
        RCP<MultiVector> nullspace = Get< RCP<MultiVector> >(coarseLevel, "Nullspace");

        // This line must be after the Get call
        SubFactoryMonitor subM(*this, "Rebalancing nullspace", coarseLevel);

        RCP<MultiVector> permutedNullspace = MultiVectorFactory::Build(importer->getTargetMap(), nullspace->getNumVectors());
        permutedNullspace->doImport(*nullspace, *importer, Xpetra::INSERT);

        if (pL.get<bool>("useSubcomm") == true)
          permutedNullspace->replaceMap(permutedNullspace->getMap()->removeEmptyProcesses());

        Set(coarseLevel, "Nullspace", permutedNullspace);
      }

    } else {
      if (pL.get<bool>("transpose: use implicit") == false) {
        RCP<Matrix> originalR = Get< RCP<Matrix> >(coarseLevel, "R");

        SubFactoryMonitor m2(*this, "Rebalancing restriction", coarseLevel);

        if (implicit || importer.is_null()) {
          GetOStream(Runtime0) << "Using original restrictor" << std::endl;
          Set(coarseLevel, "R", originalR);

        } else {
          RCP<Matrix> rebalancedR;
          {
            SubFactoryMonitor subM(*this, "Rebalancing restriction -- fusedImport", coarseLevel);

            RCP<Map> dummy;         // meaning: use originalR's domain map.
            rebalancedR = MatrixFactory::Build(originalR, *importer, dummy, importer->getTargetMap());
          }
          Set(coarseLevel, "R", rebalancedR);

          ///////////////////////// EXPERIMENTAL
          // TODO FIXME somehow we have to transfer the striding information of the permuted domain/range maps.
          // That is probably something for an external permutation factory
          // if (originalR->IsView("stridedMaps"))
          //   rebalancedR->CreateView("stridedMaps", originalR);
          ///////////////////////// EXPERIMENTAL

          if (IsPrint(Statistics1))
            GetOStream(Statistics1) << PerfUtils::PrintMatrixInfo(*rebalancedR, "R (rebalanced)", params);
        }
      }
    }
  }
Example #18
0
bool Shader::CompileProgram()
{
    // First make sure that we can use shaders
    if (!IsAvailable())
    {
        Err() << "Failed to create a shader: your system doesn't support shaders "
              << "(you should test Shader::IsAvailable() before trying to use the Shader class)" << std::endl;
        return false;
    }

    // Make sure that GLEW is initialized (extra safety -- it is already done in IsAvailable())
    priv::EnsureGlewInit();

    // Destroy the shader if it was already created
    if (myShaderProgram)
        GLCheck(glDeleteObjectARB(myShaderProgram));

    // Define the vertex shader source (we provide it directly as it doesn't have to change)
    static const char* vertexSrc =
        "void main()"
        "{"
        "    gl_TexCoord[0] = gl_MultiTexCoord0;"
        "    gl_FrontColor = gl_Color;"
        "    gl_Position = ftransform();"
        "}";

    // Create the program
    myShaderProgram = glCreateProgramObjectARB();

    // Create the shaders
    GLhandleARB vertexShader   = glCreateShaderObjectARB(GL_VERTEX_SHADER_ARB);
    GLhandleARB fragmentShader = glCreateShaderObjectARB(GL_FRAGMENT_SHADER_ARB);

    // Compile them
    const char* fragmentSrc = myFragmentShader.c_str();
    GLCheck(glShaderSourceARB(vertexShader,   1, &vertexSrc,   NULL));
    GLCheck(glShaderSourceARB(fragmentShader, 1, &fragmentSrc, NULL));
    GLCheck(glCompileShaderARB(vertexShader));
    GLCheck(glCompileShaderARB(fragmentShader));

    // Check the compile logs
    GLint success;
    GLCheck(glGetObjectParameterivARB(vertexShader, GL_OBJECT_COMPILE_STATUS_ARB, &success));
    if (success == GL_FALSE)
    {
        char log[1024];
        GLCheck(glGetInfoLogARB(vertexShader, sizeof(log), 0, log));
        Err() << "Failed to compile shader:" << std::endl
              << log << std::endl;
        GLCheck(glDeleteObjectARB(vertexShader));
        GLCheck(glDeleteObjectARB(fragmentShader));
        GLCheck(glDeleteObjectARB(myShaderProgram));
        myShaderProgram = 0;
        return false;
    }
    GLCheck(glGetObjectParameterivARB(fragmentShader, GL_OBJECT_COMPILE_STATUS_ARB, &success));
    if (success == GL_FALSE)
    {
        char log[1024];
        GLCheck(glGetInfoLogARB(fragmentShader, sizeof(log), 0, log));
        Err() << "Failed to compile shader:" << std::endl
              << log << std::endl;
        GLCheck(glDeleteObjectARB(vertexShader));
        GLCheck(glDeleteObjectARB(fragmentShader));
        GLCheck(glDeleteObjectARB(myShaderProgram));
        myShaderProgram = 0;
        return false;
    }

    // Attach the shaders to the program
    GLCheck(glAttachObjectARB(myShaderProgram, vertexShader));
    GLCheck(glAttachObjectARB(myShaderProgram, fragmentShader));

    // We can now delete the shaders
    GLCheck(glDeleteObjectARB(vertexShader));
    GLCheck(glDeleteObjectARB(fragmentShader));

    // Link the program
    GLCheck(glLinkProgramARB(myShaderProgram));

    // Get link log
    GLCheck(glGetObjectParameterivARB(myShaderProgram, GL_OBJECT_LINK_STATUS_ARB, &success));
    if (success == GL_FALSE)
    {
        // Oops... link errors
        char log[1024];
        GLCheck(glGetInfoLogARB(myShaderProgram, sizeof(log), 0, log));
        Err() << "Failed to link shader:" << std::endl
              << log << std::endl;
        GLCheck(glDeleteObjectARB(myShaderProgram));
        myShaderProgram = 0;
        return false;
    }

    return true;
}
Example #19
0
  void FactoryManager<Scalar, LocalOrdinal, GlobalOrdinal, Node, LocalMatOps>::SetFactory(const std::string & varName, const RCP<const FactoryBase> & factory) {
    if (IsAvailable(varName, factoryTable_)) // TODO: too much warnings (for smoothers)
      GetOStream(Warnings1, 0) << "Warning: FactoryManager::SetFactory(): Changing an already defined factory for " << varName << std::endl;

    factoryTable_[varName] = factory;
  }
void CMagicProcess::MagicPacket(Packet & pkt)
{
	int send_index = 0, magicid = 0;
	int16 sid, tid;
	uint16 data1 = 0, data2 = 0, data3 = 0, data4 = 0, data5 = 0, data6 = 0, TotalDex=0, righthand_damage = 0, result = 1;
	_MAGIC_TABLE* pTable = NULL;

	sid = m_pSrcUser->m_iUserId;

	BYTE command = pkt.read<uint8>();
	pkt >> tid >> magicid >> data1 >> data2 >> data3 >> data4 >> data5 >> data6 >> TotalDex, righthand_damage;
	//TRACE("MagicPacket - command=%d, tid=%d, magicid=%d\n", command, tid, magicid);

	pTable = IsAvailable( magicid, tid, command );     // If magic was successful.......
	if( !pTable ) return;

	if( command == MAGIC_EFFECTING )     // Is target another player? 
	{
		switch( pTable->bType[0] ) {
		case 1:
			result = ExecuteType1( pTable->iNum, tid, data1, data2, data3, 1 );
			break;
		case 2:
			result = ExecuteType2( pTable->iNum, tid, data1, data2, data3 );	
			break;
		case 3:
			ExecuteType3( pTable->iNum, tid, data1, data2, data3, pTable->bMoral, TotalDex, righthand_damage );
			break;
		case 4:
			ExecuteType4( pTable->iNum, sid, tid, data1, data2, data3, pTable->bMoral );
			break;
		case 5:
			ExecuteType5( pTable->iNum );
			break;
		case 6:
			ExecuteType6( pTable->iNum );
			break;
		case 7:
			ExecuteType7( pTable->iNum );
			break;
		case 8:
			ExecuteType8( pTable->iNum );
			break;
		case 9:
			ExecuteType9( pTable->iNum );
			break;
		case 10:
			ExecuteType10( pTable->iNum );
			break;
		}

		if(result != 0)	{
			switch( pTable->bType[1] ) {
			case 1:
				ExecuteType1( pTable->iNum, tid, data4, data5, data6, 2 );
				break;
			case 2:
				ExecuteType2( pTable->iNum, tid, data1, data2, data3 );	
				break;
			case 3:
				ExecuteType3( pTable->iNum, tid, data1, data2, data3, pTable->bMoral, TotalDex, righthand_damage );
				break;
			case 4:
				ExecuteType4( pTable->iNum, sid, tid, data1, data2, data3, pTable->bMoral );
				break;
			case 5:
				ExecuteType5( pTable->iNum );
				break;
			case 6:
				ExecuteType6( pTable->iNum );
				break;
			case 7:
				ExecuteType7( pTable->iNum );
				break;
			case 8:
				ExecuteType8( pTable->iNum );
				break;
			case 9:
				ExecuteType9( pTable->iNum );
				break;
			case 10:
				ExecuteType10( pTable->iNum );
				break;	
			}
		}
	}
}
/**
 * Get analytics pointer
 */
IAnalyticsProvider& FEngineAnalytics::GetProvider()
{
	checkf(bIsInitialized && IsAvailable(), TEXT("FEngineAnalytics::GetProvider called outside of Initialize/Shutdown."));

	return *Analytics.Get();
}
Example #22
0
Box
Box::FirstChild() const
{
  MOZ_ASSERT(IsAvailable());
  return Box(mContext, mChildOffset, this);
}
Example #23
0
bool CheckTarget(Matrix *matrix, Player player, Point p)
{
	/* is empty or is the tail of the snake (so it will move the next
	to make place) */
	return IsAvailable(matrix, p) || ((*matrix)[p.y][p.x] == player * GetSize(matrix, player));
}
Example #24
0
bool CppINode::isAvailable()
{
  return IsAvailable(_node->GetAccessMode());
}
Example #25
0
const T* CRecentImp<T, S>::GetItemPointer(int nIndex) const
{
	if(!IsAvailable() || nIndex<0 || nIndex>=m_nArrayCount)return NULL;
	return &m_puUserItemData[nIndex];
}
Example #26
0
Box
Box::Next() const
{
  MOZ_ASSERT(IsAvailable());
  return Box(mContext, mRange.mEnd, mParent);
}
Example #27
0
bool Slash::isAvailable(const Player *player) const{
    return IsAvailable(player);
}
// updates the instance of the sensor and initializes the stream
HRESULT KinectSensor::UpdateSensor()
{
    AutoLock lock( m_nuiLock );

    // only try to create and initialize for Opened/Selected sensors
    if( !m_bSelected )
    {
        return E_NUI_DEVICE_NOT_READY;
    }

    if( m_bInitialized )
    {
        return GetNUISensorStatus();
    }

    // if the sensor isn't ready, try to create it now
    HRESULT hr = S_OK;
    if( !IsAvailable() )
    {
        hr = CreateNuiDevice();
        if( FAILED(hr) )
        {
            return hr;
        }
    }

    // set the parameters based on the streams that were created
    DWORD dwInitFlags = 0;
    if( ( (nullptr != m_pColorStream) || (nullptr != m_pDepthStream) || (nullptr != m_pSkeletonStream) ) )
    {
        if( (nullptr != m_pColorStream) )
        {
            dwInitFlags |= NUI_INITIALIZE_FLAG_USES_COLOR;
        }
        if( (nullptr != m_pSkeletonStream)  )
        {
            dwInitFlags |= NUI_INITIALIZE_FLAG_USES_DEPTH_AND_PLAYER_INDEX;
            dwInitFlags |= NUI_INITIALIZE_FLAG_USES_SKELETON;
        }
        else if( (nullptr != m_pDepthStream)  )
        {
            dwInitFlags |= NUI_INITIALIZE_FLAG_USES_DEPTH;
        }
    }

    // initialize the sensor
    {
        hr = m_pNuiSensor->NuiInitialize( dwInitFlags );
        if( SUCCEEDED(hr) )
        {
            m_bInitialized = true;
        }
        else
        {
            ResetDevice();
            return hr;
        }

        // if we initialized the sensor, pass it along to the enabled streams
        if( m_bInitialized )
        {
            if( nullptr != m_pColorStream )
            {
                m_pColorStream->Initialize( m_pNuiSensor );
            }
            if( nullptr != m_pDepthStream )
            {
                m_pDepthStream->Initialize( m_pNuiSensor );
            }
            if( nullptr != m_pSkeletonStream )
            {
                m_pSkeletonStream->Initialize( m_pNuiSensor );
            }
        }
    }
    return hr;
}
Example #29
0
bool Analeptic::isAvailable(const Player *player) const{
    return IsAvailable(player);
}
Example #30
0
void CVolumeCtrl::Enable()
{
	if ( !m_bInitialized || !IsAvailable() )
		return;
	BOOL bAnyEnabled = FALSE;

	MMRESULT mmResult;

	MIXERLINE lineDestination;
	memset( &lineDestination, 0, sizeof(MIXERLINE) );
	lineDestination.cbStruct = sizeof(MIXERLINE);
	lineDestination.dwComponentType = MIXERLINE_COMPONENTTYPE_DST_WAVEIN;
	mmResult = mixerGetLineInfo( (HMIXEROBJ)m_dwMixerHandle, &lineDestination, MIXER_GETLINEINFOF_COMPONENTTYPE );
	if ( mmResult != MMSYSERR_NOERROR )
	{
		TRACE(".InputXxxVolume: FAILURE: Could not get the Destination Line while enabling. mmResult=%d\n", mmResult );
		return;
	}

	// Getting all line's controls
	int nControlCount = lineDestination.cControls;
	int nChannelCount = lineDestination.cChannels;
	MIXERLINECONTROLS LineControls;
	memset( &LineControls, 0, sizeof(MIXERLINECONTROLS) );
	MIXERCONTROL* aControls = (MIXERCONTROL*)malloc( nControlCount * sizeof(MIXERCONTROL) );
	if ( !aControls )
	{
		TRACE(".InputXxxVolume: FAILURE: Out of memory while enabling the line.\n" );
		return;
	}
	memset( &aControls[0], 0, sizeof(nControlCount * sizeof(MIXERCONTROL)) );
	for ( int i = 0; i < nControlCount; i++ )
	{
		aControls[i].cbStruct = sizeof(MIXERCONTROL);
	}
	LineControls.cbStruct = sizeof(MIXERLINECONTROLS);
	LineControls.dwLineID = lineDestination.dwLineID;
	LineControls.cControls = nControlCount;
	LineControls.cbmxctrl = sizeof(MIXERCONTROL);
	LineControls.pamxctrl = &aControls[0];
	           
	mmResult = mixerGetLineControls((HMIXEROBJ)m_dwMixerHandle, &LineControls, MIXER_GETLINECONTROLSF_ALL);
	if (mmResult == MMSYSERR_NOERROR)
	{
		for ( i = 0; i < nControlCount; i++ )
		{
			if ( aControls[i].dwControlType & MIXERCONTROL_CT_UNITS_BOOLEAN )
			{
				MIXERCONTROLDETAILS_BOOLEAN* aDetails = NULL;
				int nMultipleItems = aControls[i].cMultipleItems;
				int nChannels = nChannelCount;
				// MIXERCONTROLDETAILS
				MIXERCONTROLDETAILS ControlDetails;
				memset( &ControlDetails, 0, sizeof(MIXERCONTROLDETAILS) );
				ControlDetails.cbStruct = sizeof(MIXERCONTROLDETAILS);
				ControlDetails.dwControlID = aControls[i].dwControlID;
				if ( aControls[i].fdwControl & MIXERCONTROL_CONTROLF_UNIFORM )
				{
					nChannels = 1;
				}
				if ( aControls[i].fdwControl & MIXERCONTROL_CONTROLF_MULTIPLE )
				{
					nMultipleItems = aControls[i].cMultipleItems;
					aDetails = (MIXERCONTROLDETAILS_BOOLEAN*)malloc(nMultipleItems*nChannels*sizeof(MIXERCONTROLDETAILS_BOOLEAN));
					if ( !aDetails )
					{
						TRACE(".InputXxxVolume: FAILURE: Out of memory while enabling the line.\n" );
						continue;
					}
					for ( int nItem = 0; nItem < nMultipleItems; nItem++ )
					{
						LONG lValue = FALSE;
						if ( nItem == (int)(nMultipleItems-m_uSourceLineIndex))
						{
							lValue = TRUE;
						}
						for ( int nChannel = 0; nChannel < nChannels; nChannel++ )
						{
							aDetails[nItem+nChannel].fValue = lValue;
						}
					}
				}

				ControlDetails.cChannels = nChannels;
				ControlDetails.cMultipleItems = nMultipleItems;
				ControlDetails.cbDetails = sizeof(MIXERCONTROLDETAILS_BOOLEAN);
				ControlDetails.paDetails = &aDetails[0];

				mmResult = mixerSetControlDetails( (HMIXEROBJ)m_dwMixerHandle, &ControlDetails, 0L );
				if ( mmResult == MMSYSERR_NOERROR )
				{
					TRACE(".InputXxxVolume: Enabling Line: Line control \"%s\" has been enabled.\n", aControls[i].szShortName );
					bAnyEnabled = TRUE;
				}
				free( aDetails );
			}
		}
	} 
	else 
	{
		TRACE(".InputXxxVolume: FAILURE: Could not get the line's controls while enabling. mmResult=%d\n", mmResult );
	}
	free( aControls );
	if ( !bAnyEnabled )
	{
		TRACE(".InputXxxVolume: WARNING: No controls were found for enabling the line.\n" );
	}
}