void expandTree(binaryTreePtr tree)
/* This procedure expands a unique tree for the current game state
 * Pre-condition: the tree has been allocated in memory
 * Post-condition: a tree has been created for the given game state
*/
{
	if (tree != NULL)
	{
		//get the current gamestate for the level in tree we are on
		infoPtr gameInfo = retrieveNodeElm(tree);

		//store the adress of the current node in the tree
		treeNodePtr current;
		current = getCurrentNode(tree);

		//get the root level's game state
		nextNode(tree,TOROOT);
		infoPtr rootInfo = retrieveNodeElm(tree);

		//go back to current level
		setCurrentNode(tree,current);
		//we only extend 2 levels, this counts how many we have done
		int cmpSquares = squaresAvailable(rootInfo) - squaresAvailable(gameInfo);

		//is there any sqaures available?
		if ( (cmpSquares  < 3) && (squaresAvailable(gameInfo) != 0) )
		{
			//generate the next level for the tree
			generateSquares(tree);
			//go back to the node we started with
			setCurrentNode(tree, current);
			//go to the first node on the next level
			nextNode(tree, TOLEFT);
			//set this as the current node
			current = getCurrentNode(tree);
			//call this procedure again, to expand the next level
			expandTree(tree);
			//go back to first node of level we are working with
			setCurrentNode(tree, current);

			//does it have a next node on this level?
			while (existNode(tree, TORIGHT) == 1)
			{
				//then go to the next node
				nextNode(tree, TORIGHT);
				//get node on this level we are working with
				current = getCurrentNode(tree);
				//generate a next level for this node
				expandTree(tree);
				//back to working level
				setCurrentNode(tree, current);
			}
		}
	}
}
void        ControllerIf::getUserInput() {
    if(digitalRead(BUTTON_UP_PIN) == 0) {
        if(!buttonUpState) {
            buttonUpState = true;
            getCurrentNode()->buttonUp();
            GLCD.InvertRect(119, 7, 6, 7);
        }
    } else {
        if(buttonUpState) {
            buttonUpState = false;
            getCurrentNode()->updateDisplay();
        }
    }
    if(digitalRead(BUTTON_DN_PIN) == 0) {
        if(!buttonDnState) {
            buttonDnState = true;
            getCurrentNode()->buttonDn();
            GLCD.InvertRect(119, 38, 6, 7);
        }
    } else {
        if(buttonDnState) {
            buttonDnState = false;
            getCurrentNode()->updateDisplay();
        }
    }
    if(digitalRead(BUTTON_LT_PIN) == 0) {
        if(!buttonLtState) {
            buttonLtState = true;
            getCurrentNode()->buttonLt();
            GLCD.InvertRect(0, 56, 63, 7);
        }
    } else {
        if(buttonLtState) {
            buttonLtState = false;
            getCurrentNode()->updateDisplay();
        }
    }
    if(digitalRead(BUTTON_RT_PIN) == 0) {
        if(!buttonRtState) {
            buttonRtState = true;
            getCurrentNode()->buttonRt();
            GLCD.InvertRect(64, 56, 63, 7);
        }
    } else {
        if(buttonRtState) {
            buttonRtState = false;
            getCurrentNode()->updateDisplay();
        }
    }
    
    if(currentNode == liveNode) {
        unsigned long current_time = millis();
        if(current_time >= last_update + update_interval) {
            last_update = current_time;
            getCurrentNode()->updateDisplay();
        }
    }
}
const Node& Loader::parseTree()
{
	auto it = fileContents.begin() + sizeof(Identifier);
	if (static_cast<uint8_t>(*it) != Node::START) {
		throw InvalidOTBFormat{};
	}
	root.type = *(++it);
	root.propsBegin = ++it;
	NodeStack parseStack;
	parseStack.push(&root);

	for (; it != fileContents.end(); ++it) {
		switch(static_cast<uint8_t>(*it)) {
			case Node::START: {
				auto& currentNode = getCurrentNode(parseStack);
				if (currentNode.children.empty()) {
					currentNode.propsEnd = it;
				}
				currentNode.children.emplace_back();
				auto& child = currentNode.children.back();
				if (++it == fileContents.end()) {
					throw InvalidOTBFormat{};
				}
				child.type = *it;
				child.propsBegin = it + sizeof(Node::type);
				parseStack.push(&child);
				break;
			}
			case Node::END: {
				auto& currentNode = getCurrentNode(parseStack);
				if (currentNode.children.empty()) {
					currentNode.propsEnd = it;
				}
				parseStack.pop();
				break;
			}
			case Node::ESCAPE: {
				if (++it == fileContents.end()) {
					throw InvalidOTBFormat{};
				}
				break;
			}
			default: {
				break;
			}
		}
	}
	if (!parseStack.empty()) {
		throw InvalidOTBFormat{};
	}

	return root;
}
Example #4
0
/** This function handles braking. It calls determineTurnRadius() to find out
 *  the curve radius. Depending on the turn radius, it finds out the maximum
 *  speed. If the current speed is greater than the max speed and a set minimum
 *  speed, brakes are applied.
 */
void ArenaAI::handleArenaBraking()
{
    m_controls->m_brake = false;

    if (getCurrentNode() == BattleGraph::UNKNOWN_POLY ||
        m_target_node    == BattleGraph::UNKNOWN_POLY) return;

    // A kart will not brake when the speed is already slower than this
    // value. This prevents a kart from going too slow (or even backwards)
    // in tight curves.
    const float MIN_SPEED = 5.0f;

    std::vector<Vec3> points;

    points.push_back(m_kart->getXYZ());
    points.push_back(m_path_corners[0]);
    points.push_back((m_path_corners.size()>=2) ? m_path_corners[1] : m_path_corners[0]);

    float current_curve_radius = determineTurnRadius(points);

    Vec3 d1 = m_kart->getXYZ() - m_target_point;
    Vec3 d2 = m_kart->getXYZ() - m_path_corners[0];
    if (d1.length2_2d() < d2.length2_2d())
        current_curve_radius = d1.length_2d();

    float max_turn_speed = m_kart->getSpeedForTurnRadius(current_curve_radius);

    if (m_kart->getSpeed() > max_turn_speed &&
        m_kart->getSpeed() > MIN_SPEED)
    {
        m_controls->m_brake = true;
    }

}   // handleArenaBraking
Example #5
0
/** Determine whether AI is stuck, by checking if it stays on the same node for
 *  a long period of time (see \ref m_on_node), or \ref isStuck() is true.
 *  \param dt Time step size.
 *  \return True if AI is stuck
 */
void ArenaAI::checkIfStuck(const float dt)
{
    if (m_is_stuck) return;

    if (m_kart->getKartAnimation() || isWaiting())
    {
        m_on_node.clear();
        m_time_since_driving = 0.0f;
    }

    m_on_node.insert(getCurrentNode());
    m_time_since_driving += dt;

    if ((m_time_since_driving >=
        (m_cur_difficulty == RaceManager::DIFFICULTY_EASY ? 2.0f : 1.5f)
        && m_on_node.size() < 2 && !m_is_uturn &&
        fabsf(m_kart->getSpeed()) < 3.0f) || isStuck() == true)
    {
        // AI is stuck, reset now and try to get unstuck at next frame
        m_on_node.clear();
        m_time_since_driving = 0.0f;
        AIBaseController::reset();
        m_is_stuck = true;
    }
    else if (m_time_since_driving >=
        (m_cur_difficulty == RaceManager::DIFFICULTY_EASY ? 2.0f : 1.5f))
    {
        m_on_node.clear(); // Reset for any correct movement
        m_time_since_driving = 0.0f;
    }

}   //  checkIfStuck
Example #6
0
//-----------------------------------------------------------------------------
void ArenaAI::handleArenaBanana()
{
    if (m_is_uturn) return;

    const std::vector< std::pair<const Item*, int> >& item_list =
        BattleGraph::get()->getItemList();
    const unsigned int items_count = item_list.size();
    for (unsigned int i = 0; i < items_count; ++i)
    {
        const Item* item = item_list[i].first;
        if (item->getType() == Item::ITEM_BANANA && !item->wasCollected())
        {
            posData banana_pos = {0};
            Vec3 banana_lc(0, 0, 0);
            checkPosition(item->getXYZ(), &banana_pos, &banana_lc);
            if (banana_pos.angle < 0.2f && banana_pos.distance < 7.5f &&
               !banana_pos.behind)
            {
                // Check whether it's straight ahead towards a banana
                // If so, adjust target point
                banana_lc = (banana_pos.on_side ? banana_lc + Vec3 (2, 0, 0) :
                    banana_lc - Vec3 (2, 0, 0));
                m_target_point = m_kart->getTrans()(banana_lc);
                m_target_node  = BattleGraph::get()
                    ->pointToNode(getCurrentNode(), m_target_point,
                    false/*ignore_vertical*/);

                // Handle one banana only
                break;
            }
        }
    }

}   // handleArenaBanana
Example #7
0
//-----------------------------------------------------------------------------
void ArenaAI::checkIfStuck(const float dt)
{
    if (m_is_stuck) return;

    if (m_kart->getKartAnimation() || isWaiting())
    {
        m_on_node.clear();
        m_time_since_driving = 0.0f;
    }

    m_on_node.insert(getCurrentNode());
    m_time_since_driving += dt;

    if ((m_time_since_driving >=
        (m_cur_difficulty == RaceManager::DIFFICULTY_EASY ? 2.0f : 1.5f)
        && m_on_node.size() < 2 && !m_is_uturn &&
        fabsf(m_kart->getSpeed()) < 3.0f) || isStuck() == true)
    {
        // Check whether a kart stay on the same node for a period of time
        // Or crashed 3 times
        m_on_node.clear();
        m_time_since_driving = 0.0f;
        AIBaseController::reset();
        m_is_stuck = true;
    }
    else if (m_time_since_driving >=
        (m_cur_difficulty == RaceManager::DIFFICULTY_EASY ? 2.0f : 1.5f))
    {
        m_on_node.clear(); // Reset for any correct movement
        m_time_since_driving = 0.0f;
    }

}   //  checkIfStuck
Example #8
0
/** This function sets the steering.
 *  \param dt Time step size.
 */
void ArenaAI::handleArenaSteering(const float dt)
{
    const int current_node = getCurrentNode();

    if (current_node == BattleGraph::UNKNOWN_POLY ||
        m_target_node == BattleGraph::UNKNOWN_POLY) return;

    if (m_target_node == current_node)
    {
        // Very close to the item, steer directly
        checkPosition(m_target_point, &m_cur_kart_pos_data);
#ifdef AI_DEBUG
        m_debug_sphere->setPosition(m_target_point.toIrrVector());
#endif
        if (m_cur_kart_pos_data.behind)
        {
            m_adjusting_side = m_cur_kart_pos_data.on_side;
            m_is_uturn = true;
        }
        else
        {
            float target_angle = steerToPoint(m_target_point);
            setSteering(target_angle, dt);
        }
        return;
    }

    else if (m_target_node != current_node)
    {
        findPortals(current_node, m_target_node);
        stringPull(m_kart->getXYZ(), m_target_point);
        if (m_path_corners.size() > 0)
            m_target_point = m_path_corners[0];

        checkPosition(m_target_point, &m_cur_kart_pos_data);
#ifdef AI_DEBUG
        m_debug_sphere->setPosition(m_target_point.toIrrVector());
#endif
        if (m_cur_kart_pos_data.behind)
        {
            m_adjusting_side = m_cur_kart_pos_data.on_side;
            m_is_uturn = true;
        }
        else
        {
            float target_angle = steerToPoint(m_target_point);
            setSteering(target_angle, dt);
        }
        return;
    }

    else
    {
        // Do nothing (go straight) if no targets found
        setSteering(0.0f, dt);
        return;
    }
}   // handleSteering
Example #9
0
/*!\func
 * new edge
 * \params
 * - index - index source node
 * - relationWith - index destination node
 * \return
 */
bool SequenceBody::addRelation(const qint16& index,const qint16& relationWith, const State*state)
{
	Q_UNUSED(state);
	LOG(LOG_DEBUG, QString(__FUNCTION__) + " <" + QString::number(__LINE__) + ">");
	if(!getCurrentNode())return false;
	if(getCurrentNode()->nodes().contains(index) &&getCurrentNode()->nodes().contains(relationWith))
	{
		INode* source = getCurrentNode()->nodes()[index];
		INode* dest = getCurrentNode()->nodes()[relationWith];
		if(dest && source )
			if((dest->getId() != source->getId()))
				{
					getFactory()->newEdge(EDGE_SEQUENCE, source, dest, "");
					change(true);
					return true;
				}
	}
	return false;
}
Example #10
0
	PatternMatchState( const PatternMatchState & state, const TransitionRef & transition, const Context & ctx, bool releaseParent ) :
		startNode( state.startNode ), variant( releaseParent ? state.releaseVariant() : new MatchVariant( *state.variant ) ), context( ctx ) {

		if ( &transition->start != &getCurrentNode() )
			throw std::logic_error("Illegal transition");

		context.addValue( getCurrentMatcher().variable, transition );

		variant->push_back( transition );
	}
Example #11
0
/** Try to collect item in arena, if no suitable item is found, like they are
 *  swapped, it will follow closest kart instead.
 *  \param[out] aim_point Location of item.
 *  \param[out] target_node The node which item lied on.
 */
void ArenaAI::tryCollectItem(Vec3* aim_point, int* target_node) const
{
    float distance = 999999.9f;
    Item* selected = (*target_node == Graph::UNKNOWN_SECTOR ? NULL :
        ItemManager::get()->getFirstItemInQuad(*target_node));

    // Don't look for a new item unless it's collected or swapped
    if (selected && !(selected->wasCollected() ||
        selected->getType() == Item::ITEM_BANANA ||
        selected->getType() == Item::ITEM_BUBBLEGUM ||
        selected->getType() == Item::ITEM_BUBBLEGUM_NOLOK))
    {
        *aim_point = selected->getXYZ();
        return;
    }

    for (unsigned int i = 0; i < m_graph->getNumNodes(); i++)
    {
        Item* cur_item = ItemManager::get()->getFirstItemInQuad(i);
        if (cur_item == NULL) continue;
        if (cur_item->wasCollected() ||
            cur_item->getType() == Item::ITEM_BANANA ||
            cur_item->getType() == Item::ITEM_BUBBLEGUM ||
            cur_item->getType() == Item::ITEM_BUBBLEGUM_NOLOK)
            continue;

        if ((cur_item->getType() == Item::ITEM_NITRO_BIG ||
             cur_item->getType() == Item::ITEM_NITRO_SMALL) &&
            (m_kart->getEnergy() >
             m_kart->getKartProperties()->getNitroSmallContainer()))
                continue; // Ignore nitro when already has some

        const int cur_node = cur_item->getGraphNode();
        assert(cur_node != Graph::UNKNOWN_SECTOR);
        float test_distance = m_graph->getDistance(cur_node, getCurrentNode());
        if (test_distance <= distance)
        {
            selected = cur_item;
            distance = test_distance;
        }
    }

    if (selected != NULL)
    {
        *aim_point = selected->getXYZ();
        *target_node = selected->getGraphNode();
    }
    else
    {
        // Handle when all targets are swapped, which make AIs follow karts
        *aim_point = m_closest_kart_point;
        *target_node = m_closest_kart_node;
    }
}   // tryCollectItem
Example #12
0
/** This function config the steering (\ref m_steering_angle) of AI.
 */
void ArenaAI::configSteering()
{
    m_steering_angle = 0.0f;
    const int current_node = getCurrentNode();

    if (current_node == Graph::UNKNOWN_SECTOR ||
        m_target_node == Graph::UNKNOWN_SECTOR)
    {
        return;
    }

    if (ignorePathFinding())
    {
        // Steer directly, don't brake
        m_turn_radius = 100.0f;
#ifdef AI_DEBUG
        m_debug_sphere->setPosition(m_target_point.toIrrVector());
#endif
        if (m_target_point_lc.z() < 0)
        {
            m_is_uturn = true;
            m_reverse_point = m_target_point;
        }
        else
        {
            m_steering_angle = steerToPoint(m_target_point);
        }
        return;
    }

    // Otherwise use path finding to get target point
    Vec3 target_point;
    const bool found_position = updateAimingPosition(&target_point);
    if (found_position)
    {
        m_target_point = target_point;
        m_target_point_lc = m_kart->getTrans().inverse()(m_target_point);
#ifdef AI_DEBUG
        m_debug_sphere->setVisible(true);
        m_debug_sphere->setPosition(m_target_point.toIrrVector());
#endif
        if (m_target_point_lc.z() < 0)
        {
            m_is_uturn = true;
            m_reverse_point = m_target_point;
        }
        else
        {
            m_steering_angle = steerToPoint(m_target_point);
        }
    }
}   // configSteering
Example #13
0
/*!\func
 * add new node
 * \params
 * - type - type of new node
 * \return no
 */
qint16 SequenceBody::addTop(TopTypes type)
{
	LOG(LOG_DEBUG, QString(__FUNCTION__) + " <" + QString::number(__LINE__) + ">");
	QString name("");
	qint16 id = 1 + getMax();
	switch(type) {
	default:
		name = QString ("MODULE_") + QString::number(id);
	}
	getFactory()->newNode(TOP_SEQUENCE, id, getCurrentNode(), name, tr("No tool tip now!"), QPointF())->show();
	change(true);
	return id;
}
Example #14
0
	UITextInputField::UITextInputField(TextInputField *pTextInputField, CCNode *parent)
		:UIControlBase(parent)
	{
		m_pTextInputField = pTextInputField;
		m_pControlNode = m_pTextInputField;

		CreateWhiteBack();

		if(m_pWhiteBack != NULL)
		{
			parent->addChild(m_pWhiteBack);
		}

		CCNode *pNode = getCurrentNode();
		parent->addChild(pNode);
	}
Example #15
0
	UITextInputField::UITextInputField(const char *label, const char *fontName, float fontSize, cocos2d::CCNode* parent)  
		:UIControlBase(parent)
	{
		m_pTextInputField = TextInputField::textFieldWithPlaceHolder(label, fontName, fontSize);
		m_pControlNode = m_pTextInputField;

		CreateWhiteBack();

		if(m_pWhiteBack != NULL)
		{
			parent->addChild(m_pWhiteBack);
		}

		CCNode *pNode = getCurrentNode();
		parent->addChild(pNode);
	}
Example #16
0
void GLSLUberShader::compileCurrentState()
{
	UberShaderNode* node = getCurrentNode();

	if(node->m_program != 0) {
		logWarn("UberShader state already compiled");
	} else {
		node->m_program = new QGLShaderProgram();
		node->m_vertex_shader = new QGLShader(QGLShader::Vertex);
		node->m_fragment_shader = new QGLShader(QGLShader::Fragment);

		node->m_vertex_shader->compileSourceCode(buildDefineList() + m_vertex_shader);
		node->m_fragment_shader->compileSourceCode(buildDefineList() + m_fragment_shader);
		node->m_program->addShader(node->m_vertex_shader);
		node->m_program->addShader(node->m_fragment_shader);

		buildTexunitsList(node->m_texunits);
	}
}
Example #17
0
const PlanOperation* PlanOperation::execute() {
  const bool recordPerformance = _performance_attr != nullptr;

  // Check if we really need this
  epoch_t startTime = 0;
  if (recordPerformance)
    startTime = get_epoch_nanoseconds();

  PapiTracer pt;

  // Start the execution
  refreshInput();
  setupPlanOperation();

  if (recordPerformance) {
    pt.addEvent("PAPI_TOT_CYC");
    pt.addEvent(getEvent());
    pt.start();
  }

  executePlanOperation();

  if (recordPerformance)
    pt.stop();

  teardownPlanOperation();

  if (recordPerformance) {
    epoch_t endTime = get_epoch_nanoseconds();
    std::string threadId = boost::lexical_cast<std::string>(std::this_thread::get_id());

    size_t cardinality;
    unsigned core = getCurrentCore();
    unsigned node = getCurrentNode();

    std::optional<size_t> in_size;
    if (const auto& in = getInputTable()) {
      in_size = in->size();
    }

    std::optional<size_t> out_size;
    if (const auto& out = getResultTable()) {
      out_size = out->size();
    }

    if (getResultTable() != empty_result)
      cardinality = getResultTable()->size();
    else
      // the cardinality is max(size_t) by convention if there is no return table
      cardinality = std::numeric_limits<size_t>::max();

    *_performance_attr = (performance_attributes_t) {pt.value("PAPI_TOT_CYC"), pt.value(getEvent()), getEvent(),
                                                     planOperationName(),      _operatorId,          startTime,
                                                     endTime,                  threadId,             cardinality,
                                                     core,                     node,                 in_size,
                                                     out_size};
  }

  setState(OpSuccess);
  return this;
}
Example #18
0
/** Update aiming position, use path finding if necessary.
 *  \param[out] target_point Suitable target point.
 *  \return True if found a suitable target point.
 */
bool ArenaAI::updateAimingPosition(Vec3* target_point)
{
#ifdef AI_DEBUG
        m_debug_sphere_next->setVisible(false);
#endif

    m_current_forward_point = m_kart->getTrans()(Vec3(0, 0, m_kart_length));

    m_turn_radius = 0.0f;
    std::vector<int>* test_nodes = NULL;
    if (m_current_forward_node != Graph::UNKNOWN_SECTOR)
    {
        test_nodes =
            m_graph->getNode(m_current_forward_node)->getNearbyNodes();
    }
    m_graph->findRoadSector(m_current_forward_point, &m_current_forward_node,
        test_nodes);

    // Use current node if forward node is unknown, or near the target
    const int forward =
        m_current_forward_node == Graph::UNKNOWN_SECTOR ||
        m_current_forward_node == m_target_node ||
        getCurrentNode() == m_target_node ?
        getCurrentNode() : m_current_forward_node;

    if (forward == Graph::UNKNOWN_SECTOR ||
        m_target_node == Graph::UNKNOWN_SECTOR)
    {
        Log::error("ArenaAI", "Next node is unknown, path finding failed!");
        return false;
    }

    if (forward == m_target_node)
    {
        determineTurnRadius(m_target_point, NULL, &m_turn_radius);
        *target_point = m_target_point;
        return true;
    }

    std::vector<int> path;
    int next_node = m_graph->getNextNode(forward, m_target_node);

    if (next_node == Graph::UNKNOWN_SECTOR)
    {
        Log::error("ArenaAI", "Next node is unknown, did you forget to link"
                   " adjacent face in navmesh?");
        return false;
    }

    path.push_back(next_node);
    while (m_target_node != next_node)
    {
        int previous_node = next_node;
        next_node = m_graph->getNextNode(previous_node, m_target_node);
        if (next_node == Graph::UNKNOWN_SECTOR)
        {
            Log::error("ArenaAI", "Next node is unknown, did you forget to"
                       " link adjacent face in navmesh?");
            return false;
        }
        path.push_back(next_node);
    }

    determinePath(forward, &path);
    *target_point = m_graph->getNode(path.front())->getCenter();

    return true;

}   // updateAimingPosition
Example #19
0
//-----------------------------------------------------------------------------
float SoccerAI::getKartDistance(const AbstractKart* kart) const
{
    return m_graph->getDistance(getCurrentNode(),
        m_world->getSectorForKart(kart));
}   // getKartDistance
Example #20
0
void bestMove(binaryTreePtr tree)
/* This procedure will determine the best move available
 * by using a minmax method to either compute the value (on a leaf)
 * or sending it one level up where will be decided if the minimum or the maximum value will be used
 * Pre-condition:none
 * Post-condition: the root of the tree now has the minmax value needed
*/
{
	infoPtr gameInfo,temp;
	treeNodePtr current;
	//retrieve the current node's info
	gameInfo = retrieveNodeElm(tree);

	//is this a leaf?
	if ((existNode(tree,TOLEFT)== -1) )
	{
		//then compute the value of this square
		gameInfo->eval = evaluateSquares(gameInfo);
	}else
	{
		//go down a level, to first node
		nextNode(tree, TOLEFT);
		//get the current node in tree
		current = getCurrentNode(tree);

		//get the info for this node
		temp = retrieveNodeElm(tree);

		//call this procedure again, this will send up a value
		bestMove(tree);

		//go back to first node on the level
		setCurrentNode(tree, current);
		//set the parent level's value to this node's
		gameInfo->eval = temp->eval;

		//is there a next node on this level?
		while (existNode(tree,TORIGHT) == 1)
		{
			//then go to the next node
			nextNode(tree, TORIGHT);

			//set this as the current node on this level
			current = getCurrentNode(tree);

			//get the info for this node
			temp = retrieveNodeElm(tree);

			//call this procedure again, this will send up a value
			bestMove(tree);

			//go back to node on this level we're working on
			setCurrentNode(tree, current);
			//who's turn was it last
			if (gameInfo->turn == COMPUTER)
			{
				//if temp->eval is smaller
				if (gameInfo->eval > temp->eval)
				{
					//this is the new minimum value
					gameInfo->eval = temp->eval;
				}
			}else
			{
				//if temp->eval is bigger
				if (gameInfo->eval < temp->eval)
				{
					//this is the new maximum value
					gameInfo->eval = temp->eval;
				}
			}
		}
	}
}
Example #21
0
Json::Value ResponseTask::generateResponseJson() {
  Json::Value response;
  epoch_t responseStart = _recordPerformanceData ? get_epoch_nanoseconds() : 0;
  PapiTracer pt;
  pt.addEvent("PAPI_TOT_CYC");

  if (_recordPerformanceData)
    pt.start();

  auto predecessor = getResultTask();
  const auto& result = predecessor->getResultTable();

  if (getState() != OpFail) {
    if (!_isAutoCommit) {
      response["session_context"] =
          std::to_string(_txContext.tid).append(" ").append(std::to_string(_txContext.lastCid));
    }

    if (result) {
      // Make header
      Json::Value json_header(Json::arrayValue);
      for (unsigned col = 0; col < result->columnCount(); ++col) {
        Json::Value colname(result->nameOfColumn(col));
        json_header.append(colname);
      }

      // Copy the complete result
      response["real_size"] = result->size();
      response["rows"] = generateRowsJson(result, _transmitLimit, _transmitOffset);
      response["header"] = json_header;
    }

    ////////////////////////////////////////////////////////////////////////////////////////
    // Copy Performance Data
    if (_recordPerformanceData) {
      Json::Value json_perf(Json::arrayValue);
      for (const auto& attr : performance_data) {
        Json::Value element;
        element["papi_event"] = Json::Value(attr->papiEvent);
        element["duration"] = Json::Value((Json::UInt64)attr->duration);
        element["data"] = Json::Value((Json::UInt64)attr->data);
        element["name"] = Json::Value(attr->name);
        element["id"] = Json::Value(attr->operatorId);
        element["startTime"] = Json::Value((double)(attr->startTime - queryStart) / 1000000);
        element["endTime"] = Json::Value((double)(attr->endTime - queryStart) / 1000000);
        element["executingThread"] = Json::Value(attr->executingThread);
        element["lastCore"] = Json::Value(attr->core);
        element["lastNode"] = Json::Value(attr->node);
        // Put null for in/outRows if -1 was set
        element["inRows"] = attr->in_rows ? Json::Value(*(attr->in_rows)) : Json::Value();
        element["outRows"] = attr->out_rows ? Json::Value(*(attr->out_rows)) : Json::Value();

        if (_getSubQueryPerformanceData) {
          element["subQueryPerformanceData"] = _scriptOperation->getSubQueryPerformanceData();
        }

        json_perf.append(element);
      }

      pt.stop();

      Json::Value responseElement;
      responseElement["duration"] = Json::Value((Json::UInt64)pt.value("PAPI_TOT_CYC"));
      responseElement["name"] = Json::Value("ResponseTask");
      responseElement["id"] = Json::Value("respond");
      responseElement["startTime"] = Json::Value((double)(responseStart - queryStart) / 1000000);
      responseElement["endTime"] = Json::Value((double)(get_epoch_nanoseconds() - queryStart) / 1000000);

      std::string threadId = boost::lexical_cast<std::string>(std::this_thread::get_id());
      responseElement["executingThread"] = Json::Value(threadId);

      responseElement["lastCore"] = Json::Value(getCurrentCore());
      responseElement["lastNode"] = Json::Value(getCurrentNode());

      std::optional<size_t> result_size;
      if (result) {
        result_size = result->size();
      }
      responseElement["inRows"] = result_size ? Json::Value(*result_size) : Json::Value();
      responseElement["outRows"] = Json::Value();

      json_perf.append(responseElement);

      response["performanceData"] = json_perf;
    }

    Json::Value jsonKeys(Json::arrayValue);
    for (const auto& x : _generatedKeyRefs) {
      for (const auto& key : *x) {
        Json::Value element(key);
        jsonKeys.append(element);
      }
    }
    response["generatedKeys"] = jsonKeys;
    response["affectedRows"] = Json::Value(_affectedRows);

    if (_getSubQueryPerformanceData) {
      response["subQueryDataflow"] = _scriptOperation->getSubQueryDataflow();
    }
  }
  LOG4CXX_DEBUG(_logger, "Table Use Count: " << result.use_count());

  return response;
}
Example #22
0
 void XemProcessor::xemInstructionHousewife ( __XProcHandlerArgs__ )
 {
   item.getDocument().housewife ();
   getCurrentNode().getDocument().housewife ();
 }