LNE_NAMESPACE_USING void TestObject() { LNE_UINT i, v; ObjectList<LNE_UINT> list; for(int i = 0; i < 3; i++) list.PushFront(i + 1); while(list.PopFront(v) == LNERR_OK) { printf("%u\n", v); } DataBlock *block; ObjectQueue<DataBlock *> queue; DataBlockPool *pool = DataBlockPool::NewInstance(); for(i = 0; i < 10000; ++i) queue.Append(pool->Alloc()); i = 0; while(queue.Extract(block) == LNERR_OK) { ++i; block->Release(); } printf("data count: %u\n", i); pool->Release(); }
void ThreadMessenger::Finalize() { #ifndef DEBUG #warning FIXME(ThreadMessenger::Finalize): Any Nodes still in transit on finalize are leaked. Finalize should force processing of all data. #endif ObjectList<Object> *callbacks; Object *callback; UnsignedType key; void *iter_m=NULL, *iter_l=NULL; while (mCallbacks->Iterate(iter_m, key, (void*&)callbacks)) { while (callbacks->Iterate(iter_l, callback)) UnReference((Object*)callback); UnReference(callbacks); } while (mCacheCount > 0) { Thread::Message *next = mCache->NextArgument(); UnReference(mCache); mCache = next; mCacheCount--; } UnReference(mSignatures); UnReference(mCallbacks); UnReference(mQueue); Super::Finalize(); }
void LoopUnroll::simple_replication(int factor, Source &replicated_body, Source &epilogue_body, IdExpression induction_var, Statement loop_body) { for (unsigned int i = 0; i < factor; i++) { ReplaceSrcIdExpression replacement(_for_stmt.get_scope_link()); replacement.set_ignore_pragma(true); if (i > 0) { std::stringstream ss; ss << "(" << induction_var << " + " << i << ")"; replacement.add_replacement(induction_var.get_symbol(), ss.str()); } if (!loop_body.is_compound_statement() || there_is_declaration(loop_body)) { replicated_body << replacement.replace(loop_body) ; } else { ObjectList<Statement> list = loop_body.get_inner_statements(); for (ObjectList<Statement>::iterator it = list.begin(); it != list.end(); it++) { replicated_body << replacement.replace(*it) ; } } } }
void ESceneGroupTools::UngroupObjects(bool bUndo) { ObjectList lst = m_Objects; int sel_cnt = 0; if (!lst.empty()){ bool bModif = false; for (ObjectIt it=lst.begin(); it!=lst.end(); it++){ if ((*it)->Selected()){ sel_cnt++; CGroupObject* obj = dynamic_cast<CGroupObject*>(*it); VERIFY(obj); if (obj->CanUngroup(true)){ Scene->RemoveObject (obj,false); obj->UngroupObjects (); xr_delete (obj); bModif = true; }else{ ELog.DlgMsg (mtError,"Can't ungroup object: '%s'.",obj->Name); } } } if (bUndo&&bModif) Scene->UndoSave(); } if (0==sel_cnt) ELog.Msg (mtError,"Nothing selected."); }
ObjectList* FireworkShow::_getInventoryFireworks(PlayerObject* playerObject) { ObjectList* returnList = new ObjectList(); Inventory* inventory = dynamic_cast<Inventory*>(playerObject->getEquipManager()->getEquippedObject(CreatureEquipSlot_Inventory)); ObjectIDList* objList = inventory->getObjects(); ObjectIDList::iterator containerObjectIt = objList->begin(); while (containerObjectIt != objList->end()) { Object* object = gWorldManager->getObjectById((*containerObjectIt)); if (Item* item = dynamic_cast<Item*>(object)) { if(item->getItemFamily()==ItemFamily_FireWork && item->getItemType()!= ItemType_Firework_Show) { returnList->push_back(item); } } ++containerObjectIt; } return returnList; }
bool __fastcall TUI_ControlShapeAdd::Start(TShiftState Shift) { TfraShape* F = (TfraShape*)parent_tool->pFrame; if (F->ebAttachShape->Down){ CEditShape* from = dynamic_cast<CEditShape*>(Scene->RayPickObject(UI->ZFar(),UI->m_CurrentRStart, UI->m_CurrentRNorm, OBJCLASS_SHAPE, 0, 0)); if (from){ ObjectList lst; int cnt = Scene->GetQueryObjects(lst,OBJCLASS_SHAPE,1,1,0); if (1!=cnt) ELog.DlgMsg(mtError,"Select one shape."); else{ CEditShape* base = dynamic_cast<CEditShape*>(lst.back()); R_ASSERT(base); if (base!=from){ base->Attach(from); if (!Shift.Contains(ssAlt)){ F->ebAttachShape->Down = false; ResetActionToSelect (); } } } } }else DefaultAddObject(Shift,0,AfterAppendCallback); return false; }
int EScene::GetQueryObjects(ObjectList& lst, ObjClassID classfilter, int iSel, int iVis, int iLock) { if (classfilter==OBJCLASS_DUMMY){ SceneToolsMapPairIt _I = m_SceneTools.begin(); SceneToolsMapPairIt _E = m_SceneTools.end(); for (; _I!=_E; ++_I) { ESceneCustomOTool* mt = dynamic_cast<ESceneCustomOTool*>(_I->second); if (mt) mt->GetQueryObjects(lst, iSel, iVis, iLock); } }else{ ESceneCustomOTool* mt = GetOTool(classfilter); if (mt) mt->GetQueryObjects(lst, iSel, iVis, iLock); } return lst.size(); }
bool induction_variable_list_contains_variable( ObjectList<InductionVariableData*> iv_list, Nodecl::NodeclBase var ) { bool result = false; for( ObjectList<InductionVariableData*>::iterator it = iv_list.begin( ); it != iv_list.end( ); ++it ) { if( Nodecl::Utils::equal_nodecls( ( *it )->get_variable( ).get_nodecl( ), var, /* skip conversion nodes */ true ) ) { result = true; break; } } return result; }
size_t Player::getCurrentlySelectedObjects(ObjectList &buf, const Coordinate &crnt_coord, SelectionFlags_t flags) const { ObjectList cur_selected_objs; int max_objs = 16; if(this->m_selection_start_coordinate == crnt_coord) max_objs = 1; if(flags != SelectionFlags::SET) buf = this->m_selected_objs; this->m_game->findObjectByRect(cur_selected_objs, this->m_selection_start_coordinate, crnt_coord); this->filterCurSelectedObjects(cur_selected_objs, max_objs); this->mergeObjectList(buf, cur_selected_objs, flags); return buf.size(); }
AABB DBVH::createAABBFromObjList( const ObjectList& objList ) { AABB box; float minX, minY, minZ, maxX, maxY, maxZ; minX = minY = minZ = FLT_MAX; maxX = maxY = maxZ = -FLT_MAX; //Find the minimum and maximum x y and z points for(unsigned i = 0; i < objList.size(); ++i) { const Object& obj = objList[i]; Pt minPt = obj.boundingBox.center - obj.boundingBox.extents; Pt maxPt = obj.boundingBox.center + obj.boundingBox.extents; if(minPt.x < minX) minX = minPt.x; if(maxPt.x > maxX) maxX = maxPt.x; if(minPt.y < minY) minY = minPt.y; if(maxPt.y > maxY) maxY = maxPt.y; if(minPt.z < minZ) minZ = minPt.z; if(maxPt.z > maxZ) maxZ = maxPt.z; } //Extents are just width/height/depth / 2 box.extents.x = abs(maxX - minX) * 0.5f; box.extents.y = abs(maxY - minY) * 0.5f; box.extents.z = abs(maxZ - minZ) * 0.5f; //Center is just the min point plus the extents Pt minPt(minX, minY, minZ); box.center = minPt + box.extents; return box; }
//------------------------------------------------------------------------------------ // moving //------------------------------------------------------------------------------------ bool __fastcall TUI_CustomControl::MovingStart(TShiftState Shift) { ObjClassID cls = LTools->CurrentClassID(); if(Shift==ssRBOnly){ ExecCommand(COMMAND_SHOWCONTEXTMENU,parent_tool->ClassID); return false;} if(Scene->SelectionCount(true,cls)==0) return false; if (Shift.Contains(ssCtrl)){ ObjectList lst; if (Scene->GetQueryObjects(lst,LTools->CurrentClassID(),1,1,0)){ if (lst.size()==1){ Fvector p,n; UI->IR_GetMousePosReal(Device.m_hRenderWnd, UI->m_CurrentCp); Device.m_Camera.MouseRayFromPoint(UI->m_CurrentRStart,UI->m_CurrentRNorm,UI->m_CurrentCp); if (LUI->PickGround(p,UI->m_CurrentRStart,UI->m_CurrentRNorm,1,&n)){ for(ObjectIt _F = lst.begin();_F!=lst.end();_F++) (*_F)->MoveTo(p,n); Scene->UndoSave(); } }else{ Fvector p,n; Fvector D={0,-1,0}; for(ObjectIt _F = lst.begin();_F!=lst.end();_F++){ if (LUI->PickGround(p,(*_F)->PPosition,D,1,&n)){ (*_F)->MoveTo(p,n); } } } } return false; }else{ if (etAxisY==Tools->GetAxis()){ m_MovingXVector.set(0,0,0); m_MovingYVector.set(0,1,0); }else{ m_MovingXVector.set( Device.m_Camera.GetRight() ); m_MovingXVector.y = 0; m_MovingYVector.set( Device.m_Camera.GetDirection() ); m_MovingYVector.y = 0; m_MovingXVector.normalize_safe(); m_MovingYVector.normalize_safe(); } m_MovingReminder.set(0,0,0); } return true; }
bool SmartAI::IsEscortInvokerInRange() { ObjectList* targets = GetScript()->GetTargetList(SMART_ESCORT_TARGETS); if (targets) { float checkDist = me->GetInstanceScript() ? SMART_ESCORT_MAX_PLAYER_DIST*2 : SMART_ESCORT_MAX_PLAYER_DIST; if (targets->size() == 1 && GetScript()->IsPlayer((*targets->begin()))) { Player* player = (*targets->begin())->ToPlayer(); if (me->GetDistance(player) <= checkDist) return true; if (Group* group = player->GetGroup()) { for (GroupReference* groupRef = group->GetFirstMember(); groupRef != NULL; groupRef = groupRef->next()) { Player* groupGuy = groupRef->GetSource(); if (groupGuy && me->IsInMap(groupGuy) && me->GetDistance(groupGuy) <= checkDist) return true; } } } else { for (ObjectList::iterator iter = targets->begin(); iter != targets->end(); ++iter) { if (GetScript()->IsPlayer((*iter))) { if (me->GetDistance((*iter)->ToPlayer()) <= checkDist) return true; } } } // Xinef: no valid target found return false; } // Xinef: no player invoker was stored, just ignore range check return true; }
bool SmartAI::IsEscortInvokerInRange() { ObjectList* targets = GetScript()->GetTargetList(SMART_ESCORT_TARGETS); if (targets) { if (targets->size() == 1 && GetScript()->IsPlayer((*targets->begin()))) { Player* player = (*targets->begin())->ToPlayer(); if (me->GetDistance(player) <= SMART_ESCORT_MAX_PLAYER_DIST) return true; if (Group* group = player->GetGroup()) { for (GroupReference* groupRef = group->GetFirstMember(); groupRef != nullptr; groupRef = groupRef->next()) { Player* groupGuy = groupRef->GetSource(); if (me->GetDistance(groupGuy) <= SMART_ESCORT_MAX_PLAYER_DIST) return true; } } } else { for (ObjectList::iterator iter = targets->begin(); iter != targets->end(); ++iter) { if (GetScript()->IsPlayer((*iter))) { if (me->GetDistance((*iter)->ToPlayer()) <= SMART_ESCORT_MAX_PLAYER_DIST) return true; } } } } return true;//escort targets were not set, ignore range check }
void PointerSize::compute_pointer_vars_size_rec(Node* current) { if(current->is_visited()) return; current->set_visited(true); if(current->is_graph_node()) { compute_pointer_vars_size_rec(current->get_graph_entry_node()); } else { if(current->has_statements()) { NBase s; NBase value; TL::Type t; NodeclList stmts = current->get_statements(); for(NodeclList::iterator it = stmts.begin(); it != stmts.end(); ++it) { // If assignment (or object init) check whether its for is a dynamic allocation of resources for a pointer type if(it->is<Nodecl::ObjectInit>() || it->is<Nodecl::Assignment>()) { // Get the variable assigned and the value used for the assignment if(it->is<Nodecl::ObjectInit>()) { Symbol tmp(it->get_symbol()); s = Nodecl::Symbol::make(tmp); t = tmp.get_type(); s.set_type(t); value = tmp.get_value().no_conv(); } else if(it->is<Nodecl::Assignment>()) { s = it->as<Nodecl::Assignment>().get_lhs().no_conv(); t = s.get_type().no_ref(); if(!s.is<Nodecl::Symbol>() && !s.is<Nodecl::ClassMemberAccess>() && !s.is<Nodecl::ArraySubscript>()) continue; value = it->as<Nodecl::Assignment>().get_rhs().no_conv(); } // Check whether this is a pointer and the assignment is a recognized memory operation if(t.is_pointer() && !value.is_null()) // This can be null if uninitialized ObjectInit { if(value.is<Nodecl::FunctionCall>()) { Symbol called_sym = value.as<Nodecl::FunctionCall>().get_called().get_symbol(); Type return_t = called_sym.get_type().returns(); Nodecl::List args = value.as<Nodecl::FunctionCall>().get_arguments().as<Nodecl::List>(); std::string sym_name = called_sym.get_name(); NBase size = NBase::null(); if((sym_name == "malloc") && (args.size() == 1)) { // void* malloc (size_t size); Type arg0_t = args[0].get_type(); if(return_t.is_pointer() && return_t.points_to().is_void() && arg0_t.is_same_type(get_size_t_type())) { // We recognize the form 'sizeof(base_type) * n_elemes' and 'n_elemes * sizeof(base_type)' if(args[0].is<Nodecl::Mul>()) { NBase lhs = args[0].as<Nodecl::Mul>().get_lhs().no_conv(); NBase rhs = args[0].as<Nodecl::Mul>().get_rhs().no_conv(); if(lhs.is<Nodecl::Sizeof>() && (rhs.is<Nodecl::IntegerLiteral>() || rhs.is<Nodecl::Symbol>())) size = rhs; else if(rhs.is<Nodecl::Sizeof>() && (lhs.is<Nodecl::IntegerLiteral>() || lhs.is<Nodecl::Symbol>())) size = lhs; } } } else if((sym_name == "calloc") && (args.size() == 2)) { // void* calloc (size_t num, size_t size); Type arg0_t = args[0].get_type(); Type arg1_t = args[1].get_type(); if(return_t.is_pointer() && return_t.points_to().is_void() && arg0_t.is_same_type(get_size_t_type()) && arg1_t.is_same_type(get_size_t_type())) { size = args[0]; } } if(!size.is_null()) _pcfg->set_pointer_n_elems(s, size); } } // Clear up the common variables s, value and t s = NBase::null(); value = NBase::null(); t = Type(); } } } } // Keep iterating over the children ObjectList<Node*> children = current->get_children(); for(ObjectList<Node*>::iterator it = children.begin(); it != children.end(); ++it) compute_pointer_vars_size_rec(*it); }
static void convert_vla(Symbol sym, ObjectList<Symbol>& converted_vlas, ScopeLink sl) { if (converted_vlas.contains(sym)) return; ObjectList<Source> dim_decls; ObjectList<Source> dim_names; dimensional_replacements_of_variable_type_aux(sym.get_type(), sym, dim_names, dim_decls); Source new_decls; for (ObjectList<Source>::iterator it = dim_decls.begin(); it != dim_decls.end(); it++) { new_decls << *it << ";" ; } AST_t point_of_decl = sym.get_point_of_declaration(); AST_t enclosing_stmt_tree; if (sym.is_parameter()) { FunctionDefinition funct_def(point_of_decl.get_enclosing_function_definition(), sl); enclosing_stmt_tree = funct_def.get_function_body().get_inner_statements()[0].get_ast(); } else { enclosing_stmt_tree = point_of_decl.get_enclosing_statement(); } AST_t statement_seq = new_decls.parse_statement(enclosing_stmt_tree, sl); enclosing_stmt_tree.prepend(statement_seq); if (!sym.is_parameter()) { // If this is not a parameter, we'll want to rewrite the declaration itself Type new_type_spawn = compute_replacement_type_for_vla(sym.get_type(), dim_names.begin(), dim_names.end()); // Now redeclare Source redeclaration, initializer; redeclaration << new_type_spawn.get_declaration(sym.get_scope(), sym.get_name()) << initializer << ";" ; if (sym.has_initialization()) { initializer << sym.get_initialization().prettyprint() ; } AST_t redeclaration_tree = redeclaration.parse_statement(enclosing_stmt_tree, sl, Source::ALLOW_REDECLARATION); enclosing_stmt_tree.prepend(redeclaration_tree); // Now remove the declarator of the declaration Declaration decl(point_of_decl, sl); if (decl.get_declared_entities().size() == 1) { // We have to remove all the whole declaration enclosing_stmt_tree.remove_in_list(); } else { // Remove only this entity ObjectList<DeclaredEntity> entities = decl.get_declared_entities(); for (ObjectList<DeclaredEntity>::iterator it = entities.begin(); it != entities.end(); it++) { if (it->get_declared_symbol() == sym) { it->get_ast().remove_in_list(); } } } } ObjectList<Source>* new_dim_ptr = new ObjectList<Source>(dim_names); RefPtr<ObjectList<Source> > dim_names_ref(new_dim_ptr); sym.set_attribute(OMP_NANOX_VLA_DIMS, dim_names_ref); converted_vlas.insert(sym); }
void OpenMPTransform::adf_task_postorder(PragmaCustomConstruct adf_construct) { PragmaCustomClause exit_condition_clause = adf_construct.get_clause("exit_condition"); PragmaCustomClause trigger_set = adf_construct.get_clause("trigger_set"); PragmaCustomClause group_name_clause = adf_construct.get_clause("name"); bool group_name_given = group_name_clause.is_defined(); std::string group_name = "default"; if (group_name_given) { group_name = group_name_clause.get_expression_list()[0].prettyprint(); } Source main_code_layout; AST_t inner_tree, exit_condition_placeholder, trigger_set_placeholder; main_code_layout << "{" << "Transaction * __t = createtx(\"" << adf_construct.get_ast().get_file() << "\"," << adf_construct.get_ast().get_line() <<");" << "addTransactionToADFGroup(\"" << group_name << "\", __t);" << statement_placeholder(trigger_set_placeholder) << "while(1)" << "{" << "starttx(__t);" << "if (__t->status == 18 /*TS_ADF_FINISH*/) " << " break; " << statement_placeholder(exit_condition_placeholder) << "if((__t->nestingLevel > 0) || (0 == setjmp(__t->context)))" << "{" << statement_placeholder(inner_tree) << "if (committx(__t) == 0)" << "{" << "retrytx(__t);" << "break;" << "}" << "}" << "}" << "destroytx(__t);" << "}" ; AST_t code_layout_tree = main_code_layout.parse_statement( adf_construct.get_ast(), adf_construct.get_scope_link()); // empty ObjectList<Symbol> unmanaged_symbols; ObjectList<Symbol> local_symbols; // XXX - Currently using /dev/null as the filter and log files std::fstream stm_log_file; stm_log_file.open("/dev/null", std::ios_base::out | std::ios_base::trunc); STMExpressionReplacement expression_replacement(unmanaged_symbols, local_symbols, "/dev/null", "normal", "/dev/null", "normal", stm_log_file); // STMize exit condition if (exit_condition_clause.is_defined()) { Expression exit_condition = exit_condition_clause.get_expression_list()[0]; // Duplicate but by means of parsing (this updates the semantic information) Source src = exit_condition.prettyprint(); AST_t tree = src.parse_expression(inner_tree, adf_construct.get_scope_link()); Expression expr(tree, adf_construct.get_scope_link()); expression_replacement.replace_expression(expr); Source exit_condition_src; exit_condition_src << "if (" << expr.prettyprint() << ")" << "break;" ; AST_t exit_condition_tree = exit_condition_src.parse_statement(exit_condition_placeholder, adf_construct.get_scope_link()); exit_condition_placeholder.replace(exit_condition_tree); } // Main code { // Duplicate with new contextual info Source src = adf_construct.get_statement().prettyprint(); AST_t task_tree = src.parse_statement(inner_tree, adf_construct.get_scope_link()); ObjectList<AST_t> expressions = task_tree.depth_subtrees(Expression::predicate, AST_t::NON_RECURSIVE); for (ObjectList<AST_t>::iterator it = expressions.begin(); it != expressions.end(); it++) { Expression expression(*it, scope_link); expression_replacement.replace_expression(expression); } inner_tree.replace(task_tree); } // Trigger set registration due to 'exit_condition' Source trigger_set_registration; bool have_some_trigger_set = false; if (exit_condition_clause.is_defined()) { ObjectList<IdExpression> id_expression_list = exit_condition_clause.id_expressions(); for (ObjectList<IdExpression>::iterator it = id_expression_list.begin(); it != id_expression_list.end(); it++) { Symbol sym = it->get_symbol(); Type type = sym.get_type(); if (!type.is_array()) { trigger_set_registration << "add_scalar_to_trigger_set(__t, " << "&" << it->prettyprint() << ", " << "sizeof(" << it->prettyprint() << ")" << ");" ; } else { std::cerr << it->get_ast().get_locus() << ": error: exit condition expression '" << it->prettyprint() << "' involves an array. This is not yet supported" << std::endl; } have_some_trigger_set = true; } // Trigger set registration due to 'trigger_set' if (trigger_set.is_defined()) { ObjectList<Expression> trigger_set_expr = trigger_set.get_expression_list(); for (ObjectList<Expression>::iterator it = trigger_set_expr.begin(); it != trigger_set_expr.end(); it++) { Expression &trigger_expr(*it); // This should be improved to handle cases like 'a[2]' if (trigger_expr.is_id_expression()) { trigger_set_registration << "add_scalar_to_trigger_set(__t, " << "&" << trigger_expr.prettyprint() << ", " << "sizeof(" << trigger_expr.prettyprint() << ")" << ");" ; } else if (trigger_expr.is_array_section_range()) { ObjectList<Expression> lower_bounds; ObjectList<Expression> upper_bounds; Expression basic_expr = compute_bounds_of_sectioned_expression(trigger_expr, lower_bounds, upper_bounds); // FIXME - Do not be so restrictive, pointers to arrays are useful as well :) if (!basic_expr.is_id_expression()) { std::cerr << basic_expr.get_ast().get_locus() << ": error: invalid trigger set specification '" << trigger_expr.prettyprint() << "' since the basic expression '" << basic_expr.prettyprint() << "' is not an id-expression" << std::endl; set_phase_status(PHASE_STATUS_ERROR); return; } IdExpression id_expression = basic_expr.get_id_expression(); Symbol sym = id_expression.get_symbol(); if (!sym.is_valid()) { std::cerr << id_expression.get_ast().get_locus() << ": error: unknown entity '" << id_expression.prettyprint() << "'" << std::endl; set_phase_status(PHASE_STATUS_ERROR); return; } Type type = sym.get_type(); ObjectList<AST_t> array_dimensions = compute_array_dimensions_of_type(type); if (array_dimensions.size() != lower_bounds.size() || lower_bounds.size() != upper_bounds.size()) { std::cerr << id_expression.get_ast().get_locus() << ": error: mismatch between array type and array section" << std::endl; set_phase_status(PHASE_STATUS_ERROR); return; } trigger_set_registration << "add_range_to_trigger_set(__t, " << basic_expr.prettyprint() << "," << array_dimensions.size() << "," << "sizeof(" << get_basic_type(type).get_declaration(sym.get_scope(), "") << ")" ; // First add dimensions for (ObjectList<AST_t>::iterator it = array_dimensions.begin(); it != array_dimensions.end(); it++) { trigger_set_registration << "," << it->prettyprint(); } // Now lower and upper bounds { ObjectList<Expression>::iterator it_l = lower_bounds.begin(); ObjectList<Expression>::iterator it_u = upper_bounds.begin(); while (it_l != lower_bounds.end()) { trigger_set_registration << "," << it_l->prettyprint(); trigger_set_registration << "," << it_u->prettyprint(); it_u++; it_l++; } } // Final parenthesis and semicolon trigger_set_registration << ");" ; } have_some_trigger_set = true; } } } if (have_some_trigger_set) { AST_t trigger_registration_tree = trigger_set_registration.parse_statement(trigger_set_placeholder, adf_construct.get_scope_link()); trigger_set_placeholder.replace(trigger_registration_tree); } // Replace it all adf_construct.get_ast().replace(code_layout_tree); }
void SmartAI::EndPath(bool fail) { RemoveEscortState(SMART_ESCORT_ESCORTING | SMART_ESCORT_PAUSED | SMART_ESCORT_RETURNING); _path.nodes.clear(); mWPPauseTimer = 0; if (mEscortNPCFlags) { me->SetFlag(UNIT_NPC_FLAGS, mEscortNPCFlags); mEscortNPCFlags = 0; } ObjectList* targets = GetScript()->GetTargetList(SMART_ESCORT_TARGETS); if (targets && mEscortQuestID) { if (targets->size() == 1 && GetScript()->IsPlayer((*targets->begin()))) { Player* player = (*targets->begin())->ToPlayer(); if (!fail && player->IsAtGroupRewardDistance(me) && !player->HasCorpse()) player->GroupEventHappens(mEscortQuestID, me); if (fail) player->FailQuest(mEscortQuestID); if (Group* group = player->GetGroup()) { for (GroupReference* groupRef = group->GetFirstMember(); groupRef != nullptr; groupRef = groupRef->next()) { Player* groupGuy = groupRef->GetSource(); if (!fail && groupGuy->IsAtGroupRewardDistance(me) && !groupGuy->HasCorpse()) groupGuy->AreaExploredOrEventHappens(mEscortQuestID); else if (fail) groupGuy->FailQuest(mEscortQuestID); } } } else { for (ObjectList::iterator iter = targets->begin(); iter != targets->end(); ++iter) { if (GetScript()->IsPlayer((*iter))) { Player* player = (*iter)->ToPlayer(); if (!fail && player->IsAtGroupRewardDistance(me) && !player->HasCorpse()) player->AreaExploredOrEventHappens(mEscortQuestID); else if (fail) player->FailQuest(mEscortQuestID); } } } } // End Path events should be only processed if it was SUCCESSFUL stop or stop called by SMART_ACTION_WAYPOINT_STOP if (fail) return; GetScript()->ProcessEventsFor(SMART_EVENT_WAYPOINT_ENDED, nullptr, mCurrentWPID, GetScript()->GetPathId()); if (mCanRepeatPath) { if (IsAIControlled()) StartPath(mRun, GetScript()->GetPathId(), mCanRepeatPath); } else GetScript()->SetPathId(0); if (mDespawnState == 1) StartDespawn(); }
/* * \param t The value of type T * * Functor \a f will be applied to \a t and the resulting value used * for comparison. */ virtual bool operator()(T& t) const { return (find(_list.begin(), _list.end(), _f(t)) != _list.end()); }
NotInSetPredicateFunctor<T, Q> not_in_set(ObjectList<T>& list, const Functor<Q, T>& f) { ObjectList<Q> mapped_list = list.map(f); return NotInSetPredicateFunctor<T, Q>(mapped_list, f); }
Symbol Overload::solve( ObjectList<Symbol> candidate_functions, Type implicit_argument_type, ObjectList<Type> argument_types, const std::string filename, int line, bool &valid, ObjectList<Symbol>& viable_functions, ObjectList<Symbol>& argument_conversor) { valid = false; // Try hard to not to do useless work if (candidate_functions.empty()) { return Symbol(NULL); } scope_entry_list_t* first_candidate_list = NULL; // Build the candidates list for (ObjectList<Symbol>::iterator it = candidate_functions.begin(); it != candidate_functions.end(); it++) { Symbol sym(*it); first_candidate_list = entry_list_add(first_candidate_list, sym.get_internal_symbol()); } // Build the type array unsigned int i = argument_types.size(); type_t** argument_types_array = new type_t*[argument_types.size() + 1]; argument_types_array[0] = implicit_argument_type.get_internal_type(); for (i = 0; i < argument_types.size(); i++) { argument_types_array[i+1] = argument_types[i].get_internal_type(); } // Now we need a decl_context_t but we were not given any explicitly, // use the one of the first candidate decl_context_t decl_context = candidate_functions[0].get_scope().get_decl_context(); // Unfold and mix! scope_entry_list_t* candidate_list = NULL; candidate_list = unfold_and_mix_candidate_functions(first_candidate_list, NULL /* builtins */, &argument_types_array[1], argument_types.size(), decl_context, uniquestr(filename.c_str()), line, NULL /* explicit template arguments */); { ObjectList<Symbol> list; Scope::convert_to_vector(candidate_list, list); viable_functions.append(list); } candidate_t* candidate_set = NULL; scope_entry_list_iterator_t* it = NULL; for (it = entry_list_iterator_begin(candidate_list); !entry_list_iterator_end(it); entry_list_iterator_next(it)) { scope_entry_t* entry = entry_list_iterator_current(it); if (entry->entity_specs.is_member) { candidate_set = add_to_candidate_set(candidate_set, entry, argument_types.size() + 1, argument_types_array); } else { candidate_set = add_to_candidate_set(candidate_set, entry, argument_types.size(), argument_types_array + 1); } } entry_list_iterator_free(it); // We also need a scope_entry_t** for holding the conversor argument scope_entry_t** conversor_per_argument = new scope_entry_t*[argument_types.size() + 1]; // Now invoke all the machinery scope_entry_t* entry_result = solve_overload(candidate_set, decl_context, uniquestr(filename.c_str()), line, conversor_per_argument); if (entry_result != NULL) { valid = true; // Store the arguments argument_conversor.clear(); for (i = 0; i < argument_types.size(); i++) { argument_conversor.append(Symbol(conversor_per_argument[i])); } } // Free the conversor per argument delete[] conversor_per_argument; // Free the type array delete[] argument_types_array; // Free the scope entry list free_scope_entry_list(candidate_list); // This one has been allocated above free_scope_entry_list(first_candidate_list); return Symbol(entry_result); }
void SmartAI::EndPath(bool fail) { GetScript()->ProcessEventsFor(SMART_EVENT_WAYPOINT_ENDED, NULL, mLastWP->id, GetScript()->GetPathId()); RemoveEscortState( SMART_ESCORT_ESCORTING | SMART_ESCORT_PAUSED | SMART_ESCORT_RETURNING); mWayPoints = NULL; mCurrentWPID = 0; mWPPauseTimer = 0; mLastWP = NULL; if (mCanRepeatPath) StartPath(mRun, GetScript()->GetPathId(), mCanRepeatPath); else GetScript()->SetPathId(0); ObjectList* targets = GetScript()->GetTargetList(SMART_ESCORT_TARGETS); if (targets && mEscortQuestID) { if (targets->size() == 1 && GetScript()->IsPlayer((*targets->begin()))) { Player* plr = (*targets->begin())->ToPlayer(); if (!fail && plr->IsAtGroupRewardDistance(me) && !plr->GetCorpse()) plr->GroupEventHappens(mEscortQuestID, me); if (fail && plr->GetQuestStatus(mEscortQuestID) == QUEST_STATUS_INCOMPLETE) plr->FailQuest(mEscortQuestID); if (Group* pGroup = plr->GetGroup()) { for (GroupReference* gr = pGroup->GetFirstMember(); gr != NULL; gr = gr->next()) { Player* pGroupGuy = gr->getSource(); if (!fail && pGroupGuy->IsAtGroupRewardDistance(me) && !pGroupGuy->GetCorpse()) pGroupGuy->AreaExploredOrEventHappens(mEscortQuestID); if (fail && pGroupGuy->GetQuestStatus(mEscortQuestID) == QUEST_STATUS_INCOMPLETE) pGroupGuy->FailQuest(mEscortQuestID); } } } else { for (ObjectList::iterator iter = targets->begin(); iter != targets->end(); iter++) { if (GetScript()->IsPlayer((*iter))) { Player* plr = (*iter)->ToPlayer(); if (!fail && plr->IsAtGroupRewardDistance(me) && !plr->GetCorpse()) plr->AreaExploredOrEventHappens(mEscortQuestID); if (fail && plr->GetQuestStatus(mEscortQuestID) == QUEST_STATUS_INCOMPLETE) plr->FailQuest(mEscortQuestID); } } } } if (mDespawnState == 1) StartDespawn(); }
// This function is invoked only for inline tasks (and some other // constructs though target info is unused for them) void Core::ompss_get_target_info(TL::PragmaCustomLine construct, DataEnvironment& data_sharing_environment) { if (_target_context.empty()) return; TL::OmpSs::TargetInfo target_info; TL::Symbol enclosing_function = Nodecl::Utils::get_enclosing_function(construct); ERROR_CONDITION(!enclosing_function.is_valid(), "This symbol is not valid", 0); target_info.set_target_symbol(enclosing_function); OmpSs::TargetContext& target_ctx = _target_context.top(); add_copy_items(construct, data_sharing_environment, target_ctx.copy_in, TL::OmpSs::COPY_DIR_IN, target_info, in_ompss_mode()); add_copy_items(construct, data_sharing_environment, target_ctx.copy_out, TL::OmpSs::COPY_DIR_OUT, target_info, in_ompss_mode()); add_copy_items(construct, data_sharing_environment, target_ctx.copy_inout, TL::OmpSs::COPY_DIR_INOUT, target_info, in_ompss_mode()); target_info.set_file(target_ctx.file); target_info.set_name(target_ctx.name); target_info.append_to_ndrange(target_ctx.ndrange); target_info.append_to_shmem(target_ctx.shmem); target_info.append_to_onto(target_ctx.onto); target_info.append_to_device_list(target_ctx.device_list); // Set data sharings for referenced entities in copies if (target_ctx.copy_deps == OmpSs::TargetContext::COPY_DEPS) { // Copy the dependences, as well ObjectList<DependencyItem> dependences; data_sharing_environment.get_all_dependences(dependences); ObjectList<Nodecl::NodeclBase> dep_list_in; ObjectList<Nodecl::NodeclBase> dep_list_out; ObjectList<Nodecl::NodeclBase> dep_list_inout; ObjectList<Nodecl::NodeclBase> dep_list_weakin; ObjectList<Nodecl::NodeclBase> dep_list_weakout; ObjectList<Nodecl::NodeclBase> dep_list_weakinout; ObjectList<Nodecl::NodeclBase> dep_list_reductions; for (ObjectList<DependencyItem>::iterator it = dependences.begin(); it != dependences.end(); it++) { ObjectList<Nodecl::NodeclBase>* p = NULL; switch (it->get_kind()) { case DEP_DIR_IN: case DEP_OMPSS_DIR_IN_PRIVATE: { p = &dep_list_in; break; } case DEP_DIR_OUT: { p = &dep_list_out; break; } case DEP_DIR_INOUT: // OmpSs case DEP_OMPSS_CONCURRENT: case DEP_OMPSS_COMMUTATIVE: case DEP_OMPSS_REDUCTION: { p = &dep_list_inout; break; } case DEP_OMPSS_WEAK_IN: { p = &dep_list_weakin; break; } case DEP_OMPSS_WEAK_OUT: { p = &dep_list_weakout; break; } case DEP_OMPSS_WEAK_INOUT: case DEP_OMPSS_WEAK_COMMUTATIVE: { p = &dep_list_weakinout; break; } default: { internal_error("Invalid dependency kind", 0); } } p->append(*it); } add_copy_items(construct, data_sharing_environment, dep_list_in, TL::OmpSs::COPY_DIR_IN, target_info, in_ompss_mode()); add_copy_items(construct, data_sharing_environment, dep_list_out, TL::OmpSs::COPY_DIR_OUT, target_info, in_ompss_mode()); add_copy_items(construct, data_sharing_environment, dep_list_inout, TL::OmpSs::COPY_DIR_INOUT, target_info, in_ompss_mode()); if (!dep_list_weakin.empty() || !dep_list_weakout.empty() || !dep_list_weakinout.empty()) { warn_printf_at(construct.get_locus(), "weak dependences are not considered yet for copy_deps\n"); } } if (this->in_ompss_mode() && (target_ctx.copy_deps == OmpSs::TargetContext::COPY_DEPS || !target_ctx.copy_in.empty() || !target_ctx.copy_out.empty() || !target_ctx.copy_inout.empty()) && !_allow_shared_without_copies) { ObjectList<TL::OmpSs::CopyItem> all_copies; all_copies.append(target_info.get_copy_in()); all_copies.append(target_info.get_copy_out()); all_copies.append(target_info.get_copy_inout()); ObjectList<Symbol> all_copied_syms = all_copies.map<TL::Symbol>(&DataReference::get_base_symbol); // In devices with disjoint memory, it may be wrong to use a // global variables inside a pragma task without copying it. ObjectList<Symbol> ds_syms; data_sharing_environment.get_all_symbols(DS_SHARED, ds_syms); for(ObjectList<Symbol>::iterator io_it = ds_syms.begin(); io_it != ds_syms.end(); io_it++) { // Ignore 'this' if (IS_CXX_LANGUAGE && io_it->get_name() == "this") { continue; } if (!all_copied_syms.contains(*io_it)) { warn_printf_at( construct.get_locus(), "symbol '%s' has shared data-sharing but does not have" " copy directionality. This may cause problems at run-time\n", io_it->get_qualified_name().c_str()); } } } // Store the target information in the current data sharing data_sharing_environment.set_target_info(target_info); }
ObjectList<Symbol> Type::get_all_data_members() const { ObjectList<Symbol> result = get_nonstatic_data_members(); result.append(get_static_data_members()); return result; }
ObjectList PBImage::getAnnotations(int id) const { ObjectList annotations = ObjectList(); protobuf::CameraLocation location = protobuf::HEAD_LEFT; if (id == 0) { location = protobuf::HEAD_LEFT; } else if (id == 1) { location = protobuf::HEAD_RIGHT; } if (mLoadedFrame != NULL) { for (int i = 0; i < mLoadedFrame->camera_size(); i++) { const protobuf::ProtoBufFrame_Camera& cam = mLoadedFrame->camera(i); if (cam.type().location() == location) { for (int o = 0; o < cam.objects_size(); ++o) { const protobuf::ProtoBufFrame_Object obj = cam.objects(o); Object::ObjectType type; switch (obj.type()) { case protobuf::BALL: type = Object::BALL; break; case protobuf::GOAL_POLE_YELLOW: type = Object::GOAL_POLE_YELLOW; break; case protobuf::GOAL_YELLOW_CROSSBAR: type = Object::GOAL_YELLOW_CROSSBAR; break; case protobuf::ROBOT: type = Object::ROBOT; break; case protobuf::ROBOT_CYAN: type = Object::ROBOT_CYAN; break; case protobuf::ROBOT_MAGENTA: type = Object::ROBOT_MAGENTA; break; case protobuf::LINE: type = Object::LINE; break; case protobuf::LINE_POINT: type = Object::LINE_POINT; break; case protobuf::OBSTACLE: type = Object::OBSTACLE; break; case protobuf::FIELD_LINE: type = Object::FIELD_LINE; break; case protobuf::UNKNOWN: default: Debugger::DEBUG("PBImage","Unsupported ObjectType!"); type = Object::UNKNOWN; break; } Object ob = Object(obj.box().x1(), obj.box().y1(), obj.box().x2(), obj.box().y2(), type); annotations.addObject(ob); } } } } return annotations; }
//-------------------------------------------------------------------------- void PianoRollTrajectory::DrawVoice(ARMusicalVoice* v, DrawParams &drawParams) { if (fVoicesColors != NULL) { int voiceNum = v->getVoiceNum(); for (unsigned int i = 0; i < fVoicesColors->size() && fColors->empty(); i++) { std::pair<int, VGColor *> pair = fVoicesColors->at(i); if (pair.first == voiceNum) fColors->push(pair.second); } } if (!fColors->empty() || fVoicesAutoColored) { if (fColors->empty()) { int r, g, b; drawParams.colorHue += kGoldenRatio; drawParams.colorHue = fmod(drawParams.colorHue, 1); HSVtoRGB((float) drawParams.colorHue, 0.5f, 0.9f, r, g, b); fColors->push(new VGColor(r, g, b, 255)); } drawParams.dev->PushFillColor(*fColors->top()); } fChord = false; ObjectList *ol = (ObjectList *) v; GuidoPos pos = ol->GetHeadPosition(); TYPE_DURATION finalDur; while(pos) { ARMusicalObject *e = ol->GetNext(pos); TYPE_DURATION dur = e->getDuration(); TYPE_TIMEPOSITION date = e->getRelativeTimePosition(); finalDur = (dur ? dur : finalDur); if (fChord) { dur = fChordDuration; date -= dur; } TYPE_TIMEPOSITION end = date + dur; if (date >= fStartDate) { if (date < fEndDate) { if (end > fEndDate) dur = fEndDate - date; DrawMusicalObject(e, date, dur, drawParams); } } else if (end > fStartDate) { // to make the note end appear date = fStartDate; if (end > fEndDate) dur = fEndDate - date; else dur = end - date; DrawMusicalObject(e, date, dur, drawParams); } if (static_cast<ARRest *>(e->isARRest())) { handleRest(date, drawParams); fChord = false; } else if (static_cast<ARChordComma *>(e->isARChordComma())) fChord = true; else if (static_cast<ARNoteFormat *>(e->isARNoteFormat())) handleColor(static_cast<ARNoteFormat *>(e->isARNoteFormat()), drawParams); else if (static_cast<ARBar *>(e->isARBar()) && fMeasureBarsEnabled) DrawMeasureBar(date, drawParams); } DrawLinks(drawParams); // Draws link to final event DrawFinalEvent(finalDur, drawParams); // Draws link after final event while (!fColors->empty()) popColor(drawParams); previousEventInfos->clear(); currentEventInfos->clear(); fCurrentDate = 0; }
void SmartAI::EndPath(bool fail) { RemoveEscortState(SMART_ESCORT_ESCORTING | SMART_ESCORT_PAUSED | SMART_ESCORT_RETURNING); mWayPoints = NULL; mLastWP = NULL; mWPPauseTimer = 0; if (mEscortNPCFlags) { me->SetUInt32Value(UNIT_NPC_FLAGS, mEscortNPCFlags); mEscortNPCFlags = 0; } ObjectList* targets = GetScript()->GetTargetList(SMART_ESCORT_TARGETS); if (targets && mEscortQuestID) { if (targets->size() == 1 && GetScript()->IsPlayer((*targets->begin()))) { Player* player = (*targets->begin())->ToPlayer(); if (Group* group = player->GetGroup()) { for (GroupReference* groupRef = group->GetFirstMember(); groupRef != NULL; groupRef = groupRef->next()) { Player* groupGuy = groupRef->GetSource(); if (!groupGuy || !player->IsInMap(groupGuy)) continue; if (!fail && groupGuy->IsAtGroupRewardDistance(me) && !groupGuy->GetCorpse()) groupGuy->AreaExploredOrEventHappens(mEscortQuestID); else if (fail && groupGuy->GetQuestStatus(mEscortQuestID) == QUEST_STATUS_INCOMPLETE) groupGuy->FailQuest(mEscortQuestID); } } else { if (!fail && player->IsAtGroupRewardDistance(me) && !player->GetCorpse()) player->GroupEventHappens(mEscortQuestID, me); else if (fail && player->GetQuestStatus(mEscortQuestID) == QUEST_STATUS_INCOMPLETE) player->FailQuest(mEscortQuestID); } } else { for (ObjectList::iterator iter = targets->begin(); iter != targets->end(); ++iter) { if (GetScript()->IsPlayer((*iter))) { Player* player = (*iter)->ToPlayer(); if (!fail && player->IsAtGroupRewardDistance(me) && !player->GetCorpse()) player->AreaExploredOrEventHappens(mEscortQuestID); else if (fail && player->GetQuestStatus(mEscortQuestID) == QUEST_STATUS_INCOMPLETE) player->FailQuest(mEscortQuestID); } } } } // Xinef: if the escort failed - DO NOT PROCESS ANYTHING, ITS RETARDED // Xinef: End Path events should be only processed if it was SUCCESSFUL stop or stop called by SMART_ACTION_WAYPOINT_STOP if (fail) { mCurrentWPID = 0; return; } GetScript()->ProcessEventsFor(SMART_EVENT_WAYPOINT_ENDED, NULL, mCurrentWPID, GetScript()->GetPathId()); mCurrentWPID = 0; if (mCanRepeatPath) StartPath(mRun, GetScript()->GetPathId(), mCanRepeatPath); else GetScript()->SetPathId(0); if (mDespawnState == 1) StartDespawn(); }
void OMPTransform::for_postorder(PragmaCustomConstruct ctr) { ForStatement for_statement(ctr.get_statement().get_ast(), ctr.get_scope_link()); Statement for_body = for_statement.get_loop_body(); OpenMP::DataSharingEnvironment& data_sharing = openmp_info->get_data_sharing(ctr.get_ast()); ObjectList<OpenMP::DependencyItem> dependences; data_sharing.get_all_dependences(dependences); Source loop_info_field; loop_info_field << "nanos_loop_info_t loop_info;" ; DataEnvironInfo data_environ_info; compute_data_environment( data_sharing, ctr, data_environ_info, _converted_vlas); std::string struct_arg_type_name; define_arguments_structure(ctr, struct_arg_type_name, data_environ_info, ObjectList<OpenMP::DependencyItem>(), loop_info_field); FunctionDefinition funct_def = ctr.get_enclosing_function(); Symbol function_symbol = funct_def.get_function_symbol(); int outline_num = TL::CounterManager::get_counter(NANOX_OUTLINE_COUNTER); TL::CounterManager::get_counter(NANOX_OUTLINE_COUNTER)++; std::stringstream ss; ss << "_ol_" << function_symbol.get_name() << "_" << outline_num; std::string outline_name = ss.str(); Source loop_distr_setup; loop_distr_setup << "int _nth_lower = _args->loop_info.lower;" << "int _nth_upper = _args->loop_info.upper;" << "int _nth_step = _args->loop_info.step;" << "int _nth_step_sign = 1;" << "if (_nth_step < 0)" << "_nth_step_sign = -1;" ; Source final_barrier; if ( (!ctr.get_clause("nowait").is_defined() && !ctr.get_clause("input").is_defined() && !ctr.get_clause("output").is_defined() && !ctr.get_clause("inout").is_defined() ) || !data_environ_info.get_reduction_symbols().empty()) { final_barrier << get_barrier_code(ctr.get_ast()); } Source induction_var_name = for_statement.get_induction_variable().prettyprint(); Source device_descriptor, device_description, device_description_line, num_devices, ancillary_device_description; device_descriptor << outline_name << "_devices"; device_description << ancillary_device_description << "nanos_device_t " << device_descriptor << "[] =" << "{" << device_description_line << "};" ; OutlineFlags outline_flags; DeviceHandler &device_handler = DeviceHandler::get_device_handler(); ObjectList<std::string> current_targets; data_sharing.get_all_devices(current_targets); for (ObjectList<std::string>::iterator it = current_targets.begin(); it != current_targets.end(); it++) { DeviceProvider* device_provider = device_handler.get_device(*it); if (device_provider == NULL) { internal_error("invalid device '%s' at '%s'\n", it->c_str(), ctr.get_ast().get_locus().c_str()); } Source initial_setup, replaced_body; device_provider->do_replacements(data_environ_info, for_statement.get_loop_body().get_ast(), ctr.get_scope_link(), initial_setup, replaced_body); Source outline_body; outline_body << loop_distr_setup << "for (" << induction_var_name << "= _nth_lower;" << "(_nth_step_sign * " << induction_var_name << ")" << "<= (_nth_step_sign * _nth_upper);" << induction_var_name << "+= _nth_step" << ")" << "{" << replaced_body << "}" ; device_provider->create_outline(outline_name, struct_arg_type_name, data_environ_info, outline_flags, ctr.get_statement().get_ast(), ctr.get_scope_link(), initial_setup, outline_body); device_provider->get_device_descriptor(outline_name, data_environ_info, outline_flags, ctr.get_statement().get_ast(), ctr.get_scope_link(), ancillary_device_description, device_description_line); } num_devices << current_targets.size(); Source fill_outline_arguments, fill_dependences_outline; Source dependency_array, num_dependences; fill_data_args("ol_args", data_environ_info, dependences, /* is_pointer */ true, fill_outline_arguments); bool env_is_runtime_sized = data_environ_info.environment_is_runtime_sized(); // Fill dependences, if any if (!dependences.empty()) { num_dependences << dependences.size(); Source dependency_defs_outline; fill_dependences_outline << "nanos_dependence_t _dependences[" << num_dependences << "] = {" << dependency_defs_outline << "};" ; dependency_array << "_dependences"; int num_dep = 0; for (ObjectList<OpenMP::DependencyItem>::iterator it = dependences.begin(); it != dependences.end(); it++) { Source dependency_flags; dependency_flags << "{"; OpenMP::DependencyDirection attr = it->get_kind(); if ((attr & OpenMP::DEP_DIR_INPUT) == OpenMP::DEP_DIR_INPUT) { dependency_flags << "1,"; } else { dependency_flags << "0,"; } if ((attr & OpenMP::DEP_DIR_OUTPUT) == OpenMP::DEP_DIR_OUTPUT) { dependency_flags << "1,"; } else { dependency_flags << "0,"; } Source dependency_field_name; DataReference data_ref = it->get_dependency_expression(); Symbol sym = data_ref.get_base_symbol(); DataEnvironItem data_env_item = data_environ_info.get_data_of_symbol(sym); if (data_env_item.get_symbol().is_valid()) { dependency_field_name << data_env_item.get_field_name(); } else { internal_error("symbol without data environment info %s", it->get_dependency_expression().prettyprint().c_str()); } // Can rename in this case dependency_flags << "1" ; dependency_flags << "}" ; DataReference dependency_expression = it->get_dependency_expression(); Source dep_size; dep_size << dependency_expression.get_sizeof(); Source dependency_offset; dependency_defs_outline << "{" << "(void**)&ol_args->" << dependency_field_name << "," << dependency_offset << "," << dependency_flags << "," << dep_size << "}" ; Source dep_expr_addr = data_ref.get_address(); dependency_offset << "((char*)(" << dep_expr_addr << ") - " << "(char*)ol_args->" << dependency_field_name << ")" ; if ((it + 1) != dependences.end()) { dependency_defs_outline << ","; } num_dep++; } } else { dependency_array << "0"; num_dependences << "0"; } Source tiedness, priority; PragmaCustomClause untied_clause = ctr.get_clause("untied"); if (untied_clause.is_defined()) { tiedness << "props.tied = 0;"; } else { tiedness << "props.tied = 1;"; } PragmaCustomClause priority_clause = ctr.get_clause("__priority"); if (priority_clause.is_defined()) { priority << "props.tied = " << priority_clause.get_arguments()[0] << ";" ; } Source struct_runtime_size, struct_size; if (env_is_runtime_sized) { struct_runtime_size << "int struct_runtime_size = " << "sizeof(" << struct_arg_type_name << ") + " << "(" << data_environ_info.sizeof_variable_part(ctr.get_scope()) << ")" << ";" ; struct_size << "struct_runtime_size" ; } else { struct_size << "sizeof(" << struct_arg_type_name << ")" ; } bool some_device_needs_copies = false; Source num_copies; ObjectList<OpenMP::CopyItem> copy_items = data_environ_info.get_copy_items(); Source copy_data, copy_decl, copy_setup; if (copy_items.empty() || !some_device_needs_copies) { num_copies << "0"; copy_data << "(nanos_copy_data_t**)0"; } else { num_copies << copy_items.size(); copy_decl << "nanos_copy_data_t* copy_data = (nanos_copy_data_t*)0;"; Source copy_items_src; copy_setup << copy_items_src; copy_data << "©_data"; int i = 0; for (ObjectList<OpenMP::CopyItem>::iterator it = copy_items.begin(); it != copy_items.end(); it++) { Source copy_direction_in, copy_direction_out; if (it->get_kind() == OpenMP::COPY_DIR_IN) { copy_direction_in << 1; copy_direction_out << 0; } else if (it->get_kind() == OpenMP::COPY_DIR_OUT) { copy_direction_in << 0; copy_direction_out << 1; } else if (it->get_kind() == OpenMP::COPY_DIR_INOUT) { copy_direction_in << 1; copy_direction_out << 1; } DataReference data_ref = it->get_copy_expression(); OpenMP::DataSharingAttribute data_attr = data_sharing.get_data_sharing(data_ref.get_base_symbol()); ERROR_CONDITION(data_attr == OpenMP::DS_UNDEFINED, "Invalid data sharing for copy", 0); bool has_shared_data_sharing = (data_attr & OpenMP::DS_SHARED) == OpenMP::DS_SHARED; Source copy_sharing; if (has_shared_data_sharing) { copy_sharing << "NANOS_SHARED"; } else { copy_sharing << "NANOS_PRIVATE"; } struct { Source *source; const char* array; const char* struct_name; } fill_copy_data_info[] = { { ©_items_src, "copy_data", "ol_args->" }, { NULL, "" }, }; for (int j = 0; fill_copy_data_info[j].source != NULL; j++) { Source expression_size, expression_address; const char* array_name = fill_copy_data_info[j].array; (*(fill_copy_data_info[j].source)) << array_name << "[" << i << "].address = (uintptr_t)(" << expression_address << ");" << array_name << "[" << i << "].sharing = " << copy_sharing << ";" << array_name << "[" << i << "].flags.input = " << copy_direction_in << ";" << array_name << "[" << i << "].flags.output = " << copy_direction_out << ";" << array_name << "[" << i << "].size = " << expression_size << ";" ; DataReference copy_expr = it->get_copy_expression(); if (has_shared_data_sharing) { expression_address << copy_expr.get_address(); } else { DataEnvironItem data_env_item = data_environ_info.get_data_of_symbol(copy_expr.get_base_symbol()); // We have to use the value of the argument structure if it // is private expression_address << "&(" << fill_copy_data_info[j].struct_name << data_env_item.get_field_name() << ")" ; } expression_size << copy_expr.get_sizeof(); } i++; } } Source current_slicer; Source chunk_value; chunk_value = Source("0"); current_slicer = Source("static_for"); PragmaCustomClause schedule_clause = ctr.get_clause("schedule"); if (schedule_clause.is_defined()) { ObjectList<std::string> args = schedule_clause.get_arguments(ExpressionTokenizerTrim()); current_slicer = args[0] + "_for"; if (args.size() > 1) { chunk_value = Source(args[1]); } } // FIXME - Move this to a tl-workshare.cpp Source spawn_source; // FIXME - This will be meaningful with 'copy_in' and 'copy_out' Source num_copies1, copy_data1; num_copies1 << "0"; copy_data1 << "(nanos_copy_data_t**)0"; Source creation; if ( current_targets.contains( "cuda" ) ) { creation << "props.mandatory_creation = 1;" ; } ObjectList<OpenMP::ReductionSymbol> reduction_symbols = data_environ_info.get_reduction_symbols(); Source reduction_join_arr_decls; if (!reduction_symbols.empty()) reduction_join_arr_decls << "int _nth_team = omp_get_num_threads();" ; if (!reduction_symbols.empty()) reduction_join_arr_decls << "int rs_i;" ; for(ObjectList<OpenMP::ReductionSymbol>::iterator it = reduction_symbols.begin(); it != reduction_symbols.end(); it++) { Symbol rs = it->get_symbol(); OpenMP::UDRInfoItem2 udr2 = it->get_udr_2(); Source auxiliar_initializer; if (rs.get_type().is_class()) { // When the symbol has class type, we must build an auxiliary variable initialized to the symbol's identity // in order to initialize the reduction's vector auxiliar_initializer << "aux_" << rs.get_name(); Source identity; reduction_join_arr_decls << rs.get_type().get_declaration(rs.get_scope(), "") << " " << auxiliar_initializer << identity << ";" ; if (udr2.has_identity()) { identity << udr2.get_identity().prettyprint() << ";" ; } } else { auxiliar_initializer << udr2.get_identity().prettyprint(); } reduction_join_arr_decls << rs.get_type().get_declaration(rs.get_scope(), "") << " rdv_" << rs.get_name() << "[_nth_team];" << "for(rs_i=0; rs_i<_nth_team; rs_i++)" << "{" ; CXX_LANGUAGE() { if (udr2.has_identity()) { if (udr2.get_need_equal_initializer()) { reduction_join_arr_decls << "rdv_" << rs.get_name() << "[rs_i] = " << auxiliar_initializer << ";" ; } else { if (udr2.get_is_constructor()) { reduction_join_arr_decls << "rdv_" << rs.get_name() << "[rs_i] " << auxiliar_initializer << ";" ; } else if (!rs.get_type().is_enum()) { reduction_join_arr_decls << "rdv_" << rs.get_name() << "[rs_i] (" << auxiliar_initializer << ");" ; } } } } C_LANGUAGE() { reduction_join_arr_decls << "rdv_" << rs.get_name() << "[rs_i] = " << auxiliar_initializer << ";" ; } reduction_join_arr_decls << "}"; } Source omp_reduction_join, omp_reduction_argument; // Get reduction code for (ObjectList<std::string>::iterator it = current_targets.begin(); it != current_targets.end(); it++) { DeviceProvider* device_provider = device_handler.get_device(*it); if (device_provider->get_name()=="smp") { omp_reduction_join << device_provider->get_reduction_code(reduction_symbols, ctr.get_scope_link()) ; } } // Fill outline variables for (ObjectList<OpenMP::ReductionSymbol>::iterator it = reduction_symbols.begin(); it != reduction_symbols.end(); it++) { omp_reduction_argument << "ol_args->rdv_" << it->get_symbol().get_name() << " = rdv_" << it->get_symbol().get_name() << ";"; } Source alignment, slicer_alignment; if (Nanos::Version::interface_is_at_least("master", 5004)) { alignment << "__alignof__(" << struct_arg_type_name << ")," ; slicer_alignment << "__alignof__(nanos_slicer_data_for_t)," ; } Source create_sliced_wd, loop_information, decl_slicer_data_if_needed; if (Nanos::Version::interface_is_at_least("master", 5008)) { create_sliced_wd <<"nanos_create_sliced_wd(&wd, " << /* num_devices */ "1, " << device_descriptor << ", " << "sizeof(" << struct_arg_type_name << ")," << alignment << "(void**)&ol_args," << "nanos_current_wd()," << current_slicer << "," << "&props," << num_copies1 << "," << copy_data1 << ");" ; loop_information << "ol_args->loop_info.lower = " << for_statement.get_lower_bound() << ";" << "ol_args->loop_info.upper = " << for_statement.get_upper_bound() << ";" << "ol_args->loop_info.step = " << for_statement.get_step() << ";" << "ol_args->loop_info.chunk = " << chunk_value << ";" ; } else { create_sliced_wd << "nanos_create_sliced_wd(&wd, " << /* num_devices */ "1, " << device_descriptor << ", " << "sizeof(" << struct_arg_type_name << ")," << alignment << "(void**)&ol_args," << "nanos_current_wd()," << current_slicer << "," << "sizeof(nanos_slicer_data_for_t)," << slicer_alignment << "(nanos_slicer_t*) &slicer_data_for," << "&props," << num_copies1 << "," << copy_data1 << ");" ; decl_slicer_data_if_needed << "nanos_slicer_data_for_t* slicer_data_for = (nanos_slicer_data_for_t*)0;" ; loop_information << "slicer_data_for->_lower = " << for_statement.get_lower_bound() << ";" << "slicer_data_for->_upper = " << for_statement.get_upper_bound() << ";" << "slicer_data_for->_step = " << for_statement.get_step() << ";" << "slicer_data_for->_chunk = " << chunk_value << ";" ; } if(!_no_nanox_calls) { spawn_source << "{" << get_single_guard("single_guard") << "if (err != NANOS_OK) nanos_handle_error(err);" << reduction_join_arr_decls << "if (single_guard)" << "{" << struct_arg_type_name << "* ol_args = (" << struct_arg_type_name << "*)0;" << struct_runtime_size << "nanos_wd_t wd = (nanos_wd_t)0;" << "nanos_wd_props_t props;" << "__builtin_memset(&props, 0, sizeof(props));" << creation << "props.mandatory_creation = 1;" << priority << tiedness << copy_decl << "static nanos_slicer_t " << current_slicer << " = 0;" << device_description << "if (!" << current_slicer << ") " << current_slicer << " = nanos_find_slicer(\"" << current_slicer << "\");" << decl_slicer_data_if_needed << "err = " << create_sliced_wd << "if (err != NANOS_OK) nanos_handle_error(err);" << fill_outline_arguments << omp_reduction_argument << fill_dependences_outline << copy_setup << loop_information << "err = nanos_submit(wd, " << num_dependences << ", (nanos_dependence_t*)" << dependency_array << ", (nanos_team_t)0);" << "if (err != NANOS_OK) nanos_handle_error (err);" << "}" << final_barrier << omp_reduction_join << "}" ; } else { if(current_targets.contains("smp")) { std::stringstream smp_device_call; smp_device_call << "_smp_" << outline_name << "(ol_args);"; // The code generated must not contain calls to runtime. The execution will be serial spawn_source << "{" << struct_arg_type_name << "* ol_args = (" << struct_arg_type_name << "*)0;" << fill_outline_arguments << omp_reduction_argument << loop_information << smp_device_call.str() << "}" ; } else { running_error("%s: error: the code generation without calls to runtime only works in smp devices\n", ctr.get_ast().get_locus().c_str()); } } AST_t spawn_tree = spawn_source.parse_statement(ctr.get_ast(), ctr.get_scope_link()); ctr.get_ast().replace(spawn_tree); }
void ireon::kd_tree::KdTree<T>::subdivide( KdTreeNode<T>* node, const aabb& box, int depth, int a_Prims ) { // recycle used split list nodes //add sPool_ at end sList_ if (sList_) { SplitList* list = sList_; while (list->next) list = list->next; list->next = sPool_; sPool_ = sList_, sList_ = 0; } // determine split axis Vector3 s = box.getSize(); if ((s.x >= s.y) && (s.x >= s.z)) node->setAxis( 0 ); else if ((s.y >= s.x) && (s.y >= s.z)) node->setAxis( 1 ); int axis = node->getAxis(); // make a list of the split position candidates ObjectList<T>* l = node->getList(); real p1, p2; real pos1 = box.getPos().val[axis]; real pos2 = box.getPos().val[axis] + box.getSize().val[axis]; bool* pright = new bool[a_Prims]; float* eleft = new float[a_Prims], *eright = new float[a_Prims]; T** parray = new T*[a_Prims]; real etleft, etright; int aidx = 0; while (l) { T* p = parray[aidx] = l->getPrimitive(); pright[aidx] = true; etleft = eleft[aidx]; etright = eright[aidx]; p->calculateRange( etleft, etright, axis ); eleft[aidx] = (float)etleft; eright[aidx] = (float)etright; aidx++; for ( int i = 0; i < 3; i++ ) { p1 = (float)p->vertice( i )->cell[axis]; if ((p1 >= pos1) && (p1 <= pos2)) insertSplitPos( p1 ); } l = l->getNext(); } // determine n1count / n2count for each split position aabb b1, b2, b3 = box, b4 = box; SplitList* splist = sList_; float b3p1 = b3.getPos().val[axis]; float b4p2 = b4.getPos().val[axis] + b4.getSize().val[axis]; Vector3 foo; while (splist) { foo = b4.getPos(); foo.val[axis] = splist->splitpos; b4.setPos(foo); foo = b4.getSize(); foo.val[axis] = pos2 - splist->splitpos; b4.setSize(foo); foo = b3.getSize(); foo.val[axis] = splist->splitpos - pos1; b3.setSize(foo); float b3p2 = b3.getPos().val[axis] + b3.getSize().val[axis]; float b4p1 = b4.getPos().val[axis]; for ( int i = 0; i < a_Prims; i++ ) if (pright[i]) { T* p = parray[i]; if ((eleft[i] <= b3p2) && (eright[i] >= b3p1)) if (p->intersectBox( b3 )) splist->n1count++; if ((eleft[i] <= b4p2) && (eright[i] >= b4p1)) if (p->intersectBox( b4 )) splist->n2count++; else pright[i] = false; } else splist->n1count++; splist = splist->next; } delete[] pright; // calculate surface area for current node real SAV = 0.5f / (box.w() * box.d() + box.w() * box.h() + box.d() * box.h()); // calculate cost for not splitting real Cleaf = a_Prims * 1.0f; // determine optimal split plane position splist = sList_; real lowcost = 10000; real bestpos = 0; while (splist) { // calculate child node extends foo = b4.getPos(); foo.val[axis] = splist->splitpos; b4.setPos(foo); foo = b4.getSize(); foo.val[axis] = pos2 - splist->splitpos; b4.setSize(foo); foo = b3.getSize(); foo.val[axis] = splist->splitpos - pos1; b3.setSize(foo); // calculate child node cost real SA1 = 2 * (b3.w() * b3.d() + b3.w() * b3.h() + b3.d() * b3.h()); real SA2 = 2 * (b4.w() * b4.d() + b4.w() * b4.h() + b4.d() * b4.h()); real splitcost = 0.3f + 1.0f * (SA1 * SAV * splist->n1count + SA2 * SAV * splist->n2count); // update best cost tracking variables if (splitcost < lowcost) { lowcost = splitcost; bestpos = splist->splitpos; b1 = b3, b2 = b4; } splist = splist->next; } if (lowcost > Cleaf) { delete[] eleft; delete[] eright; delete[] parray; return; } node->setSplitPos( bestpos ); // construct child nodes KdTreeNode<T>* left = s_MManager->NewKdTreeNodePair(); int n1count = 0, n2count = 0, total = 0; // assign primitives to both sides float b1p1 = b1.getPos().val[axis]; float b2p2 = b2.getPos().val[axis] + b2.getSize().val[axis]; float b1p2 = b1.getPos().val[axis] + b1.getSize().val[axis]; float b2p1 = b2.getPos().val[axis]; for ( int i = 0; i < a_Prims; i++ ) { T* p = parray[i]; total++; if ((eleft[i] <= b1p2) && (eright[i] >= b1p1)) if (p->intersectBox( b1 )) { left->add( p ); n1count++; } if ((eleft[i] <= b2p2) && (eright[i] >= b2p1)) if (p->intersectBox( b2 )) { (left + 1)->add( p ); n2count++; } } delete[] eleft; delete[] eright; delete[] parray; s_MManager->FreeObjectList( node->getList() ); node->setLeft( left ); node->setLeaf( false ); if (depth < MAXTREEDEPTH) { if (n1count > 2) subdivide( left, b1, depth + 1, n1count ); if (n2count > 2) subdivide( left + 1, b2, depth + 1, n2count ); } }
void ObjectBrowserWidget::loadChild(ObjectBrowserItem* parent, const CCopasiContainer* copaParent, bool nField) { unsigned int i; ObjectBrowserItem* last = NULL; CCopasiObject* current = NULL; ObjectList* childStack = new ObjectList(); const CCopasiContainer::objectMap * pObjectList = & copaParent->getObjects(); CCopasiContainer::objectMap::const_iterator it = pObjectList->begin(); CCopasiContainer::objectMap::const_iterator end = pObjectList->end(); if ((copaParent->isVector()) && (nField)) { if ((static_cast< const CCopasiVector < CCopasiObject > * >(copaParent)->size() >= 1) && ((*static_cast< const CCopasiVector < CCopasiObject > * >(copaParent))[0]->isContainer())) {//add attribute list ObjectBrowserItem* fieldChild = new ObjectBrowserItem(parent, NULL, NULL, objectItemList); fieldChild->setObjectType(FIELDATTR); fieldChild->setText(0, "Select by attribute"); fieldChild->setSelectable(false); loadField(fieldChild, const_cast<CCopasiVector < CCopasiObject > *>(static_cast< const CCopasiVector < CCopasiObject > * >(copaParent))); fieldChild->attachKey(); last = fieldChild; } } if (copaParent->isVector()) { for (i = 0; i < static_cast< const CCopasiVector < CCopasiObject > * >(copaParent)->size(); i++) { current = (*static_cast< const CCopasiVector < CCopasiObject > * >(copaParent))[i]; ObjectBrowserItem* currentItem = new ObjectBrowserItem(parent, last, current, objectItemList); last = currentItem; currentItem->setText(0, FROM_UTF8(current->getObjectName())); if (current->isContainer()) { currentItem->setObjectType(CONTAINERATTR); currentItem->attachKey(); if (current->isVector()) currentItem->setText(0, currentItem->text(0) + "[]"); loadChild(currentItem, static_cast< CCopasiContainer * >(current), nField); } else { currentItem->setObjectType(OBJECTATTR); childStack->insert(currentItem); //attach the key later } } } else { while (it != end) { current = it->second; // Skip all strings if (dynamic_cast<CCopasiStaticString *>(current)) { it++; continue; } ObjectBrowserItem* currentItem = new ObjectBrowserItem(parent, last, current, objectItemList); last = currentItem; currentItem->setText(0, FROM_UTF8(current->getObjectName())); if (current->isContainer()) { currentItem->setObjectType(CONTAINERATTR); currentItem->attachKey(); if (current->isVector()) currentItem->setText(0, currentItem->text(0) + "[]"); loadChild(currentItem, static_cast< CCopasiContainer * >(current), nField); } else { currentItem->setObjectType(OBJECTATTR); childStack->insert(currentItem); //attach the key later } it++; } } ObjectBrowserItem* pCurrent; while (childStack->len() > 0) { pCurrent = childStack->pop(); pCurrent->attachKey(); } pdelete(childStack); }
int ireon::kd_tree::KdTree<T>::FindNearest( Ray& a_Ray, real& a_Dist, T*& a_Prim , kdstack<T> * const m_Stack, const aabb* extendBox) { real tnear = 0, tfar = a_Dist, t; int retval = 0; Vector3 p1 = extendBox->getPos(); Vector3 p2 = p1 + extendBox->getSize(); Vector3 D = a_Ray.getDirection(), O = a_Ray.getOrigin(); for ( int i = 0; i < 3; i++ ) if (D.val[i] < 0) { if (O.val[i] < p1.val[i]) return 0; } else if (O.val[i] > p2.val[i]) return 0; // clip ray segment to box for ( int i = 0; i < 3; i++ ) { real pos = O.val[i] + tfar * D.val[i]; if (D.val[i] < 0) { // clip end point if (pos < p1.val[i]) tfar = tnear + (tfar - tnear) * ((O.val[i] - p1.val[i]) / (O.val[i] - pos)); // clip start point if (O.val[i] > p2.val[i]) tnear += (tfar - tnear) * ((O.val[i] - p2.val[i]) / (tfar * D.val[i])); } else { // clip end point if (pos > p2.val[i]) tfar = tnear + (tfar - tnear) * ((p2.val[i] - O.val[i]) / (pos - O.val[i])); // clip start point if (O.val[i] < p1.val[i]) tnear += (tfar - tnear) * ((p1.val[i] - O.val[i]) / (tfar * D.val[i])); } if (tnear > tfar) return 0; } // init stack int entrypoint = 0, exitpoint = 1; // init traversal KdTreeNode<T>* farchild, *currnode; currnode = getRoot(); m_Stack[entrypoint].t = tnear; if (tnear > 0.0f) m_Stack[entrypoint].pb = O + D * tnear; else m_Stack[entrypoint].pb = O; m_Stack[exitpoint].t = tfar; m_Stack[exitpoint].pb = O + D * tfar; m_Stack[exitpoint].node = 0; // traverse kd-tree while (currnode) { while (!currnode->isLeaf()) { real splitpos = currnode->getSplitPos(); int axis = currnode->getAxis(); if (m_Stack[entrypoint].pb.val[axis] <= splitpos) { if (m_Stack[exitpoint].pb.val[axis] <= splitpos) { currnode = currnode->getLeft(); continue; } if (m_Stack[exitpoint].pb.val[axis] == splitpos) { currnode = currnode->getRight(); continue; } currnode = currnode->getLeft(); farchild = currnode + 1; // GetRight(); } else { if (m_Stack[exitpoint].pb.val[axis] > splitpos) { currnode = currnode->getRight(); continue; } farchild = currnode->getLeft(); currnode = farchild + 1; // GetRight(); } t = (splitpos - O.val[axis]) / D.val[axis]; int tmp = exitpoint++; if (exitpoint == entrypoint) exitpoint++; m_Stack[exitpoint].prev = tmp; m_Stack[exitpoint].t = t; m_Stack[exitpoint].node = farchild; m_Stack[exitpoint].pb.val[axis] = splitpos; int nextaxis = m_Mod[axis + 1]; int prevaxis = m_Mod[axis + 2]; m_Stack[exitpoint].pb.val[nextaxis] = O.val[nextaxis] + t * D.val[nextaxis]; m_Stack[exitpoint].pb.val[prevaxis] = O.val[prevaxis] + t * D.val[prevaxis]; } ObjectList<T>* list = currnode->getList(); real dist = m_Stack[exitpoint].t; while (list) { T* pr = list->getPrimitive(); int result; m_Intersections++; if (result = intersect( pr, a_Ray, dist )) { retval = result; a_Dist = dist; a_Prim = pr; } list = list->getNext(); } if (retval) return retval; entrypoint = exitpoint; currnode = m_Stack[exitpoint].node; exitpoint = m_Stack[entrypoint].prev; } return 0; }