Exemple #1
0
bool solve2Quads(const double a20, const double a02, const double a11, const double a10, const double a01, const double a00,
                const double b20, const double b02, const double b11, const double b10, const double b01, const double b00,
                std::vector<double>& E1, std::vector<double>& E2,
                bool verbose){

  // The procedure used in this function relies on a20 != 0 or b20 != 0
  if(a20 == 0. && b20 == 0.){
    
    if(a02 != 0. || b02 != 0.){
      // Swapping E1 <-> E2 should suffice!
      return solve2Quads(a02, a20, a11, a01, a10, a00,
                          b02, b20, b11, b01, b10, b00,
                          E2, E1, verbose);
    }else{
      return solve2QuadsDeg(a11, a10, a01, a00,
                            b11, b10, b01, b00,
                            E1, E2, verbose);
    }
  
  }

  const double alpha = b20*a02-a20*b02;
  const double beta = b20*a11-a20*b11;
  const double gamma = b20*a10-a20*b10;
  const double delta = b20*a01-a20*b01;
  const double omega = b20*a00-a20*b00;

  const double a = a20*SQ(alpha) + a02*SQ(beta) - a11*alpha*beta;
  const double b = 2.*a20*alpha*delta - a11*( alpha*gamma + delta*beta ) - a10*alpha*beta + 2.*a02*beta*gamma + a01*SQ(beta);
  const double c = a20*SQ(delta) + 2.*a20*alpha*omega - a11*( delta*gamma + omega*beta ) - a10*( alpha*gamma + delta*beta )
  + a02*SQ(gamma) + 2.*a01*beta*gamma + a00*SQ(beta);
  const double d = 2.*a20*delta*omega - a11*omega*gamma - a10*( delta*gamma + omega*beta ) + a01*SQ(gamma) + 2.*a00*beta*gamma;
  const double e = a20*SQ(omega) - a10*omega*gamma + a00*SQ(gamma);

  solveQuartic(a, b, c, d, e, E2, verbose);

  for(unsigned short i = 0; i < E2.size(); ++i){

    const double e2 = E2[i];
    
    if(beta*e2 + gamma != 0.){
      // Everything OK
      
      const double e1 = -(alpha * SQ(e2) + delta*e2 + omega)/(beta*e2 + gamma);
      E1.push_back(e1);
    
    }else if(alpha*SQ(e2) + delta*e2 + omega == 0.){
      // Up to two solutions for e1
      
      std::vector<double> e1;
      
      if( !solveQuadratic(a20, a11*e2 + a10, a02*SQ(e2) + a01*e2 + a00, e1, verbose) ){
        
        if( !solveQuadratic(b20, b11*e2 + b10, b02*SQ(e2) + b01*e2 + b00, e1, verbose) ){
          cout << "Error in solve2Quads: there should be at least one solution for e1!" << endl;
          E1.clear();
          E2.clear();
          return false;
        }
      
      }else{
        // We have either a double, or two roots for e1
        // In this case, e2 must be twice degenerate!
        // Since in E2 degenerate roots are grouped, E2[i+1] shoud exist and be equal to e2
        // We then go straight for i+2.
        
        if(i < E2.size() - 1){
          
          if(e2 != E2[i+1]){
            cout << "Error in solve2Quads: if there are two solutions for e1, e2 should be degenerate!" << endl;
            E1.clear();
            E2.clear();
            return false;
          }
          
          E1.push_back(e1[0]);
          E1.push_back(e1[1]);
          ++i;
          continue;
        
        }else{
          cout << "Error in solve2Quads: if there are two solutions for e1, e2 should be degenerate!" << endl;
          E1.clear();
          E2.clear();
          return false;
        }
      
      }
    
    }else{
      // There is no solution given this e2
      E2.erase(E2.begin() + i);
      --i;
    }
  
  }

  return true;
}
void Level::SimplifyGridPath(std::vector<PathFinder::SimpleNode>& path)
{
	// This function will remove nodes from a grid path to simplify the path.
	// Nodes that are directly visible to each other (the level is not obstructing view)
	// can be removed up until two nodes that can't see each other directly anylonger.
	// Nodes that are marked as unpassable on the navigation grid are also not removed.
	// This is to prevent the avatar from getting stuck at a corner.


	if (path.size() < 3)
	{
		return;
	}

	std::vector<PathFinder::SimpleNode>::iterator it = path.begin();

	while (it < (path.end() - 2))
	{
		// Check the grid-based x and y distance between this node, and the next one.
		int dX;
		int dY;

		dX = (it + 1)->x - it->x;
		dY = (it + 1)->y - it->y;

		// If it is already a diagonal-based movement, we can skip the node
		if ((std::abs(dX) == 1) && (std::abs(dY) == 1))
		{
			++it;
			continue;
		}

		// If we get here, it is not a diagonal-based movement.
		// When the node afterwards, however, is a diagonal one,
		// and no corner is in the way, then we can erase the node in between
		dX = (it + 2)->x - it->x;
		dY = (it + 2)->y - it->y;

		if ((std::abs(dX) == 1) && (std::abs(dY) == 1) &&
			m_NavigationGrid[it->y + dY][it->x] &&
			m_NavigationGrid[it->y][it->x + dX])
		{
			it = path.erase(it + 1);
		}
		else
		{
			++it;
		}
	}

	// Recurring raycast parameters
	/*DOUBLE2 intersectionRef(0, 0);
	DOUBLE2 normalRef(0, 0);
	double levelFraction = 0;
	bool levelHit = false;

	size_t currentIndex = 0;
	std::vector<PathFinder::SimpleNode>::iterator it1 = path.begin();
	while (it1 < (path.end() - 2))
	{
		DOUBLE2 rayStart = Level::GridToWorld(*it1);

		std::vector<PathFinder::SimpleNode>::iterator it2 = it1 + 1;
		while (it2 != path.end())
		{
			// First check whether the grid point is passable on the navigation grid
			if (!m_NavigationGrid[(*it2).y][(*it2).x])
			{
				break;
			}

			// Check whether the level does not obstruct the path
			DOUBLE2 rayEnd = Level::GridToWorld(*it2);
			levelHit = m_ActorLayoutPtr->Raycast(rayStart, rayEnd, intersectionRef, normalRef, levelFraction);

			if (levelHit)
			{
				break;
			}

			++it2;
		}

		// If a hit has been registered, then we can delete the nodes
		// between it1 and it2 (excluding both)
		if ((it2 - it1) > 1)
		{
			if (it2 == path.end())
			{
				path.erase(it1 + 1, it2 - 1);
			}
			else
			{
				path.erase(it1 + 1, it2);
			}

			it1 = path.begin() + currentIndex;
		}


		if (path.size() < 3)
		{
			break;
		}

		++it1;
		++currentIndex;
	}*/

	path.shrink_to_fit();
}
int path_search()
{
	//printf("Mapping_Node Path Search Started\r\n");
	try
	{
		OPEN_LIST.clear();
		CLOSED_LIST.clear();
		PATH.clear();
		Node NewNode;
		
		/*
		double p_x = distance*sin(angle) + RoverPose.x;
			double p_y = distance*cos(angle) + RoverPose.y;
			int j = round((p_x/grid_resolution) + grid_width/2.0)-1;
			int i = round((p_y/grid_resolution) + grid_height/2.0)-1;
		*/
		NewNode.x = RoverPose.x;
		NewNode.y = RoverPose.y;
		NewNode.i = round((NewNode.y/grid_resolution) + grid_height/2.0)-1;
		NewNode.j = round((NewNode.x/grid_resolution) + grid_width/2.0)-1;
		NewNode.ID = (NewNode.i*grid_width) + NewNode.j;
		NewNode.Parent_ID = -1; //No Parent here
		NewNode.f = 0.0;
		NewNode.g = 0.0;
		NewNode.h = 0.0;
		OPEN_LIST.push_back(NewNode);
		int Goal_i = round((GoalPose.y/grid_resolution) + grid_height/2.0) -1;
		int Goal_j = round((GoalPose.x/grid_resolution) + grid_width/2.0) -1;
		//int Goal_i = 80;
		//int Goal_j = 50;
		int Start_ID = NewNode.ID;
		//printf("Si: %d Sj: %d SID: %d Gi: %d Gj: %d\r\n",NewNode.i,NewNode.j,NewNode.ID,Goal_i,Goal_j);
		int iteration_counter = 0;
		int path_found = 0;
		while(OPEN_LIST.size() > 0)
		{
			//printf("\r\n\r\n\r\nI: %d OPEN:\r\n",iteration_counter);
			/*for(int l = 0; l < OPEN_LIST.size();l++)
			{
				printf(" ID: %d i: %d j: %d\r\n",OPEN_LIST.at(l).ID,OPEN_LIST.at(l).i,OPEN_LIST.at(l).j);
			}*/
			/*printf("I: %d CLOSED:\r\n",iteration_counter);
			for(int l = 0; l < CLOSED_LIST.size();l++)
			{
				printf(" ID: %d i: %d j: %d P: %d\r\n",CLOSED_LIST.at(l).ID,CLOSED_LIST.at(l).i,CLOSED_LIST.at(l).j,CLOSED_LIST.at(l).Parent_ID);
			}*/
			if(iteration_counter > (10*grid_width*grid_width))//I SEARCHED WAY TOO MANY CELLS
			{
				printf("NO PATH FOUND!\r\n");
				return 0;
			}
			//Assume the lowest f Node is the first one, and search the rest to see if there is anyone better.
			double min_f = OPEN_LIST.at(0).f;
			int index = 0;
			for(int i = 0; i < OPEN_LIST.size();i++)
			{
				if(OPEN_LIST.at(i).f < min_f) 
				{ 
					min_f = OPEN_LIST.at(i).f;
					index = i;
				}
			}
			Node q = OPEN_LIST.at(index);
			OPEN_LIST.erase(OPEN_LIST.begin()+index);
			//printf("OPEN LIST SIZE: %d\r\n",OPEN_LIST.size());
			//printf("OPENING ID: %d P: %d\r\n",q.ID,q.Parent_ID);
			std::vector<Node> SUCCESSORS;
			//Add Successors
			if((q.i == 0) || (q.i == grid_width) || (q.j == 0) || (q.j == grid_width)) 
			{ 
				//printf("Border cell, don't check this.\r\n");
				break; 
			} //Check if cell is on border.
			Node NewNode;
			//Add Successor 0
			
			NewNode.Parent_ID = q.ID;
			NewNode.i = q.i+1;
			NewNode.j = q.j-1;
			NewNode.ID = (NewNode.i * grid_width) + NewNode.j;
			SUCCESSORS.push_back(NewNode);
			//Add Successor 1
			NewNode.Parent_ID = q.ID;
			NewNode.i = q.i+1;
			NewNode.j = q.j;
			NewNode.ID = (NewNode.i * grid_width) + NewNode.j;
			SUCCESSORS.push_back(NewNode);
			//Add Successor 2
			NewNode.Parent_ID = q.ID;
			NewNode.i = q.i+1;
			NewNode.j = q.j+1;
			NewNode.ID = (NewNode.i * grid_width) + NewNode.j;
			SUCCESSORS.push_back(NewNode);
			//Add Successor 3
			NewNode.Parent_ID = q.ID;
			NewNode.i = q.i;
			NewNode.j = q.j+1;
			NewNode.ID = (NewNode.i * grid_width) + NewNode.j;
			SUCCESSORS.push_back(NewNode);
			//Add Successor 4
			NewNode.Parent_ID = q.ID;
			NewNode.i = q.i-1;
			NewNode.j = q.j+1;
			NewNode.ID = (NewNode.i * grid_width) + NewNode.j;
			SUCCESSORS.push_back(NewNode);
			//Add Successor 5
			NewNode.Parent_ID = q.ID;
			NewNode.i = q.i-1;
			NewNode.j = q.j;
			NewNode.ID = (NewNode.i * grid_width) + NewNode.j;
			SUCCESSORS.push_back(NewNode);
			//Add Successor 6
			NewNode.Parent_ID = q.ID;
			NewNode.i = q.i-1;
			NewNode.j = q.j-1;
			NewNode.ID = (NewNode.i * grid_width) + NewNode.j;
			SUCCESSORS.push_back(NewNode);
			//Add Successor 7
			NewNode.Parent_ID = q.ID;
			NewNode.i = q.i;
			NewNode.j = q.j-1;
			NewNode.ID = (NewNode.i * grid_width) + NewNode.j;
			SUCCESSORS.push_back(NewNode);
			/*for(int k = 0; k < SUCCESSORS.size();k++)
			{
				printf("S ID: %d (%d,%d),",SUCCESSORS.at(k).ID,SUCCESSORS.at(k).i,SUCCESSORS.at(k).j);
			}
			printf("\r\n");*/
			for(int k = 0; k < SUCCESSORS.size();k++)
			{
				
				//printf("2S ID:%d (%d,%d)\r\n",SUCCESSORS.at(k).ID,SUCCESSORS.at(k).i,SUCCESSORS.at(k).j);
				SUCCESSORS.at(k).x = (double)((double)SUCCESSORS.at(k).j - (grid_width/2.0) + 1.0)*grid_resolution;
				SUCCESSORS.at(k).y = (double)((double)SUCCESSORS.at(k).i - (grid_height/2.0) + 1.0)*grid_resolution;
				double di; 
				double dj;
				di = q.i - SUCCESSORS.at(k).i;
				dj = q.j - SUCCESSORS.at(k).j;
				double d_successor_to_q = pow((pow(di,2.0)+pow(dj,2.0)),0.5);
				//printf("3S ID:%d (%d,%d)\r\n",SUCCESSORS.at(k).ID,SUCCESSORS.at(k).i,SUCCESSORS.at(k).j);
				SUCCESSORS.at(k).g = q.g + d_successor_to_q;
				di = Goal_i - SUCCESSORS.at(k).i;
				dj = Goal_j - SUCCESSORS.at(k).j; 
				double d_successor_to_goal = pow((pow(di,2.0)+pow(dj,2.0)),0.5);
				//printf("4S ID:%d (%d,%d)\r\n",SUCCESSORS.at(k).ID,SUCCESSORS.at(k).i,SUCCESSORS.at(k).j);
				
				int add_successor = 1;
				if(( SUCCESSORS.at(k).i >= 0 ) and (SUCCESSORS.at(k).i < grid_width) and (SUCCESSORS.at(k).j >= 0) and (SUCCESSORS.at(k).j < grid_height))
				{
					SUCCESSORS.at(k).h = d_successor_to_goal;
					//printf("Here1\r\n");
					SUCCESSORS.at(k).f = SUCCESSORS.at(k).g + SUCCESSORS.at(k).h;
					if(OccupancyGrid[SUCCESSORS.at(k).i][SUCCESSORS.at(k).j].Probability > 0.5){ add_successor = 0; }

				}
				else
				{
					add_successor = 0;
				}
			
				/*
					int Value;
	int ID;
	int Updated;
	double Probability;
	double Center_Northing_m;
	double Center_Easting_m;
	int Changed;
				*/
				
				//printf("5S ID:%d (%d,%d)\r\n",SUCCESSORS.at(k).ID,SUCCESSORS.at(k).i,SUCCESSORS.at(k).j);
				//printf("OPEN LIST SIZE: %d\r\n",OPEN_LIST.size());
				if(OPEN_LIST.size() > 0)
				{
					for(int l = 0; l < OPEN_LIST.size();l++)
					{
						//printf("S ID:%d (%d,%d)\r\n",SUCCESSORS.at(k).ID,SUCCESSORS.at(k).i,SUCCESSORS.at(k).j);
						//printf("Checking: OPEN ID: %d w/ SUCCESSOR ID: %d\r\n",OPEN_LIST.at(l).ID,SUCCESSORS.at(k).ID);
						if(OPEN_LIST.at(l).ID == SUCCESSORS.at(k).ID)
						{
							//if(OPEN_LIST.at(l).f < SUCCESSORS.at(k).f) { add_successor = 0; }
							add_successor = 0;
						}
					}
				}
				//printf("S ID:%d (%d,%d)\r\n",SUCCESSORS.at(k).ID,SUCCESSORS.at(k).i,SUCCESSORS.at(k).j);
				for(int l = 0; l < CLOSED_LIST.size();l++)
				{
					//printf("S ID:%d (%d,%d)\r\n",SUCCESSORS.at(k).ID,SUCCESSORS.at(k).i,SUCCESSORS.at(k).j);
					if(CLOSED_LIST.at(l).ID == SUCCESSORS.at(k).ID)
					{
						//if(CLOSED_LIST.at(l).f < SUCCESSORS.at(k).f) { add_successor = 0; }
						add_successor = 0;
						//break;
					}
				}
				if(add_successor == 1)
				{
					//printf("OPEN_LIST PUSH S ID:%d (%d,%d)\r\n",SUCCESSORS.at(k).ID,SUCCESSORS.at(k).i,SUCCESSORS.at(k).j);
					OPEN_LIST.push_back(SUCCESSORS.at(k)); 
				}
				else
				{
					//printf("NOT PUSHING TO OPEN LIST: %d(%d,%d)\r\n",SUCCESSORS.at(k).ID,SUCCESSORS.at(k).i,SUCCESSORS.at(k).j);
				}
			}
			CLOSED_LIST.push_back(q);
			for(int k = 0; k < OPEN_LIST.size();k++)
			{
			
			//printf("1S ID:%d (%d,%d)\r\n",SUCCESSORS.at(k).ID,SUCCESSORS.at(k).i,SUCCESSORS.at(k).j);
				if ((OPEN_LIST.at(k).i == Goal_i) and (OPEN_LIST.at(k).j == Goal_j))
				{
					//printf("PATH FOUND!\r\n");
					
					path_found =1;
					int path_complete = 0;
					int id = OPEN_LIST.at(k).ID;
					
					//printf("PATH ID's: ");
					//printf("%d(%d)->",id,OPEN_LIST.at(k).Parent_ID);
					id = OPEN_LIST.at(k).Parent_ID;
					while(path_complete == 0)
					{
						for(int l = 0; l < CLOSED_LIST.size();l++)
						{
							//printf("id: %d checking: %d\r\n",id,CLOSED_LIST.at(l).ID);
							if(id < 0)
							{
								path_complete = 1;
								//printf("PATH COMPLETE\r\n");
								//printf("Mapping_Node Path Search Returning\r\n");
								return 1;
							}
							else if(id == CLOSED_LIST.at(l).ID)
							{	
								//printf("%d(%d)->",id,CLOSED_LIST.at(l).Parent_ID);
								id = CLOSED_LIST.at(l).Parent_ID;
								PATH.push_back(CLOSED_LIST.at(l));
							}
						}
					}
					
				}
			}
			//printf("Searching...\r\n");
			iteration_counter++;
			
		}
		if(path_found == 0)
		{
			//printf("PATH NOT FOUND!\r\n");	
			return 0;
		}
	}
	catch(exception& e)
	{
		cout << "RC Node: " << e.what() << endl;
		ROS_ERROR("%s",e.what());
	}
	printf("Mapping_Node Path Search Finished\r\n");
}
// This function is called every frame
// If between the frames there was an asyncronous connect/disconnect event
// the function will pick up on this and add the device to the viewer
void refresh_devices(std::mutex& m,
    context& ctx,
    device_changes& devices_connection_changes,
    std::vector<device>& current_connected_devices,
    std::vector<std::pair<std::string, std::string>>& device_names,
    std::vector<device_model>& device_models,
    viewer_model& viewer_model,
    std::string& error_message)
{
    event_information info({}, {});
    if (devices_connection_changes.try_get_next_changes(info))
    {
        try
        {
            auto prev_size = current_connected_devices.size();

            //Remove disconnected
            auto dev_itr = begin(current_connected_devices);
            while (dev_itr != end(current_connected_devices))
            {
                auto dev = *dev_itr;
                if (info.was_removed(dev))
                {
                    //Notify change
                    viewer_model.not_model.add_notification({ get_device_name(dev).first + " Disconnected\n",
                        0, RS2_LOG_SEVERITY_INFO, RS2_NOTIFICATION_CATEGORY_UNKNOWN_ERROR });

                    viewer_model.ppf.depth_stream_active = false;

                    // Stopping post processing filter rendering thread in case of disconnection
                    viewer_model.ppf.stop();

                    //Remove from devices
                    auto dev_model_itr = std::find_if(begin(device_models), end(device_models),
                        [&](const device_model& other) { return get_device_name(other.dev) == get_device_name(dev); });

                    if (dev_model_itr != end(device_models))
                    {
                        for (auto&& s : dev_model_itr->subdevices)
                            s->streaming = false;

                        device_models.erase(dev_model_itr);
                    }
                    auto dev_name_itr = std::find(begin(device_names), end(device_names), get_device_name(dev));
                    if (dev_name_itr != end(device_names))
                        device_names.erase(dev_name_itr);

                    dev_itr = current_connected_devices.erase(dev_itr);
                    continue;
                }
                ++dev_itr;
            }

            //Add connected
            static bool initial_refresh = true;
            for (auto dev : info.get_new_devices())
            {
                auto dev_descriptor = get_device_name(dev);
                device_names.push_back(dev_descriptor);
                if (!initial_refresh)
                    viewer_model.not_model.add_notification({ dev_descriptor.first + " Connected\n",
                        0, RS2_LOG_SEVERITY_INFO, RS2_NOTIFICATION_CATEGORY_UNKNOWN_ERROR });

                current_connected_devices.push_back(dev);
                for (auto&& s : dev.query_sensors())
                {
                    s.set_notifications_callback([&, dev_descriptor](const notification& n)
                    {
                        if (n.get_category() == RS2_NOTIFICATION_CATEGORY_HARDWARE_EVENT)
                        {
                            auto data = n.get_serialized_data();
                            if (!data.empty())
                            {
                                auto dev_model_itr = std::find_if(begin(device_models), end(device_models),
                                    [&](const device_model& other) { return get_device_name(other.dev) == dev_descriptor; });

                                if (dev_model_itr == end(device_models))
                                    return;

                                dev_model_itr->handle_harware_events(data);
                            }
                        }
                        viewer_model.not_model.add_notification({ n.get_description(), n.get_timestamp(), n.get_severity(), n.get_category() });
                    });
                }

                if (device_models.size() == 0 &&
                    dev.supports(RS2_CAMERA_INFO_NAME) && std::string(dev.get_info(RS2_CAMERA_INFO_NAME)) != "Platform Camera")
                {
                    device_models.emplace_back(dev, error_message, viewer_model);
                    viewer_model.not_model.add_log(to_string() << device_models.rbegin()->dev.get_info(RS2_CAMERA_INFO_NAME) << " was selected as a default device");
                }
            }
            initial_refresh = false;
        }
        catch (const error& e)
        {
            error_message = error_to_string(e);
        }
        catch (const std::exception& e)
        {
            error_message = e.what();
        }
        catch (...)
        {
            error_message = "Unknown error";
        }
    }
}
/**
 * If pressing an action key (keyboard or mouseclick) and the power can be used,
 * add that power to the action queue
 */
void MenuActionBar::checkAction(std::vector<ActionData> &action_queue) {
	if (inpt->pressing[ACTIONBAR_USE] && tablist.getCurrent() == -1 && slots_count > 10) {
		tablist.setCurrent(slots[10]);
		slots[10]->in_focus = true;
	}

	// check click and hotkey actions
	for (unsigned i = 0; i < slots_count; i++) {
		ActionData action;
		action.hotkey = i;
		bool have_aim = false;
		slot_activated[i] = false;

		if (!slots[i]) continue;

		if (slot_enabled[i]) {
			// part two of two step activation
			if (static_cast<unsigned>(twostep_slot) == i && inpt->pressing[MAIN1] && !inpt->lock[MAIN1]) {
				have_aim = true;
				action.power = hotkeys_mod[i];
				twostep_slot = -1;
				inpt->lock[MAIN1] = true;
			}

			// mouse/touch click
			else if (!NO_MOUSE && slots[i]->checkClick() == ACTIVATED) {
				have_aim = false;
				slot_activated[i] = true;
				action.power = hotkeys_mod[i];

				// if a power requires a fixed target (like teleportation), break up activation into two parts
				// the first step is to mark the slot that was clicked on
				if (action.power > 0) {
					const Power &power = powers->getPower(action.power);
					if (power.starting_pos == STARTING_POS_TARGET || power.buff_teleport) {
						twostep_slot = i;
						action.power = 0;
					}
					else {
						twostep_slot = -1;
					}
				}
			}

			// joystick/keyboard action button
			else if (inpt->pressing[ACTIONBAR_USE] && static_cast<unsigned>(tablist.getCurrent()) == i) {
				have_aim = false;
				slot_activated[i] = true;
				action.power = hotkeys_mod[i];
				twostep_slot = -1;
			}

			// pressing hotkey
			else if (i<10 && inpt->pressing[i+BAR_1]) {
				have_aim = true;
				action.power = hotkeys_mod[i];
				twostep_slot = -1;
			}
			else if (i==10 && inpt->pressing[MAIN1] && !inpt->lock[MAIN1] && !isWithin(window_area, inpt->mouse)) {
				have_aim = true;
				action.power = hotkeys_mod[10];
				twostep_slot = -1;
			}
			else if (i==11 && inpt->pressing[MAIN2] && !inpt->lock[MAIN2] && !isWithin(window_area, inpt->mouse)) {
				have_aim = true;
				action.power = hotkeys_mod[11];
				twostep_slot = -1;
			}
		}

		// a power slot was activated
		if (action.power > 0 && static_cast<unsigned>(action.power) < powers->powers.size()) {
			const Power &power = powers->getPower(action.power);
			bool can_use_power = true;
			action.instant_item = (power.new_state == POWSTATE_INSTANT && power.requires_item > 0);

			// check if we can add this power to the action queue
			for (unsigned j=0; j<action_queue.size(); j++) {
				if (action_queue[j].hotkey == i) {
					// this power is already in the action queue, update its target
					action_queue[j].target = setTarget(have_aim, power.aim_assist);
					can_use_power = false;
					break;
				}
				else if (!action.instant_item && !action_queue[j].instant_item) {
					can_use_power = false;
					break;
				}
			}
			if (!can_use_power)
				continue;

			// set the target depending on how the power was triggered
			action.target = setTarget(have_aim, power.aim_assist);

			// add it to the queue
			action_queue.push_back(action);
		}
		else {
			// if we're not triggering an action that is currently in the queue,
			// remove it from the queue
			for (unsigned j=0; j<action_queue.size(); j++) {
				if (action_queue[j].hotkey == i)
					action_queue.erase(action_queue.begin()+j);
			}
		}
	}
}
Exemple #6
0
bool configureGpu(bool use_gpu_acceleration, std::vector<int> &valid_devices, int use_all_gpus, 
  int &numBkgWorkers_gpu) {
#ifdef ION_COMPILE_CUDA
  const unsigned long long gpu_mem = 2.5 * 1024 * 1024 * 1024;

  if (!use_gpu_acceleration)
    return false;

  // Get number of GPUs in system
  int num_gpus = 0;
  cudaError_t err = cudaGetDeviceCount( &num_gpus );

  if (err != cudaSuccess) {
    printf("CUDA: No GPU device available. Defaulting to CPU only computation\n");
    return false;
  }

  if ( use_all_gpus )
  {
    // Add all GPUs to the valid device list
    for ( int dev = 0; dev < num_gpus;  dev++ )
      valid_devices.push_back(dev);
  }
  else
  {
    // Only add the highest compute devices to the compute list
    int version = 0;
    int major = 0;
    int minor = 0;
    cudaDeviceProp dev_props;

    // Iterate over GPUs to find the highest compute device
    for ( int dev = 0; dev < num_gpus;  dev++ )
    {
      cudaGetDeviceProperties( &dev_props, dev );
      if ( (dev_props.major*10) + dev_props.minor > version )
      {
        version = (dev_props.major*10) + dev_props.minor;
        major = dev_props.major;
        minor = dev_props.minor;
      }
    }

    for ( int dev = 0; dev < num_gpus;  dev++ )
    {
      cudaGetDeviceProperties(&dev_props, dev);
      if (dev_props.major == major && dev_props.minor == minor) {
        if (dev_props.totalGlobalMem > gpu_mem) {
    valid_devices.push_back(dev);
        }
      }
    } 
  }

  // Set the number of GPU workers and tell CUDA about our list of valid devices
  if (valid_devices.size() > 0) {
    numBkgWorkers_gpu = int(valid_devices.size());
    cudaSetValidDevices( &valid_devices[0], int( valid_devices.size() ) );
  }
  else {
    printf("CUDA: No GPU device available. Defaulting to CPU only computation\n");
    return false;   
  }

 
  PoissonCDFApproxMemo poiss_cache; 
  poiss_cache.Allocate (MAX_POISSON_TABLE_COL,MAX_POISSON_TABLE_ROW,POISSON_TABLE_STEP);
  poiss_cache.GenerateValues(); // fill out my table


  for(int i=valid_devices.size()-1 ; i >= 0; i--){
    try{
      //cudaSetDevice(valid_devices[i]);
      cout << "CUDA "<< valid_devices[i] << ": Creating Context and Constant memory on device with id: "<<  valid_devices[i]<< endl;
      InitConstantMemoryOnGpu(valid_devices[i],poiss_cache);
    }
    catch(cudaException &e) {
      cout << "CUDA "<< valid_devices[i] << ": Context could not be created. removing device with id: "<<  valid_devices[i] << " from valid device list" << endl;
      valid_devices.erase (valid_devices.begin()+i);
      numBkgWorkers_gpu -= 1;
      if(numBkgWorkers_gpu == 0) cout << "CUDA: no context could be created, defaulting to CPU only execution" << endl; 
    }

  }

  if(numBkgWorkers_gpu == 0) return false;

  return true;

#else
  
  return false;

#endif

}
/// \brief Strips any positional args and possible argv[0] from a command-line
/// provided by the user to construct a FixedCompilationDatabase.
///
/// FixedCompilationDatabase requires a command line to be in this format as it
/// constructs the command line for each file by appending the name of the file
/// to be compiled. FixedCompilationDatabase also adds its own argv[0] to the
/// start of the command line although its value is not important as it's just
/// ignored by the Driver invoked by the ClangTool using the
/// FixedCompilationDatabase.
///
/// FIXME: This functionality should probably be made available by
/// clang::driver::Driver although what the interface should look like is not
/// clear.
///
/// \param[in] Args Args as provided by the user.
/// \return Resulting stripped command line.
///          \li true if successful.
///          \li false if \c Args cannot be used for compilation jobs (e.g.
///          contains an option like -E or -version).
static bool stripPositionalArgs(std::vector<const char *> Args,
                                std::vector<std::string> &Result) {
  IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts = new DiagnosticOptions();
  UnusedInputDiagConsumer DiagClient;
  DiagnosticsEngine Diagnostics(
      IntrusiveRefCntPtr<clang::DiagnosticIDs>(new DiagnosticIDs()),
      &*DiagOpts, &DiagClient, false);

  // The clang executable path isn't required since the jobs the driver builds
  // will not be executed.
  std::unique_ptr<driver::Driver> NewDriver(new driver::Driver(
      /* ClangExecutable= */ "", llvm::sys::getDefaultTargetTriple(),
      Diagnostics));
  NewDriver->setCheckInputsExist(false);

  // This becomes the new argv[0]. The value is actually not important as it
  // isn't used for invoking Tools.
  Args.insert(Args.begin(), "clang-tool");

  // By adding -c, we force the driver to treat compilation as the last phase.
  // It will then issue warnings via Diagnostics about un-used options that
  // would have been used for linking. If the user provided a compiler name as
  // the original argv[0], this will be treated as a linker input thanks to
  // insertng a new argv[0] above. All un-used options get collected by
  // UnusedInputdiagConsumer and get stripped out later.
  Args.push_back("-c");

  // Put a dummy C++ file on to ensure there's at least one compile job for the
  // driver to construct. If the user specified some other argument that
  // prevents compilation, e.g. -E or something like -version, we may still end
  // up with no jobs but then this is the user's fault.
  Args.push_back("placeholder.cpp");

  // Remove -no-integrated-as; it's not used for syntax checking,
  // and it confuses targets which don't support this option.
  Args.erase(std::remove_if(Args.begin(), Args.end(),
                            MatchesAny(std::string("-no-integrated-as"))),
             Args.end());

  const std::unique_ptr<driver::Compilation> Compilation(
      NewDriver->BuildCompilation(Args));

  const driver::JobList &Jobs = Compilation->getJobs();

  CompileJobAnalyzer CompileAnalyzer;

  for (const auto &Job : Jobs) {
    if (Job.getKind() == driver::Job::CommandClass) {
      const driver::Command &Cmd = cast<driver::Command>(Job);
      // Collect only for Assemble jobs. If we do all jobs we get duplicates
      // since Link jobs point to Assemble jobs as inputs.
      if (Cmd.getSource().getKind() == driver::Action::AssembleJobClass)
        CompileAnalyzer.run(&Cmd.getSource());
    }
  }

  if (CompileAnalyzer.Inputs.empty()) {
    // No compile jobs found.
    // FIXME: Emit a warning of some kind?
    return false;
  }

  // Remove all compilation input files from the command line. This is
  // necessary so that getCompileCommands() can construct a command line for
  // each file.
  std::vector<const char *>::iterator End = std::remove_if(
      Args.begin(), Args.end(), MatchesAny(CompileAnalyzer.Inputs));

  // Remove all inputs deemed unused for compilation.
  End = std::remove_if(Args.begin(), End, MatchesAny(DiagClient.UnusedInputs));

  // Remove the -c add above as well. It will be at the end right now.
  assert(strcmp(*(End - 1), "-c") == 0);
  --End;

  Result = std::vector<std::string>(Args.begin() + 1, End);
  return true;
}
Exemple #8
0
// fills the vector with the k nodes from our buckets that
// are nearest to the given id.
void routing_table::find_node(node_id const& target
	, std::vector<node_entry>& l, bool include_self, int count)
{
	l.clear();
	if (count == 0) count = m_bucket_size;
	l.reserve(count);

	int bucket_index = distance_exp(m_id, target);
	bucket_t& b = m_buckets[bucket_index].first;

	// copy all nodes that hasn't failed into the target
	// vector.
	std::remove_copy_if(b.begin(), b.end(), std::back_inserter(l)
		, bind(&node_entry::fail_count, _1));
	TORRENT_ASSERT((int)l.size() <= count);

	if ((int)l.size() == count)
	{
		TORRENT_ASSERT(std::count_if(l.begin(), l.end()
			, boost::bind(&node_entry::fail_count, _1) != 0) == 0);
		return;
	}

	// if we didn't have enough nodes in that bucket
	// we have to reply with nodes from buckets closer
	// to us. i.e. all the buckets in the range
	// [0, bucket_index) if we are to include ourself
	// or [1, bucket_index) if not.
	bucket_t tmpb;
	for (int i = include_self?0:1; i < bucket_index; ++i)
	{
		bucket_t& b = m_buckets[i].first;
		std::remove_copy_if(b.begin(), b.end(), std::back_inserter(tmpb)
			, bind(&node_entry::fail_count, _1));
	}

	std::random_shuffle(tmpb.begin(), tmpb.end());
	size_t to_copy = (std::min)(m_bucket_size - l.size()
		, tmpb.size());
	std::copy(tmpb.begin(), tmpb.begin() + to_copy
		, std::back_inserter(l));
		
	TORRENT_ASSERT((int)l.size() <= m_bucket_size);

	// return if we have enough nodes or if the bucket index
	// is the biggest index available (there are no more buckets)
	// to look in.
	if ((int)l.size() == count
		|| bucket_index == (int)m_buckets.size() - 1)
	{
		TORRENT_ASSERT(std::count_if(l.begin(), l.end()
			, boost::bind(&node_entry::fail_count, _1) != 0) == 0);
		return;
	}

	for (size_t i = bucket_index + 1; i < m_buckets.size(); ++i)
	{
		bucket_t& b = m_buckets[i].first;
	
		std::remove_copy_if(b.begin(), b.end(), std::back_inserter(l)
			, bind(&node_entry::fail_count, _1));
		if ((int)l.size() >= count)
		{
			l.erase(l.begin() + count, l.end());
			TORRENT_ASSERT(std::count_if(l.begin(), l.end()
				, boost::bind(&node_entry::fail_count, _1) != 0) == 0);
			return;
		}
	}
	TORRENT_ASSERT((int)l.size() == count
		|| std::distance(l.begin(), l.end()) < m_bucket_size);
	TORRENT_ASSERT((int)l.size() <= count);

	TORRENT_ASSERT(std::count_if(l.begin(), l.end()
		, boost::bind(&node_entry::fail_count, _1) != 0) == 0);
}
Exemple #9
0
void display() {
	doIntelWarning(); // warn for possible problems with pciking on Intel graphics chipsets

	double currentTime = u_timeGet();

	// check if we should get new random dest
	if (currentTime - g_startTime > interpolationTime) {
		g_startTime = g_startTime + interpolationTime;

		// when the process has been 'asleep' for a long time, simply skip:
		if (currentTime - g_startTime > interpolationTime)
			g_startTime = currentTime;

		// start new interpolation
		copyDestToSource();
		initRandomDest();
	}

	// interpolate:
	mv::Float alpha = (mv::Float)(currentTime - g_startTime) / (mv::Float)interpolationTime;
	TRversor V = interpolateTRversor(g_sourceVersor, g_destVersor, alpha);

	// setup projection & transform for the vectors:
	glViewport(0, 0, g_viewportWidth, g_viewportHeight);
	glMatrixMode(GL_MODELVIEW);
	glLoadIdentity();
	glMatrixMode(GL_PROJECTION);
	const float screenWidth = 1600.0f;
	glLoadIdentity();
	GLpick::g_frustumWidth = 2.0 *  (double)g_viewportWidth / screenWidth;
	GLpick::g_frustumHeight = 2.0 *  (double)g_viewportHeight / screenWidth;
	glFrustum(
		-GLpick::g_frustumWidth / 2.0, GLpick::g_frustumWidth / 2.0,
		-GLpick::g_frustumHeight / 2.0, GLpick::g_frustumHeight / 2.0,
		GLpick::g_frustumNear, GLpick::g_frustumFar);
	glMatrixMode(GL_MODELVIEW);
	glTranslatef(0.0f, 0.0f, -12.0f);


	glClearColor(1.0f, 1.0f, 1.0f, 1.0f);
	glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

	glEnable(GL_DEPTH_TEST);
	glPolygonMode(GL_FRONT, GL_FILL);
	glEnable(GL_CULL_FACE);
	glCullFace(GL_BACK);
	glEnable(GL_LIGHTING);
	glEnable(GL_LIGHT0);
	glEnable(GL_NORMALIZE);
	glLineWidth(2.0f);


	glMatrixMode(GL_MODELVIEW);
	glPushMatrix();

	rotorGLMult(g_modelRotor);

	circle C = _circle((e1^e2^no) + (e1^e2^ni));
	circle imageOfC = _circle(V * C * inverse(V));

	// draw the circle
	glColor3fm(0.0f, 0.0f, 0.0f);
	draw(imageOfC);

	// draw trail:
	glEnable(GL_BLEND);
	glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
	for (unsigned int i = 0; i < g_circleTrail.size(); i++) {
		float a = 0.7f * (float)i / (float)(g_circleTrail.size());

		// draw the frame
		glColor4fm(1.0f - a, 1.0f - a, 1.0f - a, a);
		draw(g_circleTrail[i]);
	}

	glDisable(GL_BLEND);

	// update the trail:
	if (((currentTime - g_prevTrailTime) / interpolationTime) > 0.15) {
		g_prevTrailTime = currentTime;
		g_circleTrail.push_back(imageOfC);

		// trim trail to length 20:
		if (g_circleTrail.size() > 20) {
			g_circleTrail.erase(g_circleTrail.begin());
		}
	}



	glPopMatrix();

/*
	glViewport(0, 0, g_viewportWidth, g_viewportHeight);
	glMatrixMode(GL_PROJECTION);
	glLoadIdentity();
	glOrtho(0, g_viewportWidth, 0, g_viewportHeight, -100.0, 100.0);
	glMatrixMode(GL_MODELVIEW);
	glLoadIdentity();

	glDisable(GL_LIGHTING);
	glColor3f(1.0f, 1.0f, 1.0f);
	void *font = GLUT_BITMAP_HELVETICA_12;
	renderBitmapString(20, 20, font, ". . .");
*/

	glutSwapBuffers();
}
Exemple #10
0
void MainWindow::renderBoard(std::vector<MoveHistoryEntry> history, QString outFile, int removeLast, bool renderOpenTiles, bool renderFrames, bool renderPlayers, bool renderNextTile)
{
	//TODO correct backgrounds

	jcz::TileFactory tileFactory(false);
	TileImageFactory imgFactory(&tileFactory);

	QImage image;
	QPainter * painter = 0;

	RandomNextTileProvider rntp;
	HistoryProvider hp(&rntp, history, history.size() - removeLast);
	Game g(&hp, false);
	g.addPlayer(&RandomPlayer::instance);
	g.addPlayer(&RandomPlayer::instance);

	BoardGraphicsScene bgs(&tileFactory, &imgFactory);
	bgs.setRenderOpenTiles(renderOpenTiles);
	bgs.setRenderFrames(renderFrames);
	bgs.setGame(&g);
	g.addWatchingPlayer(&bgs);

	history.erase(history.end() - removeLast, history.end());
	g.newGame(Tile::BaseGame, &tileFactory, history, true);

	bgs.clearSelection();
	bgs.setSceneRect(bgs.itemsBoundingRect());

	int const spacing = 50;
	int constexpr pivScale = 4;
	QSize sceneSize = bgs.sceneRect().size().toSize();
	QSize size = sceneSize;
	QPoint offset(0, 0);
	if (renderPlayers)
	{
		QLabel remainingLabel(QString("%1 tiles left").arg(g.getTileCount() - 1));
		remainingLabel.updateGeometry();
		int nextTileType = g.getTile(hp.nextTile(&g))->tileType;

		QSize pivSize;
		for (uint p = 0; p < g.getPlayerCount(); ++p)
		{
			PlayerInfoView piv(p, &g, &imgFactory);
			piv.updateView();
			if (renderNextTile)
				piv.displayTile(g.getNextPlayer(), nextTileType);
			piv.updateGeometry();

			if (p == 0)
			{
				pivSize = piv.size() * pivScale;
				pivSize.rheight() *= g.getPlayerCount();

				QSize remSize = remainingLabel.sizeHint() * pivScale;

				size.rwidth() += pivSize.width() + spacing;
				size.rheight() = qMax(size.height(), pivSize.height() + spacing + remSize.height());

				image = QImage(size, QImage::Format_ARGB32);
				image.fill(Qt::transparent);
				painter = new QPainter(&image);
				painter->setRenderHints(QPainter::Antialiasing | QPainter::TextAntialiasing | QPainter::SmoothPixmapTransform | QPainter::HighQualityAntialiasing);

				painter->scale(pivScale, pivScale);
			}

			piv.render(painter, offset);

			offset.ry() += piv.size().height();
		}
		offset.setX(0);
		offset.setY((pivSize.height() + spacing) / pivScale);

		remainingLabel.render(painter, offset);

		offset.setX(pivSize.width() + spacing);
		offset.setY(0);
		painter->resetTransform();
	}
	else
	{
		image = QImage(size, QImage::Format_ARGB32);
		image.fill(Qt::transparent);
		painter = new QPainter(&image);
		painter->setRenderHints(QPainter::Antialiasing | QPainter::TextAntialiasing | QPainter::SmoothPixmapTransform | QPainter::HighQualityAntialiasing);
	}

	bgs.render(painter, QRectF(offset, size));

	image.save(outFile);

	delete painter;
}
int UpdateStructure(std::vector<int>& structure, int StructuringRule, double *U, int d, int d1, unsigned int n)
{
    int i,j;
    
    std::vector<double> tau(d1*d1);
    SD_Kendall_Tau_Matrix(&tau[0],U,d1,n);
    
    std::vector<double> tau1(d1);
    double Tau1;
    
    for (i=0;i<d1;i++)
    {
        for (j=0;j<d1;j++)
        {
            Tau1 = std::abs(tau[i*d1+j]);
            tau1[i] += Tau1;
        }
    }
    
    std::vector<double>::iterator Maximum;
    
    Maximum = std::max_element(tau1.begin(), tau1.end());
    int I = std::distance(tau1.begin(), Maximum);
    
    int idxI = structure[I+d-d1];
    
    structure.erase (structure.begin()+I+d-d1);
    
    structure.insert (structure.begin()+d-d1,idxI);
    switch (StructuringRule)
    {
        case 1:
        {
            tau1.resize(d1-1);
            for (j=0;j<I;j++)
            {
                Tau1 = std::abs(tau[I*d1+j]);
                tau1[j] = Tau1;
            }
            for (j=I+1;j<d1;j++)
            {
                Tau1 = std::abs(tau[I*d1+j]);
                tau1[j-1] = Tau1;
            }
            
            for (j=0;j<d1-2;j++)
            {
                Maximum = std::max_element(tau1.begin(), tau1.end());
                int I = std::distance(tau1.begin(), Maximum);
                
                tau1.erase(tau1.begin()+I);
                
                int idxI = structure[I+1+j];
                
                structure.erase (structure.begin()+I+1+j);
                
                structure.insert (structure.begin()+1+j,idxI);
            }
            break;
        }
        case 2:
        {
            tau1.resize(d1-1);
            for (j=0;j<I;j++)
            {
                Tau1 = std::abs(tau[I*d1+j]);
                tau1[j] = Tau1;
            }
            for (j=I+1;j<d1;j++)
            {
                Tau1 = std::abs(tau[I*d1+j]);
                tau1[j-1] = Tau1;
            }
            
            for (j=0;j<d1-2;j++)
            {
                Maximum = std::min_element(tau1.begin(), tau1.end()); // Note that Maximum is the minimum in this case!
                int I = std::distance(tau1.begin(), Maximum);
                
                tau1.erase(tau1.begin()+I);
                
                int idxI = structure[I+1+j];
                
                structure.erase (structure.begin()+I+1+j);
                
                structure.insert (structure.begin()+1+j,idxI);
            }
            break;
        }
        case 3:
        {
            for (j=0;j<d1-2;j++)
            {
                tau1.resize(d1-1-j);
                for (i=0;i<d1-1-j;i++)
                {
                    Tau1 = std::abs(tau[(I+j)*d1+structure[i+1+j]]);
                    tau1[i] = Tau1;
                }
                Maximum = std::min_element(tau1.begin(), tau1.end()); // Note that Maximum is the minimum in this case!
                int I = std::distance(tau1.begin(), Maximum);
                
                int idxI = structure[I+1+j];
                
                structure.erase (structure.begin()+I+1+j);
                
                structure.insert (structure.begin()+1+j,idxI);
            }
            break;
        }
        case 0:
        {
            
        }
    }
    return I;
}
Exemple #12
0
static void trimSnapshots(std::vector<T> &snapshots) {
	if (snapshots.size() > MIN_SNAPSHOT_HISTORY)
		snapshots.erase(snapshots.begin(), snapshots.begin() + snapshots.size() - MIN_SNAPSHOT_HISTORY);
}
bool CEvaluationNodeNormalizer::eliminateMultipleNumbers(CEvaluationNodeOperator::SubType subType, std::vector<CEvaluationNode*>& chainNodes)
{
  // check if there are several numerical values in the operator chain and
  // evaluate those operations
  bool changed = false;

  if (chainNodes.size() > 1)
    {
      std::vector<CEvaluationNode*>::iterator it = chainNodes.begin(), endit = chainNodes.end();

      if (subType == CEvaluationNodeOperator::MULTIPLY || subType == CEvaluationNodeOperator::PLUS)
        {

          double value = (subType == CEvaluationNodeOperator::MULTIPLY) ? 1.0 : 0.0;
          CEvaluationNodeNumber* pNumberNode = NULL;
          std::vector<CEvaluationNode*> numbers;

          while (it != endit)
            {
              pNumberNode = dynamic_cast<CEvaluationNodeNumber*>(*it);

              if (pNumberNode != NULL)
                {
                  numbers.push_back(pNumberNode);

                  if (subType == CEvaluationNodeOperator::MULTIPLY)
                    {
                      value *= pNumberNode->value();
                    }
                  else
                    {
                      value += pNumberNode->value();
                    }
                }

              ++it;
            }

          if (numbers.size() > 1)
            {
              changed = true;
              it = numbers.begin(), endit = numbers.end();
              // don't delete the last one since we reset it's value
              --endit;

              while (it != endit)
                {
                  chainNodes.erase(std::find(chainNodes.begin(), chainNodes.end(), *it));
                  delete *it;
                  ++it;
                }

              std::ostringstream os;
              os << value;
              (*it)->setData(os.str());
            }
        }
    }

  return changed;
}
bool
sp_item_list_to_curves(const std::vector<SPItem*> &items, std::vector<SPItem*>& selected, std::vector<Inkscape::XML::Node*> &to_select, bool skip_all_lpeitems)
{
    bool did = false;
    for (std::vector<SPItem*>::const_iterator i = items.begin(); i != items.end(); ++i){
        SPItem *item = *i;
        g_assert(item != NULL);
        SPDocument *document = item->document;

        SPGroup *group = dynamic_cast<SPGroup *>(item);
        if ( skip_all_lpeitems &&
             dynamic_cast<SPLPEItem *>(item) && 
             !group ) // also convert objects in an SPGroup when skip_all_lpeitems is set.
        { 
            continue;
        }

        SPPath *path = dynamic_cast<SPPath *>(item);
        if (path && !path->_curve_before_lpe) {
            // remove connector attributes
            if (item->getAttribute("inkscape:connector-type") != NULL) {
                item->removeAttribute("inkscape:connection-start");
                item->removeAttribute("inkscape:connection-end");
                item->removeAttribute("inkscape:connector-type");
                item->removeAttribute("inkscape:connector-curvature");
                did = true;
            }
            continue; // already a path, and no path effect
        }

        SPBox3D *box = dynamic_cast<SPBox3D *>(item);
        if (box) {
            // convert 3D box to ordinary group of paths; replace the old element in 'selected' with the new group
            Inkscape::XML::Node *repr = box3d_convert_to_group(box)->getRepr();
            
            if (repr) {
                to_select.insert(to_select.begin(),repr);
                did = true;
                selected.erase(remove(selected.begin(), selected.end(), item), selected.end());
            }

            continue;
        }
        
        if (group) {
            group->removeAllPathEffects(true);
            std::vector<SPItem*> item_list = sp_item_group_item_list(group);
            
            std::vector<Inkscape::XML::Node*> item_to_select;
            std::vector<SPItem*> item_selected;
            
            if (sp_item_list_to_curves(item_list, item_selected, item_to_select))
                did = true;


            continue;
        }

        Inkscape::XML::Node *repr = sp_selected_item_to_curved_repr(item, 0);
        if (!repr)
            continue;

        did = true;
        selected.erase(remove(selected.begin(), selected.end(), item), selected.end());

        // remember the position of the item
        gint pos = item->getRepr()->position();
        // remember parent
        Inkscape::XML::Node *parent = item->getRepr()->parent();
        // remember id
        char const *id = item->getRepr()->attribute("id");
        // remember title
        gchar *title = item->title();
        // remember description
        gchar *desc = item->desc();
        // remember highlight color
        guint32 highlight_color = 0;
        if (item->isHighlightSet())
            highlight_color = item->highlight_color();

        // It's going to resurrect, so we delete without notifying listeners.
        item->deleteObject(false);

        // restore id
        repr->setAttribute("id", id);
        // add the new repr to the parent
        parent->appendChild(repr);
        SPObject* newObj = document->getObjectByRepr(repr);
        if (title && newObj) {
            newObj->setTitle(title);
            g_free(title);
        }
        if (desc && newObj) {
            newObj->setDesc(desc);
            g_free(desc);
        }
        if (highlight_color && newObj) {
                SP_ITEM(newObj)->setHighlightColor( highlight_color );
        }

        // move to the saved position
        repr->setPosition(pos > 0 ? pos : 0);

        /* Buglet: We don't re-add the (new version of the) object to the selection of any other
         * desktops where it was previously selected. */
        to_select.insert(to_select.begin(),repr);
        Inkscape::GC::release(repr);
    }
    
    return did;
}
Exemple #15
0
void nextToken()
{
  tokens.erase(tokens.begin());
}
Exemple #16
0
bool test_column(boost::shared_ptr<ColumnBaseTyped<T>> col, std::vector<T>& reference_data) {
	/****** BASIC INSERT TEST ******/
	std::cout << "BASIC INSERT TEST: Filling column with data..."; // << std::endl;	
	//col->insert(reference_data.begin(),reference_data.end()); 
	
	if (reference_data.size() != col->size()) { 
		std::cout << "Fatal Error! In Unittest: invalid data size" << std::endl;
		return false;
	}

	if (!equals(reference_data, col)) {
		std::cerr << "BASIC INSERT TEST FAILED!" << std::endl;
		return false;
	}

	std::cout << std::endl;

	std::cout << "SUCCESS" << std::endl;
	/****** VIRTUAL COPY CONSTRUCTOR TEST ******/
	std::cout << "VIRTUAL COPY CONSTRUCTOR TEST...";

	//boost::shared_ptr<DictionaryCompressedColumn<int> > compressed_col (new DictionaryCompressedColumn<int>("compressed int column",INT));
	//compressed_col->insert(reference_data.begin(),reference_data.end()); 

	ColumnPtr copy = col->copy();
	if(!copy) { 
		std::cerr << std::endl << "VIRTUAL COPY CONSTRUCTOR TEST FAILED!" << std::endl;	
		return false;
	}	
	bool result = *(boost::static_pointer_cast<ColumnBaseTyped<T>>(copy)) == *(boost::static_pointer_cast<ColumnBaseTyped<T>>(col));
	if (!result) { 
		std::cerr << std::endl << "VIRTUAL COPY CONSTRUCTOR TEST FAILED!" << std::endl;	
		return false;
	}	
	std::cout << "SUCCESS"<< std::endl;
	/****** UPDATE TEST ******/
	TID tid = rand() % 100;
	T new_value = get_rand_value<T>();
	std::cout << "UPDATE TEST: Update value on Position '" << tid << "' to new value '" << new_value << "'..."; // << std::endl;

	reference_data[tid] = new_value;

	col->update(tid, new_value);

	if (!equals(reference_data, col)) {
		std::cerr << "UPDATE TEST FAILED!" << std::endl;	
		return false;
	}
	std::cout << "SUCCESS"<< std::endl;
	/****** DELETE TEST ******/
	{
		TID tid = rand() % 100;

		std::cout << "DELETE TEST: Delete value on Position '" << tid << "'..."; // << std::endl;

		reference_data.erase(reference_data.begin()+tid);

		col->remove(tid);

		if (!equals(reference_data, col)) {
			std::cerr << "DELETE TEST FAILED!" << std::endl;
			return false;
		}
		std::cout << "SUCCESS"<< std::endl;
	}
	/****** STORE AND LOAD TEST ******/
	{
		std::cout << "STORE AND LOAD TEST: store column data on disc and load it..."; // << std::endl;
		col->store("data/");

		col->clearContent();
		if(col->size() != 0) {
			std::cout << "Fatal Error! 'col->size()' returned non zero after call to 'col->clearContent()'\nTEST FAILED" << std::endl;
			return false;
		}

		//boost::shared_ptr<Column<int> > col2 (new Column<int>("int column",INT));
		col->load("data/");

		if (!equals(reference_data, col)) {
			std::cerr << "STORE AND LOAD TEST FAILED!" << std::endl;	
			return false;
		}
		std::cout << "SUCCESS"<< std::endl;
	}

	return true;
}
Exemple #17
0
void hleEnterVblank(u64 userdata, int cyclesLate) {
	int vbCount = userdata;

	DEBUG_LOG(HLE, "Enter VBlank %i", vbCount);

	isVblank = 1;

	// Fire the vblank listeners before we wake threads.
	__DisplayFireVblank();

	// Wake up threads waiting for VBlank
	for (size_t i = 0; i < vblankWaitingThreads.size(); i++) {
		if (--vblankWaitingThreads[i].vcountUnblock == 0) {
			__KernelResumeThreadFromWait(vblankWaitingThreads[i].threadID, 0);
			vblankWaitingThreads.erase(vblankWaitingThreads.begin() + i--);
		}
	}

	// Trigger VBlank interrupt handlers.
	__TriggerInterrupt(PSP_INTR_IMMEDIATE | PSP_INTR_ONLY_IF_ENABLED | PSP_INTR_ALWAYS_RESCHED, PSP_VBLANK_INTR, PSP_INTR_SUB_ALL);

	CoreTiming::ScheduleEvent(msToCycles(vblankMs) - cyclesLate, leaveVblankEvent, vbCount+1);

	// TODO: Should this be done here or in hleLeaveVblank?
	if (framebufIsLatched) {
		DEBUG_LOG(HLE, "Setting latched framebuffer %08x (prev: %08x)", latchedFramebuf.topaddr, framebuf.topaddr);
		framebuf = latchedFramebuf;
		framebufIsLatched = false;
		gpu->SetDisplayFramebuffer(framebuf.topaddr, framebuf.pspFramebufLinesize, framebuf.pspFramebufFormat);
	}

	// Draw screen overlays before blitting. Saves and restores the Ge context.
	gpuStats.numFrames++;

	// Now we can subvert the Ge engine in order to draw custom overlays like stat counters etc.
	if (g_Config.bShowDebugStats && gpuStats.numDrawCalls) {
		gpu->UpdateStats();
		char stats[2048];
		
		sprintf(stats,
			"Frames: %i\n"
			"DL processing time: %0.2f ms\n"
			"Kernel processing time: %0.2f ms\n"
			"Slowest syscall: %s : %0.2f ms\n"
			"Most active syscall: %s : %0.2f ms\n"
			"Draw calls: %i, flushes %i\n"
			"Cached Draw calls: %i\n"
			"Num Tracked Vertex Arrays: %i\n"
			"Vertices Submitted: %i\n"
			"Cached Vertices Drawn: %i\n"
			"Uncached Vertices Drawn: %i\n"
			"FBOs active: %i\n"
			"Textures active: %i, decoded: %i\n"
			"Texture invalidations: %i\n"
			"Vertex shaders loaded: %i\n"
			"Fragment shaders loaded: %i\n"
			"Combined shaders loaded: %i\n",
			gpuStats.numFrames,
			gpuStats.msProcessingDisplayLists * 1000.0f,
			kernelStats.msInSyscalls * 1000.0f,
			kernelStats.slowestSyscallName ? kernelStats.slowestSyscallName : "(none)",
			kernelStats.slowestSyscallTime * 1000.0f,
			kernelStats.summedSlowestSyscallName ? kernelStats.summedSlowestSyscallName : "(none)",
			kernelStats.summedSlowestSyscallTime * 1000.0f,
			gpuStats.numDrawCalls,
			gpuStats.numFlushes,
			gpuStats.numCachedDrawCalls,
			gpuStats.numTrackedVertexArrays,
			gpuStats.numVertsSubmitted,
			gpuStats.numCachedVertsDrawn,
			gpuStats.numUncachedVertsDrawn,
			gpuStats.numFBOs,
			gpuStats.numTextures,
			gpuStats.numTexturesDecoded,
			gpuStats.numTextureInvalidations,
			gpuStats.numVertexShaders,
			gpuStats.numFragmentShaders,
			gpuStats.numShaders
			);

		float zoom = 0.3f; /// g_Config.iWindowZoom;
		float soff = 0.3f;
		PPGeBegin();
		PPGeDrawText(stats, soff, soff, 0, zoom, 0xCC000000);
		PPGeDrawText(stats, -soff, -soff, 0, zoom, 0xCC000000);
		PPGeDrawText(stats, 0, 0, 0, zoom, 0xFFFFFFFF);
		PPGeEnd();

		gpuStats.resetFrame();
		kernelStats.ResetFrame();
	}

	if (g_Config.bShowFPSCounter) {
		char stats[50];

		sprintf(stats, "%0.1f", calculateFPS());

		#ifdef USING_GLES2
			float zoom = 0.7f; /// g_Config.iWindowZoom;
			float soff = 0.7f;
		#else
			float zoom = 0.5f; /// g_Config.iWindowZoom;
			float soff = 0.5f;
		#endif
		PPGeBegin();
		PPGeDrawText(stats, 476 + soff, 4 + soff, PPGE_ALIGN_RIGHT, zoom, 0xCC000000);
		PPGeDrawText(stats, 476 + -soff, 4 -soff, PPGE_ALIGN_RIGHT, zoom, 0xCC000000);
		PPGeDrawText(stats, 476, 4, PPGE_ALIGN_RIGHT, zoom, 0xFF30FF30);
		PPGeEnd();
	}

	// Yeah, this has to be the right moment to end the frame. Give the graphics backend opportunity
	// to blit the framebuffer, in order to support half-framerate games that otherwise wouldn't have
	// anything to draw here.
	gpu->CopyDisplayToOutput();

	host->EndFrame();

#ifdef _WIN32
	// Best place to throttle the frame rate on non vsynced platforms is probably here. Let's try it.
	time_update();
	if (lastFrameTime == 0.0)
		lastFrameTime = time_now_d();
	if (!GetAsyncKeyState(VK_TAB) && !PSP_CoreParameter().headLess) {
		while (time_now_d() < lastFrameTime + 1.0 / 60.0) {
			Common::SleepCurrentThread(1);
			time_update();
		}
		// Advance lastFrameTime by a constant amount each frame,
		// but don't let it get too far behind.
		lastFrameTime = std::max(lastFrameTime + 1.0 / 60.0, time_now_d() - 1.5 / 60.0);
	}

	// We are going to have to do something about audio timing for platforms that
	// are vsynced to something that's not exactly 60fps..

#endif

	host->BeginFrame();
	gpu->BeginFrame();

	// Tell the emu core that it's time to stop emulating
	// Win32 doesn't need this.
#ifndef _WIN32
	coreState = CORE_NEXTFRAME;
#endif
}
Exemple #18
0
void delBookmark(int idx) {
	bookmarkList.erase(bookmarkList.begin() + idx);
}
void find_unique_elements (std::vector<T>& A)
{
    std::sort(A.begin(), A.end());
    A.erase(std::unique(A.begin(), A.end()), A.end());
}
Exemple #20
0
void foo(std::vector<int> test, int random)
{
        test.erase(test.begin()+random);
        test.push_back(1);
}
// check if the simplex contains the origin and updates the simplex and d value if not
bool SteerLib::GJK_EPA::containsOrigin(std::vector<Util::Vector> simplex)
{
	// get the last point added to the simplex
	Util::Vector a = simplex.back();
	
	// compute a0 (same thing as -A)
	Util::Vector a0 = -a;

	if (simplex.size() == 3) {
		// then its the triangle case
		// since in this case the simplex can only have 3 values, b and c are the first 2 values
		Util::Vector b = simplex.at(1);
		Util::Vector c = simplex.at(0);
		
		// compute the edges
		Util::Vector ab = b - a;
		Util::Vector ac = c - a;
		
		// compute the normals to those edges
		Util::Vector abNormal = crossProduct3d(crossProduct3d(ac, ab), ab);
		Util::Vector acNormal = crossProduct3d(crossProduct3d(ab, ac), ac);
		
		// check location of origin using a series of plane tests
		// is the origin on ab side opposite to c?
		if (dotProduct3d(abNormal, a0) > 0) {

			// remove point c
			simplex.erase(simplex.begin());
			
			// set the new direction to abNormal
			d = abNormal;
		}
		else {
			// is the origin on ac side opposite to b?
			if (dotProduct3d(acNormal, a0) > 0) {

				// remove point b
				simplex.erase(simplex.begin()+1);

				// set the new direction to acNormal
				d = acNormal;
			}
			else {
				// since the last direction pointed towards a, and all directions after the initial are made to point towards the origin 
				// the origin cannot be on bc side opposite to a
				// therefore the origin is on ab side towards c, ac side towards b, and bc side towards a
				// which is inside the triangle
				return true;
			}
		}
	}
	else {
		// then its the line segment case, where we simply update the d vector to be normal to the line and pointing towards the origin
		// since in this case the simplex can only have 2 values, b is the first value
		Util::Vector b = simplex.at(0);
		
		// compute AB
		Util::Vector ab = b - a;
		
		// get the Normal to AB in the direction of the origin
		Util::Vector abNormal = crossProduct3d(crossProduct3d(ab, a0), ab);
		
		// set the direction to abNormal
		d = abNormal;
	}
	return false;
}
Exemple #22
0
NelderMead::NelderMead(std::vector<double *> newParamPtrs, std::vector<double> expectedRanges, void *object, double (*score)(void *object))
{
    alpha = 1;
    gamma = 2;
    rho = -0.5;
    sigma = 0.5;
    unlimited = false;
    
    std::vector<double *>streamlinedPtrs;
    
    for (int i = 0; i < newParamPtrs.size(); i++)
    {
        if (newParamPtrs[i] != NULL)
            streamlinedPtrs.push_back(newParamPtrs[i]);
        else
        {
            expectedRanges.erase(expectedRanges.begin() + i);
            newParamPtrs.erase(newParamPtrs.begin() + i);
            i--;
        }
    }
    
    paramPtrs = streamlinedPtrs;
    evaluationFunction = score;
    evaluatingObject = object;
    
    int testPointCount = (int)paramCount() + 1;
    testPoints.resize(testPointCount);
    
    if (paramCount() == 0)
        return;
    
    assert(paramCount() > 1);
    
    for (int i = 0; i < testPoints.size(); i++)
    {
        testPoints[i].second = 0;
        testPoints[i].first.resize(paramCount());
        
        logged << "Test point parameter " << i << ": ";
        
        for (int j = 0; j < paramCount(); j++)
        {
            if (i == 0)
            {
                testPoints[i].first[j] = *paramPtrs[j];
            }
            
            if (i > 0)
            {
                int minJ = i - 1;
                double scale = 2;
                
                testPoints[i].first[j] = testPoints[0].first[j] + (j == minJ) * scale * expectedRanges[j];
            }
            
            logged << testPoints[i].first[j] << ", " << std::endl;
        }
    }
   
    logged << "Test point evaluations: ";
    
    for (int i = 0; i < testPoints.size(); i++)
    {
        evaluateTestPoint(i);
        logged << testPoints[i].second << ", ";
    }
    
    logged << std::endl;
    
    std::vector<double> centroid = calculateCentroid();
    logged << "Starting centroid: " << std::endl;
    
    for (int i = 0; i < centroid.size(); i++)
    {
        logged << centroid[i] << ", ";
    }
    
    logged << std::endl;
    
    sendLog(LogLevelDebug);
    
    
}
Exemple #23
0
	inline void removeElementAtIndex(std::vector<T>& vec, unsigned int index)
	{
		std::iter_swap(vec.begin() + index, vec.end() - 1);
		vec.erase(vec.end() - 1);
	}
Exemple #24
0
unsigned long MeshSearchNeighbours::NeighboursFromFacet (unsigned long ulFacetIdx, float fDistance, unsigned long ulMinPoints, std::vector<Base::Vector3f> &raclResultPoints)
{
    bool bAddPoints = false;

    _fMaxDistanceP2 = fDistance * fDistance;
    _clCenter       = _rclMesh.GetFacet(ulFacetIdx).GetGravityPoint();

    unsigned long ulVisited = 1;
    std::vector<MeshFacetArray::_TConstIterator>  aclTestedFacet;

    _aclResult.clear();
    _aclOuter.clear();

    // add start facet
    bool bFound = CheckDistToFacet(_rclFAry[ulFacetIdx]);
    _rclFAry[ulFacetIdx].SetFlag(MeshFacet::MARKED);
    aclTestedFacet.push_back(_rclFAry.begin() + ulFacetIdx);

    if ((bFound == false) && (_aclResult.size() < ulMinPoints)) {
        bAddPoints = true;
        bFound = ExpandRadius(ulMinPoints);
    }

    int nCtExpandRadius = 0; 
    // search neighbours, add not marked facets, test distance, add outer points
    MeshFacetArray::_TConstIterator f_beg = _rclFAry.begin();
    while ((bFound == true) && (nCtExpandRadius < 10)) {
        bFound = false;

        std::set<unsigned long> aclTmp;
        aclTmp.swap(_aclOuter);
        for (std::set<unsigned long>::iterator pI = aclTmp.begin(); pI != aclTmp.end(); pI++) {
            const std::set<unsigned long> &rclISet = _clPt2Fa[*pI]; 
            // search all facets hanging on this point
            for (std::set<unsigned long>::const_iterator pJ = rclISet.begin(); pJ != rclISet.end(); pJ++) {
                const MeshFacet &rclF = f_beg[*pJ];

                if (rclF.IsFlag(MeshFacet::MARKED) == false) {
                    bool bLF = CheckDistToFacet(rclF);
                    bFound = bFound || bLF;
                    rclF.SetFlag(MeshFacet::MARKED);
                    aclTestedFacet.push_back(f_beg+*pJ);
                }
            }
            ulVisited += rclISet.size();
        }

        // too few points inside radius found -> expand radius
        if ((bFound == false) && (_aclResult.size() < ulMinPoints)) {
            nCtExpandRadius++;
            bAddPoints = true;
            bFound = ExpandRadius(ulMinPoints);
        }
        else
            nCtExpandRadius = 0;
    }

    // reset marked facets, points
    for (std::vector<MeshFacetArray::_TConstIterator>::iterator pF = aclTestedFacet.begin();
        pF != aclTestedFacet.end(); ++pF)
        (*pF)->ResetFlag(MeshFacet::MARKED);
    for (std::set<unsigned long>::iterator pR = _aclResult.begin(); pR != _aclResult.end(); ++pR)
        _rclPAry[*pR].ResetFlag(MeshPoint::MARKED);


    // copy points in result container
    raclResultPoints.resize(_aclResult.size());
    int i = 0;
    for (std::set<unsigned long>::iterator pI = _aclResult.begin(); pI != _aclResult.end(); pI++, i++)
        raclResultPoints[i] = _rclPAry[*pI];

    if (bAddPoints == true) {
        // sort points, remove points lying furthest from center
        std::sort(raclResultPoints.begin(), raclResultPoints.end(), CDistRad(_clCenter));
        raclResultPoints.erase(raclResultPoints.begin() + ulMinPoints, raclResultPoints.end());
    }

    return ulVisited;
}
Exemple #25
0
void hleEnterVblank(u64 userdata, int cyclesLate) {
	int vbCount = userdata;

	DEBUG_LOG(SCEDISPLAY, "Enter VBlank %i", vbCount);

	isVblank = 1;
	vCount++; // vCount increases at each VBLANK.
	hCountBase += hCountPerVblank; // This is the "accumulated" hcount base.
	if (hCountBase > 0x7FFFFFFF) {
		hCountBase -= 0x80000000;
	}
	frameStartTicks = CoreTiming::GetTicks();

	// Wake up threads waiting for VBlank
	u32 error;
	for (size_t i = 0; i < vblankWaitingThreads.size(); i++) {
		if (--vblankWaitingThreads[i].vcountUnblock == 0) {
			// Only wake it if it wasn't already released by someone else.
			SceUID waitID = __KernelGetWaitID(vblankWaitingThreads[i].threadID, WAITTYPE_VBLANK, error);
			if (waitID == 1) {
				__KernelResumeThreadFromWait(vblankWaitingThreads[i].threadID, 0);
			}
			vblankWaitingThreads.erase(vblankWaitingThreads.begin() + i--);
		}
	}

	// Trigger VBlank interrupt handlers.
	__TriggerInterrupt(PSP_INTR_IMMEDIATE | PSP_INTR_ONLY_IF_ENABLED | PSP_INTR_ALWAYS_RESCHED, PSP_VBLANK_INTR, PSP_INTR_SUB_ALL);

	CoreTiming::ScheduleEvent(msToCycles(vblankMs) - cyclesLate, leaveVblankEvent, vbCount + 1);

	gpuStats.numVBlanks++;

	numVBlanksSinceFlip++;

	// TODO: Should this be done here or in hleLeaveVblank?
	if (framebufIsLatched) {
		DEBUG_LOG(SCEDISPLAY, "Setting latched framebuffer %08x (prev: %08x)", latchedFramebuf.topaddr, framebuf.topaddr);
		framebuf = latchedFramebuf;
		framebufIsLatched = false;
		gpu->SetDisplayFramebuffer(framebuf.topaddr, framebuf.pspFramebufLinesize, framebuf.pspFramebufFormat);
	}
	// We flip only if the framebuffer was dirty. This eliminates flicker when using
	// non-buffered rendering. The interaction with frame skipping seems to need
	// some work.
	if (gpu->FramebufferDirty()) {
		if (g_Config.iShowFPSCounter && g_Config.iShowFPSCounter < 4) {
			CalculateFPS();
		}

		// Setting CORE_NEXTFRAME causes a swap.
		// Check first though, might've just quit / been paused.
		if (gpu->FramebufferReallyDirty()) {
			if (coreState == CORE_RUNNING) {
				coreState = CORE_NEXTFRAME;
				gpu->CopyDisplayToOutput();
				actualFlips++;
			}
		}

		gpuStats.numFlips++;

		bool throttle, skipFrame;
		// 1.001f to compensate for the classic 59.94 NTSC framerate that the PSP seems to have.
		DoFrameTiming(throttle, skipFrame, (float)numVBlanksSinceFlip * (1.001f / 60.0f));

		int maxFrameskip = 8;
		if (throttle) {
			if (g_Config.iFrameSkip == 1) {
				// 4 here means 1 drawn, 4 skipped - so 12 fps minimum.
				maxFrameskip = 4;
			} else {
				maxFrameskip = g_Config.iFrameSkip - 1;
			}
		}
		if (numSkippedFrames >= maxFrameskip) {
			skipFrame = false;
		}

		if (skipFrame) {
			gstate_c.skipDrawReason |= SKIPDRAW_SKIPFRAME;
			numSkippedFrames++;
		} else {
			gstate_c.skipDrawReason &= ~SKIPDRAW_SKIPFRAME;
			numSkippedFrames = 0;
		}

		// Returning here with coreState == CORE_NEXTFRAME causes a buffer flip to happen (next frame).
		// Right after, we regain control for a little bit in hleAfterFlip. I think that's a great
		// place to do housekeeping.
		CoreTiming::ScheduleEvent(0 - cyclesLate, afterFlipEvent, 0);
		numVBlanksSinceFlip = 0;
	}
}
static void* vpl_monitor_dir_handler(void* unused)
{
    int rc;
    while(true) {

        rc = VPLSem_Wait(&g_semaphoreCommand);
        if(rc != VPL_OK) {
            VPL_REPORT_WARN("Semaphore wait:%d", rc);
        }
        g_returnErrorCode = 0;
        VPL_REPORT_INFO("Command Received:%d", g_monitorCommand);

        switch(g_monitorCommand) {
        case MONITOR_COMMAND_NONE:
            break;
        case MONITOR_COMMAND_START:
            rc = beginMonitor(g_monitorHandle);
            if(rc != 0) {
                VPL_REPORT_WARN("Cannot begin monitor:%d", rc);
                g_returnErrorCode = rc;
            }else {
                g_monitorHandles.push_back(g_monitorHandle);
            }

            g_monitorCommand = MONITOR_COMMAND_NONE;
            rc = VPLSem_Post(&g_semaphoreReturn);
            if(rc != VPL_OK){
                VPL_REPORT_WARN("Semaphore Return post:%d", rc);
                g_returnErrorCode = rc;
            }
            break;
        case MONITOR_COMMAND_STOP:
            g_monitorHandle->stop = true;
#ifdef VPL_PLAT_IS_WINRT
            // TODO: properly stop dir monitoring
            rc = VPL_ERR_NOOP;
#else
            if (CancelIo(g_monitorHandle->hDir) == 0) {
                rc = VPLError_GetLastWinError();
                VPL_REPORT_WARN("CancelIo:%d", rc);
            }
#endif
            g_monitorHandles.erase(std::remove(g_monitorHandles.begin(),
                                               g_monitorHandles.end(),
                                               g_monitorHandle),
                                   g_monitorHandles.end());

            g_monitorCommand = MONITOR_COMMAND_NONE;
            rc = VPLSem_Post(&g_semaphoreReturn);
            if(rc != VPL_OK){
                VPL_REPORT_WARN("Semaphore Return post:%d", rc);
                g_returnErrorCode = rc;
            }
            break;
        case MONITOR_COMMAND_DESTROY:
            {
                std::vector<VPLFS_MonitorHandle_t*>::iterator iter =
                        g_monitorHandles.begin();
                for(;iter!=g_monitorHandles.end();++iter) {
                    (*iter)->stop = true;
#ifdef VPL_PLAT_IS_WINRT
                    // TODO: properly stop dir monitoring
                    rc = VPL_ERR_NOOP;
#else
                    if (CancelIo((*iter)->hDir) == 0) {
                        rc = VPLError_GetLastWinError();
                        VPL_REPORT_WARN("CancelIo:%d", rc);
                    }
#endif
                }
                g_monitorHandles.clear();
            }
            g_monitorCommand = MONITOR_COMMAND_NONE;
            goto exit;
        default:
            VPL_REPORT_WARN("Unrecognized command: %d", rc);
            break;
        }
    }
 exit:
    return NULL;
}
Exemple #27
0
bool RectanglePacker::addRectangle(uint16_t _width, uint16_t _height, uint16_t& _outX, uint16_t& _outY)
{
	int best_height, best_index;
	int32_t best_width;
	Node* node;
	Node* prev;
	_outX = 0;
	_outY = 0;

	best_height = INT_MAX;
	best_index = -1;
	best_width = INT_MAX;
	for (uint16_t ii = 0, num = uint16_t(m_skyline.size() ); ii < num; ++ii)
	{
		int32_t yy = fit(ii, _width, _height);
		if (yy >= 0)
		{
			node = &m_skyline[ii];
			if ( ( (yy + _height) < best_height)
			|| ( ( (yy + _height) == best_height) && (node->width < best_width) ) )
			{
				best_height = uint16_t(yy) + _height;
				best_index = ii;
				best_width = node->width;
				_outX = node->x;
				_outY = uint16_t(yy);
			}
		}
	}

	if (best_index == -1)
	{
		return false;
	}

	Node newNode(_outX, _outY + _height, _width);
	m_skyline.insert(m_skyline.begin() + best_index, newNode);

	for (uint16_t ii = uint16_t(best_index + 1), num = uint16_t(m_skyline.size() ); ii < num; ++ii)
	{
		node = &m_skyline[ii];
		prev = &m_skyline[ii - 1];
		if (node->x < (prev->x + prev->width) )
		{
			uint16_t shrink = uint16_t(prev->x + prev->width - node->x);
			node->x += shrink;
			node->width -= shrink;
			if (node->width <= 0)
			{
				m_skyline.erase(m_skyline.begin() + ii);
				--ii;
				--num;
			}
			else
			{
				break;
			}
		}
		else
		{
			break;
		}
	}

	merge();
	m_usedSpace += _width * _height;
	return true;
}
Exemple #28
0
bool TreeSocket::PreProcessOldProtocolMessage(User*& who, std::string& cmd, std::vector<std::string>& params)
{
	if ((cmd == "METADATA") && (params.size() >= 3) && (params[0][0] == '#'))
	{
		// :20D METADATA #channel extname :extdata
		return InsertCurrentChannelTS(params);
	}
	else if ((cmd == "FTOPIC") && (params.size() >= 4))
	{
		// :20D FTOPIC #channel 100 Attila :topic text
		return InsertCurrentChannelTS(params);
	}
	else if ((cmd == "PING") || (cmd == "PONG"))
	{
		if (params.size() == 1)
		{
			// If it's a PING with 1 parameter, reply with a PONG now, if it's a PONG with 1 parameter (weird), do nothing
			if (cmd[1] == 'I')
				this->WriteData(":" + ServerInstance->Config->GetSID() + " PONG " + params[0] + newline);

			// Don't process this message further
			return false;
		}

		// :20D PING 20D 22D
		// :20D PONG 20D 22D
		// Drop the first parameter
		params.erase(params.begin());

		// If the target is a server name, translate it to a SID
		if (!InspIRCd::IsSID(params[0]))
		{
			TreeServer* server = Utils->FindServer(params[0]);
			if (!server)
			{
				// We've no idea what this is, log and stop processing
				ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, "Received a " + cmd + " with an unknown target: \"" + params[0] + "\", command dropped");
				return false;
			}

			params[0] = server->GetID();
		}
	}
	else if ((cmd == "GLINE") || (cmd == "KLINE") || (cmd == "ELINE") || (cmd == "ZLINE") || (cmd == "QLINE"))
	{
		// Fix undocumented protocol usage: translate GLINE, ZLINE, etc. into ADDLINE or DELLINE
		if ((params.size() != 1) && (params.size() != 3))
			return false;

		parameterlist p;
		p.push_back(cmd.substr(0, 1));
		p.push_back(params[0]);

		if (params.size() == 3)
		{
			cmd = "ADDLINE";
			p.push_back(who->nick);
			p.push_back(ConvToStr(ServerInstance->Time()));
			p.push_back(ConvToStr(InspIRCd::Duration(params[1])));
			p.push_back(params[2]);
		}
		else
			cmd = "DELLINE";

		params.swap(p);
	}
	else if (cmd == "SVSMODE")
	{
		cmd = "MODE";
	}
	else if (cmd == "OPERQUIT")
	{
		// Translate OPERQUIT into METADATA
		if (params.empty())
			return false;

		cmd = "METADATA";
		params.insert(params.begin(), who->uuid);
		params.insert(params.begin()+1, "operquit");
		who = MyRoot->ServerUser;
	}
	else if ((cmd == "TOPIC") && (params.size() >= 2))
	{
		// :20DAAAAAC TOPIC #chan :new topic
		cmd = "FTOPIC";
		if (!InsertCurrentChannelTS(params))
			return false;

		params.insert(params.begin()+2, ConvToStr(ServerInstance->Time()));
	}
	else if (cmd == "MODENOTICE")
	{
		// MODENOTICE is always supported by 2.0 but it's optional in 2.2.
		params.insert(params.begin(), "*");
		params.insert(params.begin()+1, cmd);
		cmd = "ENCAP";
	}
	else if (cmd == "RULES")
	{
		return false;
	}
	else if (cmd == "INVITE")
	{
		// :20D INVITE 22DAAABBB #chan
		// :20D INVITE 22DAAABBB #chan 123456789
		// Insert channel timestamp after the channel name; the 3rd parameter, if there, is the invite expiration time
		return InsertCurrentChannelTS(params, 1, 2);
	}
	else if (cmd == "VERSION")
	{
		// :20D VERSION :InspIRCd-2.0
		// change to
		// :20D SINFO version :InspIRCd-2.0
		cmd = "SINFO";
		params.insert(params.begin(), "version");
	}

	return true; // Passthru
}
void AbstractRootedTreeDistribution::simulateClade(std::vector<TopologyNode *> &n, double age, double present)
{

    // Get the rng
    RandomNumberGenerator* rng = GLOBAL_RNG;

    // get the minimum age
    double current_age = n[0]->getAge();
    for (size_t i = 1; i < n.size(); ++i)
    {

        if ( current_age > n[i]->getAge() )
        {
            current_age = n[i]->getAge();
        }

    }
    

    while ( n.size() > 2 && current_age < age )
    {

        // get all the nodes before the current age
        std::vector<TopologyNode*> active_nodes;
        for (size_t i = 0; i < n.size(); ++i)
        {

            if ( current_age >= n[i]->getAge() )
            {
                active_nodes.push_back( n[i] );
            }

        }

        // we need to get next age of a node larger than the current age
        double next_node_age = age;
        for (size_t i = 0; i < n.size(); ++i)
        {

            if ( current_age < n[i]->getAge() && n[i]->getAge() < next_node_age )
            {
                next_node_age = n[i]->getAge();
            }

        }

        // only simulate if there are at least to valid/active nodes
        if ( active_nodes.size() < 2 )
        {
            current_age = next_node_age;
        }
        else
        {

            // now we simulate new ages
            double next_sim_age = simulateNextAge(active_nodes.size()-1, present-age, present-current_age, present);

            if ( next_sim_age < next_node_age )
            {

                // randomly pick two nodes
                size_t index_left = static_cast<size_t>( floor(rng->uniform01()*active_nodes.size()) );
                TopologyNode* left_child = active_nodes[index_left];
                active_nodes.erase(active_nodes.begin()+long(index_left));
                size_t index_right = static_cast<size_t>( floor(rng->uniform01()*active_nodes.size()) );
                TopologyNode* right_right = active_nodes[index_right];
                active_nodes.erase(active_nodes.begin()+long(index_right));

                // erase the nodes also from the origin nodes vector
                n.erase(std::remove(n.begin(), n.end(), left_child), n.end());
                n.erase(std::remove(n.begin(), n.end(), right_right), n.end());


                // create a parent for the two
                TopologyNode *parent = new TopologyNode();
                parent->addChild( left_child );
                parent->addChild( right_right );
                left_child->setParent( parent );
                right_right->setParent( parent );
                parent->setAge( next_sim_age );

                // insert the parent to our list
                n.push_back( parent );
                
                current_age = next_sim_age;
            }
            else
            {
                current_age = next_node_age;
            }

        }
        
    }


    if ( n.size() == 2 )
    {

        // pick two nodes
        TopologyNode* left_child = n[0];
        TopologyNode* right_right = n[1];

        // erase the nodes also from the origin nodes vector
        n.clear();

        // create a parent for the two
        TopologyNode *parent = new TopologyNode();
        parent->addChild( left_child );
        parent->addChild( right_right );
        left_child->setParent( parent );
        right_right->setParent( parent );
        parent->setAge( age );

        // insert the parent to our list
        n.push_back( parent );
    }
    else
    {
        throw RbException("Unexpected number of taxa in constrained tree simulation");
    }


}
void bad_erase2(std::vector<int> &v1, std::vector<int> &v2) {
  v2.erase(v2.cbegin(), v1.cend()); // expected-warning{{Container accessed using foreign iterator argument}}
  v2.erase(v1.cbegin(), v2.cend()); // expected-warning{{Container accessed using foreign iterator argument}}
  v2.erase(v1.cbegin(), v1.cend()); // expected-warning{{Container accessed using foreign iterator argument}}
}