Example #1
0
inline void load(
    Archive & ar,
    STD::bitset<Bits> &t,
    const unsigned int /* file_version */
){
    if (ar.get_flags() & boost::archive::packed_bools) {
        const unsigned Bytes = Bits / 8;
        for (unsigned int i = 0; i < Bytes; i++){
            unsigned char theByte;
            ar >> boost::serialization::make_nvp("item", theByte);
            const unsigned int count = 8 * i;
            t.set(count, theByte & 0x01);
            for (unsigned int j = 1; j < 8; j++) {
                theByte = theByte >> 1;
                t.set(count + j, theByte & 0x01);
            }
        }
        // handle any partial byte
        const unsigned extraBits = Bits - 8 * Bytes;
        if (extraBits > 0) {
            unsigned char theByte;
            ar >> boost::serialization::make_nvp("item", theByte);
            const unsigned int count = 8 * Bytes;
            t.set(count, theByte & 0x01);
            for (unsigned int j = 1; j < extraBits; j++) {
                theByte = theByte >> 1;
                t.set(count + j, theByte & 0x01);
            }
        }
    }
Example #2
0
	void OnUserConnect(LocalUser* user)
	{
		ConfigTag* tag = user->MyClass->config;
		std::string vhost = tag->getString("vhost");
		std::string replace;

		if (vhost.empty())
			return;

		replace = "$ident";
		if (vhost.find(replace) != std::string::npos)
		{
			std::string ident = user->ident;
			if (ident[0] == '~')
				ident.erase(0, 1);

			SearchAndReplace(vhost, replace, ident);
		}

		replace = "$account";
		if (vhost.find(replace) != std::string::npos)
		{
			std::string account = GetAccount(user);
			if (account.empty())
				account = "unidentified";

			SearchAndReplace(vhost, replace, account);
		}

		if (vhost.length() > 64)
		{
			ServerInstance->Logs->Log("m_conn_vhost", DEFAULT, "m_conn_vhost: vhost in connect block %s is too long", user->MyClass->name.c_str());
			return;
		}

		/* from m_sethost: validate the characters */
		for (std::string::const_iterator x = vhost.begin(); x != vhost.end(); x++)
		{
			if (!hostmap.test(static_cast<unsigned char>(*x)))
			{
				ServerInstance->Logs->Log("m_conn_vhost", DEFAULT, "m_conn_vhost: vhost in connect block %s has invalid characters", user->MyClass->name.c_str());
				return;
			}
		}

		user->ChangeDisplayedHost(vhost.c_str());
	}
int main(){
    // do you mind telling us in the problem statement
    // that there is more than one test case per input
    while(~scanf("%d%d",&N,&M)){
        V.clear();
        for(int i=1;i<=N;++i){
            scanf("%d",W+i);
            V.emplace_back(W[i]);
        }
        std::sort(all(V));
        V.erase(std::unique(all(V)),V.end());
        for(int i=1;i<=N;++i)
            W[i]=std::lower_bound(all(V),W[i])-V.begin();
        for(int i=1;i<=N;++i)
            adj[i].clear();
        for(int i=1,a,b;i<N;++i){
            scanf("%d%d",&a,&b);
            adj[a].emplace_back(b);
            adj[b].emplace_back(a);
        }
        dfs(1,-1);
        build();
        for(int i=0,a,b,l;i<M;++i){
            scanf("%d%d",&a,&b);
            l=lca(a,b);
            if(ein[b]<ein[a]) std::swap(a,b);
            if(a==l||b==l) qrys[i]={ein[a],ein[b],-1,i};
            else qrys[i]={eout[a],ein[b],l,i};
        }
        std::sort(qrys,qrys+M);
        vis.reset();
        memset(cnt,0,sizeof cnt);
        res=0;
        chk(tour[1]);
        for(int i=0,l=1,r=1;i<M;++i){
            while(r<qrys[i].r) chk(tour[++r]);
            while(l>qrys[i].l) chk(tour[--l]);
            while(r>qrys[i].r) chk(tour[r--]);   
            while(l<qrys[i].l) chk(tour[l++]);
            if(~qrys[i].lca) chk(qrys[i].lca);
            ans[qrys[i].i]=res;
            if(~qrys[i].lca) chk(qrys[i].lca);
        }
        for(int i=0;i<M;printf("%d\n",ans[i++]));
    }
}
Example #4
0
std::bitset<BLOCK_SIZE/2> perform_round(const std::bitset<BLOCK_SIZE/2>& data, const std::bitset<ROUND_KEY_SIZE>& round_key) {
	// expand/permute data from 32b to 48b using e_table
	std::bitset<48> expansion;
	for (int i = 0; i < e_table.size(); ++i) {
		expansion.set(i, data.test(e_table[i] - 1));
	}
	expansion ^= round_key;

	// perform s-box substitution on expanded data	
	std::bitset<32> s_box_out = perform_sbox_subst(expansion);
	
	// permute using P table
	std::bitset<32> shrinkage;
	for (int i = 0; i < p_table.size(); ++i)
		shrinkage.set(i, expansion.test(p_table[i] - 1));
	return shrinkage;
}
Example #5
0
File: 1200.cpp Project: jflyup/POJ
int main()
{
	int substr_len;
	//use the number of unique characters as number base
	int base;
	scanf("%d %d", &substr_len, &base);
	scanf("%s", str);
	int length = strlen(str);

	if(length < substr_len)
	{
		printf("0\n");
		return 0;
	}

	int unique_character = 0;
	int index = 0;
	while(unique_character < base)
	{
		if(value[str[index]] == 0)
			value[str[index]] = unique_character++;
		index++;
	}

	long rolling_hash = 0;
	for(int i = 0; i < substr_len; ++i)
		rolling_hash =  rolling_hash * base + value[str[i]];
	mark[rolling_hash] = 1;

	// Calculate hash value for next window of text: Remove leading digit, add trailing digit
	// hash(s[i+1 ... i+m] ) = base *(hash(s[i .. s+i-1]) – s[i] * (b^(m-1) ) )+ s[i + m] 

	//h = pow(base, substr_len - 1)
	int h = 1;
	for (int i = 0; i < substr_len - 1; i++)
		h *=  base; //int overflow?

	for(int i = 0; i < length - substr_len; i++)
	{
		rolling_hash = base *(rolling_hash - value[str[i]] * h) + value[str[i + substr_len]];
		mark[rolling_hash] = 1;
	}

	printf("%ld\n", mark.count());
	return 0;
};
Example #6
0
/* search_missing_combinations: traverse the BitTable
 * to find 0 bits and print out the corresponding
 * character sequences */
void
search_missing_combinations () {
    unsigned long missing_combs = 0;
    char buf[APPEARS_SEQSIZE + 1];
    for (unsigned long i = 0; i < TABLESIZE; i++) {
        if (!BitTable.test(i)) {
            index_to_tokens(i, buf);
            printf("  %s (index %lu)\n", buf, i);
            missing_combs++;
        }
    }
    if (missing_combs) {
        printf("For total %lu missing combinations found.\n",
                missing_combs);
    } else {
        printf("All combinations have appeared.\n");
    }
}
void MasksTableGenerator::generateCombinationsForK(
  const std::bitset<8> & combination,
  unsigned char offset,
  unsigned char k,
  std::vector<mask_t> & combinationMasks)
{
    if (k == 0)
    {
        combinationMasks.push_back(combination.to_ulong());
        return;
    }
    
    for (auto i = offset; i < m_numSamples - (k - 1); ++i)
    {
        auto newCombination = combination;
        newCombination.set(i, true);
        generateCombinationsForK(newCombination, i + 1, k - 1, combinationMasks);
    }
}
Example #8
0
float Apriori::calc_support(std::bitset<NUM> bsdata)
{
    float support = 0.0;
    unsigned count = 0;
    std::bitset<NUM> b;
    /*
     * 1. std::map<unsigned ,IndexBitSet_t>   m_base_dataset;
     *    (data,vec float) -> (data,bitset)
     * */
    if(bsdata.none()) return 0.0;
    for(auto iter = this->m_base_dataset.begin();
             iter!= this->m_base_dataset.end(); iter++){
        b.reset();
        b |= (this->m_bitset_vec[iter->second] & bsdata) ^ bsdata;
        if(b.none()) count++;
    }
    support = (count*1.0) / (this->m_base_dataset.size() * 1.0);
    return support;
}
Example #9
0
void BSO::randomFlip(std::bitset<chromoLength> &paramsBS, int type)
{
	
	return; //no change

	int pos = 0;
	if(type == 0) //flip in all position
	{
		pos = rand()%chromoLength;
	}
	else if(type == 1)  //flip im only
	{
		pos = rand()%imLength;
	}
	else if(type == 2)  //flip pf only
	{
		pos = imLength + rand()%pfLength;
	}
	paramsBS = paramsBS.flip(pos);
}
Example #10
0
int main()
{
    generate_sieve();

    long long result = 0;
    for (auto prime : primes) {
        int n = prime - 1;
        bool valid = true;
        for (int d=1; d*d<=n && valid; ++d) {
            if (n%d == 0) {
                valid &= sieve.test(d + n / d);
            }
        }
        if (valid) {
            result += n;
        }
    }

    std::cout << result << std::endl;
    return 0;
}
std::string  bin_to_hex(std::bitset<4> bit)
{
    if (bit.to_string().compare("0000") == 0)   return  std::string("0");
    if (bit.to_string().compare("0001") == 0)   return  std::string("1");
    if (bit.to_string().compare("0010") == 0)   return  std::string("2");
    if (bit.to_string().compare("0011") == 0)   return  std::string("3");
    if (bit.to_string().compare("0100") == 0)   return  std::string("4");
    if (bit.to_string().compare("0101") == 0)   return  std::string("5");
    if (bit.to_string().compare("0110") == 0)   return  std::string("6");
    if (bit.to_string().compare("0111") == 0)   return  std::string("7");
    if (bit.to_string().compare("1000") == 0)   return  std::string("8");
    if (bit.to_string().compare("1001") == 0)   return  std::string("9");
    if (bit.to_string().compare("1010") == 0)   return  std::string("A");
    if (bit.to_string().compare("1011") == 0)   return  std::string("B");
    if (bit.to_string().compare("1100") == 0)   return  std::string("C");
    if (bit.to_string().compare("1101") == 0)   return  std::string("D");
    if (bit.to_string().compare("1110") == 0)   return  std::string("E");
    if (bit.to_string().compare("1111") == 0)   return  std::string("F");
    
    else
        return std::string("");
    
}
  void NullDerefProtectionTransformer::instrumentCallInst(llvm::Instruction*
    TheCall, const std::bitset<32>& ArgIndexs) {
    llvm::CallSite CS = TheCall;

    for (int index = 0; index < 32; ++index) {
      if (!ArgIndexs.test(index)) continue;
      llvm::Value* Arg = CS.getArgument(index);
      if (!Arg) continue;
      llvm::Type* ArgTy = Arg->getType();

      llvm::BasicBlock* OldBB = TheCall->getParent();
      llvm::ICmpInst* Cmp
        = new llvm::ICmpInst(TheCall, llvm::CmpInst::ICMP_EQ, Arg,
                             llvm::Constant::getNullValue(ArgTy), "");

      llvm::Instruction* Inst = Builder->GetInsertPoint();
      llvm::BasicBlock* NewBB = OldBB->splitBasicBlock(Inst);

      OldBB->getTerminator()->eraseFromParent();
      llvm::BranchInst::Create(getTrapBB(NewBB), NewBB, Cmp, OldBB);
    }
  }
Example #13
0
void expect_op_result(
    std::string op,
    std::bitset<BITS> bits,
    quadset<BITS> q1,
    quadset<BITS> q2,
    quadset<BITS> quad,
    speed_tradeoff tradeoff = ACCURATE
) {
  for (bitpos i = 0; i < BITS; ++i) {
    if (bits.test(i) != quad.test(i)) {
      EXPECT_EQ(false, true) << q1.to_string() << ' ' << op << ' '
        << q2.to_string() << " = " << quad.to_string()
        << "; expected " << bits;
    }
  }
  if (tradeoff != FAST) {
    if ((BITS & 0x3F) != 0) {
      for (bitpos i = BITS; i < ((BITS+63) & ~0x3F); ++i) {
        EXPECT_EQ(false, quad.test(i)) << "found set bit (#"
          << i << ") out of set range in " << quad.to_string() << op;
      }
    }
  }
}
Example #14
0
File: dce.cpp Project: KOgames/hhvm
void remove_unused_locals(Context const ctx,
                          std::bitset<kMaxTrackedLocals> usedLocals) {
  if (!options.RemoveUnusedLocals) return;
  auto const func = ctx.func;

  /*
   * Removing unused locals in closures requires checking which ones
   * are captured variables so we can remove the relevant properties,
   * and then we'd have to mutate the CreateCl callsite, so we don't
   * bother for now.
   *
   * Note: many closure bodies have unused $this local, because of
   * some emitter quirk, so this might be worthwhile.
   */
  if (func->isClosureBody) return;

  func->locals.erase(
    std::remove_if(
      begin(func->locals) + func->params.size(),
      end(func->locals),
      [&] (const std::unique_ptr<php::Local>& l) {
        if (l->id < kMaxTrackedLocals && !usedLocals.test(l->id)) {
          FTRACE(2, "  removing: {}\n", local_string(borrow(l)));
          return true;
        }
        return false;
      }
    ),
    end(func->locals)
  );

  // Fixup local ids, in case we removed any.
  for (auto i = uint32_t{0}; i < func->locals.size(); ++i) {
    func->locals[i]->id = i;
  }
}
Example #15
0
FF::SearchState FF::Graph::SearchForPatterns(Graph *other, int row, Pattern &pattern, std::list<Pattern> &patterns, std::list<Node*> &affectedNodes, std::bitset<MAX_NODES> &affectedNodesBitset)
{
    // Fetch the current node
    Node *node = this->m_Nodes[row];

    if (affectedNodesBitset[node->Position]) {
        return NONE;
    }
    
    // Only if the pattern key is of the node's type
    if (this->m_Matrix[row][this->m_MatrixLength - 1] >= pattern.RequirementsLength && pattern.Key == node->Type) {
        // Create storage for the found matches
        std::list<Node*> matches;

        int nonTraversableMatches = 0;
        
        // Iterate of the columns for the given row
        #pragma omp parallel for ordered schedule(dynamic)
        for (unsigned int i = 0 ; i < this->m_Nodes.size() ; ++i) {
            // Narrow our matches set by only adding matches that were not yet marked
            // as affected
            if (!affectedNodesBitset[this->m_Nodes[i]->Position]) {
                // If the matrix contains a connection at row,i
                if (this->m_Matrix[row][i] == 1) {
                    // In case of a match
                    if (pattern.Requirements & (1 << this->m_Nodes[i]->Type.GetId())) {
                        matches.push_back(this->m_Nodes[i]);
                    }
                    // Nothing to do
                    else {
                        
                    }
                }
            } else {
                ++nonTraversableMatches;
            }
        }
        
        int s = matches.size() + nonTraversableMatches;

        // If the row contains all required types
        if (s >= pattern.RequirementsLength && s > 0) {
            // Invalidate the pattern
            pattern.Key = NullNodeType();
            
            ++this->m_PatternsMatched;

            // Mark the node as affected
            affectedNodesBitset.set(this->m_Nodes[row]->Position);
            
            // Insert the node into the affected nodes list
            affectedNodes.push_back(this->m_Nodes[row]);

            // Recursively search for more matches
            this->SearchInMatches(other, matches, patterns, affectedNodes, affectedNodesBitset);

            // Return searchstate
            return TRAVERSE;
        }
        // Row does not contain all required types, but is a leaf
        else if (s == 0 && pattern.RequirementsLength == 0) {
            // Invalidate the pattern
            pattern.Key = NullNodeType();

            ++this->m_PatternsMatched;
            
            // Mark the node as affected
            affectedNodesBitset.set(this->m_Nodes[row]->Position);
            
            // Insert the node into the affected nodes list
            affectedNodes.push_back(this->m_Nodes[row]);

            // Return searchstate
            return LEAF;
        }
    }
    
    return NONE;
}
bool set(std::bitset<N>& bset, uint32 pos) {
    bool old = bset.test(pos);
    bset.set(pos);
    return old;
}
Example #17
0
 inline bool isprime_safe(const INT& n) const
 {
   return p.at(static_cast<size_t>(n));
 }
Example #18
0
bool getDebugFlag(DebugFlags _flag) {

    return g_flags.test(_flag);

}
Example #19
0
 void serialize(output_archive & ar, const std::bitset<N> & bs, unsigned)
 {
     std::string const bits = bs.to_string();
     ar << bits;
 }
Example #20
0
namespace Tangram {

const static size_t MAX_WORKERS = 2;

std::mutex m_tilesMutex;
std::mutex m_tasksMutex;
std::mutex m_sceneMutex;
std::queue<std::function<void()>> m_tasks;
std::unique_ptr<TileWorker> m_tileWorker;
std::unique_ptr<TileManager> m_tileManager;
std::shared_ptr<Scene> m_scene;
std::shared_ptr<View> m_view;
std::unique_ptr<Labels> m_labels;
std::unique_ptr<InputHandler> m_inputHandler;

std::shared_ptr<Scene> m_nextScene;
std::vector<Scene::Update> m_sceneUpdates;

std::array<Ease, 4> m_eases;
enum class EaseField { position, zoom, rotation, tilt };
void setEase(EaseField _f, Ease _e) {
    m_eases[static_cast<size_t>(_f)] = _e;
    requestRender();
}
void clearEase(EaseField _f) {
    static Ease none = {};
    m_eases[static_cast<size_t>(_f)] = none;
}

static float g_time = 0.0;
static std::bitset<8> g_flags = 0;
static bool g_cacheGlState = false;

AsyncWorker m_asyncWorker;

void initialize(const char* _scenePath) {

    // For some unknown reasons, android fails to render the map, if same scene is reloaded, without resetting any of
    // the other Tangram global resources, which is what this method does.
    // As a work-around, re-initialization of an already loaded scene is done along with resetting all the Tangram
    // global resources.
    // NOTE: This will be refactored completely with Multiple Tangram Instances work being done in parallel.
    if (m_scene && m_scene->path() == _scenePath) {
        LOGD("Specified scene is already initalized.");
    }

    LOG("initialize");

    // Create view
    m_view = std::make_shared<View>();

    // Create a scene object
    m_scene = std::make_shared<Scene>(_scenePath);

    // Input handler
    m_inputHandler = std::make_unique<InputHandler>(m_view);

    // Instantiate workers
    m_tileWorker = std::make_unique<TileWorker>(MAX_WORKERS);

    // Create a tileManager
    m_tileManager = std::make_unique<TileManager>(*m_tileWorker);

    // Label setup
    m_labels = std::make_unique<Labels>();

    LOG("finish initialize");

}

void setScene(std::shared_ptr<Scene>& _scene) {
    {
        std::lock_guard<std::mutex> lock(m_sceneMutex);
        m_scene = _scene;
    }

    auto& camera = m_scene->camera();
    m_view->setCameraType(camera.type);

    switch (camera.type) {
    case CameraType::perspective:
        m_view->setVanishingPoint(camera.vanishingPoint.x,
                                  camera.vanishingPoint.y);
        if (camera.fovStops) {
            m_view->setFieldOfViewStops(camera.fovStops);
        } else {
            m_view->setFieldOfView(camera.fieldOfView);
        }
        break;
    case CameraType::isometric:
        m_view->setObliqueAxis(camera.obliqueAxis.x,
                               camera.obliqueAxis.y);
        break;
    case CameraType::flat:
        break;
    }

    if (m_scene->useScenePosition) {
        glm::dvec2 projPos = m_view->getMapProjection().LonLatToMeters(m_scene->startPosition);
        m_view->setPosition(projPos.x, projPos.y);
        m_view->setZoom(m_scene->startZoom);
    }

    m_inputHandler->setView(m_view);
    m_tileManager->setDataSources(_scene->dataSources());
    m_tileWorker->setScene(_scene);
    setPixelScale(m_view->pixelScale());

    bool animated = m_scene->animated() == Scene::animate::yes;

    if (m_scene->animated() == Scene::animate::none) {
        for (const auto& style : m_scene->styles()) {
            animated |= style->isAnimated();
        }
    }

    if (animated != isContinuousRendering()) {
        setContinuousRendering(animated);
    }
}

void loadScene(const char* _scenePath, bool _useScenePosition) {
    LOG("Loading scene file: %s", _scenePath);

    // Copy old scene
    auto scene = std::make_shared<Scene>(_scenePath);
    scene->useScenePosition = _useScenePosition;

    if (SceneLoader::loadScene(scene)) {
        setScene(scene);
    }
}

void loadSceneAsync(const char* _scenePath, bool _useScenePosition, MapReady _platformCallback) {
    LOG("Loading scene file (async): %s", _scenePath);

    {
        std::lock_guard<std::mutex> lock(m_sceneMutex);
        m_sceneUpdates.clear();
        m_nextScene = std::make_shared<Scene>(_scenePath);
        m_nextScene->useScenePosition = _useScenePosition;
    }

    Tangram::runAsyncTask([scene = m_nextScene, _platformCallback](){

            bool ok = SceneLoader::loadScene(scene);

            Tangram::runOnMainLoop([scene, ok, _platformCallback]() {
                    {
                        std::lock_guard<std::mutex> lock(m_sceneMutex);
                        if (scene == m_nextScene) {
                            m_nextScene.reset();
                        } else { return; }
                    }

                    if (ok) {
                        auto s = scene;
                        Tangram::setScene(s);
                        Tangram::applySceneUpdates();
                        if (_platformCallback) { _platformCallback(); }
                    }
                });
        });
}

void queueSceneUpdate(const char* _path, const char* _value) {
    std::lock_guard<std::mutex> lock(m_sceneMutex);
    m_sceneUpdates.push_back({_path, _value});
}

void applySceneUpdates() {

    LOG("Applying %d scene updates", m_sceneUpdates.size());

    if (m_nextScene) {
        // Changes are automatically applied once the scene is loaded
        return;
    }

    std::vector<Scene::Update> updates;
    {
        std::lock_guard<std::mutex> lock(m_sceneMutex);
        if (m_sceneUpdates.empty()) { return; }

        m_nextScene = std::make_shared<Scene>(*m_scene);
        m_nextScene->useScenePosition = false;

        updates = m_sceneUpdates;
        m_sceneUpdates.clear();
    }

    Tangram::runAsyncTask([scene = m_nextScene, updates = std::move(updates)](){

            SceneLoader::applyUpdates(scene->config(), updates);

            bool ok = SceneLoader::applyConfig(scene->config(), *scene);

            Tangram::runOnMainLoop([scene, ok]() {
                    if (scene == m_nextScene) {
                        std::lock_guard<std::mutex> lock(m_sceneMutex);
                        m_nextScene.reset();
                    } else { return; }

                    if (ok) {
                        auto s = scene;
                        Tangram::setScene(s);
                        Tangram::applySceneUpdates();
                    }
                });
        });
}

void resize(int _newWidth, int _newHeight) {

    LOGS("resize: %d x %d", _newWidth, _newHeight);
    LOG("resize: %d x %d", _newWidth, _newHeight);

    glViewport(0, 0, _newWidth, _newHeight);

    if (m_view) {
        m_view->setSize(_newWidth, _newHeight);
    }

    Primitives::setResolution(_newWidth, _newHeight);
}

bool update(float _dt) {

    FrameInfo::beginUpdate();

    g_time += _dt;

    bool viewComplete = true;

    for (auto& ease : m_eases) {
        if (!ease.finished()) {
            ease.update(_dt);
            viewComplete = false;
        }
    }

    size_t nTasks = 0;
    {
        std::lock_guard<std::mutex> lock(m_tasksMutex);
        nTasks = m_tasks.size();
    }
    while (nTasks-- > 0) {
        std::function<void()> task;
        {
            std::lock_guard<std::mutex> lock(m_tasksMutex);
            task = m_tasks.front();
            m_tasks.pop();
        }
        task();
    }

    m_inputHandler->update(_dt);
    m_view->update();

    for (const auto& style : m_scene->styles()) {
        style->onBeginUpdate();
    }

    {
        std::lock_guard<std::mutex> lock(m_tilesMutex);
        ViewState viewState {
            m_view->getMapProjection(),
            m_view->changedOnLastUpdate(),
            glm::dvec2{m_view->getPosition().x, -m_view->getPosition().y },
            m_view->getZoom()
        };

        m_tileManager->updateTileSets(viewState, m_view->getVisibleTiles());

        auto& tiles = m_tileManager->getVisibleTiles();

        if (m_view->changedOnLastUpdate() ||
            m_tileManager->hasTileSetChanged()) {

            for (const auto& tile : tiles) {
                tile->update(_dt, *m_view);
            }
            m_labels->updateLabelSet(*m_view, _dt, m_scene->styles(), tiles,
                                     m_tileManager->getTileCache());

        } else {
            m_labels->updateLabels(*m_view, _dt, m_scene->styles(), tiles);
        }
    }

    FrameInfo::endUpdate();

    bool viewChanged = m_view->changedOnLastUpdate();
    bool tilesChanged = m_tileManager->hasTileSetChanged();
    bool tilesLoading = m_tileManager->hasLoadingTiles();
    bool labelsNeedUpdate = m_labels->needUpdate();
    bool resourceLoading = (m_scene->m_resourceLoad > 0);
    bool nextScene = bool(m_nextScene);

    if (viewChanged || tilesChanged || tilesLoading || labelsNeedUpdate || resourceLoading || nextScene) {
        viewComplete = false;
    }

    // Request for render if labels are in fading in/out states
    if (m_labels->needUpdate()) { requestRender(); }

    return viewComplete;
}

void render() {
    FrameInfo::beginFrame();

    // Invalidate render states for new frame
    if (!g_cacheGlState) {
        RenderState::invalidate();
    }

    // Set up openGL for new frame
    RenderState::depthWrite(GL_TRUE);
    auto& color = m_scene->background();
    RenderState::clearColor(color.r / 255.f, color.g / 255.f, color.b / 255.f, color.a / 255.f);
    GL_CHECK(glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT));

    for (const auto& style : m_scene->styles()) {
        style->onBeginFrame();
    }

    {
        std::lock_guard<std::mutex> lock(m_tilesMutex);

        // Loop over all styles
        for (const auto& style : m_scene->styles()) {

            style->onBeginDrawFrame(*m_view, *m_scene);

            // Loop over all tiles in m_tileSet
            for (const auto& tile : m_tileManager->getVisibleTiles()) {
                style->draw(*tile);
            }

            style->onEndDrawFrame();
        }
    }

    m_labels->drawDebug(*m_view);

    FrameInfo::draw(*m_view, *m_tileManager);
}

void setPositionNow(double _lon, double _lat) {

    glm::dvec2 meters = m_view->getMapProjection().LonLatToMeters({ _lon, _lat});
    m_view->setPosition(meters.x, meters.y);
    m_inputHandler->cancelFling();
    requestRender();

}

void setPosition(double _lon, double _lat) {

    setPositionNow(_lon, _lat);
    clearEase(EaseField::position);

}

void setPosition(double _lon, double _lat, float _duration, EaseType _e) {

    double lon_start, lat_start;
    getPosition(lon_start, lat_start);
    auto cb = [=](float t) { setPositionNow(ease(lon_start, _lon, t, _e), ease(lat_start, _lat, t, _e)); };
    setEase(EaseField::position, { _duration, cb });

}

void getPosition(double& _lon, double& _lat) {

    glm::dvec2 meters(m_view->getPosition().x, m_view->getPosition().y);
    glm::dvec2 degrees = m_view->getMapProjection().MetersToLonLat(meters);
    _lon = degrees.x;
    _lat = degrees.y;

}

void setZoomNow(float _z) {

    m_view->setZoom(_z);
    m_inputHandler->cancelFling();
    requestRender();

}

void setZoom(float _z) {

    setZoomNow(_z);
    clearEase(EaseField::zoom);

}

void setZoom(float _z, float _duration, EaseType _e) {

    float z_start = getZoom();
    auto cb = [=](float t) { setZoomNow(ease(z_start, _z, t, _e)); };
    setEase(EaseField::zoom, { _duration, cb });

}

float getZoom() {

    return m_view->getZoom();

}

void setRotationNow(float _radians) {

    m_view->setRoll(_radians);
    requestRender();

}

void setRotation(float _radians) {

    setRotationNow(_radians);
    clearEase(EaseField::rotation);

}

void setRotation(float _radians, float _duration, EaseType _e) {

    float radians_start = getRotation();

    // Ease over the smallest angular distance needed
    float radians_delta = glm::mod(_radians - radians_start, (float)TWO_PI);
    if (radians_delta > PI) { radians_delta -= TWO_PI; }
    _radians = radians_start + radians_delta;

    auto cb = [=](float t) { setRotationNow(ease(radians_start, _radians, t, _e)); };
    setEase(EaseField::rotation, { _duration, cb });

}

float getRotation() {

    return m_view->getRoll();

}


void setTiltNow(float _radians) {

    m_view->setPitch(_radians);
    requestRender();

}

void setTilt(float _radians) {

    setTiltNow(_radians);
    clearEase(EaseField::tilt);

}

void setTilt(float _radians, float _duration, EaseType _e) {

    float tilt_start = getTilt();
    auto cb = [=](float t) { setTiltNow(ease(tilt_start, _radians, t, _e)); };
    setEase(EaseField::tilt, { _duration, cb });

}

float getTilt() {

    return m_view->getPitch();

}

void screenToWorldCoordinates(double& _x, double& _y) {

    m_view->screenToGroundPlane(_x, _y);
    glm::dvec2 meters(_x + m_view->getPosition().x, _y + m_view->getPosition().y);
    glm::dvec2 lonLat = m_view->getMapProjection().MetersToLonLat(meters);
    _x = lonLat.x;
    _y = lonLat.y;

}

bool lonLatToScreenPosition(double _lon, double _lat, float& _x, float& _y) {
    bool clipped = false;

    glm::vec2 screenCoords = m_view->lonLatToScreenPosition(_lon, _lat, clipped);

    _x = screenCoords.x;
    _y = screenCoords.y;

    bool withinViewport = _x >= 0.f && _x <= m_view->getWidth() && _y >= 0.f && _y <= m_view->getHeight();

    return clipped || !withinViewport;
}

void setPixelScale(float _pixelsPerPoint) {

    if (m_view) {
        m_view->setPixelScale(_pixelsPerPoint);
    }

    for (auto& style : m_scene->styles()) {
        style->setPixelScale(_pixelsPerPoint);
    }
}

void setCameraType(int _type) {

    m_view->setCameraType(static_cast<CameraType>(_type));
    requestRender();

}

int getCameraType() {

    return static_cast<int>(m_view->cameraType());

}

void addDataSource(std::shared_ptr<DataSource> _source) {
    if (!m_tileManager) { return; }
    std::lock_guard<std::mutex> lock(m_tilesMutex);
    m_tileManager->addClientDataSource(_source);
}

bool removeDataSource(DataSource& source) {
    if (!m_tileManager) { return false; }
    std::lock_guard<std::mutex> lock(m_tilesMutex);
    return m_tileManager->removeClientDataSource(source);
}

void clearDataSource(DataSource& _source, bool _data, bool _tiles) {
    if (!m_tileManager) { return; }
    std::lock_guard<std::mutex> lock(m_tilesMutex);

    if (_tiles) { m_tileManager->clearTileSet(_source.id()); }
    if (_data) { _source.clearData(); }

    requestRender();
}

void handleTapGesture(float _posX, float _posY) {

    m_inputHandler->handleTapGesture(_posX, _posY);

}

void handleDoubleTapGesture(float _posX, float _posY) {

    m_inputHandler->handleDoubleTapGesture(_posX, _posY);

}

void handlePanGesture(float _startX, float _startY, float _endX, float _endY) {

    m_inputHandler->handlePanGesture(_startX, _startY, _endX, _endY);

}

void handleFlingGesture(float _posX, float _posY, float _velocityX, float _velocityY) {

    m_inputHandler->handleFlingGesture(_posX, _posY, _velocityX, _velocityY);

}

void handlePinchGesture(float _posX, float _posY, float _scale, float _velocity) {

    m_inputHandler->handlePinchGesture(_posX, _posY, _scale, _velocity);

}

void handleRotateGesture(float _posX, float _posY, float _radians) {

    m_inputHandler->handleRotateGesture(_posX, _posY, _radians);

}

void handleShoveGesture(float _distance) {

    m_inputHandler->handleShoveGesture(_distance);

}

void setDebugFlag(DebugFlags _flag, bool _on) {

    g_flags.set(_flag, _on);
    m_view->setZoom(m_view->getZoom()); // Force the view to refresh

}

bool getDebugFlag(DebugFlags _flag) {

    return g_flags.test(_flag);

}

void toggleDebugFlag(DebugFlags _flag) {

    g_flags.flip(_flag);
    m_view->setZoom(m_view->getZoom()); // Force the view to refresh

    // Rebuild tiles for debug modes that needs it
    if (_flag == DebugFlags::proxy_colors
     || _flag == DebugFlags::tile_bounds
     || _flag == DebugFlags::tile_infos) {
        if (m_tileManager) {
            std::lock_guard<std::mutex> lock(m_tilesMutex);
            m_tileManager->clearTileSets();
        }
    }
}

const std::vector<TouchItem>& pickFeaturesAt(float _x, float _y) {
    return m_labels->getFeaturesAtPoint(*m_view, 0, m_scene->styles(),
                                        m_tileManager->getVisibleTiles(),
                                        _x, _y);
}

void useCachedGlState(bool _useCache) {
    g_cacheGlState = _useCache;
}

void setupGL() {

    LOG("setup GL");

    if (m_tileManager) {
        m_tileManager->clearTileSets();
    }

    // Reconfigure the render states. Increases context 'generation'.
    // The OpenGL context has been destroyed since the last time resources were
    // created, so we invalidate all data that depends on OpenGL object handles.
    RenderState::invalidate();
    RenderState::increaseGeneration();

    // Set default primitive render color
    Primitives::setColor(0xffffff);

    // Load GL extensions and capabilities
    Hardware::loadExtensions();
    Hardware::loadCapabilities();

    Hardware::printAvailableExtensions();
}

void runOnMainLoop(std::function<void()> _task) {
    std::lock_guard<std::mutex> lock(m_tasksMutex);
    m_tasks.emplace(std::move(_task));

    requestRender();
}

void runAsyncTask(std::function<void()> _task) {
    m_asyncWorker.enqueue(std::move(_task));
}

float frameTime() {
    return g_time;
}

}
Example #21
0
void setDebugFlag(DebugFlags _flag, bool _on) {

    g_flags.set(_flag, _on);
    m_view->setZoom(m_view->getZoom()); // Force the view to refresh

}
	bool checkFlag(T f, Args ... rest) const
	{
		if (sizeof ...(rest))
			return FLAG.test(f) && checkFlag (rest...);
		return FLAG.test (f);
	}
//Sets address in the binary form
void IPAddress::setAddressAsBinary(std::bitset<32> ip_address)
{
	unsigned long int value = ip_address.to_ulong();
	setAddressAsUnsignedLongInt(value);
}
Example #24
0
 bool TestAvailableState(EKnockBackAnimationState s) const { return x80_availableStates.test(size_t(s)); }
Example #25
0
 void SetAvailableState(EKnockBackAnimationState s, bool b) { x80_availableStates.set(size_t(s), b); }
Example #26
0
void toggleDebugFlag(DebugFlags _flag) {

    g_flags.flip(_flag);
    m_view->setZoom(m_view->getZoom()); // Force the view to refresh

}
Example #27
0
 void operator ()(Shuttler& shuttle, const char* name,
     std::bitset<N> value) const {
   std::uint64_t v = static_cast<std::uint64_t>(value.to_ullong());
   shuttle.Send(name, v);
 }
Example #28
0
BOOL CPEParser::AnalizeExport()
{
	//флаги наличия имени у функции (определяется заблаговременно, чтобы не было warning'а из-за goto).
	static std::bitset<0x10000> NamesFlags;
	NamesFlags.reset();

	//получить директорию экспорта
	PIMAGE_DATA_DIRECTORY pDataDirectory=mpImageOptionalHeader->DataDirectory+IMAGE_DIRECTORY_ENTRY_EXPORT;
	//если экспорта нет, закончить
	if(!pDataDirectory->VirtualAddress || pDataDirectory->Size<sizeof(IMAGE_EXPORT_DIRECTORY)) return TRUE;
	//считать дескриптор экспорта
	CYBER_ADDRESS DescriptorAddress=mSettings.BaseAddress+pDataDirectory->VirtualAddress;
	IMAGE_EXPORT_DIRECTORY Descriptor;
	try
	{
		mpMemory->Data(&Descriptor,DescriptorAddress,sizeof(IMAGE_EXPORT_DIRECTORY));
	}
	catch(CCyberMemoryPageFaultException)
	{
		goto error;
	}

	//создать список экспорта
	CImageListExports* pExportsList=new CImageListExports;
	//добавить его в список дополнительных объектов
	mpExtendMap->insert(std::make_pair(IMAGE_EXTEND_LIST_EXPORTS,pExportsList));
	//получить список функций
	std::list<CImageListExports::CExportFunction*>* pFunctionsList=pExportsList->GetList();

	//получить количество функций и имен
	UINT FunctionsCount=Descriptor.NumberOfFunctions;
	if(FunctionsCount>0x10000) goto error;
	UINT NamesCount=Descriptor.NumberOfNames;
	if(NamesCount>0x10000) goto error;
	//получить таблицы имен, адресов и ординалов
	CYBER_ADDRESS AddressTable=mSettings.BaseAddress+Descriptor.AddressOfFunctions;
	CYBER_ADDRESS NamesTable=mSettings.BaseAddress+Descriptor.AddressOfNames;
	CYBER_ADDRESS OrdinalsTable=mSettings.BaseAddress+Descriptor.AddressOfNameOrdinals;

	//цикл по именам
	for(UINT i=0;i<NamesCount;++i)
	{
		//считать имя, ординал, адрес и форвард функции
		LPSTR szName;
		LPSTR szForward;
		WORD Ordinal;
		CYBER_ADDRESS Address;
		//флаг форварда
		BOOL IsForward=FALSE;
		try
		{
			//считать имя
			szName=mpMemory->ReadASCIIZ(mSettings.BaseAddress+mpMemory->Dword(NamesTable+i*sizeof(DWORD)));
			//считать ординал
			Ordinal=mpMemory->Word(OrdinalsTable+i*sizeof(WORD));
			//считать адрес
			Address=mpMemory->Dword(AddressTable+Ordinal*sizeof(DWORD));

			//если адрес находится в пределах таблицы экспорта, значит, это форвард
			if(Address>=pDataDirectory->VirtualAddress && Address<pDataDirectory->VirtualAddress+pDataDirectory->Size)
				IsForward=TRUE;
			Address+=mSettings.BaseAddress;

			if(IsForward)
				//считать имя форвард-функции
				szForward=mpMemory->ReadASCIIZ(Address);
		}
		catch(CCyberMemoryPageFaultException)
		{
			goto error;
		}

		//указать флаг наличия имени
		NamesFlags[Ordinal]=true;

#ifdef UNICODE
		//преобразовать строки в Unicode
		UINT NameLength=strlen(szName)+1;
		LPTSTR szUnicodeName=new TCHAR[NameLength];
		MultiByteToWideChar(CP_ACP,0,szName,-1,szUnicodeName,NameLength);
		SafeDeleteMassive(szName);

		UINT ForwardLength;
		LPTSTR szUnicodeForward;
		if(IsForward)
		{
			ForwardLength=strlen(szForward)+1;
			szUnicodeForward=new TCHAR[ForwardLength];
			MultiByteToWideChar(CP_ACP,0,szForward,-1,szUnicodeForward,ForwardLength);
			SafeDeleteMassive(szForward);
		}
#define szName szUnicodeName
#define szForward szUnicodeForward
#endif

		//добавить функцию в список
		if(IsForward)
			pFunctionsList->push_back(new CImageListExports::CExportFunction(szName,Ordinal,szForward));
		else
			pFunctionsList->push_back(new CImageListExports::CExportFunction(szName,Ordinal,Address));

		//если функция локальная
		if(!IsForward)
		{
			//сформировать имя и установить метку
			LPTSTR szLabelName=new TCHAR[NameLength+6];
			_stprintf(szLabelName,TEXT("__exp_%s"),szName);
			CAddressData* pAddressData=mpAddressMap->OpenAddress(Address);
			CLabel* pLabel=new CLabel(szLabelName);
			SafeDeleteMassive(szLabelName);
			pAddressData->SetLabel(pLabel);
			pLabel->Release();
			//создать функцию
			pAddressData->CreateSubroutine();
			pAddressData->Release();
		}

		//освободить память
		SafeDeleteMassive(szName);
		if(IsForward)
			SafeDeleteMassive(szForward);

#ifdef UNICODE
#undef szName
#undef szForward
#endif
	}

	//цикл по функциям
	for(UINT i=0;i<FunctionsCount;++i)
	{
		//если функция имеет имя, значит, она уже обработана
		if(NamesFlags[i]) continue;

		//считать адрес
		CYBER_ADDRESS Address;
		try
		{
			Address=mSettings.BaseAddress+mpMemory->Dword(AddressTable+i*sizeof(DWORD));
		}
		catch(CCyberMemoryPageFaultException)
		{
			goto error;
		}

		//добавить функцию в список
		pFunctionsList->push_back(new CImageListExports::CExportFunction(NULL,i,Address));
	}

	return TRUE;

	//ошибка
error:
	//раздел экспорта искажен
	MessageBox(NULL,TEXT("The export section in this file is non-readable.\nPE Parser coudn't parse export."),TEXT("Export parsing"),MB_ICONSTOP);

	return FALSE;
}
Example #29
0
/* parse_seq_file: read in the sequence stream and set
 * the global BitTable variable accordingly. */
bool
parse_seq_file (const char* fname) {
    FILE* infile;
    char c;
    unsigned long lineno = 1L;
    index_t index;
    unsigned long tokens_seen = 0L;

    if (NULL == (infile = fopen(fname, "r"))) {
        fprintf(stderr,
                "ERROR: Failed to open input file %s for reading: "
                "%s\n",
                fname, strerror(errno));
        return false;
    }

    for (;;) {
        bool found_token = false;

        c = getc(infile);
        if (EOF == c) {
            if (ferror(infile)) {
                fprintf(stderr, "ERROR: Failed to read from file %s:"
                        "%s\n",
                        fname, strerror(errno));
                return false;
            }
            break;
        }

        switch (c) {
            case '\n':
                lineno++;
            case ' ':
            case '\t':
            case '\r':
                /* ignored spaces */
                break;
            case 'G':
                index <<= BITS_PER_TOKEN;
                index |= G;
                found_token = true;
                break;
            case 'A':
                index <<= BITS_PER_TOKEN;
                index |= A;
                found_token = true;
                break;
            case 'T':
                index <<= BITS_PER_TOKEN;
                index |= T;
                found_token = true;
                break;
            case 'C':
                index <<= BITS_PER_TOKEN;
                index |= C;
                found_token = true;
                break;
            default:
                fprintf(stderr, "ERROR: File %s: line %lu: "
                        "Invalid character found: '%c' (0x%x)\n",
                        fname, lineno, c, c);
                return false;
                break;
        }
        if (found_token) {
            if (tokens_seen < APPEARS_SEQSIZE) {
                tokens_seen++;
            }
            if (tokens_seen >= APPEARS_SEQSIZE) {
                /* register this subsequence combination */
                unsigned long index_ulong = index.to_ulong();
                DD("setting the %luth bit", index_ulong);
                BitTable.set(index_ulong, 1);
            }
        }
    }
    fclose(infile);
    return true;
}
Example #30
0
namespace Tangram {

std::unique_ptr<TileManager> m_tileManager;
std::shared_ptr<Scene> m_scene;
std::shared_ptr<View> m_view;
std::unique_ptr<Labels> m_labels;
std::unique_ptr<Skybox> m_skybox;
std::unique_ptr<InputHandler> m_inputHandler;
std::mutex m_tilesMutex;

static float g_time = 0.0;
static std::bitset<8> g_flags = 0;
int log_level = 2;

void initialize(const char* _scenePath) {

    if (m_tileManager) {
        LOG("Notice: Already initialized");
        return;
    }

    LOG("initialize");

    // Create view
    m_view = std::make_shared<View>();

    // Create a scene object
    m_scene = std::make_shared<Scene>();

    // Input handler
    m_inputHandler = std::unique_ptr<InputHandler>(new InputHandler(m_view));

    // Create a tileManager
    m_tileManager = TileManager::GetInstance();

    // Pass references to the view and scene into the tile manager
    m_tileManager->setView(m_view);

    // label setup
    m_labels = std::unique_ptr<Labels>(new Labels());

    loadScene(_scenePath, true);

    glm::dvec2 projPos = m_view->getMapProjection().LonLatToMeters(m_scene->startPosition);
    m_view->setPosition(projPos.x, projPos.y);
    m_view->setZoom(m_scene->startZoom);

    LOG("finish initialize");

}

void loadScene(const char* _scenePath, bool _setPositionFromScene) {
    LOG("Loading scene file: %s", _scenePath);

    auto sceneString = stringFromFile(setResourceRoot(_scenePath).c_str(), PathType::resource);

    bool setPositionFromCurrentView = bool(m_scene);

    auto scene = std::make_shared<Scene>();
    if (SceneLoader::loadScene(sceneString, *scene)) {
        m_scene = scene;
        m_scene->fontContext()->addFont("FiraSans", "Medium", "");
        if (setPositionFromCurrentView && !_setPositionFromScene) {
            m_scene->view()->setPosition(m_view->getPosition());
            m_scene->view()->setZoom(m_view->getZoom());
        }
        m_view = m_scene->view();
        m_inputHandler->setView(m_view);
        m_tileManager->setView(m_view);
        m_tileManager->setScene(scene);

    }
}

void resize(int _newWidth, int _newHeight) {

    LOG("resize: %d x %d", _newWidth, _newHeight);

    glViewport(0, 0, _newWidth, _newHeight);

    if (m_view) {
        m_view->setSize(_newWidth, _newHeight);
    }

    for (auto& style : m_scene->styles()) {
        style->viewportHasChanged();
    }

    Primitives::setResolution(_newWidth, _newHeight);

    while (Error::hadGlError("Tangram::resize()")) {}

}

void update(float _dt) {

    g_time += _dt;

    m_inputHandler->update(_dt);

    m_view->update();

    {
        std::lock_guard<std::mutex> lock(m_tilesMutex);

        m_tileManager->updateTileSets();

        if (m_view->changedOnLastUpdate() || m_tileManager->hasTileSetChanged() || m_labels->needUpdate()) {

            auto& tiles = m_tileManager->getVisibleTiles();

            for (const auto& tile : tiles) {
                tile->update(_dt, *m_view);
            }

            m_labels->update(*m_view, _dt, m_scene->styles(), tiles);
        }

        bool animated = false;
        for (const auto& style : m_scene->styles()) {
            if (style->isAnimated()) {
                animated = true;
                break;
            }
        }
        if (animated != isContinuousRendering()) {
            setContinuousRendering(animated);
        }
    }
}

void render() {

    // Set up openGL for new frame
    RenderState::depthWrite(GL_TRUE);
    auto& color = m_scene->background();
    RenderState::clearColor(color.r / 255.f, color.g / 255.f, color.b / 255.f, color.a / 255.f);
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

    {
        std::lock_guard<std::mutex> lock(m_tilesMutex);

        // Loop over all styles
        for (const auto& style : m_scene->styles()) {

            // Set time uniforms style's shader programs
            style->getShaderProgram()->setUniformf("u_time", g_time);

            style->onBeginDrawFrame(*m_view, *m_scene);

            // Loop over all tiles in m_tileSet
            for (const auto& tile : m_tileManager->getVisibleTiles()) {
                tile->draw(*style, *m_view);
            }

            style->onEndDrawFrame();
        }
    }

    m_labels->drawDebug(*m_view);

    while (Error::hadGlError("Tangram::render()")) {}
}

void setPosition(double _lon, double _lat) {

    glm::dvec2 meters = m_view->getMapProjection().LonLatToMeters({ _lon, _lat});
    m_view->setPosition(meters.x, meters.y);
    requestRender();

}

void getPosition(double& _lon, double& _lat) {

    glm::dvec2 meters(m_view->getPosition().x, m_view->getPosition().y);
    glm::dvec2 degrees = m_view->getMapProjection().MetersToLonLat(meters);
    _lon = degrees.x;
    _lat = degrees.y;

}

void setZoom(float _z) {

    m_view->setZoom(_z);
    requestRender();

}

float getZoom() {

    return m_view->getZoom();

}

void setRotation(float _radians) {

    m_view->setRoll(_radians);
    requestRender();

}

float getRotation() {

    return m_view->getRoll();

}


void setTilt(float _radians) {

    m_view->setPitch(_radians);
    requestRender();

}

float getTilt() {

    return m_view->getPitch();

}

void screenToWorldCoordinates(double& _x, double& _y) {

    m_view->screenToGroundPlane(_x, _y);
    glm::dvec2 meters(_x + m_view->getPosition().x, _y + m_view->getPosition().y);
    glm::dvec2 lonLat = m_view->getMapProjection().MetersToLonLat(meters);
    _x = lonLat.x;
    _y = lonLat.y;

}

void setPixelScale(float _pixelsPerPoint) {

    if (m_view) {
        m_view->setPixelScale(_pixelsPerPoint);
    }

    for (auto& style : m_scene->styles()) {
        style->setPixelScale(_pixelsPerPoint);
    }
}

void addDataSource(std::shared_ptr<DataSource> _source) {
    if (!m_tileManager) { return; }
    std::lock_guard<std::mutex> lock(m_tilesMutex);

    m_tileManager->addDataSource(_source);
}

void clearDataSource(DataSource& _source, bool _data, bool _tiles) {
    if (!m_tileManager) { return; }
    std::lock_guard<std::mutex> lock(m_tilesMutex);

    if (_tiles) { m_tileManager->clearTileSet(_source.id()); }
    if (_data) { _source.clearData(); }

    requestRender();
}

void handleTapGesture(float _posX, float _posY) {

    m_inputHandler->handleTapGesture(_posX, _posY);

}

void handleDoubleTapGesture(float _posX, float _posY) {

    m_inputHandler->handleDoubleTapGesture(_posX, _posY);

}

void handlePanGesture(float _startX, float _startY, float _endX, float _endY) {

    m_inputHandler->handlePanGesture(_startX, _startY, _endX, _endY);

}

void handlePinchGesture(float _posX, float _posY, float _scale, float _velocity) {

    m_inputHandler->handlePinchGesture(_posX, _posY, _scale, _velocity);

}

void handleRotateGesture(float _posX, float _posY, float _radians) {

    m_inputHandler->handleRotateGesture(_posX, _posY, _radians);

}

void handleShoveGesture(float _distance) {

    m_inputHandler->handleShoveGesture(_distance);

}

void setDebugFlag(DebugFlags _flag, bool _on) {

    g_flags.set(_flag, _on);
    m_view->setZoom(m_view->getZoom()); // Force the view to refresh

}

bool getDebugFlag(DebugFlags _flag) {

    return g_flags.test(_flag);

}

void toggleDebugFlag(DebugFlags _flag) {

    g_flags.flip(_flag);
    m_view->setZoom(m_view->getZoom()); // Force the view to refresh

}

const std::vector<TouchItem>& pickFeaturesAt(float _x, float _y) {
    return m_labels->getFeaturesAtPoint(*m_view, 0, m_scene->styles(),
                                        m_tileManager->getVisibleTiles(),
                                        _x, _y);
}



void setupGL() {

    LOG("setup GL");

    if (m_tileManager) {
        m_tileManager->clearTileSets();

        for (auto& style : m_scene->styles()) {
           style->notifyGLContextLost();
        }
    }

    // The OpenGL context has been destroyed since the last time resources were created,
    // so we invalidate all data that depends on OpenGL object handles.

    // ShaderPrograms are invalidated and immediately rebuilt
    ShaderProgram::invalidateAllPrograms();

    // Buffer objects are invalidated and re-uploaded the next time they are used
    VboMesh::invalidateAllVBOs();

    // Texture objects are invalidated and re-uploaded the next time they are updated
    Texture::invalidateAllTextures();

    // Reconfigure the render states
    RenderState::configure();

    // Set default primitive render color
    Primitives::setColor(0xffffff);

    // Load GL extensions
    GLExtensions::load();

    GLExtensions::printAvailableExtensions();

    while (Error::hadGlError("Tangram::setupGL()")) {}
}

}