hexsha
stringlengths
40
40
size
int64
19
11.4M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
3
270
max_stars_repo_name
stringlengths
5
110
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
float64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
3
270
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
78
max_issues_repo_licenses
listlengths
1
9
max_issues_count
float64
1
67k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
3
270
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
78
max_forks_repo_licenses
listlengths
1
9
max_forks_count
float64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
19
11.4M
avg_line_length
float64
1.93
229k
max_line_length
int64
12
688k
alphanum_fraction
float64
0.07
0.99
matches
listlengths
1
10
603318af68016f0cb8bdb4617089b3b4724a2193
4,741
cpp
C++
sample/PetShopClient.Test/CategoryTests.cpp
Danielku15/swagger-codegen-cpprestsdk
79315b2172697216ad6ff9d1f458a150fb382c76
[ "Apache-2.0" ]
5
2016-10-04T03:10:52.000Z
2021-07-31T12:18:12.000Z
sample/PetShopClient.Test/CategoryTests.cpp
Danielku15/swagger-codegen-cpprestsdk
79315b2172697216ad6ff9d1f458a150fb382c76
[ "Apache-2.0" ]
2
2017-06-17T16:18:57.000Z
2017-07-09T11:33:36.000Z
sample/PetShopClient.Test/CategoryTests.cpp
Danielku15/swagger-codegen-cpprestsdk
79315b2172697216ad6ff9d1f458a150fb382c76
[ "Apache-2.0" ]
1
2018-12-13T15:58:00.000Z
2018-12-13T15:58:00.000Z
#include "Tests.h" #include <model/Category.h> BOOST_AUTO_TEST_SUITE(CategoryTests) BOOST_AUTO_TEST_CASE(testToJsonFull) { swagger::petshop::model::Category category; category.setId(1); category.setName(U("Test")); web::json::value json = category.toJson(); auto jsonString = json.serialize(); BOOST_CHECK_EQUAL(U("{\"id\":1,\"name\":\"Test\"}"), jsonString); } BOOST_AUTO_TEST_CASE(testToJsonMissingId) { swagger::petshop::model::Category category; category.setName(U("Test")); web::json::value json = category.toJson(); auto jsonString = json.serialize(); BOOST_CHECK_EQUAL(U("{\"name\":\"Test\"}"), jsonString); } BOOST_AUTO_TEST_CASE(testToJsonMissingName) { swagger::petshop::model::Category category; category.setId(1); web::json::value json = category.toJson(); auto jsonString = json.serialize(); BOOST_CHECK_EQUAL(U("{\"id\":1}"), jsonString); } BOOST_AUTO_TEST_CASE(testToJsonEmpty) { swagger::petshop::model::Category category; web::json::value json = category.toJson(); auto jsonString = json.serialize(); BOOST_CHECK_EQUAL(U("{}"), jsonString); } BOOST_AUTO_TEST_CASE(testFromJsonFull) { web::json::value json = web::json::value::parse(U("{\"id\":1,\"name\":\"Test\"}")); swagger::petshop::model::Category category; category.fromJson(json); BOOST_CHECK(category.idIsSet()); BOOST_CHECK_EQUAL(category.getId(), 1); BOOST_CHECK(category.nameIsSet()); BOOST_CHECK_EQUAL(category.getName(), U("Test")); } BOOST_AUTO_TEST_CASE(testFromJsonMissingId) { web::json::value json = web::json::value::parse(U("{\"name\":\"Test\"}")); swagger::petshop::model::Category category; category.fromJson(json); BOOST_CHECK(!category.idIsSet()); BOOST_CHECK_EQUAL(category.getId(), 0); BOOST_CHECK(category.nameIsSet()); BOOST_CHECK_EQUAL(category.getName(), U("Test")); } BOOST_AUTO_TEST_CASE(testFromJsonMissingName) { web::json::value json = web::json::value::parse(U("{\"id\":1}")); swagger::petshop::model::Category category; category.fromJson(json); BOOST_CHECK(category.idIsSet()); BOOST_CHECK_EQUAL(category.getId(), 1); BOOST_CHECK(!category.nameIsSet()); BOOST_CHECK_EQUAL(category.getName(), U("")); } BOOST_AUTO_TEST_CASE(testFromJsonEmpty) { web::json::value json = web::json::value::parse(U("{}")); swagger::petshop::model::Category category; category.fromJson(json); BOOST_CHECK(!category.idIsSet()); BOOST_CHECK_EQUAL(category.getId(), 0); BOOST_CHECK(!category.nameIsSet()); BOOST_CHECK_EQUAL(category.getName(), U("")); } BOOST_AUTO_TEST_CASE(testToMultipartFull) { swagger::petshop::model::Category category; category.setId(1); category.setName(U("Test")); std::shared_ptr<swagger::petshop::model::MultipartFormData> multipart = std::make_shared<swagger::petshop::model::MultipartFormData>(U("test")); category.toMultipart(multipart, U("cat")); std::stringstream out; multipart->writeTo(out); std::string result = out.str(); BOOST_CHECK_EQUAL( "\r\n" "--test\r\n" "Content-Disposition: form-data; name=\"cat.id\"\r\n" "\r\n" "1\r\n" "--test\r\n" "Content-Disposition: form-data; name=\"cat.name\"\r\n" "\r\n" "Test\r\n" "--test--\r\n", result); } BOOST_AUTO_TEST_CASE(testToMultipartMissingId) { swagger::petshop::model::Category category; category.setName(U("Test")); std::shared_ptr<swagger::petshop::model::MultipartFormData> multipart = std::make_shared<swagger::petshop::model::MultipartFormData>(U("test")); category.toMultipart(multipart, U("cat")); std::stringstream out; multipart->writeTo(out); std::string result = out.str(); BOOST_CHECK_EQUAL( "\r\n" "--test\r\n" "Content-Disposition: form-data; name=\"cat.name\"\r\n" "\r\n" "Test\r\n" "--test--\r\n", result); } BOOST_AUTO_TEST_CASE(testToMultipartMissingName) { swagger::petshop::model::Category category; category.setId(1); std::shared_ptr<swagger::petshop::model::MultipartFormData> multipart = std::make_shared<swagger::petshop::model::MultipartFormData>(U("test")); category.toMultipart(multipart, U("cat")); std::stringstream out; multipart->writeTo(out); std::string result = out.str(); BOOST_CHECK_EQUAL( "\r\n" "--test\r\n" "Content-Disposition: form-data; name=\"cat.id\"\r\n" "\r\n" "1\r\n" "--test--\r\n", result); } BOOST_AUTO_TEST_CASE(testToMultipartEmpty) { swagger::petshop::model::Category category; std::shared_ptr<swagger::petshop::model::MultipartFormData> multipart = std::make_shared<swagger::petshop::model::MultipartFormData>(U("test")); category.toMultipart(multipart, U("cat")); std::stringstream out; multipart->writeTo(out); std::string result = out.str(); BOOST_CHECK_EQUAL( "\r\n" "--test--\r\n", result); } // TODO: from multipart BOOST_AUTO_TEST_SUITE_END()
24.82199
145
0.7085
[ "model" ]
603a6af0f6bf3d943ffd4e953414cc4742cbf448
23,853
cpp
C++
src/xrGame/ui/UIMpTradeWnd_items.cpp
acidicMercury8/ixray-1.6
8d5099b28808f09f62cf1ee08bb451c3e2a24a88
[ "Linux-OpenIB" ]
2
2020-01-30T12:51:42.000Z
2020-08-31T08:36:43.000Z
src/xrGame/ui/UIMpTradeWnd_items.cpp
Samsuper12/ixray-1.6
95b8ad458d4550118c7fbf34c5de872f3d1ca75e
[ "Linux-OpenIB" ]
null
null
null
src/xrGame/ui/UIMpTradeWnd_items.cpp
Samsuper12/ixray-1.6
95b8ad458d4550118c7fbf34c5de872f3d1ca75e
[ "Linux-OpenIB" ]
2
2020-05-17T10:01:14.000Z
2020-09-11T20:17:27.000Z
#include "stdafx.h" #include "UIMpTradeWnd.h" #include "../inventory_item.h" #include "../PhysicsShellHolder.h" #include "object_broker.h" #include "UICellItem.h" #include "UIDragDropListEx.h" #include "../string_table.h" #include "UIMpItemsStoreWnd.h" #include "../Weapon.h" #include "../WeaponMagazinedWGrenade.h" #include "UICellCustomItems.h" extern "C" DLL_Pure* __cdecl xrFactory_Create (CLASS_ID clsid); extern "C" void __cdecl xrFactory_Destroy (DLL_Pure* O); CUICellItem* create_cell_item(CInventoryItem* itm); SBuyItemInfo::SBuyItemInfo() { m_item_state = e_undefined; } SBuyItemInfo::~SBuyItemInfo() { CInventoryItem* iitem = (CInventoryItem*)m_cell_item->m_pData; xrFactory_Destroy (&iitem->object()); delete_data (m_cell_item); } void SBuyItemInfo::SetState (const EItmState& s) { if(s==e_undefined) { m_item_state = s; return; } switch(m_item_state) { case e_undefined: { m_item_state = s; break; }; case e_bought: { VERIFY2 (s==e_shop||s==e_sold,"incorrect SBuyItemInfo::SetState sequence"); m_item_state = e_shop; break; }; case e_sold: { VERIFY2 (s==e_own||s==e_bought,"incorrect SBuyItemInfo::SetState sequence"); m_item_state = e_own; break; }; case e_own: { VERIFY2 (s==e_sold,"incorrect SBuyItemInfo::SetState sequence"); m_item_state = s; break; }; case e_shop: { VERIFY2 (s==e_bought,"incorrect SBuyItemInfo::SetState sequence"); m_item_state = s; break; }; }; } LPCSTR _state_names []={ "e_undefined", "e_bought", "e_sold", "e_own", "e_shop" }; LPCSTR SBuyItemInfo::GetStateAsText() const { EItmState st = GetState(); return _state_names[st]; } CInventoryItem* CUIMpTradeWnd::CreateItem_internal(const shared_str& name_sect) { CLASS_ID class_id = pSettings->r_clsid(name_sect,"class"); DLL_Pure *dll_pure = xrFactory_Create(class_id); VERIFY (dll_pure); CInventoryItem* pIItem = smart_cast<CInventoryItem*>(dll_pure); pIItem->object().Load (name_sect.c_str()); VERIFY (pIItem); return (pIItem); } SBuyItemInfo* CUIMpTradeWnd::CreateItem(const shared_str& name_sect, SBuyItemInfo::EItmState type, bool find_if_exist) { SBuyItemInfo* iinfo = (find_if_exist)?FindItem(name_sect, type):NULL; if(iinfo) return iinfo; iinfo = xr_new<SBuyItemInfo>(); m_all_items.push_back ( iinfo ); iinfo->m_name_sect = name_sect; iinfo->SetState (type); iinfo->m_cell_item = create_cell_item(CreateItem_internal(name_sect)); iinfo->m_cell_item->m_b_destroy_childs = false; return iinfo; } struct state_eq{ SBuyItemInfo::EItmState m_state; state_eq(SBuyItemInfo::EItmState state):m_state(state){} bool operator () (SBuyItemInfo* itm){ return ( m_state==itm->GetState() ); } }; SBuyItemInfo* CUIMpTradeWnd::FindItem(SBuyItemInfo::EItmState state) { state_eq eq (state); ITEMS_vec_cit it = std::find_if(m_all_items.begin(), m_all_items.end(), eq ); return (it==m_all_items.end())?NULL:(*it); } SBuyItemInfo* CUIMpTradeWnd::FindItem(const shared_str& name_sect, SBuyItemInfo::EItmState type) { ITEMS_vec_cit it = m_all_items.begin(); ITEMS_vec_cit it_e = m_all_items.end(); for(;it!=it_e;++it) { SBuyItemInfo* pitm = *it; if(pitm->m_name_sect==name_sect && pitm->GetState()==type) return pitm; } return NULL; } SBuyItemInfo* CUIMpTradeWnd::FindItem(CUICellItem* item) { ITEMS_vec_cit it = m_all_items.begin(); ITEMS_vec_cit it_e = m_all_items.end(); for(;it!=it_e;++it) { SBuyItemInfo* pitm = *it; if(pitm->m_cell_item==item) return pitm; } R_ASSERT2 (0, "buy menu data corruption. cant find corresponding SBuyItemInfo* for CellItem"); return NULL; } bool CUIMpTradeWnd::HasItemInGroup(shared_str const & section_name) { return m_store_hierarchy->FindItem(section_name) ? true : false; } void CUIMpTradeWnd::DeleteHelperItems () { int lists[] = { e_medkit, e_granade, e_rifle_ammo, e_pistol_ammo }; for ( int i=0; i<sizeof(lists)/sizeof(lists[0]); ++i ) { DeleteHelperItems(m_list[lists[i]]); } } void CUIMpTradeWnd::DeleteHelperItems (CUIDragDropListEx* list) { ITEMS_vec to_sell; for ( ITEMS_vec::iterator it = m_all_items.begin(); it != m_all_items.end(); ++it ) { SBuyItemInfo* item = *it; if ( item->m_cell_item->OwnerList() != list ) { continue; } if ( item->GetState() != SBuyItemInfo::e_bought && item->GetState() != SBuyItemInfo::e_own ) { continue; } if ( item->m_cell_item->IsHelper() ) { if ( std::find(to_sell.begin(), to_sell.end(), item) == to_sell.end() ) { to_sell.push_back(item); } } } for ( ITEMS_vec::iterator it = to_sell.begin(); it != to_sell.end(); ++it ) { SBuyItemInfo* tempo = NULL; TryToSellItem(*it, true, tempo); } } void CUIMpTradeWnd::UpdateHelperItems () { DeleteHelperItems(); int lists[] = { e_medkit, e_granade, e_rifle_ammo, e_pistol_ammo }; for ( int i=0; i<sizeof(lists)/sizeof(lists[0]); ++i ) { CreateHelperItems(m_list[lists[i]]); } } void CUIMpTradeWnd::CreateHelperItems (xr_vector<shared_str>& ammo_types) { for ( xr_vector<shared_str>::iterator it = ammo_types.begin(); it != ammo_types.end(); ++it ) { const shared_str& ammo_name = *it; if ( !m_store_hierarchy->FindItem (ammo_name) ) { continue; } SBuyItemInfo* ammo_item = CreateItem(ammo_name, SBuyItemInfo::e_undefined, false); ammo_item->m_cell_item->SetIsHelper (true); TryToBuyItem (ammo_item, bf_normal, NULL); } } void CUIMpTradeWnd::CreateHelperItems (CUIDragDropListEx* list, const CStoreHierarchy::item* shop_level) { for ( xr_vector<shared_str>::const_iterator it = shop_level->m_items_in_group.begin(); it != shop_level->m_items_in_group.end(); ++it ) { shared_str item_name = *it; CUIDragDropListEx* match_list = GetMatchedListForItem(item_name); if ( match_list == list ) { SBuyItemInfo* new_item = CreateItem(item_name, SBuyItemInfo::e_undefined, false); CUIInventoryCellItem* inventory_cell_item; if ( (inventory_cell_item = dynamic_cast<CUIInventoryCellItem*>(new_item->m_cell_item)) != NULL ) { inventory_cell_item->SetIsHelper(true); inventory_cell_item->UpdateItemText(); TryToBuyItem (new_item, bf_normal, NULL); } } } for ( u32 i = 0; i < shop_level->ChildCount(); ++i ) { const CStoreHierarchy::item* child = &shop_level->ChildAtIdx(i); CreateHelperItems (list, child); } } void CUIMpTradeWnd::CreateHelperItems (CUIDragDropListEx* list) { CUIDragDropListEx* parent_list = NULL; if ( list == m_list[e_pistol_ammo] ) { parent_list = m_list[e_pistol]; } else if ( list == m_list[e_rifle_ammo] ) { parent_list = m_list[e_rifle]; } if ( list == m_list[e_medkit] || list == m_list[e_granade] ) { CreateHelperItems(list, &m_store_hierarchy->GetRoot()); return; } VERIFY(parent_list); if ( !parent_list->ItemsCount() ) { return; } CInventoryItem* parent_item = (CInventoryItem*)parent_list->GetItemIdx(0)->m_pData; CWeapon* wpn = smart_cast<CWeapon*>(parent_item); R_ASSERT (wpn); CreateHelperItems (wpn->m_ammoTypes); if ( CWeaponMagazinedWGrenade* wpn2 = smart_cast<CWeaponMagazinedWGrenade*>(parent_item) ) { if ( wpn2->IsGrenadeLauncherAttached() ) { CreateHelperItems (wpn2->m_ammoTypes2); } } } void CUIMpTradeWnd::UpdateCorrespondingItemsForList(CUIDragDropListEx* _list) { CUIDragDropListEx* dependent_list = NULL; CUIDragDropListEx* bag_list = m_list[e_player_bag]; if(_list==m_list[e_pistol]) dependent_list = m_list[e_pistol_ammo]; else if(_list==m_list[e_rifle]) dependent_list = m_list[e_rifle_ammo]; if(!dependent_list) return; DeleteHelperItems(dependent_list); xr_list<SBuyItemInfo*> _tmp_list; while(dependent_list->ItemsCount()!=0) { CUICellItem* ci = dependent_list->GetItemIdx(0); CUICellItem* ci2 = dependent_list->RemoveItem(ci, false); SBuyItemInfo* bi = FindItem(ci2); _tmp_list.push_back ( bi ); bag_list->SetItem ( ci2 ); }; CreateHelperItems(dependent_list); if(_list->ItemsCount()!=0) { R_ASSERT(_list->ItemsCount()==1); CInventoryItem* main_item = (CInventoryItem*)_list->GetItemIdx(0)->m_pData; while( bag_list->ItemsCount() ) { u32 cnt = bag_list->ItemsCount(); for(u32 idx=0; idx<cnt; ++idx) { CUICellItem* ci = bag_list->GetItemIdx(idx); SBuyItemInfo* iinfo = FindItem(ci); if(main_item->IsNecessaryItem (iinfo->m_name_sect)) { CUICellItem* ci2 = bag_list->RemoveItem(ci, false); dependent_list->SetItem (ci2); goto _l1; } } break; _l1: ; } } while( !_tmp_list.empty() ) { xr_list<SBuyItemInfo*>::iterator _curr = _tmp_list.begin(); SBuyItemInfo* bi = *(_curr); CUIDragDropListEx* _owner_list = bi->m_cell_item->OwnerList(); if(_owner_list!=bag_list){ _tmp_list.erase ( _curr ); continue; } u32 _bag_cnt = bag_list->ItemsCount(); bool bNecessary = false; for(u32 _i=0; _i<_bag_cnt; ++_i) { CUICellItem* _ci = bag_list->GetItemIdx(_i); CInventoryItem* _ii = (CInventoryItem*)_ci->m_pData; bNecessary = _ii->IsNecessaryItem(bi->m_name_sect); if(bNecessary) { _tmp_list.erase ( _curr ); break; } } if(!bNecessary) { //sell SBuyItemInfo* res_info = NULL; TryToSellItem (bi, true, res_info); xr_list<SBuyItemInfo*>::iterator tmp_it = find(_tmp_list.begin(), _tmp_list.end(), res_info); VERIFY (tmp_it!=_tmp_list.end()); _tmp_list.erase ( tmp_it ); } } } void CUIMpTradeWnd::DestroyItem(SBuyItemInfo* item) { ITEMS_vec_it it = std::find(m_all_items.begin(), m_all_items.end(), item); R_ASSERT (it!= m_all_items.end() ); R_ASSERT (!IsAddonAttached(item,at_scope)); R_ASSERT (!IsAddonAttached(item,at_glauncher)); R_ASSERT (!IsAddonAttached(item,at_silencer)); m_all_items.erase (it); delete_data (item); } struct eq_name_state_comparer { shared_str m_name; SBuyItemInfo::EItmState m_state; eq_name_state_comparer (const shared_str& _name, SBuyItemInfo::EItmState _state):m_name(_name),m_state(_state){} bool operator () (SBuyItemInfo* info) { return (info->m_name_sect==m_name)&&(info->GetState()==m_state); } }; struct eq_name_state_addon_comparer { shared_str m_name; SBuyItemInfo::EItmState m_state; u8 m_addons; eq_name_state_addon_comparer (const shared_str& _name, SBuyItemInfo::EItmState _state, u8 ad):m_name(_name),m_state(_state),m_addons(ad){} bool operator () (SBuyItemInfo* info) { if( (info->m_name_sect==m_name)&&(info->GetState()==m_state) ) { return GetItemAddonsState_ext(info) == m_addons; }else return false; } }; struct eq_group_state_comparer { shared_str m_group; SBuyItemInfo::EItmState m_state; eq_group_state_comparer (const shared_str& _group, SBuyItemInfo::EItmState _state):m_group(_group),m_state(_state){} bool operator () (SBuyItemInfo* info) { if( !info->m_cell_item->IsHelper() && (info->GetState()==m_state)) { const shared_str& _grp = g_mp_restrictions.GetItemGroup(info->m_name_sect); return (_grp==m_group); }else return false; } }; struct eq_state_comparer { SBuyItemInfo::EItmState m_state; eq_state_comparer (SBuyItemInfo::EItmState _state):m_state(_state){} bool operator () (SBuyItemInfo* info) { return (info->GetState()==m_state); } }; u32 CUIMpTradeWnd::GetItemCount(SBuyItemInfo::EItmState state) const { return (u32)std::count_if(m_all_items.begin(), m_all_items.end(),eq_state_comparer(state)); } u32 CUIMpTradeWnd::GetItemCount(const shared_str& name_sect, SBuyItemInfo::EItmState state) const { return (u32)std::count_if(m_all_items.begin(), m_all_items.end(),eq_name_state_comparer(name_sect,state)); } u32 CUIMpTradeWnd::GetItemCount(const shared_str& name_sect, SBuyItemInfo::EItmState state, u8 addon) const { return (u32)std::count_if(m_all_items.begin(), m_all_items.end(),eq_name_state_addon_comparer(name_sect,state,addon)); } u32 CUIMpTradeWnd::GetGroupCount(const shared_str& name_group, SBuyItemInfo::EItmState state) const { return (u32)std::count_if(m_all_items.begin(), m_all_items.end(),eq_group_state_comparer(name_group,state)); } void CUIMpTradeWnd::ClearPreset(ETradePreset idx) { VERIFY (idx<_preset_count); m_preset_storage[idx].clear(); } const preset_items& CUIMpTradeWnd::GetPreset(ETradePreset idx) { VERIFY (idx<_preset_count); return m_preset_storage[idx]; }; u32 _list_prio[]={ 6, // e_pistol 4, // e_pistol_ammo 7, // e_rifle 5, // e_rifle_ammo 10, // e_outfit 9, // e_medkit 8, // e_granade 3, // e_others 2, // e_player_bag 0, // e_shop 0, 0, 0, 0, }; struct preset_sorter { CItemMgr* m_mgr; preset_sorter(CItemMgr* mgr):m_mgr(mgr){}; bool operator() (const _preset_item& i1, const _preset_item& i2) { u8 list_idx1 = m_mgr->GetItemSlotIdx(i1.sect_name); u8 list_idx2 = m_mgr->GetItemSlotIdx(i2.sect_name); return (_list_prio[list_idx1] > _list_prio[list_idx2]); }; }; struct preset_eq { shared_str m_name; u8 m_addon; preset_eq(const shared_str& _name, u8 ad):m_name(_name),m_addon(ad){}; bool operator() (const _preset_item& pitem) { return (pitem.sect_name==m_name)&&(pitem.addon_state==m_addon); }; }; void CUIMpTradeWnd::StorePreset(ETradePreset idx, bool bSilent, bool check_allowed_items, bool flush_helpers) { if ( flush_helpers ) { DeleteHelperItems(); } if(!bSilent) { string512 buff; xr_sprintf (buff, "%s [%d]", CStringTable().translate("ui_st_preset_stored_to").c_str(), idx); SetInfoString (buff); } ITEMS_vec_cit it = m_all_items.begin(); ITEMS_vec_cit it_e = m_all_items.end(); preset_items& v = m_preset_storage[idx]; v.clear_not_free (); for(;it!=it_e; ++it) { SBuyItemInfo* iinfo = *it; if( !(iinfo->GetState()==SBuyItemInfo::e_bought || iinfo->GetState()==SBuyItemInfo::e_own) ) continue; if ( iinfo->m_cell_item->IsHelper() ) { continue; } u8 addon_state = GetItemAddonsState_ext(iinfo); preset_items::iterator fit = std::find_if(v.begin(), v.end(), preset_eq(iinfo->m_name_sect, addon_state) ); if(fit!=v.end()) continue; u32 cnt = GetItemCount(iinfo->m_name_sect, SBuyItemInfo::e_bought, addon_state); cnt +=GetItemCount(iinfo->m_name_sect, SBuyItemInfo::e_own, addon_state); if(0==cnt) continue; if(check_allowed_items) { if(NULL==m_store_hierarchy->FindItem(iinfo->m_name_sect,0)) continue; } v.resize (v.size()+1); _preset_item& _one = v.back(); _one.sect_name = iinfo->m_name_sect; _one.count = cnt; _one.addon_state = addon_state; if(addon_state&at_scope) _one.addon_names[0] = GetAddonNameSect(iinfo, at_scope); if(addon_state&at_glauncher) _one.addon_names[1] = GetAddonNameSect(iinfo, at_glauncher); if(addon_state&at_silencer) _one.addon_names[2] = GetAddonNameSect(iinfo, at_silencer); } std::sort (v.begin(), v.end(), preset_sorter(m_item_mngr)); if ( flush_helpers ) { UpdateHelperItems(); } } void CUIMpTradeWnd::ApplyPreset(ETradePreset idx) { SellAll (); UpdateHelperItems(); const preset_items& v = GetPreset(idx); preset_items::const_iterator it = v.begin(); preset_items::const_iterator it_e = v.end(); for(;it!=it_e;++it) { const _preset_item& _one = *it; u32 _cnt = GetItemCount(_one.sect_name, SBuyItemInfo::e_own); for(u32 i=_cnt; i<_one.count; ++i) { SBuyItemInfo* pitem = CreateItem(_one.sect_name, SBuyItemInfo::e_undefined, false); bool b_res = TryToBuyItem(pitem, bf_normal, NULL ); if(!b_res) { DestroyItem (pitem); }else { if(_one.addon_state) { for(u32 i=0; i<3; ++i) { item_addon_type at = (i==0)?at_scope : ((i==1)?at_glauncher : at_silencer); if(!(_one.addon_state&at) ) continue; shared_str addon_name = GetAddonNameSect(pitem, at); SBuyItemInfo* addon_item = CreateItem(addon_name, SBuyItemInfo::e_undefined, false); bool b_res_addon = TryToBuyItem(addon_item, bf_normal, pitem ); if(!b_res_addon) DestroyItem (addon_item); } } } } } } void CUIMpTradeWnd::CleanUserItems() { SBuyItemInfo* iinfo = NULL; SBuyItemInfo::EItmState _state=SBuyItemInfo::e_bought; for(int i=0; i<3;++i ) { if(i==0) _state = SBuyItemInfo::e_bought; else if(i==1) _state = SBuyItemInfo::e_sold; else if(i==2) _state = SBuyItemInfo::e_own; do{ iinfo = FindItem(_state); if(iinfo) { while( iinfo->m_cell_item->ChildsCount() ) { CUICellItem* iii = iinfo->m_cell_item->PopChild (NULL); SBuyItemInfo* iinfo_sub = FindItem(iii); R_ASSERT2( iinfo_sub->GetState()==_state || iinfo_sub->GetState()==SBuyItemInfo::e_shop || iinfo_sub->GetState()==SBuyItemInfo::e_own, _state_names[_state]); } if(IsAddonAttached(iinfo, at_scope) ) { SBuyItemInfo* detached_addon = DetachAddon(iinfo, at_scope); detached_addon->SetState (SBuyItemInfo::e_undefined); detached_addon->SetState (SBuyItemInfo::e_shop); detached_addon->m_cell_item->SetOwnerList(NULL); } if(IsAddonAttached(iinfo, at_silencer) ) { SBuyItemInfo* detached_addon = DetachAddon(iinfo, at_silencer); detached_addon->SetState (SBuyItemInfo::e_undefined); detached_addon->SetState (SBuyItemInfo::e_shop); detached_addon->m_cell_item->SetOwnerList(NULL); } if(IsAddonAttached(iinfo, at_glauncher) ) { SBuyItemInfo* detached_addon = DetachAddon(iinfo, at_glauncher); detached_addon->SetState (SBuyItemInfo::e_undefined); detached_addon->SetState (SBuyItemInfo::e_shop); detached_addon->m_cell_item->SetOwnerList(NULL); } iinfo->SetState (SBuyItemInfo::e_undefined); iinfo->SetState (SBuyItemInfo::e_shop); iinfo->m_cell_item->SetOwnerList (NULL); } }while(iinfo); } for(u32 i = e_first; i<e_player_total; ++i) m_list[i]->ClearAll (false); } void CUIMpTradeWnd::SellAll() { SBuyItemInfo* iinfo = NULL; SBuyItemInfo* tmp_iinfo = NULL; bool b_ok = true; do{ iinfo = FindItem(SBuyItemInfo::e_bought); if(iinfo) b_ok = TryToSellItem(iinfo, true, tmp_iinfo); R_ASSERT (b_ok); }while(iinfo); do{ iinfo = FindItem(SBuyItemInfo::e_own); if(iinfo) { VERIFY (iinfo->m_cell_item->OwnerList()); CUICellItem* citem = iinfo->m_cell_item->OwnerList()->RemoveItem(iinfo->m_cell_item, false ); SBuyItemInfo* iinfo_int = FindItem(citem); R_ASSERT ( TryToSellItem(iinfo_int, true, tmp_iinfo) ); } }while(iinfo); } void CUIMpTradeWnd::ResetToOrigin() { // 1-sell all bought items // 2-buy all sold items SBuyItemInfo* iinfo = NULL; SBuyItemInfo* tmp_iinfo = NULL; bool b_ok = true; DeleteHelperItems (); do{ iinfo = FindItem(SBuyItemInfo::e_bought); if(iinfo) b_ok = TryToSellItem(iinfo, true, tmp_iinfo); R_ASSERT (b_ok); }while(iinfo); do{ iinfo = FindItem(SBuyItemInfo::e_sold); if(iinfo) b_ok = TryToBuyItem(iinfo, bf_normal, NULL); R_ASSERT (b_ok); }while(iinfo); } void CUIMpTradeWnd::OnBtnSellClicked(CUIWindow* w, void* d) { CheckDragItemToDestroy (); CUIDragDropListEx* pList = m_list[e_player_bag]; SBuyItemInfo* iinfo = NULL; while( pList->ItemsCount() ) { CUICellItem* ci = pList->GetItemIdx(0); iinfo = FindItem(ci); bool b_ok = true; SBuyItemInfo* tmp_iinfo = NULL; b_ok = TryToSellItem(iinfo, true, tmp_iinfo); R_ASSERT (b_ok); } } void CUIMpTradeWnd::SetupPlayerItemsBegin() { for(int idx = e_first; idx<e_player_total; ++idx) { CUIDragDropListEx* lst = m_list[idx]; R_ASSERT(0==lst->ItemsCount()); } UpdateHelperItems(); } void CUIMpTradeWnd::SetupPlayerItemsEnd() { StorePreset (_preset_idx_origin, true, false, true); } void CUIMpTradeWnd::SetupDefaultItemsBegin() { SetupPlayerItemsBegin(); } void CUIMpTradeWnd::SetupDefaultItemsEnd() { StorePreset (_preset_idx_default, true, false, true); } void CUIMpTradeWnd::CheckDragItemToDestroy() { if(CUIDragDropListEx::m_drag_item && CUIDragDropListEx::m_drag_item->ParentItem()) { CUIDragDropListEx* _drag_owner = CUIDragDropListEx::m_drag_item->ParentItem()->OwnerList(); _drag_owner->DestroyDragItem (); } } struct items_sorter { items_sorter(){}; bool operator() (SBuyItemInfo* i1, SBuyItemInfo* i2) { if(i1->m_name_sect == i2->m_name_sect) return i1->GetState()<i2->GetState(); return i1->m_name_sect < i2->m_name_sect; }; }; void CUIMpTradeWnd::DumpAllItems(LPCSTR s) { std::sort (m_all_items.begin(), m_all_items.end(), items_sorter()); #ifndef MASTER_GOLD Msg("CUIMpTradeWnd::DumpAllItems.total[%d] reason [%s]", m_all_items.size(), s); ITEMS_vec_cit it = m_all_items.begin(); ITEMS_vec_cit it_e = m_all_items.end(); for(;it!=it_e;++it) { SBuyItemInfo* iinfo = *it; Msg("[%s] state[%s]", iinfo->m_name_sect.c_str(), iinfo->GetStateAsText()); } Msg("------"); #endif // #ifndef MASTER_GOLD } void CUIMpTradeWnd::DumpPreset(ETradePreset idx) { #ifndef MASTER_GOLD const preset_items& v = GetPreset(idx); preset_items::const_iterator it = v.begin(); preset_items::const_iterator it_e = v.end(); Msg("dump preset [%d]", idx); for(;it!=it_e;++it) { const _preset_item& _one = *it; Msg("[%s]-[%d]", _one.sect_name.c_str(), _one.count); if(_one.addon_names[0].c_str()) Msg(" [%s]",_one.addon_names[0].c_str()); if(_one.addon_names[1].c_str()) Msg(" [%s]",_one.addon_names[1].c_str()); if(_one.addon_names[2].c_str()) Msg(" [%s]",_one.addon_names[2].c_str()); } #endif // #ifndef MASTER_GOLD } #include <dinput.h> void CUICellItemTradeMenuDraw::OnDraw(CUICellItem* cell) { Fvector2 pos; cell->GetAbsolutePos (pos); UI().ClientToScreenScaled (pos, pos.x, pos.y); int acc = cell->GetAccelerator(); if(acc!=0) { if(acc==11) acc = 1; string64 buff; xr_sprintf (buff," %d", acc - DIK_ESCAPE); CGameFont* pFont = UI().Font().pFontLetterica16Russian; pFont->SetAligment (CGameFont::alCenter); pFont->SetColor (color_rgba(135,123,116,255)); pFont->Out (pos.x, pos.y, buff); pFont->OnRender (); } bool b_can_buy_rank = m_trade_wnd->CheckBuyPossibility(m_info_item->m_name_sect, CUIMpTradeWnd::bf_check_rank_restr, true); if(!b_can_buy_rank) { cell->SetTextureColor (m_trade_wnd->m_item_color_restr_rank); return; } bool b_can_buy_money = m_trade_wnd->CheckBuyPossibility(m_info_item->m_name_sect, CUIMpTradeWnd::bf_check_money, true); if(!b_can_buy_money) { cell->SetTextureColor (m_trade_wnd->m_item_color_restr_money); return; } cell->SetTextureColor (m_trade_wnd->m_item_color_normal); }
25.703664
140
0.657779
[ "object" ]
603b22811c17b655e538a9f254b4d94c3d6b223f
75,107
cc
C++
Validation/pyFrame3DD-master/gcc-master/gcc/analyzer/constraint-manager.cc
djamal2727/Main-Bearing-Analytical-Model
2f00c2219c71be0175c6f4f8f1d4cca231d97096
[ "Apache-2.0" ]
null
null
null
Validation/pyFrame3DD-master/gcc-master/gcc/analyzer/constraint-manager.cc
djamal2727/Main-Bearing-Analytical-Model
2f00c2219c71be0175c6f4f8f1d4cca231d97096
[ "Apache-2.0" ]
null
null
null
Validation/pyFrame3DD-master/gcc-master/gcc/analyzer/constraint-manager.cc
djamal2727/Main-Bearing-Analytical-Model
2f00c2219c71be0175c6f4f8f1d4cca231d97096
[ "Apache-2.0" ]
null
null
null
/* Tracking equivalence classes and constraints at a point on an execution path. Copyright (C) 2019-2020 Free Software Foundation, Inc. Contributed by David Malcolm <dmalcolm@redhat.com>. This file is part of GCC. GCC is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3, or (at your option) any later version. GCC is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with GCC; see the file COPYING3. If not see <http://www.gnu.org/licenses/>. */ #include "config.h" #include "system.h" #include "coretypes.h" #include "tree.h" #include "function.h" #include "basic-block.h" #include "gimple.h" #include "gimple-iterator.h" #include "fold-const.h" #include "selftest.h" #include "diagnostic-core.h" #include "graphviz.h" #include "function.h" #include "json.h" #include "analyzer/analyzer.h" #include "ordered-hash-map.h" #include "options.h" #include "cgraph.h" #include "cfg.h" #include "digraph.h" #include "analyzer/supergraph.h" #include "sbitmap.h" #include "bitmap.h" #include "tristate.h" #include "analyzer/call-string.h" #include "analyzer/program-point.h" #include "analyzer/store.h" #include "analyzer/region-model.h" #include "analyzer/constraint-manager.h" #include "analyzer/analyzer-selftests.h" #if ENABLE_ANALYZER namespace ana { static tristate compare_constants (tree lhs_const, enum tree_code op, tree rhs_const) { tree comparison = fold_binary (op, boolean_type_node, lhs_const, rhs_const); if (comparison == boolean_true_node) return tristate (tristate::TS_TRUE); if (comparison == boolean_false_node) return tristate (tristate::TS_FALSE); return tristate (tristate::TS_UNKNOWN); } /* struct bound. */ /* Ensure that this bound is closed by converting an open bound to a closed one. */ void bound::ensure_closed (bool is_upper) { if (!m_closed) { /* Offset by 1 in the appropriate direction. For example, convert 3 < x into 4 <= x, and convert x < 5 into x <= 4. */ gcc_assert (CONSTANT_CLASS_P (m_constant)); m_constant = fold_build2 (is_upper ? MINUS_EXPR : PLUS_EXPR, TREE_TYPE (m_constant), m_constant, integer_one_node); gcc_assert (CONSTANT_CLASS_P (m_constant)); m_closed = true; } } /* Get "<=" vs "<" for this bound. */ const char * bound::get_relation_as_str () const { if (m_closed) return "<="; else return "<"; } /* struct range. */ /* Dump this range to PP, which must support %E for tree. */ void range::dump_to_pp (pretty_printer *pp) const { if (m_lower_bound.m_constant) { if (m_upper_bound.m_constant) pp_printf (pp, "%qE %s x %s %qE", m_lower_bound.m_constant, m_lower_bound.get_relation_as_str (), m_upper_bound.get_relation_as_str (), m_upper_bound.m_constant); else pp_printf (pp, "%qE %s x", m_lower_bound.m_constant, m_lower_bound.get_relation_as_str ()); } else { if (m_upper_bound.m_constant) pp_printf (pp, "x %s %qE", m_upper_bound.get_relation_as_str (), m_upper_bound.m_constant); else pp_string (pp, "x"); } } /* Dump this range to stderr. */ DEBUG_FUNCTION void range::dump () const { pretty_printer pp; pp_format_decoder (&pp) = default_tree_printer; pp_show_color (&pp) = pp_show_color (global_dc->printer); pp.buffer->stream = stderr; dump_to_pp (&pp); pp_newline (&pp); pp_flush (&pp); } /* Determine if there is only one possible value for this range. If so, return the constant; otherwise, return NULL_TREE. */ tree range::constrained_to_single_element () { if (m_lower_bound.m_constant == NULL_TREE || m_upper_bound.m_constant == NULL_TREE) return NULL_TREE; if (!INTEGRAL_TYPE_P (TREE_TYPE (m_lower_bound.m_constant))) return NULL_TREE; if (!INTEGRAL_TYPE_P (TREE_TYPE (m_upper_bound.m_constant))) return NULL_TREE; /* Convert any open bounds to closed bounds. */ m_lower_bound.ensure_closed (false); m_upper_bound.ensure_closed (true); // Are they equal? tree comparison = fold_binary (EQ_EXPR, boolean_type_node, m_lower_bound.m_constant, m_upper_bound.m_constant); if (comparison == boolean_true_node) return m_lower_bound.m_constant; else return NULL_TREE; } /* Eval the condition "X OP RHS_CONST" for X within the range. */ tristate range::eval_condition (enum tree_code op, tree rhs_const) const { range copy (*this); if (tree single_element = copy.constrained_to_single_element ()) return compare_constants (single_element, op, rhs_const); switch (op) { case EQ_EXPR: if (below_lower_bound (rhs_const)) return tristate (tristate::TS_FALSE); if (above_upper_bound (rhs_const)) return tristate (tristate::TS_FALSE); break; case LT_EXPR: case LE_EXPR: /* Qn: "X </<= RHS_CONST". */ /* If RHS_CONST > upper bound, then it's true. If RHS_CONST < lower bound, then it's false. Otherwise unknown. */ if (above_upper_bound (rhs_const)) return tristate (tristate::TS_TRUE); if (below_lower_bound (rhs_const)) return tristate (tristate::TS_FALSE); break; case NE_EXPR: /* Qn: "X != RHS_CONST". */ /* If RHS_CONST < lower bound, then it's true. If RHS_CONST > upper bound, then it's false. Otherwise unknown. */ if (below_lower_bound (rhs_const)) return tristate (tristate::TS_TRUE); if (above_upper_bound (rhs_const)) return tristate (tristate::TS_TRUE); break; case GE_EXPR: case GT_EXPR: /* Qn: "X >=/> RHS_CONST". */ if (above_upper_bound (rhs_const)) return tristate (tristate::TS_FALSE); if (below_lower_bound (rhs_const)) return tristate (tristate::TS_TRUE); break; default: gcc_unreachable (); break; } return tristate (tristate::TS_UNKNOWN); } /* Return true if RHS_CONST is below the lower bound of this range. */ bool range::below_lower_bound (tree rhs_const) const { if (!m_lower_bound.m_constant) return false; return compare_constants (rhs_const, m_lower_bound.m_closed ? LT_EXPR : LE_EXPR, m_lower_bound.m_constant).is_true (); } /* Return true if RHS_CONST is above the upper bound of this range. */ bool range::above_upper_bound (tree rhs_const) const { if (!m_upper_bound.m_constant) return false; return compare_constants (rhs_const, m_upper_bound.m_closed ? GT_EXPR : GE_EXPR, m_upper_bound.m_constant).is_true (); } /* class equiv_class. */ /* equiv_class's default ctor. */ equiv_class::equiv_class () : m_constant (NULL_TREE), m_cst_sval (NULL), m_vars () { } /* equiv_class's copy ctor. */ equiv_class::equiv_class (const equiv_class &other) : m_constant (other.m_constant), m_cst_sval (other.m_cst_sval), m_vars (other.m_vars.length ()) { int i; const svalue *sval; FOR_EACH_VEC_ELT (other.m_vars, i, sval) m_vars.quick_push (sval); } /* Print an all-on-one-line representation of this equiv_class to PP, which must support %E for trees. */ void equiv_class::print (pretty_printer *pp) const { pp_character (pp, '{'); int i; const svalue *sval; FOR_EACH_VEC_ELT (m_vars, i, sval) { if (i > 0) pp_string (pp, " == "); sval->dump_to_pp (pp, true); } if (m_constant) { if (i > 0) pp_string (pp, " == "); pp_printf (pp, "[m_constant]%qE", m_constant); } pp_character (pp, '}'); } /* Return a new json::object of the form {"svals" : [str], "constant" : optional str}. */ json::object * equiv_class::to_json () const { json::object *ec_obj = new json::object (); json::array *sval_arr = new json::array (); int i; const svalue *sval; FOR_EACH_VEC_ELT (m_vars, i, sval) sval_arr->append (sval->to_json ()); ec_obj->set ("svals", sval_arr); if (m_constant) { pretty_printer pp; pp_format_decoder (&pp) = default_tree_printer; pp_printf (&pp, "%qE", m_constant); ec_obj->set ("constant", new json::string (pp_formatted_text (&pp))); } return ec_obj; } /* Generate a hash value for this equiv_class. This relies on the ordering of m_vars, and so this object needs to have been canonicalized for this to be meaningful. */ hashval_t equiv_class::hash () const { inchash::hash hstate; inchash::add_expr (m_constant, hstate); int i; const svalue *sval; FOR_EACH_VEC_ELT (m_vars, i, sval) hstate.add_ptr (sval); return hstate.end (); } /* Equality operator for equiv_class. This relies on the ordering of m_vars, and so this object and OTHER need to have been canonicalized for this to be meaningful. */ bool equiv_class::operator== (const equiv_class &other) { if (m_constant != other.m_constant) return false; // TODO: use tree equality here? /* FIXME: should we compare m_cst_sval? */ if (m_vars.length () != other.m_vars.length ()) return false; int i; const svalue *sval; FOR_EACH_VEC_ELT (m_vars, i, sval) if (sval != other.m_vars[i]) return false; return true; } /* Add SID to this equiv_class, using CM to check if it's a constant. */ void equiv_class::add (const svalue *sval) { gcc_assert (sval); if (tree cst = sval->maybe_get_constant ()) { gcc_assert (CONSTANT_CLASS_P (cst)); /* FIXME: should we canonicalize which svalue is the constant when there are multiple equal constants? */ m_constant = cst; m_cst_sval = sval; } m_vars.safe_push (sval); } /* Remove SID from this equivalence class. Return true if SID was the last var in the equivalence class (suggesting a possible leak). */ bool equiv_class::del (const svalue *sval) { gcc_assert (sval); gcc_assert (sval != m_cst_sval); int i; const svalue *iv; FOR_EACH_VEC_ELT (m_vars, i, iv) { if (iv == sval) { m_vars[i] = m_vars[m_vars.length () - 1]; m_vars.pop (); return m_vars.length () == 0; } } /* SVAL must be in the class. */ gcc_unreachable (); return false; } /* Get a representative member of this class, for handling cases where the IDs can change mid-traversal. */ const svalue * equiv_class::get_representative () const { gcc_assert (m_vars.length () > 0); return m_vars[0]; } /* Comparator for use by equiv_class::canonicalize. */ static int svalue_cmp_by_ptr (const void *p1, const void *p2) { const svalue *sval1 = *(const svalue * const *)p1; const svalue *sval2 = *(const svalue * const *)p2; if (sval1 < sval2) return 1; if (sval1 > sval2) return -1; return 0; } /* Sort the svalues within this equiv_class. */ void equiv_class::canonicalize () { m_vars.qsort (svalue_cmp_by_ptr); } /* Get a debug string for C_OP. */ const char * constraint_op_code (enum constraint_op c_op) { switch (c_op) { default: gcc_unreachable (); case CONSTRAINT_NE: return "!="; case CONSTRAINT_LT: return "<"; case CONSTRAINT_LE: return "<="; } } /* Convert C_OP to an enum tree_code. */ enum tree_code constraint_tree_code (enum constraint_op c_op) { switch (c_op) { default: gcc_unreachable (); case CONSTRAINT_NE: return NE_EXPR; case CONSTRAINT_LT: return LT_EXPR; case CONSTRAINT_LE: return LE_EXPR; } } /* Given "lhs C_OP rhs", determine "lhs T_OP rhs". For example, given "x < y", then "x > y" is false. */ static tristate eval_constraint_op_for_op (enum constraint_op c_op, enum tree_code t_op) { switch (c_op) { default: gcc_unreachable (); case CONSTRAINT_NE: if (t_op == EQ_EXPR) return tristate (tristate::TS_FALSE); if (t_op == NE_EXPR) return tristate (tristate::TS_TRUE); break; case CONSTRAINT_LT: if (t_op == LT_EXPR || t_op == LE_EXPR || t_op == NE_EXPR) return tristate (tristate::TS_TRUE); if (t_op == EQ_EXPR || t_op == GT_EXPR || t_op == GE_EXPR) return tristate (tristate::TS_FALSE); break; case CONSTRAINT_LE: if (t_op == LE_EXPR) return tristate (tristate::TS_TRUE); if (t_op == GT_EXPR) return tristate (tristate::TS_FALSE); break; } return tristate (tristate::TS_UNKNOWN); } /* class constraint. */ /* Print this constraint to PP (which must support %E for trees), using CM to look up equiv_class instances from ids. */ void constraint::print (pretty_printer *pp, const constraint_manager &cm) const { m_lhs.print (pp); pp_string (pp, ": "); m_lhs.get_obj (cm).print (pp); pp_string (pp, " "); pp_string (pp, constraint_op_code (m_op)); pp_string (pp, " "); m_rhs.print (pp); pp_string (pp, ": "); m_rhs.get_obj (cm).print (pp); } /* Return a new json::object of the form {"lhs" : int, the EC index "op" : str, "rhs" : int, the EC index}. */ json::object * constraint::to_json () const { json::object *con_obj = new json::object (); con_obj->set ("lhs", new json::integer_number (m_lhs.as_int ())); con_obj->set ("op", new json::string (constraint_op_code (m_op))); con_obj->set ("rhs", new json::integer_number (m_rhs.as_int ())); return con_obj; } /* Generate a hash value for this constraint. */ hashval_t constraint::hash () const { inchash::hash hstate; hstate.add_int (m_lhs.m_idx); hstate.add_int (m_op); hstate.add_int (m_rhs.m_idx); return hstate.end (); } /* Equality operator for constraints. */ bool constraint::operator== (const constraint &other) const { if (m_lhs != other.m_lhs) return false; if (m_op != other.m_op) return false; if (m_rhs != other.m_rhs) return false; return true; } /* Return true if this constraint is implied by OTHER. */ bool constraint::implied_by (const constraint &other, const constraint_manager &cm) const { if (m_lhs == other.m_lhs) if (tree rhs_const = m_rhs.get_obj (cm).get_any_constant ()) if (tree other_rhs_const = other.m_rhs.get_obj (cm).get_any_constant ()) if (m_lhs.get_obj (cm).get_any_constant () == NULL_TREE) if (m_op == other.m_op) switch (m_op) { default: break; case CONSTRAINT_LE: case CONSTRAINT_LT: if (compare_constants (rhs_const, GE_EXPR, other_rhs_const).is_true ()) return true; break; } return false; } /* class equiv_class_id. */ /* Get the underlying equiv_class for this ID from CM. */ const equiv_class & equiv_class_id::get_obj (const constraint_manager &cm) const { return cm.get_equiv_class_by_index (m_idx); } /* Access the underlying equiv_class for this ID from CM. */ equiv_class & equiv_class_id::get_obj (constraint_manager &cm) const { return cm.get_equiv_class_by_index (m_idx); } /* Print this equiv_class_id to PP. */ void equiv_class_id::print (pretty_printer *pp) const { if (null_p ()) pp_printf (pp, "null"); else pp_printf (pp, "ec%i", m_idx); } /* class constraint_manager. */ /* constraint_manager's copy ctor. */ constraint_manager::constraint_manager (const constraint_manager &other) : m_equiv_classes (other.m_equiv_classes.length ()), m_constraints (other.m_constraints.length ()), m_mgr (other.m_mgr) { int i; equiv_class *ec; FOR_EACH_VEC_ELT (other.m_equiv_classes, i, ec) m_equiv_classes.quick_push (new equiv_class (*ec)); constraint *c; FOR_EACH_VEC_ELT (other.m_constraints, i, c) m_constraints.quick_push (*c); } /* constraint_manager's assignment operator. */ constraint_manager& constraint_manager::operator= (const constraint_manager &other) { gcc_assert (m_equiv_classes.length () == 0); gcc_assert (m_constraints.length () == 0); int i; equiv_class *ec; m_equiv_classes.reserve (other.m_equiv_classes.length ()); FOR_EACH_VEC_ELT (other.m_equiv_classes, i, ec) m_equiv_classes.quick_push (new equiv_class (*ec)); constraint *c; m_constraints.reserve (other.m_constraints.length ()); FOR_EACH_VEC_ELT (other.m_constraints, i, c) m_constraints.quick_push (*c); return *this; } /* Generate a hash value for this constraint_manager. */ hashval_t constraint_manager::hash () const { inchash::hash hstate; int i; equiv_class *ec; constraint *c; FOR_EACH_VEC_ELT (m_equiv_classes, i, ec) hstate.merge_hash (ec->hash ()); FOR_EACH_VEC_ELT (m_constraints, i, c) hstate.merge_hash (c->hash ()); return hstate.end (); } /* Equality operator for constraint_manager. */ bool constraint_manager::operator== (const constraint_manager &other) const { if (m_equiv_classes.length () != other.m_equiv_classes.length ()) return false; if (m_constraints.length () != other.m_constraints.length ()) return false; int i; equiv_class *ec; FOR_EACH_VEC_ELT (m_equiv_classes, i, ec) if (!(*ec == *other.m_equiv_classes[i])) return false; constraint *c; FOR_EACH_VEC_ELT (m_constraints, i, c) if (!(*c == other.m_constraints[i])) return false; return true; } /* Print this constraint_manager to PP (which must support %E for trees). */ void constraint_manager::print (pretty_printer *pp) const { pp_string (pp, "{"); int i; equiv_class *ec; FOR_EACH_VEC_ELT (m_equiv_classes, i, ec) { if (i > 0) pp_string (pp, ", "); equiv_class_id (i).print (pp); pp_string (pp, ": "); ec->print (pp); } pp_string (pp, " | "); constraint *c; FOR_EACH_VEC_ELT (m_constraints, i, c) { if (i > 0) pp_string (pp, " && "); c->print (pp, *this); } pp_printf (pp, "}"); } /* Dump a representation of this constraint_manager to PP (which must support %E for trees). */ void constraint_manager::dump_to_pp (pretty_printer *pp, bool multiline) const { if (multiline) pp_string (pp, " "); pp_string (pp, "equiv classes:"); if (multiline) pp_newline (pp); else pp_string (pp, " {"); int i; equiv_class *ec; FOR_EACH_VEC_ELT (m_equiv_classes, i, ec) { if (multiline) pp_string (pp, " "); else if (i > 0) pp_string (pp, ", "); equiv_class_id (i).print (pp); pp_string (pp, ": "); ec->print (pp); if (multiline) pp_newline (pp); } if (multiline) pp_string (pp, " "); else pp_string (pp, "}"); pp_string (pp, "constraints:"); if (multiline) pp_newline (pp); else pp_string (pp, "{"); constraint *c; FOR_EACH_VEC_ELT (m_constraints, i, c) { if (multiline) pp_string (pp, " "); pp_printf (pp, "%i: ", i); c->print (pp, *this); if (multiline) pp_newline (pp); } if (!multiline) pp_string (pp, "}"); } /* Dump a multiline representation of this constraint_manager to FP. */ void constraint_manager::dump (FILE *fp) const { pretty_printer pp; pp_format_decoder (&pp) = default_tree_printer; pp_show_color (&pp) = pp_show_color (global_dc->printer); pp.buffer->stream = fp; dump_to_pp (&pp, true); pp_flush (&pp); } /* Dump a multiline representation of this constraint_manager to stderr. */ DEBUG_FUNCTION void constraint_manager::dump () const { dump (stderr); } /* Dump a multiline representation of CM to stderr. */ DEBUG_FUNCTION void debug (const constraint_manager &cm) { cm.dump (); } /* Return a new json::object of the form {"ecs" : array of objects, one per equiv_class "constraints" : array of objects, one per constraint}. */ json::object * constraint_manager::to_json () const { json::object *cm_obj = new json::object (); /* Equivalence classes. */ { json::array *ec_arr = new json::array (); int i; equiv_class *ec; FOR_EACH_VEC_ELT (m_equiv_classes, i, ec) ec_arr->append (ec->to_json ()); cm_obj->set ("ecs", ec_arr); } /* Constraints. */ { json::array *con_arr = new json::array (); int i; constraint *c; FOR_EACH_VEC_ELT (m_constraints, i, c) con_arr->append (c->to_json ()); cm_obj->set ("constraints", con_arr); } return cm_obj; } /* Attempt to add the constraint LHS OP RHS to this constraint_manager. Return true if the constraint could be added (or is already true). Return false if the constraint contradicts existing knowledge. */ bool constraint_manager::add_constraint (const svalue *lhs, enum tree_code op, const svalue *rhs) { lhs = lhs->unwrap_any_unmergeable (); rhs = rhs->unwrap_any_unmergeable (); /* Nothing can be known about unknown values. */ if (lhs->get_kind () == SK_UNKNOWN || rhs->get_kind () == SK_UNKNOWN) /* Not a contradiction. */ return true; /* Check the conditions on svalues. */ { tristate t_cond = eval_condition (lhs, op, rhs); /* If we already have the condition, do nothing. */ if (t_cond.is_true ()) return true; /* Reject a constraint that would contradict existing knowledge, as unsatisfiable. */ if (t_cond.is_false ()) return false; } equiv_class_id lhs_ec_id = get_or_add_equiv_class (lhs); equiv_class_id rhs_ec_id = get_or_add_equiv_class (rhs); /* Check the stronger conditions on ECs. */ { tristate t = eval_condition (lhs_ec_id, op, rhs_ec_id); /* Discard constraints that are already known. */ if (t.is_true ()) return true; /* Reject unsatisfiable constraints. */ if (t.is_false ()) return false; } add_unknown_constraint (lhs_ec_id, op, rhs_ec_id); return true; } /* Attempt to add the constraint LHS_EC_ID OP RHS_EC_ID to this constraint_manager. Return true if the constraint could be added (or is already true). Return false if the constraint contradicts existing knowledge. */ bool constraint_manager::add_constraint (equiv_class_id lhs_ec_id, enum tree_code op, equiv_class_id rhs_ec_id) { tristate t = eval_condition (lhs_ec_id, op, rhs_ec_id); /* Discard constraints that are already known. */ if (t.is_true ()) return true; /* Reject unsatisfiable constraints. */ if (t.is_false ()) return false; add_unknown_constraint (lhs_ec_id, op, rhs_ec_id); return true; } /* Add the constraint LHS_EC_ID OP RHS_EC_ID to this constraint_manager, where the constraint has already been checked for being "unknown". */ void constraint_manager::add_unknown_constraint (equiv_class_id lhs_ec_id, enum tree_code op, equiv_class_id rhs_ec_id) { gcc_assert (lhs_ec_id != rhs_ec_id); /* For now, simply accumulate constraints, without attempting any further optimization. */ switch (op) { case EQ_EXPR: { /* Merge rhs_ec into lhs_ec. */ equiv_class &lhs_ec_obj = lhs_ec_id.get_obj (*this); const equiv_class &rhs_ec_obj = rhs_ec_id.get_obj (*this); int i; const svalue *sval; FOR_EACH_VEC_ELT (rhs_ec_obj.m_vars, i, sval) lhs_ec_obj.add (sval); if (rhs_ec_obj.m_constant) { lhs_ec_obj.m_constant = rhs_ec_obj.m_constant; lhs_ec_obj.m_cst_sval = rhs_ec_obj.m_cst_sval; } /* Drop rhs equivalence class, overwriting it with the final ec (which might be the same one). */ equiv_class_id final_ec_id = m_equiv_classes.length () - 1; equiv_class *old_ec = m_equiv_classes[rhs_ec_id.m_idx]; equiv_class *final_ec = m_equiv_classes.pop (); if (final_ec != old_ec) m_equiv_classes[rhs_ec_id.m_idx] = final_ec; delete old_ec; /* Update the constraints. */ constraint *c; FOR_EACH_VEC_ELT (m_constraints, i, c) { /* Update references to the rhs_ec so that they refer to the lhs_ec. */ if (c->m_lhs == rhs_ec_id) c->m_lhs = lhs_ec_id; if (c->m_rhs == rhs_ec_id) c->m_rhs = lhs_ec_id; /* Renumber all constraints that refer to the final rhs_ec to the old rhs_ec, where the old final_ec now lives. */ if (c->m_lhs == final_ec_id) c->m_lhs = rhs_ec_id; if (c->m_rhs == final_ec_id) c->m_rhs = rhs_ec_id; } /* We may now have self-comparisons due to the merger; these constraints should be removed. */ unsigned read_index, write_index; VEC_ORDERED_REMOVE_IF (m_constraints, read_index, write_index, c, (c->m_lhs == c->m_rhs)); } break; case GE_EXPR: add_constraint_internal (rhs_ec_id, CONSTRAINT_LE, lhs_ec_id); break; case LE_EXPR: add_constraint_internal (lhs_ec_id, CONSTRAINT_LE, rhs_ec_id); break; case NE_EXPR: add_constraint_internal (lhs_ec_id, CONSTRAINT_NE, rhs_ec_id); break; case GT_EXPR: add_constraint_internal (rhs_ec_id, CONSTRAINT_LT, lhs_ec_id); break; case LT_EXPR: add_constraint_internal (lhs_ec_id, CONSTRAINT_LT, rhs_ec_id); break; default: /* do nothing. */ break; } validate (); } /* Subroutine of constraint_manager::add_constraint, for handling all operations other than equality (for which equiv classes are merged). */ void constraint_manager::add_constraint_internal (equiv_class_id lhs_id, enum constraint_op c_op, equiv_class_id rhs_id) { if (m_constraints.length () >= (unsigned)param_analyzer_max_constraints) return; constraint new_c (lhs_id, c_op, rhs_id); /* Remove existing constraints that would be implied by the new constraint. */ unsigned read_index, write_index; constraint *c; VEC_ORDERED_REMOVE_IF (m_constraints, read_index, write_index, c, (c->implied_by (new_c, *this))); /* Add the constraint. */ m_constraints.safe_push (new_c); if (!flag_analyzer_transitivity) return; if (c_op != CONSTRAINT_NE) { /* The following can potentially add EQ_EXPR facts, which could lead to ECs being merged, which would change the meaning of the EC IDs. Hence we need to do this via representatives. */ const svalue *lhs = lhs_id.get_obj (*this).get_representative (); const svalue *rhs = rhs_id.get_obj (*this).get_representative (); /* We have LHS </<= RHS */ /* Handle transitivity of ordering by adding additional constraints based on what we already knew. So if we have already have: (a < b) (c < d) Then adding: (b < c) will also add: (a < c) (b < d) We need to recurse to ensure we also add: (a < d). We call the checked add_constraint to avoid adding constraints that are already present. Doing so also ensures termination in the case of cycles. We also check for single-element ranges, adding EQ_EXPR facts where we discover them. For example 3 < x < 5 implies that x == 4 (if x is an integer). */ for (unsigned i = 0; i < m_constraints.length (); i++) { const constraint *other = &m_constraints[i]; if (other->is_ordering_p ()) { /* Refresh the EC IDs, in case any mergers have happened. */ lhs_id = get_or_add_equiv_class (lhs); rhs_id = get_or_add_equiv_class (rhs); tree lhs_const = lhs_id.get_obj (*this).m_constant; tree rhs_const = rhs_id.get_obj (*this).m_constant; tree other_lhs_const = other->m_lhs.get_obj (*this).m_constant; tree other_rhs_const = other->m_rhs.get_obj (*this).m_constant; /* We have "LHS </<= RHS" and "other.lhs </<= other.rhs". */ /* If we have LHS </<= RHS and RHS </<= LHS, then we have a cycle. */ if (rhs_id == other->m_lhs && other->m_rhs == lhs_id) { /* We must have equality for this to be possible. */ gcc_assert (c_op == CONSTRAINT_LE && other->m_op == CONSTRAINT_LE); add_constraint (lhs_id, EQ_EXPR, rhs_id); /* Adding an equality will merge the two ECs and potentially reorganize the constraints. Stop iterating. */ return; } /* Otherwise, check for transitivity. */ if (rhs_id == other->m_lhs) { /* With RHS == other.lhs, we have: "LHS </<= (RHS, other.lhs) </<= other.rhs" and thus this implies "LHS </<= other.rhs". */ /* Do we have a tightly-constrained range? */ if (lhs_const && !rhs_const && other_rhs_const) { range r (bound (lhs_const, c_op == CONSTRAINT_LE), bound (other_rhs_const, other->m_op == CONSTRAINT_LE)); if (tree constant = r.constrained_to_single_element ()) { const svalue *cst_sval = m_mgr->get_or_create_constant_svalue (constant); add_constraint (rhs_id, EQ_EXPR, get_or_add_equiv_class (cst_sval)); return; } } /* Otherwise, add the constraint implied by transitivity. */ enum tree_code new_op = ((c_op == CONSTRAINT_LE && other->m_op == CONSTRAINT_LE) ? LE_EXPR : LT_EXPR); add_constraint (lhs_id, new_op, other->m_rhs); } else if (other->m_rhs == lhs_id) { /* With other.rhs == LHS, we have: "other.lhs </<= (other.rhs, LHS) </<= RHS" and thus this implies "other.lhs </<= RHS". */ /* Do we have a tightly-constrained range? */ if (other_lhs_const && !lhs_const && rhs_const) { range r (bound (other_lhs_const, other->m_op == CONSTRAINT_LE), bound (rhs_const, c_op == CONSTRAINT_LE)); if (tree constant = r.constrained_to_single_element ()) { const svalue *cst_sval = m_mgr->get_or_create_constant_svalue (constant); add_constraint (lhs_id, EQ_EXPR, get_or_add_equiv_class (cst_sval)); return; } } /* Otherwise, add the constraint implied by transitivity. */ enum tree_code new_op = ((c_op == CONSTRAINT_LE && other->m_op == CONSTRAINT_LE) ? LE_EXPR : LT_EXPR); add_constraint (other->m_lhs, new_op, rhs_id); } } } } } /* Look for SVAL within the equivalence classes of this constraint_manager; if found, return true, writing the id to *OUT if OUT is non-NULL, otherwise return false. */ bool constraint_manager::get_equiv_class_by_svalue (const svalue *sval, equiv_class_id *out) const { /* TODO: should we have a map, rather than these searches? */ int i; equiv_class *ec; FOR_EACH_VEC_ELT (m_equiv_classes, i, ec) { int j; const svalue *iv; FOR_EACH_VEC_ELT (ec->m_vars, j, iv) if (iv == sval) { if (out) *out = equiv_class_id (i); return true; } } return false; } /* Ensure that SVAL has an equivalence class within this constraint_manager; return the ID of the class. */ equiv_class_id constraint_manager::get_or_add_equiv_class (const svalue *sval) { equiv_class_id result (-1); gcc_assert (sval->get_kind () != SK_UNKNOWN); /* Convert all NULL pointers to (void *) to avoid state explosions involving all of the various (foo *)NULL vs (bar *)NULL. */ if (POINTER_TYPE_P (sval->get_type ())) if (tree cst = sval->maybe_get_constant ()) if (zerop (cst)) sval = m_mgr->get_or_create_constant_svalue (null_pointer_node); /* Try svalue match. */ if (get_equiv_class_by_svalue (sval, &result)) return result; /* Try equality of constants. */ if (tree cst = sval->maybe_get_constant ()) { int i; equiv_class *ec; FOR_EACH_VEC_ELT (m_equiv_classes, i, ec) if (ec->m_constant && types_compatible_p (TREE_TYPE (cst), TREE_TYPE (ec->m_constant))) { tree eq = fold_binary (EQ_EXPR, boolean_type_node, cst, ec->m_constant); if (eq == boolean_true_node) { ec->add (sval); return equiv_class_id (i); } } } /* Not found. */ equiv_class *new_ec = new equiv_class (); new_ec->add (sval); m_equiv_classes.safe_push (new_ec); equiv_class_id new_id (m_equiv_classes.length () - 1); return new_id; } /* Evaluate the condition LHS_EC OP RHS_EC. */ tristate constraint_manager::eval_condition (equiv_class_id lhs_ec, enum tree_code op, equiv_class_id rhs_ec) const { if (lhs_ec == rhs_ec) { switch (op) { case EQ_EXPR: case GE_EXPR: case LE_EXPR: return tristate (tristate::TS_TRUE); case NE_EXPR: case GT_EXPR: case LT_EXPR: return tristate (tristate::TS_FALSE); default: break; } } tree lhs_const = lhs_ec.get_obj (*this).get_any_constant (); tree rhs_const = rhs_ec.get_obj (*this).get_any_constant (); if (lhs_const && rhs_const) { tristate result_for_constants = compare_constants (lhs_const, op, rhs_const); if (result_for_constants.is_known ()) return result_for_constants; } enum tree_code swapped_op = swap_tree_comparison (op); int i; constraint *c; FOR_EACH_VEC_ELT (m_constraints, i, c) { if (c->m_lhs == lhs_ec && c->m_rhs == rhs_ec) { tristate result_for_constraint = eval_constraint_op_for_op (c->m_op, op); if (result_for_constraint.is_known ()) return result_for_constraint; } /* Swapped operands. */ if (c->m_lhs == rhs_ec && c->m_rhs == lhs_ec) { tristate result_for_constraint = eval_constraint_op_for_op (c->m_op, swapped_op); if (result_for_constraint.is_known ()) return result_for_constraint; } } return tristate (tristate::TS_UNKNOWN); } range constraint_manager::get_ec_bounds (equiv_class_id ec_id) const { range result; int i; constraint *c; FOR_EACH_VEC_ELT (m_constraints, i, c) { if (c->m_lhs == ec_id) { if (tree other_cst = c->m_rhs.get_obj (*this).get_any_constant ()) switch (c->m_op) { default: gcc_unreachable (); case CONSTRAINT_NE: continue; case CONSTRAINT_LT: /* We have "EC_ID < OTHER_CST". */ result.m_upper_bound = bound (other_cst, false); break; case CONSTRAINT_LE: /* We have "EC_ID <= OTHER_CST". */ result.m_upper_bound = bound (other_cst, true); break; } } if (c->m_rhs == ec_id) { if (tree other_cst = c->m_lhs.get_obj (*this).get_any_constant ()) switch (c->m_op) { default: gcc_unreachable (); case CONSTRAINT_NE: continue; case CONSTRAINT_LT: /* We have "OTHER_CST < EC_ID" i.e. "EC_ID > OTHER_CST". */ result.m_lower_bound = bound (other_cst, false); break; case CONSTRAINT_LE: /* We have "OTHER_CST <= EC_ID" i.e. "EC_ID >= OTHER_CST". */ result.m_lower_bound = bound (other_cst, true); break; } } } return result; } /* Evaluate the condition LHS_EC OP RHS_CONST, avoiding the creation of equiv_class instances. */ tristate constraint_manager::eval_condition (equiv_class_id lhs_ec, enum tree_code op, tree rhs_const) const { gcc_assert (!lhs_ec.null_p ()); gcc_assert (CONSTANT_CLASS_P (rhs_const)); if (tree lhs_const = lhs_ec.get_obj (*this).get_any_constant ()) return compare_constants (lhs_const, op, rhs_const); /* Check for known inequalities of the form (LHS_EC != OTHER_CST) or (OTHER_CST != LHS_EC). If RHS_CONST == OTHER_CST, then we also know that LHS_EC != OTHER_CST. For example, we might have the constraint ptr != (void *)0 so we want the condition ptr == (foo *)0 to be false. */ int i; constraint *c; FOR_EACH_VEC_ELT (m_constraints, i, c) { if (c->m_op == CONSTRAINT_NE) { if (c->m_lhs == lhs_ec) { if (tree other_cst = c->m_rhs.get_obj (*this).get_any_constant ()) if (compare_constants (rhs_const, EQ_EXPR, other_cst).is_true ()) { switch (op) { case EQ_EXPR: return tristate (tristate::TS_FALSE); case NE_EXPR: return tristate (tristate::TS_TRUE); default: break; } } } if (c->m_rhs == lhs_ec) { if (tree other_cst = c->m_lhs.get_obj (*this).get_any_constant ()) if (compare_constants (rhs_const, EQ_EXPR, other_cst).is_true ()) { switch (op) { case EQ_EXPR: return tristate (tristate::TS_FALSE); case NE_EXPR: return tristate (tristate::TS_TRUE); default: break; } } } } } /* Look at existing bounds on LHS_EC. */ range lhs_bounds = get_ec_bounds (lhs_ec); return lhs_bounds.eval_condition (op, rhs_const); } /* Evaluate the condition LHS OP RHS, without modifying this constraint_manager (avoiding the creation of equiv_class instances). */ tristate constraint_manager::eval_condition (const svalue *lhs, enum tree_code op, const svalue *rhs) const { lhs = lhs->unwrap_any_unmergeable (); rhs = rhs->unwrap_any_unmergeable (); /* Nothing can be known about unknown or poisoned values. */ if (lhs->get_kind () == SK_UNKNOWN || lhs->get_kind () == SK_POISONED || rhs->get_kind () == SK_UNKNOWN || rhs->get_kind () == SK_POISONED) return tristate (tristate::TS_UNKNOWN); if (lhs == rhs && !(FLOAT_TYPE_P (lhs->get_type ()) || FLOAT_TYPE_P (rhs->get_type ()))) { switch (op) { case EQ_EXPR: case GE_EXPR: case LE_EXPR: return tristate (tristate::TS_TRUE); case NE_EXPR: case GT_EXPR: case LT_EXPR: return tristate (tristate::TS_FALSE); default: break; } } equiv_class_id lhs_ec (-1); equiv_class_id rhs_ec (-1); get_equiv_class_by_svalue (lhs, &lhs_ec); get_equiv_class_by_svalue (rhs, &rhs_ec); if (!lhs_ec.null_p () && !rhs_ec.null_p ()) { tristate result_for_ecs = eval_condition (lhs_ec, op, rhs_ec); if (result_for_ecs.is_known ()) return result_for_ecs; } /* If at least one is not in an EC, we have no constraints comparing LHS and RHS yet. They might still be comparable if one (or both) is a constant. Alternatively, we can also get here if we had ECs but they weren't comparable. Again, constant comparisons might give an answer. */ tree lhs_const = lhs->maybe_get_constant (); tree rhs_const = rhs->maybe_get_constant (); if (lhs_const && rhs_const) { tristate result_for_constants = compare_constants (lhs_const, op, rhs_const); if (result_for_constants.is_known ()) return result_for_constants; } if (!lhs_ec.null_p ()) { if (rhs_const) return eval_condition (lhs_ec, op, rhs_const); } if (!rhs_ec.null_p ()) { if (lhs_const) { enum tree_code swapped_op = swap_tree_comparison (op); return eval_condition (rhs_ec, swapped_op, lhs_const); } } return tristate (tristate::TS_UNKNOWN); } /* Delete any information about svalues identified by P. Such instances are removed from equivalence classes, and any redundant ECs and constraints are also removed. Accumulate stats into STATS. */ template <typename PurgeCriteria> void constraint_manager::purge (const PurgeCriteria &p, purge_stats *stats) { /* Delete any svalues identified by P within the various equivalence classes. */ for (unsigned ec_idx = 0; ec_idx < m_equiv_classes.length (); ) { equiv_class *ec = m_equiv_classes[ec_idx]; int i; const svalue *sval; bool delete_ec = false; FOR_EACH_VEC_ELT (ec->m_vars, i, sval) { if (sval == ec->m_cst_sval) continue; if (p.should_purge_p (sval)) { if (ec->del (sval)) if (!ec->m_constant) delete_ec = true; } } if (delete_ec) { delete ec; m_equiv_classes.ordered_remove (ec_idx); if (stats) stats->m_num_equiv_classes++; /* Update the constraints, potentially removing some. */ for (unsigned con_idx = 0; con_idx < m_constraints.length (); ) { constraint *c = &m_constraints[con_idx]; /* Remove constraints that refer to the deleted EC. */ if (c->m_lhs == ec_idx || c->m_rhs == ec_idx) { m_constraints.ordered_remove (con_idx); if (stats) stats->m_num_constraints++; } else { /* Renumber constraints that refer to ECs that have had their idx changed. */ c->m_lhs.update_for_removal (ec_idx); c->m_rhs.update_for_removal (ec_idx); con_idx++; } } } else ec_idx++; } /* Now delete any constraints that are purely between constants. */ for (unsigned con_idx = 0; con_idx < m_constraints.length (); ) { constraint *c = &m_constraints[con_idx]; if (m_equiv_classes[c->m_lhs.m_idx]->m_vars.length () == 0 && m_equiv_classes[c->m_rhs.m_idx]->m_vars.length () == 0) { m_constraints.ordered_remove (con_idx); if (stats) stats->m_num_constraints++; } else { con_idx++; } } /* Finally, delete any ECs that purely contain constants and aren't referenced by any constraints. */ for (unsigned ec_idx = 0; ec_idx < m_equiv_classes.length (); ) { equiv_class *ec = m_equiv_classes[ec_idx]; if (ec->m_vars.length () == 0) { equiv_class_id ec_id (ec_idx); bool has_constraint = false; for (unsigned con_idx = 0; con_idx < m_constraints.length (); con_idx++) { constraint *c = &m_constraints[con_idx]; if (c->m_lhs == ec_id || c->m_rhs == ec_id) { has_constraint = true; break; } } if (!has_constraint) { delete ec; m_equiv_classes.ordered_remove (ec_idx); if (stats) stats->m_num_equiv_classes++; /* Renumber constraints that refer to ECs that have had their idx changed. */ for (unsigned con_idx = 0; con_idx < m_constraints.length (); con_idx++) { constraint *c = &m_constraints[con_idx]; c->m_lhs.update_for_removal (ec_idx); c->m_rhs.update_for_removal (ec_idx); } continue; } } ec_idx++; } validate (); } /* Implementation of PurgeCriteria: purge svalues that are not live with respect to LIVE_SVALUES and MODEL. */ class dead_svalue_purger { public: dead_svalue_purger (const svalue_set &live_svalues, const region_model *model) : m_live_svalues (live_svalues), m_model (model) { } bool should_purge_p (const svalue *sval) const { return !sval->live_p (m_live_svalues, m_model); } private: const svalue_set &m_live_svalues; const region_model *m_model; }; /* Purge dead svalues from equivalence classes and update constraints accordingly. */ void constraint_manager:: on_liveness_change (const svalue_set &live_svalues, const region_model *model) { dead_svalue_purger p (live_svalues, model); purge (p, NULL); } /* Comparator for use by constraint_manager::canonicalize. Sort a pair of equiv_class instances, using the representative svalue as a sort key. */ static int equiv_class_cmp (const void *p1, const void *p2) { const equiv_class *ec1 = *(const equiv_class * const *)p1; const equiv_class *ec2 = *(const equiv_class * const *)p2; const svalue *rep1 = ec1->get_representative (); const svalue *rep2 = ec2->get_representative (); gcc_assert (rep1); gcc_assert (rep2); if (rep1 < rep2) return 1; if (rep1 > rep2) return -1; return 0; } /* Comparator for use by constraint_manager::canonicalize. Sort a pair of constraint instances. */ static int constraint_cmp (const void *p1, const void *p2) { const constraint *c1 = (const constraint *)p1; const constraint *c2 = (const constraint *)p2; int lhs_cmp = c1->m_lhs.as_int () - c2->m_lhs.as_int (); if (lhs_cmp) return lhs_cmp; int rhs_cmp = c1->m_rhs.as_int () - c2->m_rhs.as_int (); if (rhs_cmp) return rhs_cmp; return c1->m_op - c2->m_op; } /* Purge redundant equivalence classes and constraints, and reorder them within this constraint_manager into a canonical order, to increase the chances of finding equality with another instance. */ void constraint_manager::canonicalize () { /* First, sort svalues within the ECs. */ unsigned i; equiv_class *ec; FOR_EACH_VEC_ELT (m_equiv_classes, i, ec) ec->canonicalize (); /* TODO: remove constraints where both sides have a constant, and are thus implicit. But does this break transitivity? */ /* We will be purging and reordering ECs. We will need to remap the equiv_class_ids in the constraints, so we need to store the original index of each EC. Build a lookup table, mapping from the representative svalue to the original equiv_class_id of that svalue. */ hash_map<const svalue *, equiv_class_id> original_ec_id; const unsigned orig_num_equiv_classes = m_equiv_classes.length (); FOR_EACH_VEC_ELT (m_equiv_classes, i, ec) { const svalue *rep = ec->get_representative (); gcc_assert (rep); original_ec_id.put (rep, i); } /* Find ECs used by constraints. */ hash_set<const equiv_class *> used_ecs; constraint *c; FOR_EACH_VEC_ELT (m_constraints, i, c) { used_ecs.add (m_equiv_classes[c->m_lhs.as_int ()]); used_ecs.add (m_equiv_classes[c->m_rhs.as_int ()]); } /* Purge unused ECs: those that aren't used by constraints and that effectively have only one svalue (either in m_constant or in m_vars). */ { /* "unordered remove if" from a vec. */ unsigned i = 0; while (i < m_equiv_classes.length ()) { equiv_class *ec = m_equiv_classes[i]; if (!used_ecs.contains (ec) && ((ec->m_vars.length () < 2 && ec->m_constant == NULL_TREE) || (ec->m_vars.length () == 0))) { m_equiv_classes.unordered_remove (i); delete ec; } else i++; } } /* Next, sort the surviving ECs into a canonical order. */ m_equiv_classes.qsort (equiv_class_cmp); /* Populate ec_id_map based on the old vs new EC ids. */ one_way_id_map<equiv_class_id> ec_id_map (orig_num_equiv_classes); FOR_EACH_VEC_ELT (m_equiv_classes, i, ec) { const svalue *rep = ec->get_representative (); gcc_assert (rep); ec_id_map.put (*original_ec_id.get (rep), i); } /* Use ec_id_map to update the EC ids within the constraints. */ FOR_EACH_VEC_ELT (m_constraints, i, c) { ec_id_map.update (&c->m_lhs); ec_id_map.update (&c->m_rhs); } /* Finally, sort the constraints. */ m_constraints.qsort (constraint_cmp); } /* Concrete subclass of fact_visitor for use by constraint_manager::merge. For every fact in CM_A, see if it is also true in *CM_B. Add such facts to *OUT. */ class merger_fact_visitor : public fact_visitor { public: merger_fact_visitor (const constraint_manager *cm_b, constraint_manager *out, const model_merger &merger) : m_cm_b (cm_b), m_out (out), m_merger (merger) {} void on_fact (const svalue *lhs, enum tree_code code, const svalue *rhs) FINAL OVERRIDE { /* Special-case for widening. */ if (lhs->get_kind () == SK_WIDENING) if (!m_cm_b->get_equiv_class_by_svalue (lhs, NULL)) { /* LHS isn't constrained within m_cm_b. */ bool sat = m_out->add_constraint (lhs, code, rhs); gcc_assert (sat); return; } if (m_cm_b->eval_condition (lhs, code, rhs).is_true ()) { bool sat = m_out->add_constraint (lhs, code, rhs); if (!sat) { /* If -fanalyzer-transitivity is off, we can encounter cases where at least one of the two constraint_managers being merged is infeasible, but we only discover that infeasibility during merging (PR analyzer/96650). Silently drop such constraints. */ gcc_assert (!flag_analyzer_transitivity); } } } private: const constraint_manager *m_cm_b; constraint_manager *m_out; const model_merger &m_merger; }; /* Use MERGER to merge CM_A and CM_B into *OUT. If one thinks of a constraint_manager as a subset of N-dimensional space, this takes the union of the points of CM_A and CM_B, and expresses that into *OUT. Alternatively, it can be thought of as the intersection of the constraints. */ void constraint_manager::merge (const constraint_manager &cm_a, const constraint_manager &cm_b, constraint_manager *out, const model_merger &merger) { /* Merge the equivalence classes and constraints. The easiest way to do this seems to be to enumerate all of the facts in cm_a, see which are also true in cm_b, and add those to *OUT. */ merger_fact_visitor v (&cm_b, out, merger); cm_a.for_each_fact (&v); } /* Call VISITOR's on_fact vfunc repeatedly to express the various equivalence classes and constraints. This is used by constraint_manager::merge to find the common facts between two input constraint_managers. */ void constraint_manager::for_each_fact (fact_visitor *visitor) const { /* First, call EQ_EXPR within the various equivalence classes. */ unsigned ec_idx; equiv_class *ec; FOR_EACH_VEC_ELT (m_equiv_classes, ec_idx, ec) { if (ec->m_cst_sval) { unsigned i; const svalue *sval; FOR_EACH_VEC_ELT (ec->m_vars, i, sval) visitor->on_fact (ec->m_cst_sval, EQ_EXPR, sval); } for (unsigned i = 0; i < ec->m_vars.length (); i++) for (unsigned j = i + 1; j < ec->m_vars.length (); j++) visitor->on_fact (ec->m_vars[i], EQ_EXPR, ec->m_vars[j]); } /* Now, express the various constraints. */ unsigned con_idx; constraint *c; FOR_EACH_VEC_ELT (m_constraints, con_idx, c) { const equiv_class &ec_lhs = c->m_lhs.get_obj (*this); const equiv_class &ec_rhs = c->m_rhs.get_obj (*this); enum tree_code code = constraint_tree_code (c->m_op); if (ec_lhs.m_cst_sval) { for (unsigned j = 0; j < ec_rhs.m_vars.length (); j++) { visitor->on_fact (ec_lhs.m_cst_sval, code, ec_rhs.m_vars[j]); } } for (unsigned i = 0; i < ec_lhs.m_vars.length (); i++) { if (ec_rhs.m_cst_sval) visitor->on_fact (ec_lhs.m_vars[i], code, ec_rhs.m_cst_sval); for (unsigned j = 0; j < ec_rhs.m_vars.length (); j++) visitor->on_fact (ec_lhs.m_vars[i], code, ec_rhs.m_vars[j]); } } } /* Assert that this object is valid. */ void constraint_manager::validate () const { /* Skip this in a release build. */ #if !CHECKING_P return; #endif int i; equiv_class *ec; FOR_EACH_VEC_ELT (m_equiv_classes, i, ec) { gcc_assert (ec); int j; const svalue *sval; FOR_EACH_VEC_ELT (ec->m_vars, j, sval) gcc_assert (sval); if (ec->m_constant) { gcc_assert (CONSTANT_CLASS_P (ec->m_constant)); gcc_assert (ec->m_cst_sval); } #if 0 else gcc_assert (ec->m_vars.length () > 0); #endif } constraint *c; FOR_EACH_VEC_ELT (m_constraints, i, c) { gcc_assert (!c->m_lhs.null_p ()); gcc_assert (c->m_lhs.as_int () <= (int)m_equiv_classes.length ()); gcc_assert (!c->m_rhs.null_p ()); gcc_assert (c->m_rhs.as_int () <= (int)m_equiv_classes.length ()); } } #if CHECKING_P namespace selftest { /* Various constraint_manager selftests. These have to be written in terms of a region_model, since the latter is responsible for managing svalue instances. */ /* Verify that setting and getting simple conditions within a region_model work (thus exercising the underlying constraint_manager). */ static void test_constraint_conditions () { tree int_42 = build_int_cst (integer_type_node, 42); tree int_0 = build_int_cst (integer_type_node, 0); tree x = build_global_decl ("x", integer_type_node); tree y = build_global_decl ("y", integer_type_node); tree z = build_global_decl ("z", integer_type_node); /* Self-comparisons. */ { region_model_manager mgr; region_model model (&mgr); ASSERT_CONDITION_TRUE (model, x, EQ_EXPR, x); ASSERT_CONDITION_TRUE (model, x, LE_EXPR, x); ASSERT_CONDITION_TRUE (model, x, GE_EXPR, x); ASSERT_CONDITION_FALSE (model, x, NE_EXPR, x); ASSERT_CONDITION_FALSE (model, x, LT_EXPR, x); ASSERT_CONDITION_FALSE (model, x, GT_EXPR, x); } /* Adding self-equality shouldn't add equiv classes. */ { region_model_manager mgr; region_model model (&mgr); ADD_SAT_CONSTRAINT (model, x, EQ_EXPR, x); ADD_SAT_CONSTRAINT (model, int_42, EQ_EXPR, int_42); /* ...even when done directly via svalues: */ const svalue *sval_int_42 = model.get_rvalue (int_42, NULL); bool sat = model.get_constraints ()->add_constraint (sval_int_42, EQ_EXPR, sval_int_42); ASSERT_TRUE (sat); ASSERT_EQ (model.get_constraints ()->m_equiv_classes.length (), 0); } /* x == y. */ { region_model_manager mgr; region_model model (&mgr); ASSERT_CONDITION_UNKNOWN (model, x, EQ_EXPR, y); ADD_SAT_CONSTRAINT (model, x, EQ_EXPR, y); ASSERT_CONDITION_TRUE (model, x, EQ_EXPR, y); ASSERT_CONDITION_TRUE (model, x, LE_EXPR, y); ASSERT_CONDITION_TRUE (model, x, GE_EXPR, y); ASSERT_CONDITION_FALSE (model, x, NE_EXPR, y); ASSERT_CONDITION_FALSE (model, x, LT_EXPR, y); ASSERT_CONDITION_FALSE (model, x, GT_EXPR, y); /* Swapped operands. */ ASSERT_CONDITION_TRUE (model, y, EQ_EXPR, x); ASSERT_CONDITION_TRUE (model, y, LE_EXPR, x); ASSERT_CONDITION_TRUE (model, y, GE_EXPR, x); ASSERT_CONDITION_FALSE (model, y, NE_EXPR, x); ASSERT_CONDITION_FALSE (model, y, LT_EXPR, x); ASSERT_CONDITION_FALSE (model, y, GT_EXPR, x); /* Comparison with other var. */ ASSERT_CONDITION_UNKNOWN (model, x, EQ_EXPR, z); ASSERT_CONDITION_UNKNOWN (model, x, LE_EXPR, z); ASSERT_CONDITION_UNKNOWN (model, x, GE_EXPR, z); ASSERT_CONDITION_UNKNOWN (model, x, NE_EXPR, z); ASSERT_CONDITION_UNKNOWN (model, x, LT_EXPR, z); ASSERT_CONDITION_UNKNOWN (model, x, GT_EXPR, z); } /* x == y, then y == z */ { region_model_manager mgr; region_model model (&mgr); ASSERT_CONDITION_UNKNOWN (model, x, EQ_EXPR, y); ADD_SAT_CONSTRAINT (model, x, EQ_EXPR, y); ADD_SAT_CONSTRAINT (model, y, EQ_EXPR, z); ASSERT_CONDITION_TRUE (model, x, EQ_EXPR, z); ASSERT_CONDITION_TRUE (model, x, LE_EXPR, z); ASSERT_CONDITION_TRUE (model, x, GE_EXPR, z); ASSERT_CONDITION_FALSE (model, x, NE_EXPR, z); ASSERT_CONDITION_FALSE (model, x, LT_EXPR, z); ASSERT_CONDITION_FALSE (model, x, GT_EXPR, z); } /* x != y. */ { region_model_manager mgr; region_model model (&mgr); ADD_SAT_CONSTRAINT (model, x, NE_EXPR, y); ASSERT_CONDITION_TRUE (model, x, NE_EXPR, y); ASSERT_CONDITION_FALSE (model, x, EQ_EXPR, y); ASSERT_CONDITION_UNKNOWN (model, x, LE_EXPR, y); ASSERT_CONDITION_UNKNOWN (model, x, GE_EXPR, y); ASSERT_CONDITION_UNKNOWN (model, x, LT_EXPR, y); ASSERT_CONDITION_UNKNOWN (model, x, GT_EXPR, y); /* Swapped operands. */ ASSERT_CONDITION_TRUE (model, y, NE_EXPR, x); ASSERT_CONDITION_FALSE (model, y, EQ_EXPR, x); ASSERT_CONDITION_UNKNOWN (model, y, LE_EXPR, x); ASSERT_CONDITION_UNKNOWN (model, y, GE_EXPR, x); ASSERT_CONDITION_UNKNOWN (model, y, LT_EXPR, x); ASSERT_CONDITION_UNKNOWN (model, y, GT_EXPR, x); /* Comparison with other var. */ ASSERT_CONDITION_UNKNOWN (model, x, EQ_EXPR, z); ASSERT_CONDITION_UNKNOWN (model, x, LE_EXPR, z); ASSERT_CONDITION_UNKNOWN (model, x, GE_EXPR, z); ASSERT_CONDITION_UNKNOWN (model, x, NE_EXPR, z); ASSERT_CONDITION_UNKNOWN (model, x, LT_EXPR, z); ASSERT_CONDITION_UNKNOWN (model, x, GT_EXPR, z); } /* x < y. */ { region_model_manager mgr; region_model model (&mgr); ADD_SAT_CONSTRAINT (model, x, LT_EXPR, y); ASSERT_CONDITION_TRUE (model, x, LT_EXPR, y); ASSERT_CONDITION_TRUE (model, x, LE_EXPR, y); ASSERT_CONDITION_TRUE (model, x, NE_EXPR, y); ASSERT_CONDITION_FALSE (model, x, EQ_EXPR, y); ASSERT_CONDITION_FALSE (model, x, GT_EXPR, y); ASSERT_CONDITION_FALSE (model, x, GE_EXPR, y); /* Swapped operands. */ ASSERT_CONDITION_FALSE (model, y, LT_EXPR, x); ASSERT_CONDITION_FALSE (model, y, LE_EXPR, x); ASSERT_CONDITION_TRUE (model, y, NE_EXPR, x); ASSERT_CONDITION_FALSE (model, y, EQ_EXPR, x); ASSERT_CONDITION_TRUE (model, y, GT_EXPR, x); ASSERT_CONDITION_TRUE (model, y, GE_EXPR, x); } /* x <= y. */ { region_model_manager mgr; region_model model (&mgr); ADD_SAT_CONSTRAINT (model, x, LE_EXPR, y); ASSERT_CONDITION_UNKNOWN (model, x, LT_EXPR, y); ASSERT_CONDITION_TRUE (model, x, LE_EXPR, y); ASSERT_CONDITION_UNKNOWN (model, x, NE_EXPR, y); ASSERT_CONDITION_UNKNOWN (model, x, EQ_EXPR, y); ASSERT_CONDITION_FALSE (model, x, GT_EXPR, y); ASSERT_CONDITION_UNKNOWN (model, x, GE_EXPR, y); /* Swapped operands. */ ASSERT_CONDITION_FALSE (model, y, LT_EXPR, x); ASSERT_CONDITION_UNKNOWN (model, y, LE_EXPR, x); ASSERT_CONDITION_UNKNOWN (model, y, NE_EXPR, x); ASSERT_CONDITION_UNKNOWN (model, y, EQ_EXPR, x); ASSERT_CONDITION_UNKNOWN (model, y, GT_EXPR, x); ASSERT_CONDITION_TRUE (model, y, GE_EXPR, x); } /* x > y. */ { region_model_manager mgr; region_model model (&mgr); ADD_SAT_CONSTRAINT (model, x, GT_EXPR, y); ASSERT_CONDITION_TRUE (model, x, GT_EXPR, y); ASSERT_CONDITION_TRUE (model, x, GE_EXPR, y); ASSERT_CONDITION_TRUE (model, x, NE_EXPR, y); ASSERT_CONDITION_FALSE (model, x, EQ_EXPR, y); ASSERT_CONDITION_FALSE (model, x, LT_EXPR, y); ASSERT_CONDITION_FALSE (model, x, LE_EXPR, y); /* Swapped operands. */ ASSERT_CONDITION_FALSE (model, y, GT_EXPR, x); ASSERT_CONDITION_FALSE (model, y, GE_EXPR, x); ASSERT_CONDITION_TRUE (model, y, NE_EXPR, x); ASSERT_CONDITION_FALSE (model, y, EQ_EXPR, x); ASSERT_CONDITION_TRUE (model, y, LT_EXPR, x); ASSERT_CONDITION_TRUE (model, y, LE_EXPR, x); } /* x >= y. */ { region_model_manager mgr; region_model model (&mgr); ADD_SAT_CONSTRAINT (model, x, GE_EXPR, y); ASSERT_CONDITION_UNKNOWN (model, x, GT_EXPR, y); ASSERT_CONDITION_TRUE (model, x, GE_EXPR, y); ASSERT_CONDITION_UNKNOWN (model, x, NE_EXPR, y); ASSERT_CONDITION_UNKNOWN (model, x, EQ_EXPR, y); ASSERT_CONDITION_FALSE (model, x, LT_EXPR, y); ASSERT_CONDITION_UNKNOWN (model, x, LE_EXPR, y); /* Swapped operands. */ ASSERT_CONDITION_FALSE (model, y, GT_EXPR, x); ASSERT_CONDITION_UNKNOWN (model, y, GE_EXPR, x); ASSERT_CONDITION_UNKNOWN (model, y, NE_EXPR, x); ASSERT_CONDITION_UNKNOWN (model, y, EQ_EXPR, x); ASSERT_CONDITION_UNKNOWN (model, y, LT_EXPR, x); ASSERT_CONDITION_TRUE (model, y, LE_EXPR, x); } // TODO: implied orderings /* Constants. */ { region_model_manager mgr; region_model model (&mgr); ASSERT_CONDITION_FALSE (model, int_0, EQ_EXPR, int_42); ASSERT_CONDITION_TRUE (model, int_0, NE_EXPR, int_42); ASSERT_CONDITION_TRUE (model, int_0, LT_EXPR, int_42); ASSERT_CONDITION_TRUE (model, int_0, LE_EXPR, int_42); ASSERT_CONDITION_FALSE (model, int_0, GT_EXPR, int_42); ASSERT_CONDITION_FALSE (model, int_0, GE_EXPR, int_42); } /* x == 0, y == 42. */ { region_model_manager mgr; region_model model (&mgr); ADD_SAT_CONSTRAINT (model, x, EQ_EXPR, int_0); ADD_SAT_CONSTRAINT (model, y, EQ_EXPR, int_42); ASSERT_CONDITION_TRUE (model, x, NE_EXPR, y); ASSERT_CONDITION_FALSE (model, x, EQ_EXPR, y); ASSERT_CONDITION_TRUE (model, x, LE_EXPR, y); ASSERT_CONDITION_FALSE (model, x, GE_EXPR, y); ASSERT_CONDITION_TRUE (model, x, LT_EXPR, y); ASSERT_CONDITION_FALSE (model, x, GT_EXPR, y); } /* Unsatisfiable combinations. */ /* x == y && x != y. */ { region_model_manager mgr; region_model model (&mgr); ADD_SAT_CONSTRAINT (model, x, EQ_EXPR, y); ADD_UNSAT_CONSTRAINT (model, x, NE_EXPR, y); } /* x == 0 then x == 42. */ { region_model_manager mgr; region_model model (&mgr); ADD_SAT_CONSTRAINT (model, x, EQ_EXPR, int_0); ADD_UNSAT_CONSTRAINT (model, x, EQ_EXPR, int_42); } /* x == 0 then x != 0. */ { region_model_manager mgr; region_model model (&mgr); ADD_SAT_CONSTRAINT (model, x, EQ_EXPR, int_0); ADD_UNSAT_CONSTRAINT (model, x, NE_EXPR, int_0); } /* x == 0 then x > 0. */ { region_model_manager mgr; region_model model (&mgr); ADD_SAT_CONSTRAINT (model, x, EQ_EXPR, int_0); ADD_UNSAT_CONSTRAINT (model, x, GT_EXPR, int_0); } /* x != y && x == y. */ { region_model_manager mgr; region_model model (&mgr); ADD_SAT_CONSTRAINT (model, x, NE_EXPR, y); ADD_UNSAT_CONSTRAINT (model, x, EQ_EXPR, y); } /* x <= y && x > y. */ { region_model_manager mgr; region_model model (&mgr); ADD_SAT_CONSTRAINT (model, x, LE_EXPR, y); ADD_UNSAT_CONSTRAINT (model, x, GT_EXPR, y); } // etc } /* Test transitivity of conditions. */ static void test_transitivity () { tree a = build_global_decl ("a", integer_type_node); tree b = build_global_decl ("b", integer_type_node); tree c = build_global_decl ("c", integer_type_node); tree d = build_global_decl ("d", integer_type_node); /* a == b, then c == d, then c == b. */ { region_model_manager mgr; region_model model (&mgr); ASSERT_CONDITION_UNKNOWN (model, a, EQ_EXPR, b); ASSERT_CONDITION_UNKNOWN (model, b, EQ_EXPR, c); ASSERT_CONDITION_UNKNOWN (model, c, EQ_EXPR, d); ASSERT_CONDITION_UNKNOWN (model, a, EQ_EXPR, d); ADD_SAT_CONSTRAINT (model, a, EQ_EXPR, b); ASSERT_CONDITION_TRUE (model, a, EQ_EXPR, b); ADD_SAT_CONSTRAINT (model, c, EQ_EXPR, d); ASSERT_CONDITION_TRUE (model, c, EQ_EXPR, d); ASSERT_CONDITION_UNKNOWN (model, a, EQ_EXPR, d); ADD_SAT_CONSTRAINT (model, c, EQ_EXPR, b); ASSERT_CONDITION_TRUE (model, c, EQ_EXPR, b); ASSERT_CONDITION_TRUE (model, a, EQ_EXPR, d); } /* Transitivity: "a < b", "b < c" should imply "a < c". */ { region_model_manager mgr; region_model model (&mgr); ADD_SAT_CONSTRAINT (model, a, LT_EXPR, b); ADD_SAT_CONSTRAINT (model, b, LT_EXPR, c); ASSERT_CONDITION_TRUE (model, a, LT_EXPR, c); ASSERT_CONDITION_FALSE (model, a, EQ_EXPR, c); } /* Transitivity: "a <= b", "b < c" should imply "a < c". */ { region_model_manager mgr; region_model model (&mgr); ADD_SAT_CONSTRAINT (model, a, LE_EXPR, b); ADD_SAT_CONSTRAINT (model, b, LT_EXPR, c); ASSERT_CONDITION_TRUE (model, a, LT_EXPR, c); ASSERT_CONDITION_FALSE (model, a, EQ_EXPR, c); } /* Transitivity: "a <= b", "b <= c" should imply "a <= c". */ { region_model_manager mgr; region_model model (&mgr); ADD_SAT_CONSTRAINT (model, a, LE_EXPR, b); ADD_SAT_CONSTRAINT (model, b, LE_EXPR, c); ASSERT_CONDITION_TRUE (model, a, LE_EXPR, c); ASSERT_CONDITION_UNKNOWN (model, a, EQ_EXPR, c); } /* Transitivity: "a > b", "b > c" should imply "a > c". */ { region_model_manager mgr; region_model model (&mgr); ADD_SAT_CONSTRAINT (model, a, GT_EXPR, b); ADD_SAT_CONSTRAINT (model, b, GT_EXPR, c); ASSERT_CONDITION_TRUE (model, a, GT_EXPR, c); ASSERT_CONDITION_FALSE (model, a, EQ_EXPR, c); } /* Transitivity: "a >= b", "b > c" should imply " a > c". */ { region_model_manager mgr; region_model model (&mgr); ADD_SAT_CONSTRAINT (model, a, GE_EXPR, b); ADD_SAT_CONSTRAINT (model, b, GT_EXPR, c); ASSERT_CONDITION_TRUE (model, a, GT_EXPR, c); ASSERT_CONDITION_FALSE (model, a, EQ_EXPR, c); } /* Transitivity: "a >= b", "b >= c" should imply "a >= c". */ { region_model_manager mgr; region_model model (&mgr); ADD_SAT_CONSTRAINT (model, a, GE_EXPR, b); ADD_SAT_CONSTRAINT (model, b, GE_EXPR, c); ASSERT_CONDITION_TRUE (model, a, GE_EXPR, c); ASSERT_CONDITION_UNKNOWN (model, a, EQ_EXPR, c); } /* Transitivity: "(a < b)", "(c < d)", "(b < c)" should imply the easy cases: (a < c) (b < d) but also that: (a < d). */ { region_model_manager mgr; region_model model (&mgr); ADD_SAT_CONSTRAINT (model, a, LT_EXPR, b); ADD_SAT_CONSTRAINT (model, c, LT_EXPR, d); ADD_SAT_CONSTRAINT (model, b, LT_EXPR, c); ASSERT_CONDITION_TRUE (model, a, LT_EXPR, c); ASSERT_CONDITION_TRUE (model, b, LT_EXPR, d); ASSERT_CONDITION_TRUE (model, a, LT_EXPR, d); } /* Transitivity: "a >= b", "b >= a" should imply that a == b. */ { region_model_manager mgr; region_model model (&mgr); ADD_SAT_CONSTRAINT (model, a, GE_EXPR, b); ADD_SAT_CONSTRAINT (model, b, GE_EXPR, a); // TODO: ASSERT_CONDITION_TRUE (model, a, EQ_EXPR, b); /* The ECs for a and b should have merged, and any constraints removed. */ ASSERT_EQ (model.get_constraints ()->m_equiv_classes.length (), 1); ASSERT_EQ (model.get_constraints ()->m_constraints.length (), 0); } /* Transitivity: "a >= b", "b > a" should be impossible. */ { region_model_manager mgr; region_model model (&mgr); ADD_SAT_CONSTRAINT (model, a, GE_EXPR, b); ADD_UNSAT_CONSTRAINT (model, b, GT_EXPR, a); } /* Transitivity: "a >= b", "b >= c", "c >= a" should imply that a == b == c. */ { region_model_manager mgr; region_model model (&mgr); ADD_SAT_CONSTRAINT (model, a, GE_EXPR, b); ADD_SAT_CONSTRAINT (model, b, GE_EXPR, c); ADD_SAT_CONSTRAINT (model, c, GE_EXPR, a); ASSERT_CONDITION_TRUE (model, a, EQ_EXPR, c); } /* Transitivity: "a > b", "b > c", "c > a" should be impossible. */ { region_model_manager mgr; region_model model (&mgr); ADD_SAT_CONSTRAINT (model, a, GT_EXPR, b); ADD_SAT_CONSTRAINT (model, b, GT_EXPR, c); ADD_UNSAT_CONSTRAINT (model, c, GT_EXPR, a); } } /* Test various conditionals involving constants where the results ought to be implied based on the values of the constants. */ static void test_constant_comparisons () { tree int_3 = build_int_cst (integer_type_node, 3); tree int_4 = build_int_cst (integer_type_node, 4); tree int_5 = build_int_cst (integer_type_node, 5); tree int_1023 = build_int_cst (integer_type_node, 1023); tree int_1024 = build_int_cst (integer_type_node, 1024); tree a = build_global_decl ("a", integer_type_node); tree b = build_global_decl ("b", integer_type_node); /* Given a >= 1024, then a <= 1023 should be impossible. */ { region_model_manager mgr; region_model model (&mgr); ADD_SAT_CONSTRAINT (model, a, GE_EXPR, int_1024); ADD_UNSAT_CONSTRAINT (model, a, LE_EXPR, int_1023); } /* a > 4. */ { region_model_manager mgr; region_model model (&mgr); ADD_SAT_CONSTRAINT (model, a, GT_EXPR, int_4); ASSERT_CONDITION_TRUE (model, a, GT_EXPR, int_4); ASSERT_CONDITION_TRUE (model, a, NE_EXPR, int_3); ASSERT_CONDITION_UNKNOWN (model, a, NE_EXPR, int_5); } /* a <= 4. */ { region_model_manager mgr; region_model model (&mgr); ADD_SAT_CONSTRAINT (model, a, LE_EXPR, int_4); ASSERT_CONDITION_FALSE (model, a, GT_EXPR, int_4); ASSERT_CONDITION_FALSE (model, a, GT_EXPR, int_5); ASSERT_CONDITION_UNKNOWN (model, a, NE_EXPR, int_3); } /* If "a > b" and "a == 3", then "b == 4" ought to be unsatisfiable. */ { region_model_manager mgr; region_model model (&mgr); ADD_SAT_CONSTRAINT (model, a, GT_EXPR, b); ADD_SAT_CONSTRAINT (model, a, EQ_EXPR, int_3); ADD_UNSAT_CONSTRAINT (model, b, EQ_EXPR, int_4); } /* Various tests of int ranges where there is only one possible candidate. */ { /* If "a <= 4" && "a > 3", then "a == 4", assuming a is of integral type. */ { region_model_manager mgr; region_model model (&mgr); ADD_SAT_CONSTRAINT (model, a, LE_EXPR, int_4); ADD_SAT_CONSTRAINT (model, a, GT_EXPR, int_3); ASSERT_CONDITION_TRUE (model, a, EQ_EXPR, int_4); } /* If "a > 3" && "a <= 4", then "a == 4", assuming a is of integral type. */ { region_model_manager mgr; region_model model (&mgr); ADD_SAT_CONSTRAINT (model, a, GT_EXPR, int_3); ADD_SAT_CONSTRAINT (model, a, LE_EXPR, int_4); ASSERT_CONDITION_TRUE (model, a, EQ_EXPR, int_4); } /* If "a > 3" && "a < 5", then "a == 4", assuming a is of integral type. */ { region_model_manager mgr; region_model model (&mgr); ADD_SAT_CONSTRAINT (model, a, GT_EXPR, int_3); ADD_SAT_CONSTRAINT (model, a, LT_EXPR, int_5); ASSERT_CONDITION_TRUE (model, a, EQ_EXPR, int_4); } /* If "a >= 4" && "a < 5", then "a == 4", assuming a is of integral type. */ { region_model_manager mgr; region_model model (&mgr); ADD_SAT_CONSTRAINT (model, a, GE_EXPR, int_4); ADD_SAT_CONSTRAINT (model, a, LT_EXPR, int_5); ASSERT_CONDITION_TRUE (model, a, EQ_EXPR, int_4); } /* If "a >= 4" && "a <= 4", then "a == 4". */ { region_model_manager mgr; region_model model (&mgr); ADD_SAT_CONSTRAINT (model, a, GE_EXPR, int_4); ADD_SAT_CONSTRAINT (model, a, LE_EXPR, int_4); ASSERT_CONDITION_TRUE (model, a, EQ_EXPR, int_4); } } /* As above, but for floating-point: if "f > 3" && "f <= 4" we don't know that f == 4. */ { tree f = build_global_decl ("f", double_type_node); tree float_3 = build_real_from_int_cst (double_type_node, int_3); tree float_4 = build_real_from_int_cst (double_type_node, int_4); region_model_manager mgr; region_model model (&mgr); ADD_SAT_CONSTRAINT (model, f, GT_EXPR, float_3); ADD_SAT_CONSTRAINT (model, f, LE_EXPR, float_4); ASSERT_CONDITION_UNKNOWN (model, f, EQ_EXPR, float_4); ASSERT_CONDITION_UNKNOWN (model, f, EQ_EXPR, int_4); } } /* Verify various lower-level implementation details about constraint_manager. */ static void test_constraint_impl () { tree int_42 = build_int_cst (integer_type_node, 42); tree int_0 = build_int_cst (integer_type_node, 0); tree x = build_global_decl ("x", integer_type_node); tree y = build_global_decl ("y", integer_type_node); tree z = build_global_decl ("z", integer_type_node); /* x == y. */ { region_model_manager mgr; region_model model (&mgr); ADD_SAT_CONSTRAINT (model, x, EQ_EXPR, y); /* Assert various things about the insides of model. */ constraint_manager *cm = model.get_constraints (); ASSERT_EQ (cm->m_constraints.length (), 0); ASSERT_EQ (cm->m_equiv_classes.length (), 1); } /* y <= z; x == y. */ { region_model_manager mgr; region_model model (&mgr); ASSERT_CONDITION_UNKNOWN (model, x, EQ_EXPR, y); ASSERT_CONDITION_UNKNOWN (model, x, GE_EXPR, z); ADD_SAT_CONSTRAINT (model, y, GE_EXPR, z); ASSERT_CONDITION_TRUE (model, y, GE_EXPR, z); ASSERT_CONDITION_UNKNOWN (model, x, GE_EXPR, z); ADD_SAT_CONSTRAINT (model, x, EQ_EXPR, y); /* Assert various things about the insides of model. */ constraint_manager *cm = model.get_constraints (); ASSERT_EQ (cm->m_constraints.length (), 1); ASSERT_EQ (cm->m_equiv_classes.length (), 2); /* Ensure that we merged the constraints. */ ASSERT_CONDITION_TRUE (model, x, GE_EXPR, z); } /* y <= z; y == x. */ { region_model_manager mgr; region_model model (&mgr); ASSERT_CONDITION_UNKNOWN (model, x, EQ_EXPR, y); ASSERT_CONDITION_UNKNOWN (model, x, GE_EXPR, z); ADD_SAT_CONSTRAINT (model, y, GE_EXPR, z); ASSERT_CONDITION_TRUE (model, y, GE_EXPR, z); ASSERT_CONDITION_UNKNOWN (model, x, GE_EXPR, z); ADD_SAT_CONSTRAINT (model, y, EQ_EXPR, x); /* Assert various things about the insides of model. */ constraint_manager *cm = model.get_constraints (); ASSERT_EQ (cm->m_constraints.length (), 1); ASSERT_EQ (cm->m_equiv_classes.length (), 2); /* Ensure that we merged the constraints. */ ASSERT_CONDITION_TRUE (model, x, GE_EXPR, z); } /* x == 0, then x != 42. */ { region_model_manager mgr; region_model model (&mgr); ADD_SAT_CONSTRAINT (model, x, EQ_EXPR, int_0); ADD_SAT_CONSTRAINT (model, x, NE_EXPR, int_42); /* Assert various things about the insides of model. */ constraint_manager *cm = model.get_constraints (); ASSERT_EQ (cm->m_constraints.length (), 0); ASSERT_EQ (cm->m_equiv_classes.length (), 1); } // TODO: selftest for merging ecs "in the middle" // where a non-final one gets overwritten // TODO: selftest where there are pre-existing constraints } /* Check that operator== and hashing works as expected for the various types. */ static void test_equality () { tree x = build_global_decl ("x", integer_type_node); tree y = build_global_decl ("y", integer_type_node); { region_model_manager mgr; region_model model0 (&mgr); region_model model1 (&mgr); constraint_manager *cm0 = model0.get_constraints (); constraint_manager *cm1 = model1.get_constraints (); ASSERT_EQ (cm0->hash (), cm1->hash ()); ASSERT_EQ (*cm0, *cm1); ASSERT_EQ (model0.hash (), model1.hash ()); ASSERT_EQ (model0, model1); ADD_SAT_CONSTRAINT (model1, x, EQ_EXPR, y); ASSERT_NE (cm0->hash (), cm1->hash ()); ASSERT_NE (*cm0, *cm1); ASSERT_NE (model0.hash (), model1.hash ()); ASSERT_NE (model0, model1); region_model model2 (&mgr); constraint_manager *cm2 = model2.get_constraints (); /* Make the same change to cm2. */ ADD_SAT_CONSTRAINT (model2, x, EQ_EXPR, y); ASSERT_EQ (cm1->hash (), cm2->hash ()); ASSERT_EQ (*cm1, *cm2); ASSERT_EQ (model1.hash (), model2.hash ()); ASSERT_EQ (model1, model2); } } /* Verify tracking inequality of a variable against many constants. */ static void test_many_constants () { program_point point (program_point::origin ()); tree a = build_global_decl ("a", integer_type_node); region_model_manager mgr; region_model model (&mgr); auto_vec<tree> constants; for (int i = 0; i < 20; i++) { tree constant = build_int_cst (integer_type_node, i); constants.safe_push (constant); ADD_SAT_CONSTRAINT (model, a, NE_EXPR, constant); /* Merge, and check the result. */ region_model other (model); region_model merged (&mgr); ASSERT_TRUE (model.can_merge_with_p (other, point, &merged)); model.canonicalize (); merged.canonicalize (); ASSERT_EQ (model, merged); for (int j = 0; j <= i; j++) ASSERT_CONDITION_TRUE (model, a, NE_EXPR, constants[j]); } } /* Run the selftests in this file, temporarily overriding flag_analyzer_transitivity with TRANSITIVITY. */ static void run_constraint_manager_tests (bool transitivity) { int saved_flag_analyzer_transitivity = flag_analyzer_transitivity; flag_analyzer_transitivity = transitivity; test_constraint_conditions (); if (flag_analyzer_transitivity) { /* These selftests assume transitivity. */ test_transitivity (); } test_constant_comparisons (); test_constraint_impl (); test_equality (); test_many_constants (); flag_analyzer_transitivity = saved_flag_analyzer_transitivity; } /* Run all of the selftests within this file. */ void analyzer_constraint_manager_cc_tests () { /* Run the tests twice: with and without transitivity. */ run_constraint_manager_tests (true); run_constraint_manager_tests (false); } } // namespace selftest #endif /* CHECKING_P */ } // namespace ana #endif /* #if ENABLE_ANALYZER */
27.341463
80
0.659446
[ "object", "model" ]
603ba826e5efe74654e49fb357cf497d3b14071d
5,627
cpp
C++
lib/ToolDrivers/llvm-dlltool/DlltoolDriver.cpp
ssahasra/llvm-roc
2202c6c408395679e92813bbfcc3690d37ba4810
[ "Apache-2.0" ]
15
2019-08-05T01:24:20.000Z
2022-01-12T08:19:55.000Z
lib/ToolDrivers/llvm-dlltool/DlltoolDriver.cpp
ssahasra/llvm-roc
2202c6c408395679e92813bbfcc3690d37ba4810
[ "Apache-2.0" ]
3
2019-05-28T16:42:25.000Z
2019-06-07T02:12:24.000Z
lib/ToolDrivers/llvm-dlltool/DlltoolDriver.cpp
ssahasra/llvm-roc
2202c6c408395679e92813bbfcc3690d37ba4810
[ "Apache-2.0" ]
9
2019-09-24T06:26:58.000Z
2021-11-22T08:54:00.000Z
//===- DlltoolDriver.cpp - dlltool.exe-compatible driver ------------------===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// // // Defines an interface to a dlltool.exe-compatible driver. // //===----------------------------------------------------------------------===// #include "llvm/ToolDrivers/llvm-dlltool/DlltoolDriver.h" #include "llvm/Object/COFF.h" #include "llvm/Object/COFFImportFile.h" #include "llvm/Object/COFFModuleDefinition.h" #include "llvm/Option/Arg.h" #include "llvm/Option/ArgList.h" #include "llvm/Option/Option.h" #include "llvm/Support/Path.h" #include <vector> using namespace llvm; using namespace llvm::object; using namespace llvm::COFF; namespace { enum { OPT_INVALID = 0, #define OPTION(_1, _2, ID, _4, _5, _6, _7, _8, _9, _10, _11, _12) OPT_##ID, #include "Options.inc" #undef OPTION }; #define PREFIX(NAME, VALUE) const char *const NAME[] = VALUE; #include "Options.inc" #undef PREFIX static const llvm::opt::OptTable::Info InfoTable[] = { #define OPTION(X1, X2, ID, KIND, GROUP, ALIAS, X7, X8, X9, X10, X11, X12) \ {X1, X2, X10, X11, OPT_##ID, llvm::opt::Option::KIND##Class, \ X9, X8, OPT_##GROUP, OPT_##ALIAS, X7, X12}, #include "Options.inc" #undef OPTION }; class DllOptTable : public llvm::opt::OptTable { public: DllOptTable() : OptTable(InfoTable, false) {} }; } // namespace // Opens a file. Path has to be resolved already. static std::unique_ptr<MemoryBuffer> openFile(const Twine &Path) { ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> MB = MemoryBuffer::getFile(Path); if (std::error_code EC = MB.getError()) { llvm::errs() << "cannot open file " << Path << ": " << EC.message() << "\n"; return nullptr; } return std::move(*MB); } static MachineTypes getEmulation(StringRef S) { return StringSwitch<MachineTypes>(S) .Case("i386", IMAGE_FILE_MACHINE_I386) .Case("i386:x86-64", IMAGE_FILE_MACHINE_AMD64) .Case("arm", IMAGE_FILE_MACHINE_ARMNT) .Case("arm64", IMAGE_FILE_MACHINE_ARM64) .Default(IMAGE_FILE_MACHINE_UNKNOWN); } static std::string getImplibPath(StringRef Path) { SmallString<128> Out = StringRef("lib"); Out.append(Path); sys::path::replace_extension(Out, ".a"); return Out.str(); } int llvm::dlltoolDriverMain(llvm::ArrayRef<const char *> ArgsArr) { DllOptTable Table; unsigned MissingIndex; unsigned MissingCount; llvm::opt::InputArgList Args = Table.ParseArgs(ArgsArr.slice(1), MissingIndex, MissingCount); if (MissingCount) { llvm::errs() << Args.getArgString(MissingIndex) << ": missing argument\n"; return 1; } // Handle when no input or output is specified if (Args.hasArgNoClaim(OPT_INPUT) || (!Args.hasArgNoClaim(OPT_d) && !Args.hasArgNoClaim(OPT_l))) { Table.PrintHelp(outs(), "llvm-dlltool [options] file...", "llvm-dlltool", false); llvm::outs() << "\nTARGETS: i386, i386:x86-64, arm, arm64\n"; return 1; } if (!Args.hasArgNoClaim(OPT_m) && Args.hasArgNoClaim(OPT_d)) { llvm::errs() << "error: no target machine specified\n" << "supported targets: i386, i386:x86-64, arm, arm64\n"; return 1; } for (auto *Arg : Args.filtered(OPT_UNKNOWN)) llvm::errs() << "ignoring unknown argument: " << Arg->getAsString(Args) << "\n"; if (!Args.hasArg(OPT_d)) { llvm::errs() << "no definition file specified\n"; return 1; } std::unique_ptr<MemoryBuffer> MB = openFile(Args.getLastArg(OPT_d)->getValue()); if (!MB) return 1; if (!MB->getBufferSize()) { llvm::errs() << "definition file empty\n"; return 1; } COFF::MachineTypes Machine = IMAGE_FILE_MACHINE_UNKNOWN; if (auto *Arg = Args.getLastArg(OPT_m)) Machine = getEmulation(Arg->getValue()); if (Machine == IMAGE_FILE_MACHINE_UNKNOWN) { llvm::errs() << "unknown target\n"; return 1; } Expected<COFFModuleDefinition> Def = parseCOFFModuleDefinition(*MB, Machine, true); if (!Def) { llvm::errs() << "error parsing definition\n" << errorToErrorCode(Def.takeError()).message(); return 1; } // Do this after the parser because parseCOFFModuleDefinition sets OutputFile. if (auto *Arg = Args.getLastArg(OPT_D)) Def->OutputFile = Arg->getValue(); if (Def->OutputFile.empty()) { llvm::errs() << "no DLL name specified\n"; return 1; } std::string Path = Args.getLastArgValue(OPT_l); if (Path.empty()) Path = getImplibPath(Def->OutputFile); if (Machine == IMAGE_FILE_MACHINE_I386 && Args.getLastArg(OPT_k)) { for (COFFShortExport& E : Def->Exports) { if (!E.AliasTarget.empty() || (!E.Name.empty() && E.Name[0] == '?')) continue; E.SymbolName = E.Name; // Trim off the trailing decoration. Symbols will always have a // starting prefix here (either _ for cdecl/stdcall, @ for fastcall // or ? for C++ functions). Vectorcall functions won't have any // fixed prefix, but the function base name will still be at least // one char. E.Name = E.Name.substr(0, E.Name.find('@', 1)); // By making sure E.SymbolName != E.Name for decorated symbols, // writeImportLibrary writes these symbols with the type // IMPORT_NAME_UNDECORATE. } } if (writeImportLibrary(Def->OutputFile, Path, Def->Exports, Machine, true)) return 1; return 0; }
31.088398
80
0.634619
[ "object", "vector" ]
603bfb1a9a53bdd4b3c3694cdc2caa831c168c51
18,176
cpp
C++
dev/Gems/PhysX/Code/Source/EditorForceRegionComponent.cpp
brianherrera/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
[ "AML" ]
1,738
2017-09-21T10:59:12.000Z
2022-03-31T21:05:46.000Z
dev/Gems/PhysX/Code/Source/EditorForceRegionComponent.cpp
ArchitectureStudios/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
[ "AML" ]
427
2017-09-29T22:54:36.000Z
2022-02-15T19:26:50.000Z
dev/Gems/PhysX/Code/Source/EditorForceRegionComponent.cpp
ArchitectureStudios/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
[ "AML" ]
671
2017-09-21T08:04:01.000Z
2022-03-29T14:30:07.000Z
/* * All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or * its licensors. * * For complete copyright and license terms please see the LICENSE at the root of this * distribution (the "License"). All use of this software is governed by the License, * or, if provided, by the license below or the license accompanying this file. Do not * remove or modify any license notices. This file is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * */ #include <PhysX_precompiled.h> #include <Source/EditorColliderComponent.h> #include <Source/EditorShapeColliderComponent.h> #include <Source/EditorForceRegionComponent.h> #include <Source/ForceRegionComponent.h> #include <Source/Utils.h> #include <PhysX/ColliderShapeBus.h> #include <AzCore/Serialization/EditContext.h> #include <AzCore/Serialization/SerializeContext.h> #include <LmbrCentral/Shape/SplineComponentBus.h> namespace PhysX { void EditorForceRegionComponent::EditorForceProxy::Reflect(AZ::ReflectContext* context) { if (auto serializeContext = azrtti_cast<AZ::SerializeContext*>(context)) { serializeContext->Class<EditorForceProxy>() ->Version(1) ->Field("Type", &EditorForceProxy::m_type) ->Field("ForceWorldSpace", &EditorForceProxy::m_forceWorldSpace) ->Field("ForceLocalSpace", &EditorForceProxy::m_forceLocalSpace) ->Field("ForcePoint", &EditorForceProxy::m_forcePoint) ->Field("ForceSplineFollow", &EditorForceProxy::m_forceSplineFollow) ->Field("ForceSimpleDrag", &EditorForceProxy::m_forceSimpleDrag) ->Field("ForceLinearDamping", &EditorForceProxy::m_forceLinearDamping) ; if (auto editContext = serializeContext->GetEditContext()) { editContext->Class<EditorForceProxy>( "Forces", "forces") ->ClassElement(AZ::Edit::ClassElements::EditorData, "") ->Attribute(AZ::Edit::Attributes::AutoExpand, true) ->DataElement(AZ::Edit::UIHandlers::ComboBox, &EditorForceProxy::m_type, "Force Type", "") ->EnumAttribute(ForceType::WorldSpace, "World Space") ->EnumAttribute(ForceType::LocalSpace, "Local Space") ->EnumAttribute(ForceType::Point, "Point") ->EnumAttribute(ForceType::SplineFollow, "Spline Follow") ->EnumAttribute(ForceType::SimpleDrag, "Simple Drag") ->EnumAttribute(ForceType::LinearDamping, "Linear Damping") ->Attribute(AZ::Edit::Attributes::ChangeNotify, AZ::Edit::PropertyRefreshLevels::EntireTree) ->DataElement(AZ::Edit::UIHandlers::Default, &EditorForceProxy::m_forceWorldSpace, "World Space Force", "") ->Attribute(AZ::Edit::Attributes::Visibility, &EditorForceProxy::IsWorldSpaceForce) ->DataElement(AZ::Edit::UIHandlers::Default, &EditorForceProxy::m_forceLocalSpace, "Local Space Force", "") ->Attribute(AZ::Edit::Attributes::Visibility, &EditorForceProxy::IsLocalSpaceForce) ->DataElement(AZ::Edit::UIHandlers::Default, &EditorForceProxy::m_forcePoint, "Point Force", "") ->Attribute(AZ::Edit::Attributes::Visibility, &EditorForceProxy::IsPointForce) ->DataElement(AZ::Edit::UIHandlers::Default, &EditorForceProxy::m_forceSplineFollow, "Spline Follow Force", "") ->Attribute(AZ::Edit::Attributes::Visibility, &EditorForceProxy::IsSplineFollowForce) ->DataElement(AZ::Edit::UIHandlers::Default, &EditorForceProxy::m_forceSimpleDrag, "Simple Drag Force", "") ->Attribute(AZ::Edit::Attributes::Visibility, &EditorForceProxy::IsSimpleDragForce) ->DataElement(AZ::Edit::UIHandlers::Default, &EditorForceProxy::m_forceLinearDamping, "Linear Damping Force", "") ->Attribute(AZ::Edit::Attributes::Visibility, &EditorForceProxy::IsLinearDampingForce) ; } } } const BaseForce& EditorForceRegionComponent::EditorForceProxy::GetCurrentBaseForce() const { auto* deconstThis = const_cast<EditorForceProxy*>(this); return deconstThis->GetCurrentBaseForce(); } BaseForce& EditorForceRegionComponent::EditorForceProxy::GetCurrentBaseForce() { switch (m_type) { case ForceType::WorldSpace: return m_forceWorldSpace; case ForceType::LocalSpace: return m_forceLocalSpace; case ForceType::Point: return m_forcePoint; case ForceType::SplineFollow: return m_forceSplineFollow; case ForceType::SimpleDrag: return m_forceSimpleDrag; case ForceType::LinearDamping: return m_forceLinearDamping; default: AZ_Error("EditorForceRegionComponent", false, "Unsupported force type"); return m_forceWorldSpace; } } void EditorForceRegionComponent::EditorForceProxy::Activate(AZ::EntityId entityId) { BaseForce& force = GetCurrentBaseForce(); force.Activate(entityId); } void EditorForceRegionComponent::EditorForceProxy::Deactivate() { BaseForce& force = GetCurrentBaseForce(); force.Deactivate(); } AZ::Vector3 EditorForceRegionComponent::EditorForceProxy::CalculateForce(const EntityParams& entity, const RegionParams& region) const { const BaseForce& force = GetCurrentBaseForce(); return force.CalculateForce(entity, region); } bool EditorForceRegionComponent::EditorForceProxy::IsWorldSpaceForce() const { return m_type == ForceType::WorldSpace; } bool EditorForceRegionComponent::EditorForceProxy::IsLocalSpaceForce() const { return m_type == ForceType::LocalSpace; } bool EditorForceRegionComponent::EditorForceProxy::IsPointForce() const { return m_type == ForceType::Point; } bool EditorForceRegionComponent::EditorForceProxy::IsSplineFollowForce() const { return m_type == ForceType::SplineFollow; } bool EditorForceRegionComponent::EditorForceProxy::IsSimpleDragForce() const { return m_type == ForceType::SimpleDrag; } bool EditorForceRegionComponent::EditorForceProxy::IsLinearDampingForce() const { return m_type == ForceType::LinearDamping; } void EditorForceRegionComponent::Reflect(AZ::ReflectContext* context) { EditorForceRegionComponent::EditorForceProxy::Reflect(context); if (auto serializeContext = azrtti_cast<AZ::SerializeContext*>(context)) { serializeContext->Class<EditorForceRegionComponent, EditorComponentBase>() ->Field("Visible", &EditorForceRegionComponent::m_visibleInEditor) ->Field("DebugForces", &EditorForceRegionComponent::m_debugForces) ->Field("Forces", &EditorForceRegionComponent::m_forces) ->Version(2) ; if (auto editContext = serializeContext->GetEditContext()) { // EditorForceRegionComponent editContext->Class<EditorForceRegionComponent>( "PhysX Force Region", "The force region component is used to apply a physical force on objects within the region") ->ClassElement(AZ::Edit::ClassElements::EditorData, "") ->Attribute(AZ::Edit::Attributes::Category, "PhysX") ->Attribute(AZ::Edit::Attributes::Icon, "Editor/Icons/Components/ForceRegion.png") ->Attribute(AZ::Edit::Attributes::ViewportIcon, "Editor/Icons/Components/Viewport/ForceRegion.png") ->Attribute(AZ::Edit::Attributes::AppearsInAddComponentMenu, AZ_CRC("Game", 0x232b318c)) ->Attribute(AZ::Edit::Attributes::HelpPageURL, "https://docs.aws.amazon.com/console/lumberyard/physx/force-region") ->Attribute(AZ::Edit::Attributes::AutoExpand, true) ->Attribute(AZ::Edit::Attributes::RequiredService, AZ_CRC("PhysXTriggerService", 0x3a117d7b)) ->DataElement(AZ::Edit::UIHandlers::Default, &EditorForceRegionComponent::m_visibleInEditor, "Visible", "Always show the component in viewport") ->DataElement(AZ::Edit::UIHandlers::Default, &EditorForceRegionComponent::m_debugForces, "Debug Forces", "Draws debug arrows when an entity enters a force region. This occurs in gameplay mode to show the force direction on an entity.") ->DataElement(AZ::Edit::UIHandlers::Default, &EditorForceRegionComponent::m_forces, "Forces", "Forces in force region") ->Attribute(AZ::Edit::Attributes::AutoExpand, true) ->Attribute(AZ::Edit::Attributes::ChangeNotify, &EditorForceRegionComponent::OnForcesChanged) ; } } } void EditorForceRegionComponent::BuildGameEntity(AZ::Entity* gameEntity) { ForceRegion forceRegion; using ForceType = EditorForceRegionComponent::EditorForceProxy::ForceType; // Copy edit component's forces to game-time component. for (auto& forceProxy : m_forces) { forceProxy.Deactivate(); switch (forceProxy.m_type) { case ForceType::WorldSpace: forceRegion.AddAndActivateForce(AZStd::make_unique<ForceWorldSpace>(forceProxy.m_forceWorldSpace)); break; case ForceType::LocalSpace: forceRegion.AddAndActivateForce(AZStd::make_unique<ForceLocalSpace>(forceProxy.m_forceLocalSpace)); break; case ForceType::Point: forceRegion.AddAndActivateForce(AZStd::make_unique<ForcePoint>(forceProxy.m_forcePoint)); break; case ForceType::SplineFollow: forceRegion.AddAndActivateForce(AZStd::make_unique<ForceSplineFollow>(forceProxy.m_forceSplineFollow)); break; case ForceType::SimpleDrag: forceRegion.AddAndActivateForce(AZStd::make_unique<ForceSimpleDrag>(forceProxy.m_forceSimpleDrag)); break; case ForceType::LinearDamping: forceRegion.AddAndActivateForce(AZStd::make_unique<ForceLinearDamping>(forceProxy.m_forceLinearDamping)); break; } } gameEntity->CreateComponent<ForceRegionComponent>(std::move(forceRegion), m_debugForces); } void EditorForceRegionComponent::GetIncompatibleServices(AZ::ComponentDescriptor::DependencyArrayType& incompatible) { incompatible.push_back(AZ_CRC("ForceRegionService", 0x3c3e4061)); incompatible.push_back(AZ_CRC("LegacyCryPhysicsService", 0xbb370351)); } void EditorForceRegionComponent::GetProvidedServices(AZ::ComponentDescriptor::DependencyArrayType& provided) { provided.push_back(AZ_CRC("ForceRegionService", 0x3c3e4061)); } void EditorForceRegionComponent::GetRequiredServices(AZ::ComponentDescriptor::DependencyArrayType& required) { required.push_back(AZ_CRC("TransformService", 0x8ee22c50)); required.push_back(AZ_CRC("PhysXTriggerService", 0x3a117d7b)); } void EditorForceRegionComponent::Activate() { AZ::EntityId entityId = GetEntityId(); EditorComponentBase::Activate(); AzFramework::EntityDebugDisplayEventBus::Handler::BusConnect(entityId); for (auto& force : m_forces) { force.Activate(entityId); } AZ_Warning("PhysX Force Region" , PhysX::Utils::TriggerColliderExists(entityId) , "Please ensure collider component marked as trigger exists in entity <%s: %s> with force region." , GetEntity()->GetName().c_str() , entityId.ToString().c_str()); } void EditorForceRegionComponent::Deactivate() { for (auto& force : m_forces) { force.Deactivate(); } AzFramework::EntityDebugDisplayEventBus::Handler::BusDisconnect(); EditorComponentBase::Deactivate(); } void EditorForceRegionComponent::DisplayEntityViewport(const AzFramework::ViewportInfo& viewportInfo , AzFramework::DebugDisplayRequests& debugDisplayRequests) { if (!IsSelected() && !m_visibleInEditor) { return; } AZ::Entity* forceRegionEntity = GetEntity(); if (!forceRegionEntity) { return; } // Update AABB cache of collider components if they're outdated or dirty. AZ::Aabb aabb; ColliderShapeRequestBus::EventResult(aabb , GetEntityId() , &ColliderShapeRequestBus::Events::GetColliderShapeAabb); const AZ::Entity::ComponentArrayType& enabledComponents = forceRegionEntity->GetComponents(); for (AZ::Component* component : enabledComponents) { EditorColliderComponent* editorColliderComponent = azrtti_cast<EditorColliderComponent*>(component); EditorShapeColliderComponent* editorShapeColliderComponent = azrtti_cast<EditorShapeColliderComponent*>(component); if (!editorColliderComponent && !editorShapeColliderComponent) { continue; } if (editorColliderComponent) { const PhysX::EditorProxyShapeConfig& shapeConfig = editorColliderComponent->GetShapeConfiguration(); AZStd::vector<AZ::Vector3> randomPoints; if (shapeConfig.IsBoxConfig()) { AZ::Vector3 dimensions = shapeConfig.m_box.m_dimensions; randomPoints = Utils::Geometry::GenerateBoxPoints(dimensions * -0.5f , dimensions * 0.5f); } else if (shapeConfig.IsCapsuleConfig()) { float height = shapeConfig.m_capsule.m_height; float radius = shapeConfig.m_capsule.m_radius; randomPoints = Utils::Geometry::GenerateCylinderPoints(height - radius * 2.0f , radius); } else if (shapeConfig.IsSphereConfig()) { float radius = shapeConfig.m_sphere.m_radius; randomPoints = Utils::Geometry::GenerateSpherePoints(radius); } else if (shapeConfig.IsAssetConfig()) { const AZ::Vector3 halfExtents = aabb.GetExtents() * 0.5f; randomPoints = Utils::Geometry::GenerateBoxPoints(-halfExtents, halfExtents); } PhysX::Utils::ColliderPointsLocalToWorld(randomPoints , GetWorldTM() , editorColliderComponent->GetColliderConfiguration().m_position , editorColliderComponent->GetColliderConfiguration().m_rotation); DrawForceArrows(randomPoints, debugDisplayRequests); } else if (editorShapeColliderComponent) { DrawForceArrows(editorShapeColliderComponent->GetSamplePoints(), debugDisplayRequests); } } } void EditorForceRegionComponent::DrawForceArrows(const AZStd::vector<AZ::Vector3>& arrowPositions , AzFramework::DebugDisplayRequests& debugDisplayRequests) { const AZ::Color color = AZ::Color(0.f, 0.f, 1.f, 1.f); debugDisplayRequests.SetColor(color); EntityParams entityParams; entityParams.m_id.SetInvalid(); entityParams.m_velocity = AZ::Vector3::CreateZero(); entityParams.m_mass = 1.f; const PhysX::RegionParams regionParams = ForceRegionUtil::CreateRegionParams(GetEntityId()); for (const auto& arrowPosition : arrowPositions) { entityParams.m_position = arrowPosition; auto totalForce = AZ::Vector3::CreateZero(); for (const auto& force : m_forces) { totalForce += force.CalculateForce(entityParams, regionParams); } if (!totalForce.IsZero() && totalForce.IsFinite()) { totalForce.Normalize(); totalForce *= 0.5f; const float arrowHeadScale = 1.5f; debugDisplayRequests.DrawArrow(arrowPosition - totalForce , arrowPosition + totalForce , arrowHeadScale); } else { const float ballRadius = 0.05f; debugDisplayRequests.DrawBall(arrowPosition, ballRadius); } } } bool EditorForceRegionComponent::HasSplineFollowForce() const { for (const auto& force : m_forces) { if (force.m_type == EditorForceProxy::ForceType::SplineFollow) { return true; } } return false; } void EditorForceRegionComponent::OnForcesChanged() const { if (HasSplineFollowForce()) { AZ::ConstSplinePtr splinePtr = nullptr; LmbrCentral::SplineComponentRequestBus::EventResult(splinePtr, GetEntityId() , &LmbrCentral::SplineComponentRequestBus::Events::GetSpline); AZ::Entity* entity = GetEntity(); AZ_Warning("PhysX EditorForceRegionComponent" , splinePtr!=nullptr , "Please add spline shape for force region in entity <%s: %s>." , entity->GetName().c_str() , entity->GetId().ToString().c_str()); } ForceRegionNotificationBus::Broadcast( &ForceRegionNotificationBus::Events::OnForceRegionForceChanged, GetEntityId()); } }
44.116505
255
0.628961
[ "geometry", "shape", "vector" ]
603c0aade0c670feecb85aa4a00acb22f1d225c6
14,754
hpp
C++
modules/dnn/src/ocl4dnn/include/ocl4dnn.hpp
lzx1413/opencv
2c1b4f571123cae115850c49830c217783669270
[ "BSD-3-Clause" ]
null
null
null
modules/dnn/src/ocl4dnn/include/ocl4dnn.hpp
lzx1413/opencv
2c1b4f571123cae115850c49830c217783669270
[ "BSD-3-Clause" ]
null
null
null
modules/dnn/src/ocl4dnn/include/ocl4dnn.hpp
lzx1413/opencv
2c1b4f571123cae115850c49830c217783669270
[ "BSD-3-Clause" ]
2
2017-11-03T08:23:04.000Z
2019-10-07T02:39:00.000Z
/*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // // License Agreement // For Open Source Computer Vision Library // // Copyright (C) 2017, Intel Corporation, all rights reserved. // Copyright (c) 2016-2017 Fabian David Tschopp, all rights reserved. // Third party copyrights are property of their respective owners. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * The name of the copyright holders may not be used to endorse or promote products // derived from this software without specific prior written permission. // // This software is provided by the copyright holders and contributors "as is" and // any express or implied warranties, including, but not limited to, the implied // warranties of merchantability and fitness for a particular purpose are disclaimed. // In no event shall the Intel Corporation or contributors be liable for any direct, // indirect, incidental, special, exemplary, or consequential damages // (including, but not limited to, procurement of substitute goods or services; // loss of use, data, or profits; or business interruption) however caused // and on any theory of liability, whether in contract, strict liability, // or tort (including negligence or otherwise) arising in any way out of // the use of this software, even if advised of the possibility of such damage. // //M*/ #ifndef _OPENCV_LIBDNN_HPP_ #define _OPENCV_LIBDNN_HPP_ #include "../../precomp.hpp" #include <iomanip> #include <map> #include <memory> #include <string> #include <vector> #include "common.hpp" namespace cv { namespace dnn { namespace ocl4dnn { #ifdef HAVE_OPENCL struct OCL4DNNConvConfig { OCL4DNNConvConfig() : kernel(1, 1), pad(0, 0), stride(1, 1), dilation(1, 1), group(1), bias_term(false) {} MatShape in_shape; MatShape out_shape; Size kernel; Size pad; Size stride; Size dilation; int group; // = 1; bool bias_term; // = false; }; template<typename Dtype> class OCL4DNNConvSpatial { public: explicit OCL4DNNConvSpatial(OCL4DNNConvConfig config); ~OCL4DNNConvSpatial(); bool Forward(const UMat& bottom_data, const UMat& weight, const UMat& bias, UMat& top_data, int32_t batch_size); private: struct kernelConfig { std::string kernelName; float executionTime; size_t local_work_size[3]; size_t global_work_size[3]; int32_t workItem_output[3]; bool verified; bool tested; bool swizzle_weights; bool use_null_local; int32_t kernelType; kernelConfig() {} kernelConfig(const std::string& name, const size_t* global_size, const size_t* local_size, const int32_t* workItem, bool swizzle, int32_t type = 0) : executionTime(0) { kernelName = name; for (int32_t x = 0; x < 3; x++) { local_work_size[x] = local_size ? local_size[x] : 1; global_work_size[x] = global_size[x]; workItem_output[x] = workItem[x]; } swizzle_weights = swizzle; use_null_local = local_size == NULL; verified = false; tested = false; kernelType = type; } }; struct tunerParam { int kernelType; int blockWidth; int blockHeight; int blockDepth; tunerParam(int type, int w, int h, int d) { kernelType = type; blockWidth = w; blockHeight= h; blockDepth = d; } }; inline void addDef(const char* name) { options_ << " -D " << name; } inline void addDef(const char* name, const int value) { options_ << " -D " << name << "=" << value; } inline void addDef(const char* name, const float value) { options_ << " -D " << name << "=(float)" << value; } inline void addDef(const char* name, const double value) { options_ << " -D " << name << "=(double)" << value; } inline void addDef(const char* name, const char* value) { options_ << " -D " << name << "=" << value; } void useFirstAvailable(const UMat &bottom, UMat &top, const UMat &weight, const UMat &bias, int32_t numImages, UMat &verifyTop); void setupKernel(); void collectCommonInformation(); void setupKernelDetails(int32_t kernelType, int32_t blockM, int32_t blockK, int32_t blockN); ocl::Program compileKernel(); typedef std::map<std::string, ocl::Program> phash_t; phash_t phash; void calculateBenchmark(const UMat &bottom, UMat &verifyTop, const UMat &weight, const UMat &bias, int32_t numImages); void setupConvolution(const UMat &bottom, UMat &top, const UMat &weight, const UMat &bias, int32_t numImags, UMat &verifyTop); bool createConvolutionKernel(int32_t kernelType, int32_t blockWidth, int32_t blockHeight, int32_t blockDepth); bool setupIDLF(int32_t blockWidth, int32_t blockHeight, int32_t blockDepth); bool createBasicKernel(int32_t blockWidth, int32_t blockHeight, int32_t blockDepth); bool createGEMMLikeConvKernel(int32_t blockWidth, int32_t blockHeight, int32_t blockDepth); void CreateSubBuffer(const UMat& buffer, UMat& sub_buffer, int32_t offset, int32_t size, bool write_only); bool convolve(const UMat &bottom, UMat &top, const UMat &weight, const UMat &bias, int32_t numImages, kernelConfig* config, const cv::ocl::Queue& queue); float timedConvolve(const UMat &bottom, UMat &top, const UMat &weight, const UMat &bias, int32_t numImages, kernelConfig* config); bool verifyResult(const UMat &bottom, UMat &top, const UMat &weight, const UMat &bias, int32_t numImages, kernelConfig* config, UMat &verifyTop); bool swizzleWeight(const UMat &weight, int32_t swizzled_factor, bool interleave = false); void generateKey(); std::string generateSpecificKey(int32_t type, int32_t blockWidth, int32_t blockHeight, int32_t blockDepth); void cacheTunedConfig(); bool loadTunedConfig(); void saveTunedConfig(); bool loadCachedConfig(); void unloadProgram(const std::string& kernelName); void prepareKernel(const UMat &bottom, UMat &top, const UMat &weight, const UMat &bias, int32_t numImages); bool setupKernelByConfig(int x, int y, int z, int type, int lx, int ly, int lz, bool swizzle, bool nullLocal); void generateTunerItems(std::vector< cv::Ptr<tunerParam> > &tunerItems); int32_t group_; bool bias_term_; UMat swizzled_weights_umat; int32_t bottom_index_; int32_t output_h_; int32_t output_w_; int32_t kernel_h_; int32_t kernel_w_; int32_t height_; int32_t width_; int32_t pad_h_; int32_t pad_w_; int32_t stride_h_; int32_t stride_w_; int32_t dilation_h_; int32_t dilation_w_; /// M_ is the channel dimension of the output for a single group, which is the /// leading dimension of the filter matrix. int32_t M_; bool tuned_; std::string key_, key_sanitized_; std::string short_key_; std::string kernel_name_; std::string cache_path_; bool use_cache_path_; // true if cache_path_ directory exists bool force_auto_tuning_; int32_t kernel_index_; std::vector< cv::Ptr<kernelConfig> > kernelQueue; cv::Ptr<kernelConfig> bestKernelConfig; int32_t bottom_dim_; int32_t top_dim_; int32_t num_; int32_t channels_; int32_t num_output_; int32_t kernelType_; int32_t blockM_; int32_t blockK_; int32_t blockN_; std::stringstream options_; cv::ocl::ProgramSource src_; int32_t prev_kernel_type_; }; typedef enum { LIBDNN_POOLING_METHOD_MAX = 0, LIBDNN_POOLING_METHOD_AVE = 1, LIBDNN_POOLING_METHOD_STO = 2 } ocl4dnnPoolingMethod_t; struct OCL4DNNPoolConfig { OCL4DNNPoolConfig() : kernel(1, 1), pad(0, 0), stride(1, 1), dilation(1, 1), channels(0), pool_method(LIBDNN_POOLING_METHOD_MAX), global_pooling(false) {} MatShape in_shape; MatShape out_shape; Size kernel; Size pad; Size stride; Size dilation; int channels; ocl4dnnPoolingMethod_t pool_method; // = LIBDNN_POOLING_METHOD_MAX; bool global_pooling; // = false; }; template<typename Dtype> class OCL4DNNPool { public: explicit OCL4DNNPool(OCL4DNNPoolConfig config); ~OCL4DNNPool(); bool Forward(const UMat& bottom_data, UMat& top_data, UMat& top_mask); private: UMat mask_idx_; // Pooling parameters std::vector<int32_t> pad_; std::vector<int32_t> stride_; std::vector<int32_t> kernel_shape_; std::vector<int32_t> im_in_shape_; std::vector<int32_t> im_out_shape_; ocl4dnnPoolingMethod_t pool_method_; int32_t count_; int32_t batch_size_; int32_t channels_; int32_t kernel_h_; int32_t kernel_w_; int32_t stride_h_; int32_t stride_w_; int32_t pad_h_; int32_t pad_w_; int32_t height_; int32_t width_; int32_t pooled_height_; int32_t pooled_width_; }; struct OCL4DNNInnerProductConfig { OCL4DNNInnerProductConfig() : num_output(0), M(0), K(0), bias_term(false), transpose(false), phase_test(true) {} int num_output; int M; int K; bool bias_term; bool transpose; // = false; bool phase_test; // = true; }; template<typename Dtype> class OCL4DNNInnerProduct { public: explicit OCL4DNNInnerProduct(OCL4DNNInnerProductConfig config); ~OCL4DNNInnerProduct(); bool Forward(const UMat& bottom_data, const UMat& weight, const UMat& bias, UMat& top_data); private: OCL4DNNInnerProductConfig config_; int32_t axis_; int32_t num_output_; int32_t M_; int32_t N_; int32_t K_; bool bias_term_; bool transpose_; bool image_copied_; bool phase_test_; }; typedef enum { LRNParameter_NormRegion_ACROSS_CHANNELS = 0, LRNParameter_NormRegion_WITHIN_CHANNEL = 1 } LRNParameter_NormRegion_WITHIN_CHANNEL_t; struct OCL4DNNLRNConfig { OCL4DNNLRNConfig() : phase_test(true) {} MatShape in_shape; LRNParameter_NormRegion_WITHIN_CHANNEL_t lrn_type; bool phase_test; // = true; int local_size; float alpha; float beta; float k; bool norm_by_size; int32_t batch_size; int32_t channels; int32_t height; int32_t width; }; template<typename Dtype> class OCL4DNNLRN { public: explicit OCL4DNNLRN(OCL4DNNLRNConfig config); bool Forward(const UMat& bottom_data, UMat& top_data); private: bool crossChannelForward(const UMat& bottom_data, UMat& top_data); LRNParameter_NormRegion_WITHIN_CHANNEL_t lrn_type_; bool phase_test_; int32_t size_; Dtype alpha_; Dtype beta_; Dtype k_; int32_t num_; int32_t channels_; int32_t height_; int32_t width_; bool norm_by_size_; }; struct OCL4DNNSoftmaxConfig { OCL4DNNSoftmaxConfig() {} MatShape in_shape; int axis; int channels; }; template<typename Dtype> class OCL4DNNSoftmax { public: explicit OCL4DNNSoftmax(OCL4DNNSoftmaxConfig config); ~OCL4DNNSoftmax(); bool Forward(const UMat& bottom_data, UMat& top_data); private: int32_t softmax_axis_; int32_t inner_num_; int32_t outer_num_; int32_t channels_; int32_t count_; bool use_slm_; UMat scale_data_; }; #endif // HAVE_OPENCL } // namespace ocl4dnn } // namespace dnn } // namespce cv #endif
31.126582
102
0.565338
[ "vector" ]
603cceecab35b33629cd0d404ea0cfaa726cf564
1,310
cpp
C++
SPHINXsys/src/for_3D_build/particle_generator/particle_generator_lattice_supplementary.cpp
Irvise/SPHinXsys
dfa67ec02bbc85824e2d6adf6d0395bb887e2bdb
[ "Apache-2.0" ]
3
2020-11-30T15:24:54.000Z
2021-04-11T09:16:09.000Z
SPHINXsys/src/for_3D_build/particle_generator/particle_generator_lattice_supplementary.cpp
Bo-Zhang1995/SPHinXsys
ee03f41711cc8ee7dcf75cdff6afa0859b0a0e89
[ "Apache-2.0" ]
null
null
null
SPHINXsys/src/for_3D_build/particle_generator/particle_generator_lattice_supplementary.cpp
Bo-Zhang1995/SPHinXsys
ee03f41711cc8ee7dcf75cdff6afa0859b0a0e89
[ "Apache-2.0" ]
null
null
null
//common functions used by 3d buildings only #include "particle_generator_lattice.h" #include "geometry.h" #include "base_mesh.h" #include "base_body.h" #include "base_particles.h" namespace SPH { //=================================================================================================// void ParticleGeneratorLattice::createBaseParticles(BaseParticles* base_particles) { std::unique_ptr<Mesh> mesh(new Mesh(domain_bounds_, lattice_spacing_, 0)); size_t total_real_particles = 0; Real particle_volume = lattice_spacing_ * lattice_spacing_ * lattice_spacing_; Vecu number_of_lattices = mesh->NumberOfCells(); for (size_t i = 0; i < number_of_lattices[0]; ++i) for (size_t j = 0; j < number_of_lattices[1]; ++j) for (size_t k = 0; k < number_of_lattices[2]; ++k) { Vecd particle_position = mesh->CellPositionFromIndex(Vecu(i, j, k)); if (body_shape_->checkNotFar(particle_position, lattice_spacing_)) { if (body_shape_->checkContain(particle_position)) { createABaseParticle(base_particles, particle_position, particle_volume, total_real_particles); } } } base_particles->total_real_particles_ = total_real_particles; } //=================================================================================================// }
38.529412
102
0.616794
[ "mesh", "geometry", "3d" ]
6041f20d5514a2b3237e0e3e3bf14d7f08a82531
3,585
cpp
C++
src/Engine/Drawables/Object/Torus.cpp
DaftMat/Daft-Engine
e3d918b4b876d17abd889b9b6b13bd858a079538
[ "MIT" ]
1
2020-10-26T02:36:58.000Z
2020-10-26T02:36:58.000Z
src/Engine/Drawables/Object/Torus.cpp
DaftMat/Daft-Engine
e3d918b4b876d17abd889b9b6b13bd858a079538
[ "MIT" ]
6
2020-02-14T21:45:52.000Z
2020-09-23T17:58:58.000Z
src/Engine/Drawables/Object/Torus.cpp
DaftMat/Daft-Engine
e3d918b4b876d17abd889b9b6b13bd858a079538
[ "MIT" ]
null
null
null
// // Created by mathis on 10/09/2020. // #include "Torus.hpp" #include <Core/Utils/DrawableVisitor.hpp> namespace daft::engine { int Torus::m_nrTorus{0}; Torus::Torus(int meridians, int parallels, float innerRadius, float outerRadius, Composite *parent, std::string name) : Object(parent, std::move(name)), m_meridians{meridians}, m_parallels{parallels}, m_innerRadius{innerRadius}, m_outerRadius{outerRadius} { createTorus(); } core::SettingManager Torus::getSettings() const { core::SettingManager sm; sm.add("Meridians", m_meridians); sm.add("Parallels", m_parallels); sm.add("Inner Radius", m_innerRadius); sm.add("Outer Radius", m_outerRadius); return sm; } void Torus::setSettings(const core::SettingManager &s) { if (s.has("Meridians")) setMeridians(s.get<int>("Meridians")); if (s.has("Parallels")) setParallels(s.get<int>("Parallels")); if (s.has("Inner Radius")) setInnerRadius(s.get<float>("Inner Radius")); if (s.has("Outer Radius")) setOuterRadius(s.get<float>("Outer Radius")); } void Torus::setMeridians(int m) { if (m_meridians == m) return; m_meridians = m; updateNextFrame(); } void Torus::setParallels(int p) { if (m_parallels == p) return; m_parallels = p; updateNextFrame(); } void Torus::setInnerRadius(float r) { if (m_innerRadius == r) return; m_innerRadius = r; updateNextFrame(); } void Torus::setOuterRadius(float r) { if (m_outerRadius == r) return; m_outerRadius = r; updateNextFrame(); } void Torus::createTorus() { core::AttribManager am; std::vector<glm::vec3> positions; std::vector<glm::vec3> normals; std::vector<glm::vec2> texCoords; std::vector<glm::vec3> tangents; float mStep = (2.f * glm::pi<float>()) / float(m_meridians); float pStep = (2.f * glm::pi<float>()) / float(m_parallels); for (int j = 0; j <= m_meridians; ++j) { float mAngle = float(j) * mStep; for (int i = 0; i <= m_parallels; ++i) { float pAngle = float(i) * pStep; glm::vec3 outCenter = m_innerRadius * glm::vec3{glm::cos(mAngle), 0.f, glm::sin(mAngle)}; auto w = glm::normalize(outCenter); glm::vec3 pos = outCenter + m_outerRadius * glm::cos(pAngle) * w + m_outerRadius * glm::sin(pAngle) * glm::vec3{0.f, 1.f, 0.f}; positions.push_back(pos); glm::vec3 n = glm::normalize(pos - outCenter); normals.push_back(n); texCoords.emplace_back(mAngle, pAngle); glm::vec3 t, b; core::orthoVectors(n, t, b); tangents.push_back(t); } } am.addAttrib(positions); am.addAttrib(normals); am.addAttrib(texCoords); /// topology for (int i = 1; i <= m_meridians; ++i) { for (int j = 0; j < m_parallels; ++j) { int max = m_parallels + 1; /// first triangle am.indices().push_back(j + max * i); am.indices().push_back((j + 1) + max * i); am.indices().push_back(j + max * (i - 1)); /// second triangle am.indices().push_back(j + max * (i - 1)); am.indices().push_back((j + 1) + max * i); am.indices().push_back((j + 1) + max * (i - 1)); } } m_meshObjects.clear(); std::vector<core::Mesh> meshes; meshes.emplace_back(am); m_meshObjects.emplace_back(std::move(meshes)); } void Torus::accept(core::DrawableVisitor *visitor) { visitor->visit(this); } } // namespace daft::engine
31.173913
117
0.593584
[ "mesh", "object", "vector" ]
60446f10172a8197cbc9a23bdc7161598e2919cd
32,020
cpp
C++
DSPFilters4JUCEDemo/JuceLibraryCode/modules/juce_audio_devices/native/juce_android_OpenSL.cpp
rc-h/dspfilters4juce
60b32a3af7eb89289f89e01db1239e312544ec2c
[ "MIT" ]
10
2017-07-16T04:50:47.000Z
2022-02-14T06:10:45.000Z
DSPFilters4JUCEDemo/JuceLibraryCode/modules/juce_audio_devices/native/juce_android_OpenSL.cpp
rc-h/dspfilters4juce
60b32a3af7eb89289f89e01db1239e312544ec2c
[ "MIT" ]
null
null
null
DSPFilters4JUCEDemo/JuceLibraryCode/modules/juce_audio_devices/native/juce_android_OpenSL.cpp
rc-h/dspfilters4juce
60b32a3af7eb89289f89e01db1239e312544ec2c
[ "MIT" ]
3
2017-11-07T14:44:14.000Z
2021-03-16T02:45:57.000Z
/* ============================================================================== This file is part of the JUCE library. Copyright (c) 2016 - ROLI Ltd. Permission is granted to use this software under the terms of the ISC license http://www.isc.org/downloads/software-support-policy/isc-license/ Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL ISC BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. ----------------------------------------------------------------------------- To release a closed-source product which uses other parts of JUCE not licensed under the ISC terms, commercial licenses are available: visit www.juce.com for more information. ============================================================================== */ #undef check const char* const openSLTypeName = "Android OpenSL"; bool isOpenSLAvailable() { DynamicLibrary library; return library.open ("libOpenSLES.so"); } //============================================================================== class OpenSLAudioIODevice : public AudioIODevice, private Thread { public: OpenSLAudioIODevice (const String& deviceName) : AudioIODevice (deviceName, openSLTypeName), Thread ("OpenSL"), callback (nullptr), sampleRate (0), deviceOpen (false), inputBuffer (2, 2), outputBuffer (2, 2) { // OpenSL has piss-poor support for determining latency, so the only way I can find to // get a number for this is by asking the AudioTrack/AudioRecord classes.. AndroidAudioIODevice javaDevice (deviceName); // this is a total guess about how to calculate the latency, but seems to vaguely agree // with the devices I've tested.. YMMV inputLatency = (javaDevice.minBufferSizeIn * 2) / 3; outputLatency = (javaDevice.minBufferSizeOut * 2) / 3; const int64 longestLatency = jmax (inputLatency, outputLatency); const int64 totalLatency = inputLatency + outputLatency; inputLatency = (int) ((longestLatency * inputLatency) / totalLatency) & ~15; outputLatency = (int) ((longestLatency * outputLatency) / totalLatency) & ~15; } ~OpenSLAudioIODevice() { close(); } bool openedOk() const { return engine.outputMixObject != nullptr; } StringArray getOutputChannelNames() override { StringArray s; s.add ("Left"); s.add ("Right"); return s; } StringArray getInputChannelNames() override { StringArray s; s.add ("Audio Input"); return s; } Array<double> getAvailableSampleRates() override { static const double rates[] = { 8000.0, 16000.0, 32000.0, 44100.0, 48000.0 }; Array<double> retval (rates, numElementsInArray (rates)); // make sure the native sample rate is pafrt of the list double native = getNativeSampleRate(); if (native != 0.0 && ! retval.contains (native)) retval.add (native); return retval; } Array<int> getAvailableBufferSizes() override { // we need to offer the lowest possible buffer size which // is the native buffer size const int defaultNumMultiples = 8; const int nativeBufferSize = getNativeBufferSize(); Array<int> retval; for (int i = 1; i < defaultNumMultiples; ++i) retval.add (i * nativeBufferSize); return retval; } String open (const BigInteger& inputChannels, const BigInteger& outputChannels, double requestedSampleRate, int bufferSize) override { close(); lastError.clear(); sampleRate = (int) requestedSampleRate; int preferredBufferSize = (bufferSize <= 0) ? getDefaultBufferSize() : bufferSize; activeOutputChans = outputChannels; activeOutputChans.setRange (2, activeOutputChans.getHighestBit(), false); numOutputChannels = activeOutputChans.countNumberOfSetBits(); activeInputChans = inputChannels; activeInputChans.setRange (1, activeInputChans.getHighestBit(), false); numInputChannels = activeInputChans.countNumberOfSetBits(); actualBufferSize = preferredBufferSize; inputBuffer.setSize (jmax (1, numInputChannels), actualBufferSize); outputBuffer.setSize (jmax (1, numOutputChannels), actualBufferSize); outputBuffer.clear(); const int audioBuffersToEnqueue = hasLowLatencyAudioPath() ? buffersToEnqueueForLowLatency : buffersToEnqueueSlowAudio; DBG ("OpenSL: numInputChannels = " << numInputChannels << ", numOutputChannels = " << numOutputChannels << ", nativeBufferSize = " << getNativeBufferSize() << ", nativeSampleRate = " << getNativeSampleRate() << ", actualBufferSize = " << actualBufferSize << ", audioBuffersToEnqueue = " << audioBuffersToEnqueue << ", sampleRate = " << sampleRate); if (numInputChannels > 0) { if (! RuntimePermissions::isGranted (RuntimePermissions::recordAudio)) { // If you hit this assert, you probably forgot to get RuntimePermissions::recordAudio // before trying to open an audio input device. This is not going to work! jassertfalse; lastError = "Error opening OpenSL input device: the app was not granted android.permission.RECORD_AUDIO"; } else { recorder = engine.createRecorder (numInputChannels, sampleRate, audioBuffersToEnqueue, actualBufferSize); if (recorder == nullptr) lastError = "Error opening OpenSL input device: creating Recorder failed."; } } if (numOutputChannels > 0) { player = engine.createPlayer (numOutputChannels, sampleRate, audioBuffersToEnqueue, actualBufferSize); if (player == nullptr) lastError = "Error opening OpenSL input device: creating Player failed."; } // pre-fill buffers for (int i = 0; i < audioBuffersToEnqueue; ++i) processBuffers(); startThread (8); deviceOpen = true; return lastError; } void close() override { stop(); stopThread (6000); deviceOpen = false; recorder = nullptr; player = nullptr; } int getOutputLatencyInSamples() override { return outputLatency; } int getInputLatencyInSamples() override { return inputLatency; } bool isOpen() override { return deviceOpen; } int getCurrentBufferSizeSamples() override { return actualBufferSize; } int getCurrentBitDepth() override { return 16; } BigInteger getActiveOutputChannels() const override { return activeOutputChans; } BigInteger getActiveInputChannels() const override { return activeInputChans; } String getLastError() override { return lastError; } bool isPlaying() override { return callback != nullptr; } int getDefaultBufferSize() override { // Only on a Pro-Audio device will we set the lowest possible buffer size // by default. We need to be more conservative on other devices // as they may be low-latency, but still have a crappy CPU. return (isProAudioDevice() ? 1 : 6) * defaultBufferSizeIsMultipleOfNative * getNativeBufferSize(); } double getCurrentSampleRate() override { return (sampleRate == 0.0 ? getNativeSampleRate() : sampleRate); } void start (AudioIODeviceCallback* newCallback) override { stop(); if (deviceOpen && callback != newCallback) { if (newCallback != nullptr) newCallback->audioDeviceAboutToStart (this); setCallback (newCallback); } } void stop() override { if (AudioIODeviceCallback* const oldCallback = setCallback (nullptr)) oldCallback->audioDeviceStopped(); } bool setAudioPreprocessingEnabled (bool enable) override { return recorder != nullptr && recorder->setAudioPreprocessingEnabled (enable); } private: //============================================================================== CriticalSection callbackLock; AudioIODeviceCallback* callback; int actualBufferSize, sampleRate; int inputLatency, outputLatency; bool deviceOpen; String lastError; BigInteger activeOutputChans, activeInputChans; int numInputChannels, numOutputChannels; AudioSampleBuffer inputBuffer, outputBuffer; struct Player; struct Recorder; enum { // The number of buffers to enqueue needs to be at least two for the audio to use the low-latency // audio path (see "Performance" section in ndk/docs/Additional_library_docs/opensles/index.html) buffersToEnqueueForLowLatency = 2, buffersToEnqueueSlowAudio = 4, defaultBufferSizeIsMultipleOfNative = 1 }; //============================================================================== static String audioManagerGetProperty (const String& property) { const LocalRef<jstring> jProperty (javaString (property)); const LocalRef<jstring> text ((jstring) android.activity.callObjectMethod (JuceAppActivity.audioManagerGetProperty, jProperty.get())); if (text.get() != 0) return juceString (text); return String(); } static bool androidHasSystemFeature (const String& property) { const LocalRef<jstring> jProperty (javaString (property)); return android.activity.callBooleanMethod (JuceAppActivity.hasSystemFeature, jProperty.get()); } static double getNativeSampleRate() { return audioManagerGetProperty ("android.media.property.OUTPUT_SAMPLE_RATE").getDoubleValue(); } static int getNativeBufferSize() { const int val = audioManagerGetProperty ("android.media.property.OUTPUT_FRAMES_PER_BUFFER").getIntValue(); return val > 0 ? val : 512; } static bool isProAudioDevice() { return androidHasSystemFeature ("android.hardware.audio.pro"); } static bool hasLowLatencyAudioPath() { return androidHasSystemFeature ("android.hardware.audio.low_latency"); } //============================================================================== AudioIODeviceCallback* setCallback (AudioIODeviceCallback* const newCallback) { const ScopedLock sl (callbackLock); AudioIODeviceCallback* const oldCallback = callback; callback = newCallback; return oldCallback; } void processBuffers() { if (recorder != nullptr) recorder->readNextBlock (inputBuffer, *this); { const ScopedLock sl (callbackLock); if (callback != nullptr) callback->audioDeviceIOCallback (numInputChannels > 0 ? inputBuffer.getArrayOfReadPointers() : nullptr, numInputChannels, numOutputChannels > 0 ? outputBuffer.getArrayOfWritePointers() : nullptr, numOutputChannels, actualBufferSize); else outputBuffer.clear(); } if (player != nullptr) player->writeBuffer (outputBuffer, *this); } void run() override { setThreadToAudioPriority(); if (recorder != nullptr) recorder->start(); if (player != nullptr) player->start(); while (! threadShouldExit()) processBuffers(); } void setThreadToAudioPriority() { // see android.os.Process.THREAD_PRIORITY_AUDIO const int THREAD_PRIORITY_AUDIO = -16; jint priority = THREAD_PRIORITY_AUDIO; if (priority != android.activity.callIntMethod (JuceAppActivity.setCurrentThreadPriority, (jint) priority)) DBG ("Unable to set audio thread priority: priority is still " << priority); } //============================================================================== struct Engine { Engine() : engineObject (nullptr), engineInterface (nullptr), outputMixObject (nullptr) { if (library.open ("libOpenSLES.so")) { typedef SLresult (*CreateEngineFunc) (SLObjectItf*, SLuint32, const SLEngineOption*, SLuint32, const SLInterfaceID*, const SLboolean*); if (CreateEngineFunc createEngine = (CreateEngineFunc) library.getFunction ("slCreateEngine")) { check (createEngine (&engineObject, 0, nullptr, 0, nullptr, nullptr)); SLInterfaceID* SL_IID_ENGINE = (SLInterfaceID*) library.getFunction ("SL_IID_ENGINE"); SL_IID_ANDROIDSIMPLEBUFFERQUEUE = (SLInterfaceID*) library.getFunction ("SL_IID_ANDROIDSIMPLEBUFFERQUEUE"); SL_IID_PLAY = (SLInterfaceID*) library.getFunction ("SL_IID_PLAY"); SL_IID_RECORD = (SLInterfaceID*) library.getFunction ("SL_IID_RECORD"); SL_IID_ANDROIDCONFIGURATION = (SLInterfaceID*) library.getFunction ("SL_IID_ANDROIDCONFIGURATION"); check ((*engineObject)->Realize (engineObject, SL_BOOLEAN_FALSE)); check ((*engineObject)->GetInterface (engineObject, *SL_IID_ENGINE, &engineInterface)); check ((*engineInterface)->CreateOutputMix (engineInterface, &outputMixObject, 0, nullptr, nullptr)); check ((*outputMixObject)->Realize (outputMixObject, SL_BOOLEAN_FALSE)); } } } ~Engine() { if (outputMixObject != nullptr) (*outputMixObject)->Destroy (outputMixObject); if (engineObject != nullptr) (*engineObject)->Destroy (engineObject); } Player* createPlayer (const int numChannels, const int sampleRate, const int numBuffers, const int bufferSize) { if (numChannels <= 0) return nullptr; ScopedPointer<Player> player (new Player (numChannels, sampleRate, *this, numBuffers, bufferSize)); return player->openedOk() ? player.release() : nullptr; } Recorder* createRecorder (const int numChannels, const int sampleRate, const int numBuffers, const int bufferSize) { if (numChannels <= 0) return nullptr; ScopedPointer<Recorder> recorder (new Recorder (numChannels, sampleRate, *this, numBuffers, bufferSize)); return recorder->openedOk() ? recorder.release() : nullptr; } SLObjectItf engineObject; SLEngineItf engineInterface; SLObjectItf outputMixObject; SLInterfaceID* SL_IID_ANDROIDSIMPLEBUFFERQUEUE; SLInterfaceID* SL_IID_PLAY; SLInterfaceID* SL_IID_RECORD; SLInterfaceID* SL_IID_ANDROIDCONFIGURATION; private: DynamicLibrary library; JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Engine) }; //============================================================================== struct BufferList { BufferList (const int numChannels_, const int numBuffers_, const int numSamples_) : numChannels (numChannels_), numBuffers (numBuffers_), numSamples (numSamples_), bufferSpace (numChannels_ * numSamples * numBuffers), nextBlock (0) { } int16* waitForFreeBuffer (Thread& threadToCheck) noexcept { while (numBlocksOut.get() == numBuffers) { dataArrived.wait (1); if (threadToCheck.threadShouldExit()) return nullptr; } return getNextBuffer(); } int16* getNextBuffer() noexcept { if (++nextBlock == numBuffers) nextBlock = 0; return bufferSpace + nextBlock * numChannels * numSamples; } void bufferReturned() noexcept { --numBlocksOut; dataArrived.signal(); } void bufferSent() noexcept { ++numBlocksOut; dataArrived.signal(); } int getBufferSizeBytes() const noexcept { return numChannels * numSamples * sizeof (int16); } const int numChannels, numBuffers, numSamples; private: HeapBlock<int16> bufferSpace; int nextBlock; Atomic<int> numBlocksOut; WaitableEvent dataArrived; }; //============================================================================== struct Player { Player (int numChannels, int sampleRate, Engine& engine, int playerNumBuffers, int playerBufferSize) : playerObject (nullptr), playerPlay (nullptr), playerBufferQueue (nullptr), bufferList (numChannels, playerNumBuffers, playerBufferSize) { SLDataFormat_PCM pcmFormat = { SL_DATAFORMAT_PCM, (SLuint32) numChannels, (SLuint32) (sampleRate * 1000), SL_PCMSAMPLEFORMAT_FIXED_16, SL_PCMSAMPLEFORMAT_FIXED_16, (numChannels == 1) ? SL_SPEAKER_FRONT_CENTER : (SL_SPEAKER_FRONT_LEFT | SL_SPEAKER_FRONT_RIGHT), SL_BYTEORDER_LITTLEENDIAN }; SLDataLocator_AndroidSimpleBufferQueue bufferQueue = { SL_DATALOCATOR_ANDROIDSIMPLEBUFFERQUEUE, static_cast<SLuint32> (bufferList.numBuffers) }; SLDataSource audioSrc = { &bufferQueue, &pcmFormat }; SLDataLocator_OutputMix outputMix = { SL_DATALOCATOR_OUTPUTMIX, engine.outputMixObject }; SLDataSink audioSink = { &outputMix, nullptr }; // (SL_IID_BUFFERQUEUE is not guaranteed to remain future-proof, so use SL_IID_ANDROIDSIMPLEBUFFERQUEUE) const SLInterfaceID interfaceIDs[] = { *engine.SL_IID_ANDROIDSIMPLEBUFFERQUEUE }; const SLboolean flags[] = { SL_BOOLEAN_TRUE }; check ((*engine.engineInterface)->CreateAudioPlayer (engine.engineInterface, &playerObject, &audioSrc, &audioSink, 1, interfaceIDs, flags)); check ((*playerObject)->Realize (playerObject, SL_BOOLEAN_FALSE)); check ((*playerObject)->GetInterface (playerObject, *engine.SL_IID_PLAY, &playerPlay)); check ((*playerObject)->GetInterface (playerObject, *engine.SL_IID_ANDROIDSIMPLEBUFFERQUEUE, &playerBufferQueue)); check ((*playerBufferQueue)->RegisterCallback (playerBufferQueue, staticCallback, this)); } ~Player() { if (playerPlay != nullptr) check ((*playerPlay)->SetPlayState (playerPlay, SL_PLAYSTATE_STOPPED)); if (playerBufferQueue != nullptr) check ((*playerBufferQueue)->Clear (playerBufferQueue)); if (playerObject != nullptr) (*playerObject)->Destroy (playerObject); } bool openedOk() const noexcept { return playerBufferQueue != nullptr; } void start() { jassert (openedOk()); check ((*playerPlay)->SetPlayState (playerPlay, SL_PLAYSTATE_PLAYING)); } void writeBuffer (const AudioSampleBuffer& buffer, Thread& thread) noexcept { jassert (buffer.getNumChannels() == bufferList.numChannels); jassert (buffer.getNumSamples() < bufferList.numSamples * bufferList.numBuffers); int offset = 0; int numSamples = buffer.getNumSamples(); while (numSamples > 0) { if (int16* const destBuffer = bufferList.waitForFreeBuffer (thread)) { for (int i = 0; i < bufferList.numChannels; ++i) { typedef AudioData::Pointer<AudioData::Int16, AudioData::LittleEndian, AudioData::Interleaved, AudioData::NonConst> DstSampleType; typedef AudioData::Pointer<AudioData::Float32, AudioData::NativeEndian, AudioData::NonInterleaved, AudioData::Const> SrcSampleType; DstSampleType dstData (destBuffer + i, bufferList.numChannels); SrcSampleType srcData (buffer.getReadPointer (i, offset)); dstData.convertSamples (srcData, bufferList.numSamples); } enqueueBuffer (destBuffer); numSamples -= bufferList.numSamples; offset += bufferList.numSamples; } else { break; } } } private: SLObjectItf playerObject; SLPlayItf playerPlay; SLAndroidSimpleBufferQueueItf playerBufferQueue; BufferList bufferList; void enqueueBuffer (int16* buffer) noexcept { check ((*playerBufferQueue)->Enqueue (playerBufferQueue, buffer, bufferList.getBufferSizeBytes())); bufferList.bufferSent(); } static void staticCallback (SLAndroidSimpleBufferQueueItf queue, void* context) noexcept { jassert (queue == static_cast<Player*> (context)->playerBufferQueue); ignoreUnused (queue); static_cast<Player*> (context)->bufferList.bufferReturned(); } JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Player) }; //============================================================================== struct Recorder { Recorder (int numChannels, int sampleRate, Engine& engine, const int numBuffers, const int numSamples) : recorderObject (nullptr), recorderRecord (nullptr), recorderBufferQueue (nullptr), configObject (nullptr), bufferList (numChannels, numBuffers, numSamples) { SLDataFormat_PCM pcmFormat = { SL_DATAFORMAT_PCM, (SLuint32) numChannels, (SLuint32) (sampleRate * 1000), // (sample rate units are millihertz) SL_PCMSAMPLEFORMAT_FIXED_16, SL_PCMSAMPLEFORMAT_FIXED_16, (numChannels == 1) ? SL_SPEAKER_FRONT_CENTER : (SL_SPEAKER_FRONT_LEFT | SL_SPEAKER_FRONT_RIGHT), SL_BYTEORDER_LITTLEENDIAN }; SLDataLocator_IODevice ioDevice = { SL_DATALOCATOR_IODEVICE, SL_IODEVICE_AUDIOINPUT, SL_DEFAULTDEVICEID_AUDIOINPUT, nullptr }; SLDataSource audioSrc = { &ioDevice, nullptr }; SLDataLocator_AndroidSimpleBufferQueue bufferQueue = { SL_DATALOCATOR_ANDROIDSIMPLEBUFFERQUEUE, static_cast<SLuint32> (bufferList.numBuffers) }; SLDataSink audioSink = { &bufferQueue, &pcmFormat }; const SLInterfaceID interfaceIDs[] = { *engine.SL_IID_ANDROIDSIMPLEBUFFERQUEUE }; const SLboolean flags[] = { SL_BOOLEAN_TRUE }; if (check ((*engine.engineInterface)->CreateAudioRecorder (engine.engineInterface, &recorderObject, &audioSrc, &audioSink, 1, interfaceIDs, flags))) { if (check ((*recorderObject)->Realize (recorderObject, SL_BOOLEAN_FALSE))) { check ((*recorderObject)->GetInterface (recorderObject, *engine.SL_IID_RECORD, &recorderRecord)); check ((*recorderObject)->GetInterface (recorderObject, *engine.SL_IID_ANDROIDSIMPLEBUFFERQUEUE, &recorderBufferQueue)); // not all android versions seem to have a config object SLresult result = (*recorderObject)->GetInterface (recorderObject, *engine.SL_IID_ANDROIDCONFIGURATION, &configObject); if (result != SL_RESULT_SUCCESS) configObject = nullptr; check ((*recorderBufferQueue)->RegisterCallback (recorderBufferQueue, staticCallback, this)); check ((*recorderRecord)->SetRecordState (recorderRecord, SL_RECORDSTATE_STOPPED)); } } } ~Recorder() { if (recorderRecord != nullptr) check ((*recorderRecord)->SetRecordState (recorderRecord, SL_RECORDSTATE_STOPPED)); if (recorderBufferQueue != nullptr) check ((*recorderBufferQueue)->Clear (recorderBufferQueue)); if (recorderObject != nullptr) (*recorderObject)->Destroy (recorderObject); } bool openedOk() const noexcept { return recorderBufferQueue != nullptr; } void start() { jassert (openedOk()); check ((*recorderRecord)->SetRecordState (recorderRecord, SL_RECORDSTATE_RECORDING)); } void readNextBlock (AudioSampleBuffer& buffer, Thread& thread) { jassert (buffer.getNumChannels() == bufferList.numChannels); jassert (buffer.getNumSamples() < bufferList.numSamples * bufferList.numBuffers); jassert ((buffer.getNumSamples() % bufferList.numSamples) == 0); int offset = 0; int numSamples = buffer.getNumSamples(); while (numSamples > 0) { if (int16* const srcBuffer = bufferList.waitForFreeBuffer (thread)) { for (int i = 0; i < bufferList.numChannels; ++i) { typedef AudioData::Pointer<AudioData::Float32, AudioData::NativeEndian, AudioData::NonInterleaved, AudioData::NonConst> DstSampleType; typedef AudioData::Pointer<AudioData::Int16, AudioData::LittleEndian, AudioData::Interleaved, AudioData::Const> SrcSampleType; DstSampleType dstData (buffer.getWritePointer (i, offset)); SrcSampleType srcData (srcBuffer + i, bufferList.numChannels); dstData.convertSamples (srcData, bufferList.numSamples); } enqueueBuffer (srcBuffer); numSamples -= bufferList.numSamples; offset += bufferList.numSamples; } else { break; } } } bool setAudioPreprocessingEnabled (bool enable) { SLuint32 mode = enable ? SL_ANDROID_RECORDING_PRESET_GENERIC : SL_ANDROID_RECORDING_PRESET_VOICE_RECOGNITION; return configObject != nullptr && check ((*configObject)->SetConfiguration (configObject, SL_ANDROID_KEY_RECORDING_PRESET, &mode, sizeof (mode))); } private: SLObjectItf recorderObject; SLRecordItf recorderRecord; SLAndroidSimpleBufferQueueItf recorderBufferQueue; SLAndroidConfigurationItf configObject; BufferList bufferList; void enqueueBuffer (int16* buffer) noexcept { check ((*recorderBufferQueue)->Enqueue (recorderBufferQueue, buffer, bufferList.getBufferSizeBytes())); bufferList.bufferSent(); } static void staticCallback (SLAndroidSimpleBufferQueueItf queue, void* context) noexcept { jassert (queue == static_cast<Recorder*> (context)->recorderBufferQueue); ignoreUnused (queue); static_cast<Recorder*> (context)->bufferList.bufferReturned(); } JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Recorder) }; //============================================================================== Engine engine; ScopedPointer<Player> player; ScopedPointer<Recorder> recorder; //============================================================================== static bool check (const SLresult result) noexcept { jassert (result == SL_RESULT_SUCCESS); return result == SL_RESULT_SUCCESS; } JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (OpenSLAudioIODevice) }; //============================================================================== class OpenSLAudioDeviceType : public AudioIODeviceType { public: OpenSLAudioDeviceType() : AudioIODeviceType (openSLTypeName) {} //============================================================================== void scanForDevices() override {} StringArray getDeviceNames (bool wantInputNames) const override { return StringArray (openSLTypeName); } int getDefaultDeviceIndex (bool forInput) const override { return 0; } int getIndexOfDevice (AudioIODevice* device, bool asInput) const override { return device != nullptr ? 0 : -1; } bool hasSeparateInputsAndOutputs() const override { return false; } AudioIODevice* createDevice (const String& outputDeviceName, const String& inputDeviceName) override { ScopedPointer<OpenSLAudioIODevice> dev; if (outputDeviceName.isNotEmpty() || inputDeviceName.isNotEmpty()) { dev = new OpenSLAudioIODevice (outputDeviceName.isNotEmpty() ? outputDeviceName : inputDeviceName); if (! dev->openedOk()) dev = nullptr; } return dev.release(); } private: JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (OpenSLAudioDeviceType) }; //============================================================================== AudioIODeviceType* AudioIODeviceType::createAudioIODeviceType_OpenSLES() { return isOpenSLAvailable() ? new OpenSLAudioDeviceType() : nullptr; }
41.051282
159
0.56777
[ "object" ]
604a79d02b0014b50f3c99ccf393d1759491136b
22,207
cpp
C++
src/plugins/http/gfal_http_plugin.cpp
gabrielefronze/gfal2
5d958ec10ecd32b02e8fada457b6b5dd7bc7c4e1
[ "Apache-2.0" ]
null
null
null
src/plugins/http/gfal_http_plugin.cpp
gabrielefronze/gfal2
5d958ec10ecd32b02e8fada457b6b5dd7bc7c4e1
[ "Apache-2.0" ]
null
null
null
src/plugins/http/gfal_http_plugin.cpp
gabrielefronze/gfal2
5d958ec10ecd32b02e8fada457b6b5dd7bc7c4e1
[ "Apache-2.0" ]
null
null
null
/* * Copyright (c) CERN 2013-2015 * * Copyright (c) Members of the EMI Collaboration. 2010-2013 * See http://www.eu-emi.eu/partners for details on the copyright * holders. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "gfal_http_plugin.h" #include <cstdio> #include <cstring> #include <sstream> #include <davix.hpp> #include <errno.h> #include <davix/utils/davix_gcloud_utils.hpp> using namespace Davix; static const char* http_module_name = "http_plugin"; GQuark http_plugin_domain = g_quark_from_static_string(http_module_name); const char* gfal_http_get_name(void) { return GFAL2_PLUGIN_VERSIONED("http", VERSION);; } // this is to understand if the active storage in TPC needs gridsite delegation // if the destination does not need tls we avoid it static bool delegation_required(const Davix::Uri& uri) { bool needs_delegation = false; if ((uri.getProtocol().compare(0, 5, "https") == 0) || (uri.getProtocol().compare(0, 4, "davs") == 0)) { needs_delegation = true; } return needs_delegation; } static int get_corresponding_davix_log_level() { int davix_log_level = DAVIX_LOG_CRITICAL; GLogLevelFlags gfal2_log_level = gfal2_log_get_level(); if (gfal2_log_level & G_LOG_LEVEL_DEBUG) davix_log_level = DAVIX_LOG_TRACE; else if (gfal2_log_level & G_LOG_LEVEL_INFO) davix_log_level = DAVIX_LOG_VERBOSE; return davix_log_level; } static bool isS3SignedURL(const Davix::Uri &url) { if(url.queryParamExists("AWSAccessKeyId") && url.queryParamExists("Signature")) { return true; } if(url.queryParamExists("X-Amz-Credential") && url.queryParamExists("X-Amz-Signature")) { return true; } return false; } /// Token-based authorization. // If this returns `true`, the RequestParams have been successfully // configured to utilize a bearer token. In such a case, no other // authorization mechanism (such as user certs) should be used. static bool gfal_http_get_token(RequestParams & params, gfal2_context_t handle, const Davix::Uri &url, bool secondary_endpoint) { if (isS3SignedURL(url)) { return false; } GError *error = NULL; gchar *token = gfal2_cred_get(handle, GFAL_CRED_BEARER, url.getString().c_str(), NULL, &error); g_clear_error(&error); // for now, ignore the error messages. if (!token) { // if we don't have specific token for requested URL fallback // to token stored for hostname (for TPC with macaroon tokens // we need at least BEARER set for full source URL and hostname // BEARER for destination because that one could be also used // to create all missing parent directories) token = gfal2_cred_get(handle, GFAL_CRED_BEARER, url.getHost().c_str(), NULL, &error); g_clear_error(&error); // for now, ignore the error messages. } if (!token) { return false; } std::stringstream ss; ss << "Bearer " << token; gfal2_log(G_LOG_LEVEL_DEBUG, "Using bearer token for HTTPS request authorization%s", secondary_endpoint ? " (passive TPC)" : ""); if (secondary_endpoint) { params.addHeader("TransferHeaderAuthorization", ss.str()); // If we have a valid token for the destination, we explicitly disable credential // delegation. params.addHeader("Credential", "none"); } else { params.addHeader("Authorization", ss.str()); } g_free(token); return true; } /// Authn implementation static void gfal_http_get_ucert(const Davix::Uri &url, RequestParams & params, gfal2_context_t handle) { std::string ukey, ucert; DavixError* tmp_err = NULL; GError *error = NULL; // Try user defined first std::string url_string = url.getString(); gchar *ucert_p = gfal2_cred_get(handle, GFAL_CRED_X509_CERT, url_string.c_str(), NULL, &error); g_clear_error(&error); gchar *ukey_p = gfal2_cred_get(handle, GFAL_CRED_X509_KEY, url_string.c_str(), NULL, &error); g_clear_error(&error); if (ucert_p) { gfal2_log(G_LOG_LEVEL_DEBUG, "Using client X509 for HTTPS session authorization"); ucert.assign(ucert_p); ukey= (ukey_p != NULL)?(std::string(ukey_p)):(ucert); X509Credential cred; if(cred.loadFromFilePEM(ukey,ucert,"", &tmp_err) <0){ gfal2_log(G_LOG_LEVEL_WARNING, "Could not load the user credentials: %s", tmp_err->getErrMsg().c_str()); }else{ params.setClientCertX509(cred); } } g_free(ucert_p); g_free(ukey_p); } /// AWS implementation static void gfal_http_get_aws_keys(gfal2_context_t handle, const std::string& group, gchar** secret_key, gchar** access_key, gchar** token, gchar** region, bool *alternate_url) { *secret_key = gfal2_get_opt_string(handle, group.c_str(), "SECRET_KEY", NULL); *access_key = gfal2_get_opt_string(handle, group.c_str(), "ACCESS_KEY", NULL); *token = gfal2_get_opt_string(handle, group.c_str(), "TOKEN", NULL); *region = gfal2_get_opt_string(handle, group.c_str(), "REGION", NULL); *alternate_url =gfal2_get_opt_boolean_with_default(handle, group.c_str(), "ALTERNATE", false); // For retrocompatibility if (!*secret_key) { *secret_key = gfal2_get_opt_string(handle, group.c_str(), "ACCESS_TOKEN_SECRET", NULL); } if (!*access_key) { *access_key = gfal2_get_opt_string(handle, group.c_str(), "ACCESS_TOKEN", NULL); } } static void gfal_http_get_aws(RequestParams & params, gfal2_context_t handle, const Davix::Uri& uri) { // Try generic configuration bool alternate_url; gchar *secret_key, *access_key, *token, *region; // Try S3:HOST std::string group_label("S3:"); group_label += uri.getHost(); std::transform(group_label.begin(), group_label.end(), group_label.begin(), ::toupper); gfal_http_get_aws_keys(handle, group_label, &secret_key, &access_key, &token, &region, &alternate_url); // Try S3:host removing bucket if (!secret_key) { std::string group_label("S3:"); std::string host = uri.getHost(); size_t i = host.find('.'); if (i != std::string::npos) { group_label += host.substr(i + 1); std::transform(group_label.begin(), group_label.end(), group_label.begin(), ::toupper); gfal_http_get_aws_keys(handle, group_label, &secret_key, &access_key, &token, &region, &alternate_url); } } // Try default if (!secret_key) { gfal_http_get_aws_keys(handle, "S3", &secret_key, &access_key, &token, &region, &alternate_url); } if (secret_key && access_key) { gfal2_log(G_LOG_LEVEL_DEBUG, "Setting S3 key pair"); params.setAwsAuthorizationKeys(secret_key, access_key); } if (token) { gfal2_log(G_LOG_LEVEL_DEBUG, "Using short-lived access token"); params.setAwsToken(token); } if (region) { gfal2_log(G_LOG_LEVEL_DEBUG, "Using region %s", region); params.setAwsRegion(region); } if (alternate_url) { gfal2_log(G_LOG_LEVEL_DEBUG, "Using S3 alternate URL"); params.setAwsAlternate(alternate_url); } g_free(secret_key); g_free(access_key); g_free(token); g_free(region); } static void gfal_http_get_gcloud(RequestParams & params, gfal2_context_t handle, const Davix::Uri& uri) { gchar *gcloud_json_file, *gcloud_json_string; std::string group_label("GCLOUD"); gcloud_json_file = gfal2_get_opt_string(handle, group_label.c_str(), "JSON_AUTH_FILE", NULL); gcloud_json_string = gfal2_get_opt_string(handle, group_label.c_str(), "JSON_AUTH_STRING", NULL); gcloud::CredentialProvider provider; if (gcloud_json_file) { gfal2_log(G_LOG_LEVEL_DEBUG, "Using gcloud json credential file"); params.setGcloudCredentials(provider.fromFile(std::string(gcloud_json_file))); } else if (gcloud_json_string) { gfal2_log(G_LOG_LEVEL_DEBUG, "Using gcloud json credential string"); params.setGcloudCredentials(provider.fromJSONString (std::string(gcloud_json_string))); } g_free(gcloud_json_file); g_free(gcloud_json_string); } static void gfal_http_get_cred(RequestParams & params, gfal2_context_t handle, const Davix::Uri& uri, bool secondary_endpoint = false) { gfal_http_get_ucert(uri, params, handle); // Only utilize AWS or GCLOUD tokens if a bearer token isn't available. // We still setup GSI in case the storage endpoint tries to fall back to GridSite delegation. // That does mean that we might contact the endpoint with both X509 and token auth -- but seems // to be an acceptable compromise. if (!gfal_http_get_token(params, handle, uri, secondary_endpoint)) { gfal_http_get_aws(params, handle, uri); gfal_http_get_gcloud(params, handle, uri); } } static void gfal_http_get_params(RequestParams & params, gfal2_context_t handle, const Davix::Uri& uri) { gboolean insecure_mode = gfal2_get_opt_boolean_with_default(handle, "HTTP PLUGIN", "INSECURE", FALSE); if (insecure_mode) { params.setSSLCAcheck(false); } if (uri.getProtocol().compare(0, 4, "http") == 0 ) { params.setProtocol(Davix::RequestProtocol::Http); } else if (uri.getProtocol().compare(0, 3, "dav") == 0) { params.setProtocol(Davix::RequestProtocol::Webdav); } else if (uri.getProtocol().compare(0, 2, "s3") == 0) { params.setProtocol(Davix::RequestProtocol::AwsS3); } else if (uri.getProtocol().compare(0, 6, "gcloud") == 0) { params.setProtocol(Davix::RequestProtocol::Gcloud); } else { params.setProtocol(Davix::RequestProtocol::Auto); } // Keep alive gboolean keep_alive = gfal2_get_opt_boolean_with_default(handle, "HTTP PLUGIN", "KEEP_ALIVE", TRUE); params.setKeepAlive(keep_alive); // Reset here the verbosity level davix_set_log_level(get_corresponding_davix_log_level()); // Avoid retries params.setOperationRetry(0); // User agent const char *agent, *version; gfal2_get_user_agent(handle, &agent, &version); std::ostringstream user_agent; if (agent) { user_agent << agent << "/" << version << " " << "gfal2/" << gfal2_version(); } else { user_agent << "gfal2/" << gfal2_version(); } params.setUserAgent(user_agent.str()); // Client information char* client_info = gfal2_get_client_info_string(handle); if (client_info) { params.addHeader("ClientInfo", client_info); } g_free(client_info); // Custom headers gsize headers_length = 0; char **headers = gfal2_get_opt_string_list_with_default(handle, "HTTP PLUGIN", "HEADERS", &headers_length, NULL); if (headers) { for (char **hi = headers; *hi != NULL; ++hi) { char **kv = g_strsplit(*hi, ":", 2); g_strstrip(kv[0]); g_strstrip(kv[1]); params.addHeader(kv[0], kv[1]); g_strfreev(kv); } g_strfreev(headers); } // Timeout struct timespec opTimeout; opTimeout.tv_sec = gfal2_get_opt_integer_with_default(handle, "HTTP PLUGIN", HTTP_CONFIG_OP_TIMEOUT, 8000); params.setOperationTimeout(&opTimeout); } void GfalHttpPluginData::get_tpc_params(bool push_mode, Davix::RequestParams * req_params, const Davix::Uri& src_uri, const Davix::Uri& dst_uri) { *req_params = reference_params; bool do_delegation = false; if (push_mode) { gfal_http_get_params(*req_params, handle, src_uri); gfal_http_get_cred(*req_params, handle, src_uri); gfal_http_get_cred(*req_params, handle, dst_uri, true); do_delegation = delegation_required(dst_uri); } else { // Pull mode gfal_http_get_params(*req_params, handle, dst_uri); gfal_http_get_cred(*req_params, handle, src_uri, true); gfal_http_get_cred(*req_params, handle, dst_uri); do_delegation = delegation_required(src_uri); } // The TPC request should be explicit in terms of how the active endpoint should manage credentials, // as it can be ambiguous from the request (i.e., client X509 authenticated by Macaroon present or // Macaroon present at an endpoint that supports OIDC). // If a token is present for the inactive endpoint, then we set `Credential: none` earlier; hence, // if that header is missing, we explicitly chose `gridsite` here. We should first check if source/dest // needs delegation if (do_delegation) { const HeaderVec &headers = req_params->getHeaders(); bool set_credential = false; for (HeaderVec::const_iterator iter = headers.begin(); iter != headers.end(); iter++) { if (!strcasecmp(iter->first.c_str(), "Credential")) { set_credential = true; } } if (!set_credential) { req_params->addHeader("Credential", "gridsite"); } } else { req_params->addHeader("Credential", "none"); req_params->addHeader("X-No-Delegate", "true"); } } void GfalHttpPluginData::get_params(Davix::RequestParams* req_params, const Davix::Uri& uri) { *req_params = reference_params; gfal_http_get_cred(*req_params, handle, uri); gfal_http_get_params(*req_params, handle, uri); } static void log_davix2gfal(void* userdata, int msg_level, const char* msg) { GLogLevelFlags gfal_level = G_LOG_LEVEL_MESSAGE; switch (msg_level) { case DAVIX_LOG_TRACE: case DAVIX_LOG_DEBUG: gfal_level = G_LOG_LEVEL_DEBUG; break; default: gfal_level = G_LOG_LEVEL_INFO; } gfal2_log(gfal_level, "Davix: %s", msg); } GfalHttpPluginData::GfalHttpPluginData(gfal2_context_t handle): context(), posix(&context), handle(handle), reference_params() { davix_set_log_handler(log_davix2gfal, NULL); int davix_level = get_corresponding_davix_log_level(); int davix_config_level = gfal2_get_opt_integer_with_default(handle, "HTTP PLUGIN", "LOG_LEVEL", 0); if (davix_config_level) davix_level = davix_config_level; davix_set_log_level(davix_level); reference_params.setTransparentRedirectionSupport(true); reference_params.setUserAgent("gfal2::http"); context.loadModule("grid"); } GfalHttpPluginData* gfal_http_get_plugin_context(gpointer ptr) { return static_cast<GfalHttpPluginData*>(ptr); } void gfal_http_context_delete(gpointer plugin_data){ GfalHttpPluginData* data = static_cast<GfalHttpPluginData*>(plugin_data); delete data; } void gfal_http_delete(plugin_handle plugin_data) { gfal_http_context_delete(plugin_data); } static gboolean gfal_http_check_url(plugin_handle plugin_data, const char* url, plugin_mode operation, GError** err) { switch(operation){ case GFAL_PLUGIN_QOS_CHECK_CLASSES: case GFAL_PLUGIN_CHECK_FILE_QOS: case GFAL_PLUGIN_CHECK_QOS_AVAILABLE_TRANSITIONS: case GFAL_PLUGIN_CHECK_TARGET_QOS: case GFAL_PLUGIN_CHANGE_OBJECT_QOS: return true; case GFAL_PLUGIN_ACCESS: case GFAL_PLUGIN_OPEN: case GFAL_PLUGIN_STAT: case GFAL_PLUGIN_MKDIR: case GFAL_PLUGIN_OPENDIR: case GFAL_PLUGIN_RMDIR: case GFAL_PLUGIN_UNLINK: case GFAL_PLUGIN_CHECKSUM: case GFAL_PLUGIN_RENAME: return (strncmp("http:", url, 5) == 0 || strncmp("https:", url, 6) == 0 || strncmp("dav:", url, 4) == 0 || strncmp("davs:", url, 5) == 0 || strncmp("s3:", url, 3) == 0 || strncmp("s3s:", url, 4) == 0 || strncmp("gcloud:", url, 7) == 0 || strncmp("gclouds:", url, 8) == 0 || strncmp("http+3rd:", url, 9) == 0 || strncmp("https+3rd:", url, 10) == 0 || strncmp("dav+3rd:", url, 8) == 0 || strncmp("davs+3rd:", url, 9) == 0); default: return false; } } gboolean gfal_should_fallback(int error_code) { switch(error_code) { case ECANCELED: return false; default: return true; } } static int davix2errno(StatusCode::Code code) { int errcode; switch (code) { case StatusCode::OK: case StatusCode::PartialDone: errcode = 0; break; case StatusCode::WebDavPropertiesParsingError: case StatusCode::UriParsingError: errcode = EIO; break; case StatusCode::SessionCreationError: errcode = EPERM; break; case StatusCode::NameResolutionFailure: errcode = EHOSTUNREACH; break; case StatusCode::ConnectionProblem: errcode = EHOSTDOWN; break; case StatusCode::OperationNonSupported: case StatusCode::RedirectionNeeded: errcode = ENOSYS; break; case StatusCode::ConnectionTimeout: case StatusCode::OperationTimeout: errcode = ETIMEDOUT; break; case StatusCode::PermissionRefused: errcode = EPERM; break; case StatusCode::IsADirectory: errcode = EISDIR; break; case StatusCode::IsNotADirectory: errcode = ENOTDIR; break; case StatusCode::InvalidFileHandle: errcode = EBADF; break; case StatusCode::AuthentificationError: case StatusCode::LoginPasswordError: case StatusCode::CredentialNotFound: case StatusCode::CredDecryptionError: case StatusCode::SSLError: case StatusCode::DelegationError: errcode = EACCES; break; case StatusCode::FileNotFound: errcode = ENOENT; break; case StatusCode::FileExist: errcode = EEXIST; break; case StatusCode::Canceled: errcode = ECANCELED; break; default: errcode = EIO; break; } return errcode; } void davix2gliberr(const DavixError* daverr, GError** err) { std::string error_string= g_utf8_validate(daverr->getErrMsg().c_str(), daverr->getErrMsg().length(),NULL) ? daverr->getErrMsg().c_str(): "Error string contains not valid UTF-8 chars"; gfal2_set_error(err, http_plugin_domain, davix2errno(daverr->getStatus()), __func__, "%s", error_string.c_str()); } static int http2errno(int http) { if (http < 400) return 0; switch (http) { case 400: case 406: return EINVAL; case 401: case 402: case 403: return EACCES; case 404: case 410: return ENOENT; case 405: return EPERM; case 409: return EEXIST; case 501: return ENOSYS; default: if (http >= 400 && http < 500) { return EINVAL; } else { #ifdef ECOMM return ECOMM; #else return EIO; #endif } } } void http2gliberr(GError** err, int http, const char* func, const char* msg) { int errn = http2errno(http); char buffer[512] = {0}; strerror_r(errn, buffer, sizeof(buffer)); gfal2_set_error(err, http_plugin_domain, errn, func, "%s: %s (HTTP %d)", msg, buffer, http); } /// Init function extern "C" gfal_plugin_interface gfal_plugin_init(gfal2_context_t handle, GError** err) { gfal_plugin_interface http_plugin; *err = NULL; memset(&http_plugin, 0, sizeof(http_plugin)); // Bind metadata http_plugin.check_plugin_url = &gfal_http_check_url; http_plugin.getName = &gfal_http_get_name; http_plugin.priority = GFAL_PLUGIN_PRIORITY_DATA ; http_plugin.plugin_data = new GfalHttpPluginData(handle); http_plugin.plugin_delete = &gfal_http_delete; http_plugin.statG = &gfal_http_stat; http_plugin.accessG = &gfal_http_access; http_plugin.mkdirpG = &gfal_http_mkdirpG; http_plugin.unlinkG = &gfal_http_unlinkG; http_plugin.rmdirG = &gfal_http_rmdirG; http_plugin.renameG = &gfal_http_rename; http_plugin.opendirG = &gfal_http_opendir; http_plugin.readdirG = &gfal_http_readdir; http_plugin.readdirppG = &gfal_http_readdirpp; http_plugin.closedirG = &gfal_http_closedir; // Bind IO http_plugin.openG = &gfal_http_fopen; http_plugin.readG = &gfal_http_fread; http_plugin.writeG = &gfal_http_fwrite; http_plugin.lseekG = &gfal_http_fseek; http_plugin.closeG = &gfal_http_fclose; // Checksum http_plugin.checksum_calcG = &gfal_http_checksum; // Bind 3rd party copy http_plugin.check_plugin_url_transfer = gfal_http_copy_check; http_plugin.copy_file = gfal_http_copy; // QoS http_plugin.check_qos_classes = &gfal_http_check_classes; http_plugin.check_file_qos = &gfal_http_check_file_qos; http_plugin.check_qos_available_transitions = &gfal_http_check_qos_available_transitions; http_plugin.check_target_qos = &gfal_http_check_target_qos; http_plugin.change_object_qos = &gfal_http_change_object_qos; return http_plugin; }
32.997028
117
0.647859
[ "transform" ]
604da4902298b1b8d935493a35ee62a8672a8505
902,083
inl
C++
runtime/legion/legion.inl
mmccarty/legion
30e00fa6016527c4cf60025a461fb7865f8def6b
[ "Apache-2.0" ]
null
null
null
runtime/legion/legion.inl
mmccarty/legion
30e00fa6016527c4cf60025a461fb7865f8def6b
[ "Apache-2.0" ]
null
null
null
runtime/legion/legion.inl
mmccarty/legion
30e00fa6016527c4cf60025a461fb7865f8def6b
[ "Apache-2.0" ]
null
null
null
/* Copyright 2021 Stanford University, NVIDIA Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // Included from legion.h - do not include this directly // Useful for IDEs #include "legion.h" namespace Legion { /** * \struct SerdezRedopFns * Small helper class for storing instantiated templates */ struct SerdezRedopFns { public: SerdezInitFnptr init_fn; SerdezFoldFnptr fold_fn; }; /** * \class LegionSerialization * The Legion serialization class provides template meta-programming * help for returning complex data types from task calls. If the * types have three special methods defined on them then we know * how to serialize the type for the runtime rather than just doing * a dumb bit copy. This is especially useful for types which * require deep copies instead of shallow bit copies. The three * methods which must be defined are: * size_t legion_buffer_size(void) * void legion_serialize(void *buffer) * void legion_deserialize(const void *buffer) */ class LegionSerialization { public: // A helper method for getting access to the runtime's // end_task method with private access static inline void end_helper(Runtime *rt, Context ctx, const void *result, size_t result_size, bool owned) { Runtime::legion_task_postamble(rt, ctx, result, result_size, owned); } static inline Future from_value_helper(Runtime *rt, const void *value, size_t value_size, bool owned) { return rt->from_value(value, value_size, owned); } // WARNING: There are two levels of SFINAE (substitution failure is // not an error) here. Proceed at your own risk. First we have to // check to see if the type is a struct. If it is then we check to // see if it has a 'legion_serialize' method. We assume if there is // a 'legion_serialize' method there are also 'legion_buffer_size' // and 'legion_deserialize' methods. template<typename T, bool HAS_SERIALIZE> struct NonPODSerializer { static inline void end_task(Runtime *rt, Context ctx, T *result) { size_t buffer_size = result->legion_buffer_size(); if (buffer_size > 0) { void *buffer = malloc(buffer_size); result->legion_serialize(buffer); end_helper(rt, ctx, buffer, buffer_size, true/*owned*/); // No need to free the buffer, the Legion runtime owns it now } else end_helper(rt, ctx, NULL, 0, false/*owned*/); } static inline Future from_value(Runtime *rt, const T *value) { size_t buffer_size = value->legion_buffer_size(); void *buffer = malloc(buffer_size); value->legion_serialize(buffer); return from_value_helper(rt, buffer, buffer_size, true/*owned*/); } static inline T unpack(const Future &f, bool silence_warnings, const char *warning_string) { const void *result = f.get_untyped_pointer(silence_warnings, warning_string); T derez; derez.legion_deserialize(result); return derez; } }; // Further specialization for deferred reductions template<typename REDOP, bool EXCLUSIVE> struct NonPODSerializer<DeferredReduction<REDOP,EXCLUSIVE>,false> { static inline void end_task(Runtime *rt, Context ctx, DeferredReduction<REDOP,EXCLUSIVE> *result) { result->finalize(rt, ctx); } static inline Future from_value(Runtime *rt, const DeferredReduction<REDOP,EXCLUSIVE> *value) { // Should never be called assert(false); return from_value_helper(rt, (const void*)value, sizeof(DeferredReduction<REDOP,EXCLUSIVE>), false/*owned*/); } static inline DeferredReduction<REDOP,EXCLUSIVE> unpack(const Future &f, bool silence_warnings, const char *warning) { // Should never be called assert(false); const void *result = f.get_untyped_pointer(silence_warnings, warning); return (*((const DeferredReduction<REDOP,EXCLUSIVE>*)result)); } }; // Further specialization to see if this a deferred value template<typename T> struct NonPODSerializer<DeferredValue<T>,false> { static inline void end_task(Runtime *rt, Context ctx, DeferredValue<T> *result) { result->finalize(rt, ctx); } static inline Future from_value(Runtime *rt, const DeferredValue<T> *value) { // Should never be called assert(false); return from_value_helper(rt, (const void*)value, sizeof(DeferredValue<T>), false/*owned*/); } static inline DeferredValue<T> unpack(const Future &f, bool silence_warnings, const char *warning_string) { // Should never be called assert(false); const void *result = f.get_untyped_pointer(silence_warnings, warning_string); return (*((const DeferredValue<T>*)result)); } }; template<typename T> struct NonPODSerializer<T,false> { static inline void end_task(Runtime *rt, Context ctx, T *result) { end_helper(rt, ctx, (void*)result, sizeof(T), false/*owned*/); } static inline Future from_value(Runtime *rt, const T *value) { return from_value_helper(rt, (const void*)value, sizeof(T), false/*owned*/); } static inline T unpack(const Future &f, bool silence_warnings, const char *warning_string) { return f.get_reference<T>(silence_warnings, warning_string); } }; template <typename T> struct IsSerdezType { typedef char yes; typedef long no; template <typename C> static yes test(decltype(&C::legion_buffer_size), decltype(&C::legion_serialize), decltype(&C::legion_deserialize)); template <typename C> static no test(...); static constexpr bool value = sizeof(test<T>(nullptr, nullptr, nullptr)) == sizeof(yes); }; template<typename T, bool IS_STRUCT> struct StructHandler { static inline void end_task(Runtime *rt, Context ctx, T *result) { // Otherwise this is a struct, so see if it has serialization methods NonPODSerializer<T,IsSerdezType<T>::value>::end_task(rt, ctx, result); } static inline Future from_value(Runtime *rt, const T *value) { return NonPODSerializer<T,IsSerdezType<T>::value>::from_value( rt, value); } static inline T unpack(const Future &f, bool silence_warnings, const char *warning_string) { return NonPODSerializer<T,IsSerdezType<T>::value>::unpack(f, silence_warnings, warning_string); } }; // False case of template specialization template<typename T> struct StructHandler<T,false> { static inline void end_task(Runtime *rt, Context ctx, T *result) { end_helper(rt, ctx, (void*)result, sizeof(T), false/*owned*/); } static inline Future from_value(Runtime *rt, const T *value) { return from_value_helper(rt, (const void*)value, sizeof(T), false/*owned*/); } static inline T unpack(const Future &f, bool silence_warnings, const char *warning_string) { return f.get_reference<T>(silence_warnings, warning_string); } }; // Figure out whether this is a struct or not // and call the appropriate Finisher template<typename T> static inline void end_task(Runtime *rt, Context ctx, T *result) { StructHandler<T,std::is_class<T>::value>::end_task(rt, ctx, result); } template<typename T> static inline Future from_value(Runtime *rt, const T *value) { return StructHandler<T,std::is_class<T>::value>::from_value(rt, value); } template<typename T> static inline T unpack(const Future &f, bool silence_warnings, const char *warning_string) { return StructHandler<T,std::is_class<T>::value>::unpack(f, silence_warnings, warning_string); } // Some more help for reduction operations with RHS types // that have serialize and deserialize methods template<typename REDOP_RHS> static void serdez_redop_init(const ReductionOp *reduction_op, void *&ptr, size_t &size) { REDOP_RHS init_serdez; memcpy(&init_serdez, reduction_op->identity, reduction_op->sizeof_rhs); size_t new_size = init_serdez.legion_buffer_size(); if (new_size > size) { size = new_size; ptr = realloc(ptr, size); } init_serdez.legion_serialize(ptr); } template<typename REDOP_RHS> static void serdez_redop_fold(const ReductionOp *reduction_op, void *&lhs_ptr, size_t &lhs_size, const void *rhs_ptr) { REDOP_RHS lhs_serdez, rhs_serdez; lhs_serdez.legion_deserialize(lhs_ptr); rhs_serdez.legion_deserialize(rhs_ptr); (reduction_op->cpu_fold_excl_fn)(&lhs_serdez, 0, &rhs_serdez, 0, 1, reduction_op->userdata); size_t new_size = lhs_serdez.legion_buffer_size(); // Reallocate the buffer if it has grown if (new_size > lhs_size) { lhs_size = new_size; lhs_ptr = realloc(lhs_ptr, lhs_size); } // Now save the value lhs_serdez.legion_serialize(lhs_ptr); } template<typename REDOP_RHS, bool HAS_SERDEZ> struct SerdezRedopHandler { static inline void register_reduction(ReductionOp *redop, ReductionOpID redop_id, bool permit_duplicates) { Runtime::register_reduction_op(redop_id, redop, NULL, NULL, permit_duplicates); } }; // True case of template specialization template<typename REDOP_RHS> struct SerdezRedopHandler<REDOP_RHS,true> { static inline void register_reduction(ReductionOp *redop, ReductionOpID redop_id, bool permit_duplicates) { Runtime::register_reduction_op(redop_id, redop, serdez_redop_init<REDOP_RHS>, serdez_redop_fold<REDOP_RHS>, permit_duplicates); } }; template<typename REDOP_RHS, bool IS_STRUCT> struct StructRedopHandler { static inline void register_reduction(ReductionOp *redop, ReductionOpID redop_id, bool permit_duplicates) { Runtime::register_reduction_op(redop_id, redop, NULL, NULL, permit_duplicates); } }; // True case of template specialization template<typename REDOP_RHS> struct StructRedopHandler<REDOP_RHS,true> { static inline void register_reduction(ReductionOp *redop, ReductionOpID redop_id, bool permit_duplicates) { SerdezRedopHandler<REDOP_RHS,IsSerdezType<REDOP_RHS>::value>:: register_reduction(redop, redop_id, permit_duplicates); } }; // Register reduction functions if necessary template<typename REDOP> static inline void register_reduction(ReductionOpID redop_id, bool permit_duplicates) { StructRedopHandler<typename REDOP::RHS, std::is_class<typename REDOP::RHS>::value>::register_reduction( Realm::ReductionOpUntyped::create_reduction_op<REDOP>(), redop_id, permit_duplicates); } template<typename T> struct HasSerdezBound { typedef char yes; typedef long no; template <typename C> static yes test(decltype(&C::legion_upper_bound_size)); template <typename C> static no test(...); static constexpr bool value = sizeof(test<T>(nullptr)) == sizeof(yes); }; template<typename T, bool HAS_BOUND> struct SerdezBound { static constexpr size_t value = T::legion_upper_bound_size(); }; template<typename T> struct SerdezBound<T,false> { static constexpr size_t value = LEGION_MAX_RETURN_SIZE; }; template<typename T> struct SizeBound { static constexpr size_t value = sizeof(T); }; template<typename T> struct ReturnSize { static constexpr size_t value = std::conditional<IsSerdezType<T>::value, SerdezBound<T,HasSerdezBound<T>::value>, SizeBound<T> >::type::value; }; }; // Serialization namespace // Special namespace for providing multi-dimensional // array syntax on accessors namespace ArraySyntax { // A helper class for handling reductions template<typename A, typename FT, int N, typename T> class ReductionHelper { public: __CUDA_HD__ ReductionHelper(const A &acc, const Point<N> &p) : accessor(acc), point(p) { } public: __CUDA_HD__ inline void reduce(FT val) const { accessor.reduce(point, val); } __CUDA_HD__ inline void operator<<=(FT val) const { accessor.reduce(point, val); } public: const A &accessor; const Point<N,T> point; }; template<typename FT, PrivilegeMode P> class AccessorRefHelper { public: AccessorRefHelper(const Realm::AccessorRefHelper<FT> &h) : helper(h) { } public: // read inline operator FT(void) const { return helper; } // writes inline AccessorRefHelper<FT,P>& operator=(const FT &newval) { helper = newval; return *this; } template<PrivilegeMode P2> inline AccessorRefHelper<FT,P>& operator=( const AccessorRefHelper<FT,P2> &rhs) { helper = rhs.helper; return *this; } protected: template<typename T, PrivilegeMode P2> friend class AccessorRefHelper; Realm::AccessorRefHelper<FT> helper; }; template<typename FT> class AccessorRefHelper<FT,LEGION_READ_ONLY> { public: AccessorRefHelper(const Realm::AccessorRefHelper<FT> &h) : helper(h) { } // read inline operator FT(void) const { return helper; } private: // no writes allowed inline AccessorRefHelper<FT,LEGION_READ_ONLY>& operator=( const AccessorRefHelper<FT,LEGION_READ_ONLY> &rhs) { helper = rhs.helper; return *this; } protected: template<typename T, PrivilegeMode P2> friend class AccessorRefHelper; Realm::AccessorRefHelper<FT> helper; }; // LEGION_NO_ACCESS means we dynamically check the privilege template<typename FT> class AccessorRefHelper<FT,LEGION_NO_ACCESS> { public: AccessorRefHelper(const Realm::AccessorRefHelper<FT> &h, FieldID fid, const DomainPoint &pt, PrivilegeMode p) : helper(h), point(pt), field(fid), privilege(p) { } public: // read inline operator FT(void) const { if ((privilege & LEGION_READ_PRIV) == 0) PhysicalRegion::fail_privilege_check(point, field, privilege); return helper; } // writes inline AccessorRefHelper<FT,LEGION_NO_ACCESS>& operator=( const FT &newval) { if ((privilege & LEGION_WRITE_PRIV) == 0) PhysicalRegion::fail_privilege_check(point, field, privilege); helper = newval; return *this; } template<PrivilegeMode P2> inline AccessorRefHelper<FT,LEGION_NO_ACCESS>& operator=( const AccessorRefHelper<FT,P2> &rhs) { if ((privilege & LEGION_WRITE_PRIV) == 0) PhysicalRegion::fail_privilege_check(point, field, privilege); helper = rhs.helper; return *this; } protected: template<typename T, PrivilegeMode P2> friend class AccessorRefHelper; Realm::AccessorRefHelper<FT> helper; DomainPoint point; FieldID field; PrivilegeMode privilege; }; // A small helper class that helps provide some syntactic sugar for // indexing accessors like a multi-dimensional array for generic accessors template<typename A, typename FT, int N, typename T, int M, PrivilegeMode P> class GenericSyntaxHelper { public: GenericSyntaxHelper(const A &acc, const Point<M-1,T> &p) : accessor(acc) { for (int i = 0; i < (M-1); i++) point[i] = p[i]; } public: inline GenericSyntaxHelper<A,FT,N,T,M+1,P> operator[](T val) { point[M-1] = val; return GenericSyntaxHelper<A,FT,N,T,M+1,P>(accessor, point); } public: const A &accessor; Point<M,T> point; }; // Specialization for M = N template<typename A, typename FT, int N, typename T, PrivilegeMode P> class GenericSyntaxHelper<A,FT,N,T,N,P> { public: GenericSyntaxHelper(const A &acc, const Point<N-1,T> &p) : accessor(acc) { for (int i = 0; i < (N-1); i++) point[i] = p[i]; } public: inline AccessorRefHelper<FT,P> operator[](T val) { point[N-1] = val; return accessor[point]; } public: const A &accessor; Point<N,T> point; }; // Further specialization for M = N and read-only template<typename A, typename FT, int N, typename T> class GenericSyntaxHelper<A,FT,N,T,N,LEGION_READ_ONLY> { public: GenericSyntaxHelper(const A &acc, const Point<N-1,T> &p) : accessor(acc) { for (int i = 0; i < (N-1); i++) point[i] = p[i]; } public: inline AccessorRefHelper<FT,LEGION_READ_ONLY> operator[](T val) { point[N-1] = val; return accessor[point]; } public: const A &accessor; Point<N,T> point; }; // Further specialization for M = N and reductions template<typename A, typename FT, int N, typename T> class GenericSyntaxHelper<A,FT,N,T,N,LEGION_REDUCE> { public: GenericSyntaxHelper(const A &acc, const Point<N-1,T> &p) : accessor(acc) { for (int i = 0; i < (N-1); i++) point[i] = p[i]; } public: inline const ReductionHelper<A,FT,N,T> operator[](T val) { point[N-1] = val; return ReductionHelper<A,FT,N,T>(accessor, point); } public: const A &accessor; Point<N,T> point; }; // A small helper class that helps provide some syntactic sugar for // indexing accessors like a multi-dimensional array for affine accessors template<typename A, typename FT, int N, typename T, int M, PrivilegeMode P> class AffineSyntaxHelper { public: __CUDA_HD__ AffineSyntaxHelper(const A &acc, const Point<M-1,T> &p) : accessor(acc) { for (int i = 0; i < (M-1); i++) point[i] = p[i]; } public: __CUDA_HD__ inline AffineSyntaxHelper<A,FT,N,T,M+1,P> operator[](T val) { point[M-1] = val; return AffineSyntaxHelper<A,FT,N,T,M+1,P>(accessor, point); } public: const A &accessor; Point<M,T> point; }; // Specialization for M = N template<typename A, typename FT, int N, typename T, PrivilegeMode P> class AffineSyntaxHelper<A,FT,N,T,N,P> { public: __CUDA_HD__ AffineSyntaxHelper(const A &acc, const Point<N-1,T> &p) : accessor(acc) { for (int i = 0; i < (N-1); i++) point[i] = p[i]; } public: __CUDA_HD__ inline FT& operator[](T val) { point[N-1] = val; return accessor[point]; } public: const A &accessor; Point<N,T> point; }; // Further specialization for M = N and read-only template<typename A, typename FT, int N, typename T> class AffineSyntaxHelper<A,FT,N,T,N,LEGION_READ_ONLY> { public: __CUDA_HD__ AffineSyntaxHelper(const A &acc, const Point<N-1,T> &p) : accessor(acc) { for (int i = 0; i < (N-1); i++) point[i] = p[i]; } public: __CUDA_HD__ inline const FT& operator[](T val) { point[N-1] = val; return accessor[point]; } public: const A &accessor; Point<N,T> point; }; // Further specialize for M = N and reductions template<typename A, typename FT, int N, typename T> class AffineSyntaxHelper<A,FT,N,T,N,LEGION_REDUCE> { public: __CUDA_HD__ AffineSyntaxHelper(const A &acc, const Point<N-1,T> &p) : accessor(acc) { for (int i = 0; i < (N-1); i++) point[i] = p[i]; } public: __CUDA_HD__ inline const ReductionHelper<A,FT,N,T> operator[](T val) { point[N-1] = val; return ReductionHelper<A,FT,N,T>(accessor, point); } public: const A &accessor; Point<N,T> point; }; // Helper class for affine syntax that behaves like a // pointer/reference, but does dynamic privilege checks template<typename FT> class AffineRefHelper { public: __CUDA_HD__ AffineRefHelper(FT &r,FieldID fid,const DomainPoint &pt,PrivilegeMode p) : ref(r), #ifndef __CUDA_ARCH__ point(pt), field(fid), #endif privilege(p) { } public: // read __CUDA_HD__ inline operator const FT&(void) const { #ifdef __CUDA_ARCH__ assert(privilege & LEGION_READ_PRIV); #else if ((privilege & LEGION_READ_PRIV) == 0) PhysicalRegion::fail_privilege_check(point, field, privilege); #endif return ref; } // writes __CUDA_HD__ inline AffineRefHelper<FT>& operator=(const FT &newval) { #ifdef __CUDA_ARCH__ assert(privilege & LEGION_WRITE_PRIV); #else if ((privilege & LEGION_WRITE_PRIV) == 0) PhysicalRegion::fail_privilege_check(point, field, privilege); #endif ref = newval; return *this; } __CUDA_HD__ inline AffineRefHelper<FT>& operator=(const AffineRefHelper<FT> &rhs) { #ifdef __CUDA_ARCH__ assert(privilege & LEGION_WRITE_PRIV); #else if ((privilege & LEGION_WRITE_PRIV) == 0) PhysicalRegion::fail_privilege_check(point, field, privilege); #endif ref = rhs.ref; return *this; } protected: FT &ref; #ifndef __CUDA_ARCH__ DomainPoint point; FieldID field; #endif PrivilegeMode privilege; }; // Further specialization for M = N and NO_ACCESS (dynamic privilege) template<typename A, typename FT, int N, typename T> class AffineSyntaxHelper<A,FT,N,T,N,LEGION_NO_ACCESS> { public: __CUDA_HD__ AffineSyntaxHelper(const A &acc, const Point<N-1,T> &p) : accessor(acc) { for (int i = 0; i < (N-1); i++) point[i] = p[i]; } public: __CUDA_HD__ inline AffineRefHelper<FT> operator[](T val) { point[N-1] = val; return accessor[point]; } public: const A &accessor; Point<N,T> point; }; }; //////////////////////////////////////////////////////////// // Specializations for Generic Accessors //////////////////////////////////////////////////////////// // Read-only FieldAccessor specialization template<typename FT, int N, typename T, bool CB> class FieldAccessor<LEGION_READ_ONLY,FT,N,T, Realm::GenericAccessor<FT,N,T>,CB> { public: FieldAccessor(void) { } FieldAccessor(const PhysicalRegion &region, FieldID fid, size_t actual_field_size = sizeof(FT), #ifdef DEBUG_LEGION bool check_field_size = true, #else bool check_field_size = false, #endif bool silence_warnings = false, const char *warning_string = NULL, size_t offset = 0) { DomainT<N,T> is; const Realm::RegionInstance instance = region.get_instance_info(LEGION_READ_ONLY, fid, actual_field_size,&is, Internal::NT_TemplateHelper::encode_tag<N,T>(), warning_string, silence_warnings, true/*generic accessor*/, check_field_size); if (!Realm::GenericAccessor<FT,N,T>::is_compatible(instance, fid, is.bounds)) region.report_incompatible_accessor("GenericAccessor", instance, fid); accessor = Realm::GenericAccessor<FT,N,T>(instance, fid, is.bounds, offset); } FieldAccessor(const PhysicalRegion &region, FieldID fid, const Rect<N,T> source_bounds, size_t actual_field_size = sizeof(FT), #ifdef DEBUG_LEGION bool check_field_size = true, #else bool check_field_size = false, #endif bool silence_warnings = false, const char *warning_string = NULL, size_t offset = 0) { DomainT<N,T> is; const Realm::RegionInstance instance = region.get_instance_info(LEGION_READ_ONLY, fid, actual_field_size,&is, Internal::NT_TemplateHelper::encode_tag<N,T>(), warning_string, silence_warnings, true/*generic accessor*/, check_field_size); if (!Realm::GenericAccessor<FT,N,T>::is_compatible(instance, fid, source_bounds)) region.report_incompatible_accessor("GenericAccessor", instance, fid); accessor = Realm::GenericAccessor<FT,N,T>(instance, fid, source_bounds, offset); } public: inline FT read(const Point<N,T>& p) const { return accessor.read(p); } inline const ArraySyntax::AccessorRefHelper<FT,LEGION_READ_ONLY> operator[](const Point<N,T>& p) const { return ArraySyntax::AccessorRefHelper<FT,LEGION_READ_ONLY>( accessor[p]); } inline ArraySyntax::GenericSyntaxHelper< FieldAccessor<LEGION_READ_ONLY,FT,N,T, Realm::GenericAccessor<FT,N,T>,CB>,FT,N,T,2,LEGION_READ_ONLY> operator[](T index) const { return ArraySyntax::GenericSyntaxHelper< FieldAccessor<LEGION_READ_ONLY,FT,N,T, Realm::GenericAccessor<FT,N,T>,CB>,FT,N,T,2,LEGION_READ_ONLY>( *this, Point<1,T>(index)); } public: mutable Realm::GenericAccessor<FT,N,T> accessor; public: typedef FT value_type; typedef FT& reference; typedef const FT& const_reference; static const int dim = N; }; // Read-only FieldAccessor specialization // with bounds checks template<typename FT, int N, typename T> class FieldAccessor<LEGION_READ_ONLY,FT,N,T, Realm::GenericAccessor<FT,N,T>,true> { public: FieldAccessor(void) { } FieldAccessor(const PhysicalRegion &region, FieldID fid, size_t actual_field_size = sizeof(FT), #ifdef DEBUG_LEGION bool check_field_size = true, #else bool check_field_size = false, #endif bool silence_warnings = false, const char *warning_string = NULL, size_t offset = 0) : field(fid) { const Realm::RegionInstance instance = region.get_instance_info(LEGION_READ_ONLY, fid, actual_field_size, &bounds, Internal::NT_TemplateHelper::encode_tag<N,T>(), warning_string, silence_warnings, true/*generic accessor*/, check_field_size); if (!Realm::GenericAccessor<FT,N,T>::is_compatible(instance, fid, bounds.bounds)) region.report_incompatible_accessor("GenericAccessor", instance, fid); accessor = Realm::GenericAccessor<FT,N,T>(instance, fid, bounds.bounds, offset); } FieldAccessor(const PhysicalRegion &region, FieldID fid, const Rect<N,T> source_bounds, size_t actual_field_size = sizeof(FT), #ifdef DEBUG_LEGION bool check_field_size = true, #else bool check_field_size = false, #endif bool silence_warnings = false, const char *warning_string = NULL, size_t offset = 0) : field(fid), bounds(source_bounds) { const Realm::RegionInstance instance = region.get_instance_info(LEGION_READ_ONLY, fid, actual_field_size, &bounds, Internal::NT_TemplateHelper::encode_tag<N,T>(), warning_string, silence_warnings, true/*generic accessor*/, check_field_size); if (!Realm::GenericAccessor<FT,N,T>::is_compatible(instance, fid, source_bounds)) region.report_incompatible_accessor("GenericAccessor", instance, fid); accessor = Realm::GenericAccessor<FT,N,T>(instance, fid, source_bounds, offset); bounds.bounds = source_bounds.intersection(bounds.bounds); } public: inline FT read(const Point<N,T>& p) const { if (!bounds.contains(p)) PhysicalRegion::fail_bounds_check(DomainPoint(p), field, LEGION_READ_ONLY); return accessor.read(p); } inline const ArraySyntax::AccessorRefHelper<FT,LEGION_READ_ONLY> operator[](const Point<N,T>& p) const { if (!bounds.contains(p)) PhysicalRegion::fail_bounds_check(DomainPoint(p), field, LEGION_READ_ONLY); return ArraySyntax::AccessorRefHelper<FT,LEGION_READ_ONLY>( accessor[p]); } inline ArraySyntax::GenericSyntaxHelper< FieldAccessor<LEGION_READ_ONLY,FT,N,T, Realm::GenericAccessor<FT,N,T>,true>,FT,N,T,2,LEGION_READ_ONLY> operator[](T index) const { return ArraySyntax::GenericSyntaxHelper< FieldAccessor<LEGION_READ_ONLY,FT,N,T, Realm::GenericAccessor<FT,N,T>,true>,FT,N,T,2,LEGION_READ_ONLY>( *this, Point<1,T>(index)); } public: mutable Realm::GenericAccessor<FT,N,T> accessor; FieldID field; DomainT<N,T> bounds; public: typedef FT value_type; typedef FT& reference; typedef const FT& const_reference; static const int dim = N; }; // Read-only FieldAccessor specialization // with N==1 to avoid array ambiguity template<typename FT, typename T, bool CB> class FieldAccessor<LEGION_READ_ONLY,FT,1,T, Realm::GenericAccessor<FT,1,T>,CB> { public: FieldAccessor(void) { } FieldAccessor(const PhysicalRegion &region, FieldID fid, size_t actual_field_size = sizeof(FT), #ifdef DEBUG_LEGION bool check_field_size = true, #else bool check_field_size = false, #endif bool silence_warnings = false, const char *warning_string = NULL, size_t offset = 0) { DomainT<1,T> is; const Realm::RegionInstance instance = region.get_instance_info(LEGION_READ_ONLY, fid, actual_field_size,&is, Internal::NT_TemplateHelper::encode_tag<1,T>(), warning_string, silence_warnings, true/*generic accessor*/, check_field_size); if (!Realm::GenericAccessor<FT,1,T>::is_compatible(instance, fid, is.bounds)) region.report_incompatible_accessor("GenericAccessor", instance, fid); accessor = Realm::GenericAccessor<FT,1,T>(instance, fid, is.bounds, offset); } FieldAccessor(const PhysicalRegion &region, FieldID fid, const Rect<1,T> source_bounds, size_t actual_field_size = sizeof(FT), #ifdef DEBUG_LEGION bool check_field_size = true, #else bool check_field_size = false, #endif bool silence_warnings = false, const char *warning_string = NULL, size_t offset = 0) { DomainT<1,T> is; const Realm::RegionInstance instance = region.get_instance_info(LEGION_READ_ONLY, fid, actual_field_size,&is, Internal::NT_TemplateHelper::encode_tag<1,T>(), warning_string, silence_warnings, true/*generic accessor*/, check_field_size); if (!Realm::GenericAccessor<FT,1,T>::is_compatible(instance, fid, source_bounds)) region.report_incompatible_accessor("GenericAccessor", instance, fid); accessor = Realm::GenericAccessor<FT,1,T>(instance, fid, source_bounds, offset); } public: inline FT read(const Point<1,T>& p) const { return accessor.read(p); } inline const ArraySyntax::AccessorRefHelper<FT,LEGION_READ_ONLY> operator[](const Point<1,T>& p) const { return ArraySyntax::AccessorRefHelper<FT,LEGION_READ_ONLY>( accessor[p]); } public: mutable Realm::GenericAccessor<FT,1,T> accessor; public: typedef FT value_type; typedef FT& reference; typedef const FT& const_reference; static const int dim = 1; }; // Read-only FieldAccessor specialization // with N==1 to avoid array ambiguity and bounds checks template<typename FT, typename T> class FieldAccessor<LEGION_READ_ONLY,FT,1,T, Realm::GenericAccessor<FT,1,T>,true> { public: // No CUDA support due to PhysicalRegion constructor FieldAccessor(void) { } FieldAccessor(const PhysicalRegion &region, FieldID fid, size_t actual_field_size = sizeof(FT), #ifdef DEBUG_LEGION bool check_field_size = true, #else bool check_field_size = false, #endif bool silence_warnings = false, const char *warning_string = NULL, size_t offset = 0) : field(fid) { const Realm::RegionInstance instance = region.get_instance_info(LEGION_READ_ONLY, fid, actual_field_size, &bounds, Internal::NT_TemplateHelper::encode_tag<1,T>(), warning_string, silence_warnings, true/*generic accessor*/, check_field_size); if (!Realm::GenericAccessor<FT,1,T>::is_compatible(instance, fid, bounds.bounds)) region.report_incompatible_accessor("GenericAccessor", instance, fid); accessor = Realm::GenericAccessor<FT,1,T>(instance, fid, bounds.bounds, offset); } FieldAccessor(const PhysicalRegion &region, FieldID fid, const Rect<1,T> source_bounds, size_t actual_field_size = sizeof(FT), #ifdef DEBUG_LEGION bool check_field_size = true, #else bool check_field_size = false, #endif bool silence_warnings = false, const char *warning_string = NULL, size_t offset = 0) : field(fid) { const Realm::RegionInstance instance = region.get_instance_info(LEGION_READ_ONLY, fid, actual_field_size, &bounds, Internal::NT_TemplateHelper::encode_tag<1,T>(), warning_string, silence_warnings, true/*generic accessor*/, check_field_size); if (!Realm::GenericAccessor<FT,1,T>::is_compatible(instance, fid, source_bounds)) region.report_incompatible_accessor("GenericAccessor", instance, fid); accessor = Realm::GenericAccessor<FT,1,T>(instance, fid, source_bounds, offset); bounds.bounds = source_bounds.intersection(bounds.bounds); } public: inline FT read(const Point<1,T>& p) const { if (!bounds.contains(p)) PhysicalRegion::fail_bounds_check(DomainPoint(p), field, LEGION_READ_ONLY); return accessor.read(p); } inline const ArraySyntax::AccessorRefHelper<FT,LEGION_READ_ONLY> operator[](const Point<1,T>& p) const { if (!bounds.contains(p)) PhysicalRegion::fail_bounds_check(DomainPoint(p), field, LEGION_READ_ONLY); return ArraySyntax::AccessorRefHelper<FT,LEGION_READ_ONLY>( accessor[p]); } public: mutable Realm::GenericAccessor<FT,1,T> accessor; FieldID field; DomainT<1,T> bounds; public: typedef FT value_type; typedef FT& reference; typedef const FT& const_reference; static const int dim = 1; }; // Read-write FieldAccessor specialization template<typename FT, int N, typename T, bool CB> class FieldAccessor<LEGION_READ_WRITE,FT,N,T, Realm::GenericAccessor<FT,N,T>,CB> { public: FieldAccessor(void) { } FieldAccessor(const PhysicalRegion &region, FieldID fid, size_t actual_field_size = sizeof(FT), #ifdef DEBUG_LEGION bool check_field_size = true, #else bool check_field_size = false, #endif bool silence_warnings = false, const char *warning_string = NULL, size_t offset = 0) { DomainT<N,T> is; const Realm::RegionInstance instance = region.get_instance_info(LEGION_READ_WRITE, fid,actual_field_size,&is, Internal::NT_TemplateHelper::encode_tag<N,T>(), warning_string, silence_warnings, true/*generic accessor*/, check_field_size); if (!Realm::GenericAccessor<FT,N,T>::is_compatible(instance, fid, is.bounds)) region.report_incompatible_accessor("GenericAccessor", instance, fid); accessor = Realm::GenericAccessor<FT,N,T>(instance, fid, is.bounds, offset); } FieldAccessor(const PhysicalRegion &region, FieldID fid, const Rect<N,T> source_bounds, size_t actual_field_size = sizeof(FT), #ifdef DEBUG_LEGION bool check_field_size = true, #else bool check_field_size = false, #endif bool silence_warnings = false, const char *warning_string = NULL, size_t offset = 0) { DomainT<N,T> is; const Realm::RegionInstance instance = region.get_instance_info(LEGION_READ_WRITE, fid,actual_field_size,&is, Internal::NT_TemplateHelper::encode_tag<N,T>(), warning_string, silence_warnings, true/*generic accessor*/, check_field_size); if (!Realm::GenericAccessor<FT,N,T>::is_compatible(instance, fid, source_bounds)) region.report_incompatible_accessor("GenericAccessor", instance, fid); accessor = Realm::GenericAccessor<FT,N,T>(instance, fid, source_bounds, offset); } public: inline FT read(const Point<N,T>& p) const { return accessor.read(p); } inline void write(const Point<N,T>& p, FT val) const { accessor.write(p, val); } inline ArraySyntax::AccessorRefHelper<FT,LEGION_READ_WRITE> operator[](const Point<N,T>& p) const { return ArraySyntax::AccessorRefHelper<FT,LEGION_READ_WRITE>( accessor[p]); } inline ArraySyntax::GenericSyntaxHelper< FieldAccessor<LEGION_READ_WRITE,FT,N,T, Realm::GenericAccessor<FT,N,T>,CB>,FT,N,T,2,LEGION_READ_WRITE> operator[](T index) const { return ArraySyntax::GenericSyntaxHelper< FieldAccessor<LEGION_READ_WRITE,FT,N,T, Realm::GenericAccessor<FT,N,T>,CB>,FT,N,T,2,LEGION_READ_WRITE>( *this, Point<1,T>(index)); } // No reductions since we can't handle atomicity correctly public: mutable Realm::GenericAccessor<FT,N,T> accessor; public: typedef FT value_type; typedef FT& reference; typedef const FT& const_reference; static const int dim = N; }; // Read-write FieldAccessor specialization // with bounds checks template<typename FT, int N, typename T> class FieldAccessor<LEGION_READ_WRITE,FT,N,T, Realm::GenericAccessor<FT,N,T>,true> { public: FieldAccessor(void) { } FieldAccessor(const PhysicalRegion &region, FieldID fid, size_t actual_field_size = sizeof(FT), #ifdef DEBUG_LEGION bool check_field_size = true, #else bool check_field_size = false, #endif bool silence_warnings = false, const char *warning_string = NULL, size_t offset = 0) : field(fid) { const Realm::RegionInstance instance = region.get_instance_info(LEGION_READ_WRITE, fid, actual_field_size, &bounds, Internal::NT_TemplateHelper::encode_tag<N,T>(), warning_string, silence_warnings, true/*generic accessor*/, check_field_size); if (!Realm::GenericAccessor<FT,N,T>::is_compatible(instance, fid, bounds.bounds)) region.report_incompatible_accessor("GenericAccessor", instance, fid); accessor = Realm::GenericAccessor<FT,N,T>(instance, fid, bounds.bounds, offset); } FieldAccessor(const PhysicalRegion &region, FieldID fid, const Rect<N,T> source_bounds, size_t actual_field_size = sizeof(FT), #ifdef DEBUG_LEGION bool check_field_size = true, #else bool check_field_size = false, #endif bool silence_warnings = false, const char *warning_string = NULL, size_t offset = 0) : field(fid) { const Realm::RegionInstance instance = region.get_instance_info(LEGION_READ_WRITE, fid, actual_field_size, &bounds, Internal::NT_TemplateHelper::encode_tag<N,T>(), warning_string, silence_warnings, true/*generic accessor*/, check_field_size); if (!Realm::GenericAccessor<FT,N,T>::is_compatible(instance, fid, source_bounds)) region.report_incompatible_accessor("GenericAccessor", instance, fid); accessor = Realm::GenericAccessor<FT,N,T>(instance, fid, source_bounds, offset); bounds.bounds = source_bounds.intersection(bounds.bounds); } public: inline FT read(const Point<N,T>& p) const { if (!bounds.contains(p)) PhysicalRegion::fail_bounds_check(DomainPoint(p), field, LEGION_READ_ONLY); return accessor.read(p); } inline void write(const Point<N,T>& p, FT val) const { if (!bounds.contains(p)) PhysicalRegion::fail_bounds_check(DomainPoint(p), field, LEGION_WRITE_DISCARD); accessor.write(p, val); } inline ArraySyntax::AccessorRefHelper<FT,LEGION_READ_WRITE> operator[](const Point<N,T>& p) const { if (!bounds.contains(p)) PhysicalRegion::fail_bounds_check(DomainPoint(p), field, LEGION_READ_WRITE); return ArraySyntax::AccessorRefHelper<FT,LEGION_READ_WRITE>( accessor[p]); } inline ArraySyntax::GenericSyntaxHelper< FieldAccessor<LEGION_READ_WRITE,FT,N,T, Realm::GenericAccessor<FT,N,T>,true>,FT,N,T,2,LEGION_READ_WRITE> operator[](T index) const { return ArraySyntax::GenericSyntaxHelper< FieldAccessor<LEGION_READ_WRITE,FT,N,T, Realm::GenericAccessor<FT,N,T>,true>,FT,N,T,2,LEGION_READ_WRITE>( *this, Point<1,T>(index)); } // No reductions since we can't handle atomicity correctly public: mutable Realm::GenericAccessor<FT,N,T> accessor; FieldID field; DomainT<N,T> bounds; public: typedef FT value_type; typedef FT& reference; typedef const FT& const_reference; static const int dim = N; }; // Read-write FieldAccessor specialization // with N==1 to avoid array ambiguity template<typename FT, typename T, bool CB> class FieldAccessor<LEGION_READ_WRITE,FT,1,T, Realm::GenericAccessor<FT,1,T>,CB> { public: FieldAccessor(void) { } FieldAccessor(const PhysicalRegion &region, FieldID fid, size_t actual_field_size = sizeof(FT), #ifdef DEBUG_LEGION bool check_field_size = true, #else bool check_field_size = false, #endif bool silence_warnings = false, const char *warning_string = NULL, size_t offset = 0) { DomainT<1,T> is; const Realm::RegionInstance instance = region.get_instance_info(LEGION_READ_WRITE, fid,actual_field_size,&is, Internal::NT_TemplateHelper::encode_tag<1,T>(), warning_string, silence_warnings, true/*generic accessor*/, check_field_size); if (!Realm::GenericAccessor<FT,1,T>::is_compatible(instance, fid, is.bounds)) region.report_incompatible_accessor("GenericAccessor", instance, fid); accessor = Realm::GenericAccessor<FT,1,T>(instance, fid, is.bounds, offset); } FieldAccessor(const PhysicalRegion &region, FieldID fid, const Rect<1,T> source_bounds, size_t actual_field_size = sizeof(FT), #ifdef DEBUG_LEGION bool check_field_size = true, #else bool check_field_size = false, #endif bool silence_warnings = false, const char *warning_string = NULL, size_t offset = 0) { DomainT<1,T> is; const Realm::RegionInstance instance = region.get_instance_info(LEGION_READ_WRITE, fid,actual_field_size,&is, Internal::NT_TemplateHelper::encode_tag<1,T>(), warning_string, silence_warnings, true/*generic accessor*/, check_field_size); if (!Realm::GenericAccessor<FT,1,T>::is_compatible(instance, fid, source_bounds)) region.report_incompatible_accessor("GenericAccessor", instance, fid); accessor = Realm::GenericAccessor<FT,1,T>(instance, fid, source_bounds, offset); } public: inline FT read(const Point<1,T>& p) const { return accessor.read(p); } inline void write(const Point<1,T>& p, FT val) const { accessor.write(p, val); } inline ArraySyntax::AccessorRefHelper<FT,LEGION_READ_WRITE> operator[](const Point<1,T>& p) const { return ArraySyntax::AccessorRefHelper<FT,LEGION_READ_WRITE>( accessor[p]); } // No reductions since we can't handle atomicity correctly public: mutable Realm::GenericAccessor<FT,1,T> accessor; public: typedef FT value_type; typedef FT& reference; typedef const FT& const_reference; static const int dim = 1; }; // Read-write FieldAccessor specialization // with N==1 to avoid array ambiguity and bounds checks template<typename FT, typename T> class FieldAccessor<LEGION_READ_WRITE,FT,1,T, Realm::GenericAccessor<FT,1,T>,true> { public: FieldAccessor(void) { } FieldAccessor(const PhysicalRegion &region, FieldID fid, size_t actual_field_size = sizeof(FT), #ifdef DEBUG_LEGION bool check_field_size = true, #else bool check_field_size = false, #endif bool silence_warnings = false, const char *warning_string = NULL, size_t offset = 0) : field(fid) { const Realm::RegionInstance instance = region.get_instance_info(LEGION_READ_WRITE, fid, actual_field_size, &bounds, Internal::NT_TemplateHelper::encode_tag<1,T>(), warning_string, silence_warnings, true/*generic accessor*/, check_field_size); if (!Realm::GenericAccessor<FT,1,T>::is_compatible(instance, fid, bounds.bounds)) region.report_incompatible_accessor("GenericAccessor", instance, fid); accessor = Realm::GenericAccessor<FT,1,T>(instance, fid, bounds.bounds, offset); } FieldAccessor(const PhysicalRegion &region, FieldID fid, const Rect<1,T> source_bounds, size_t actual_field_size = sizeof(FT), #ifdef DEBUG_LEGION bool check_field_size = true, #else bool check_field_size = false, #endif bool silence_warnings = false, const char *warning_string = NULL, size_t offset = 0) : field(fid) { const Realm::RegionInstance instance = region.get_instance_info(LEGION_READ_WRITE, fid, actual_field_size, &bounds, Internal::NT_TemplateHelper::encode_tag<1,T>(), warning_string, silence_warnings, true/*generic accessor*/, check_field_size); if (!Realm::GenericAccessor<FT,1,T>::is_compatible(instance, fid, source_bounds)) region.report_incompatible_accessor("GenericAccessor", instance, fid); accessor = Realm::GenericAccessor<FT,1,T>(instance, fid, source_bounds, offset); bounds.bounds = source_bounds.intersection(bounds.bounds); } public: inline FT read(const Point<1,T>& p) const { if (!bounds.contains(p)) PhysicalRegion::fail_bounds_check(DomainPoint(p), field, LEGION_READ_ONLY); return accessor.read(p); } inline void write(const Point<1,T>& p, FT val) const { if (!bounds.contains(p)) PhysicalRegion::fail_bounds_check(DomainPoint(p), field, LEGION_WRITE_DISCARD); accessor.write(p, val); } inline ArraySyntax::AccessorRefHelper<FT,LEGION_READ_WRITE> operator[](const Point<1,T>& p) const { if (!bounds.contains(p)) PhysicalRegion::fail_bounds_check(DomainPoint(p), field, LEGION_READ_WRITE); return ArraySyntax::AccessorRefHelper<FT,LEGION_READ_WRITE>( accessor[p]); } // No reduction since we can't handle atomicity correctly public: mutable Realm::GenericAccessor<FT,1,T> accessor; FieldID field; DomainT<1,T> bounds; public: typedef FT value_type; typedef FT& reference; typedef const FT& const_reference; static const int dim = 1; }; // Write-discard FieldAccessor specialization template<typename FT, int N, typename T, bool CB> class FieldAccessor<LEGION_WRITE_DISCARD,FT,N,T, Realm::GenericAccessor<FT,N,T>,CB> { public: FieldAccessor(void) { } FieldAccessor(const PhysicalRegion &region, FieldID fid, size_t actual_field_size = sizeof(FT), #ifdef DEBUG_LEGION bool check_field_size = true, #else bool check_field_size = false, #endif bool silence_warnings = false, const char *warning_string = NULL, size_t offset = 0) { DomainT<N,T> is; const Realm::RegionInstance instance = region.get_instance_info(LEGION_WRITE_DISCARD, fid, actual_field_size, &is,Internal::NT_TemplateHelper::encode_tag<N,T>(),warning_string, silence_warnings, true/*generic accessor*/, check_field_size); if (!Realm::GenericAccessor<FT,N,T>::is_compatible(instance, fid, is.bounds)) region.report_incompatible_accessor("GenericAccessor", instance, fid); accessor = Realm::GenericAccessor<FT,N,T>(instance, fid, is.bounds, offset); } FieldAccessor(const PhysicalRegion &region, FieldID fid, const Rect<N,T> source_bounds, size_t actual_field_size = sizeof(FT), #ifdef DEBUG_LEGION bool check_field_size = true, #else bool check_field_size = false, #endif bool silence_warnings = false, const char *warning_string = NULL, size_t offset = 0) { DomainT<N,T> is; const Realm::RegionInstance instance = region.get_instance_info(LEGION_WRITE_DISCARD, fid, actual_field_size, &is,Internal::NT_TemplateHelper::encode_tag<N,T>(),warning_string, silence_warnings, true/*generic accessor*/, check_field_size); if (!Realm::GenericAccessor<FT,N,T>::is_compatible(instance, fid, source_bounds)) region.report_incompatible_accessor("GenericAccessor", instance, fid); accessor = Realm::GenericAccessor<FT,N,T>(instance, fid, source_bounds, offset); } public: inline FT read(const Point<N,T>& p) const { return accessor.read(p); } inline void write(const Point<N,T>& p, FT val) const { accessor.write(p, val); } inline ArraySyntax::AccessorRefHelper<FT,LEGION_WRITE_DISCARD> operator[](const Point<N,T>& p) const { return ArraySyntax::AccessorRefHelper<FT,LEGION_WRITE_DISCARD>( accessor[p]); } inline ArraySyntax::GenericSyntaxHelper< FieldAccessor<LEGION_WRITE_DISCARD,FT,N,T, Realm::GenericAccessor<FT,N,T>,CB>,FT,N,T,2,LEGION_WRITE_DISCARD> operator[](T index) const { return ArraySyntax::GenericSyntaxHelper< FieldAccessor<LEGION_WRITE_DISCARD,FT,N,T, Realm::GenericAccessor<FT,N,T>,CB>,FT,N,T,2,LEGION_WRITE_DISCARD>( *this, Point<1,T>(index)); } public: mutable Realm::GenericAccessor<FT,N,T> accessor; public: typedef FT value_type; typedef FT& reference; typedef const FT& const_reference; static const int dim = 1; }; // Write-discard FieldAccessor specialization // with bounds checks template<typename FT, int N, typename T> class FieldAccessor<LEGION_WRITE_DISCARD,FT,N,T, Realm::GenericAccessor<FT,N,T>,true> { public: // No CUDA support due to PhysicalRegion constructor FieldAccessor(void) { } FieldAccessor(const PhysicalRegion &region, FieldID fid, size_t actual_field_size = sizeof(FT), #ifdef DEBUG_LEGION bool check_field_size = true, #else bool check_field_size = false, #endif bool silence_warnings = false, const char *warning_string = NULL, size_t offset = 0) : field(fid) { const Realm::RegionInstance instance = region.get_instance_info(LEGION_WRITE_DISCARD, fid, actual_field_size, &bounds, Internal::NT_TemplateHelper::encode_tag<N,T>(), warning_string, silence_warnings, true/*generic accessor*/, check_field_size); if (!Realm::GenericAccessor<FT,N,T>::is_compatible(instance, fid, bounds.bounds)) region.report_incompatible_accessor("GenericAccessor", instance, fid); accessor = Realm::GenericAccessor<FT,N,T>(instance, fid, bounds.bounds, offset); } FieldAccessor(const PhysicalRegion &region, FieldID fid, const Rect<N,T> source_bounds, size_t actual_field_size = sizeof(FT), #ifdef DEBUG_LEGION bool check_field_size = true, #else bool check_field_size = false, #endif bool silence_warnings = false, const char *warning_string = NULL, size_t offset = 0) : field(fid) { const Realm::RegionInstance instance = region.get_instance_info(LEGION_WRITE_DISCARD, fid, actual_field_size, &bounds, Internal::NT_TemplateHelper::encode_tag<N,T>(), warning_string, silence_warnings, true/*generic accessor*/, check_field_size); if (!Realm::GenericAccessor<FT,N,T>::is_compatible(instance, fid, source_bounds)) region.report_incompatible_accessor("GenericAccessor", instance, fid); accessor = Realm::GenericAccessor<FT,N,T>(instance, fid, source_bounds, offset); bounds.bounds = source_bounds.intersection(bounds.bounds); } public: inline FT read(const Point<N,T>& p) const { if (!bounds.contains(p)) PhysicalRegion::fail_bounds_check(DomainPoint(p), field, LEGION_READ_ONLY); return accessor.read(p); } inline void write(const Point<N,T>& p, FT val) const { if (!bounds.contains(p)) PhysicalRegion::fail_bounds_check(DomainPoint(p), field, LEGION_WRITE_DISCARD); accessor.write(p, val); } inline ArraySyntax::AccessorRefHelper<FT,LEGION_WRITE_DISCARD> operator[](const Point<N,T>& p) const { if (!bounds.contains(p)) PhysicalRegion::fail_bounds_check(DomainPoint(p), field, LEGION_READ_WRITE); return ArraySyntax::AccessorRefHelper<FT,LEGION_WRITE_DISCARD>( accessor[p]); } inline ArraySyntax::GenericSyntaxHelper< FieldAccessor<LEGION_WRITE_DISCARD,FT,N,T, Realm::GenericAccessor<FT,N,T>,true>,FT,N,T,2,LEGION_WRITE_DISCARD> operator[](T index) const { return ArraySyntax::GenericSyntaxHelper< FieldAccessor<LEGION_WRITE_DISCARD,FT,N,T, Realm::GenericAccessor<FT,N,T>,true>,FT,N,T,2,LEGION_WRITE_DISCARD>( *this, Point<1,T>(index)); } public: mutable Realm::GenericAccessor<FT,N,T> accessor; FieldID field; DomainT<N,T> bounds; public: typedef FT value_type; typedef FT& reference; typedef const FT& const_reference; static const int dim = N; }; // Write-discard FieldAccessor specialization with // N == 1 to avoid array ambiguity template<typename FT, typename T, bool CB> class FieldAccessor<LEGION_WRITE_DISCARD,FT,1,T, Realm::GenericAccessor<FT,1,T>,CB> { public: FieldAccessor(void) { } FieldAccessor(const PhysicalRegion &region, FieldID fid, size_t actual_field_size = sizeof(FT), #ifdef DEBUG_LEGION bool check_field_size = true, #else bool check_field_size = false, #endif bool silence_warnings = false, const char *warning_string = NULL, size_t offset = 0) { DomainT<1,T> is; const Realm::RegionInstance instance = region.get_instance_info(LEGION_WRITE_DISCARD, fid, actual_field_size, &is,Internal::NT_TemplateHelper::encode_tag<1,T>(),warning_string, silence_warnings, true/*generic accessor*/, check_field_size); if (!Realm::GenericAccessor<FT,1,T>::is_compatible(instance, fid, is.bounds)) region.report_incompatible_accessor("GenericAccessor", instance, fid); accessor = Realm::GenericAccessor<FT,1,T>(instance, fid, is.bounds, offset); } FieldAccessor(const PhysicalRegion &region, FieldID fid, const Rect<1,T> source_bounds, size_t actual_field_size = sizeof(FT), #ifdef DEBUG_LEGION bool check_field_size = true, #else bool check_field_size = false, #endif bool silence_warnings = false, const char *warning_string = NULL, size_t offset = 0) { DomainT<1,T> is; const Realm::RegionInstance instance = region.get_instance_info(LEGION_WRITE_DISCARD, fid, actual_field_size, &is,Internal::NT_TemplateHelper::encode_tag<1,T>(),warning_string, silence_warnings, true/*generic accessor*/, check_field_size); if (!Realm::GenericAccessor<FT,1,T>::is_compatible(instance, fid, source_bounds)) region.report_incompatible_accessor("GenericAccessor", instance, fid); accessor = Realm::GenericAccessor<FT,1,T>(instance, fid, source_bounds, offset); } public: inline FT read(const Point<1,T>& p) const { return accessor.read(p); } inline void write(const Point<1,T>& p, FT val) const { accessor.write(p, val); } inline ArraySyntax::AccessorRefHelper<FT,LEGION_WRITE_DISCARD> operator[](const Point<1,T>& p) const { return ArraySyntax::AccessorRefHelper<FT,LEGION_WRITE_DISCARD>( accessor[p]); } public: mutable Realm::GenericAccessor<FT,1,T> accessor; public: typedef FT value_type; typedef FT& reference; typedef const FT& const_reference; static const int dim = 1; }; // Write-discard FieldAccessor specialization with // N == 1 to avoid array ambiguity and bounds checks template<typename FT, typename T> class FieldAccessor<LEGION_WRITE_DISCARD,FT,1,T, Realm::GenericAccessor<FT,1,T>,true> { public: FieldAccessor(void) { } FieldAccessor(const PhysicalRegion &region, FieldID fid, size_t actual_field_size = sizeof(FT), #ifdef DEBUG_LEGION bool check_field_size = true, #else bool check_field_size = false, #endif bool silence_warnings = false, const char *warning_string = NULL, size_t offset = 0) : field(fid) { const Realm::RegionInstance instance = region.get_instance_info(LEGION_WRITE_DISCARD, fid, actual_field_size, &bounds, Internal::NT_TemplateHelper::encode_tag<1,T>(), warning_string, silence_warnings, true/*generic accessor*/, check_field_size); if (!Realm::GenericAccessor<FT,1,T>::is_compatible(instance, fid, bounds.bounds)) region.report_incompatible_accessor("GenericAccessor", instance, fid); accessor = Realm::GenericAccessor<FT,1,T>(instance, fid, bounds.bounds, offset); } FieldAccessor(const PhysicalRegion &region, FieldID fid, const Rect<1,T> source_bounds, size_t actual_field_size = sizeof(FT), #ifdef DEBUG_LEGION bool check_field_size = true, #else bool check_field_size = false, #endif bool silence_warnings = false, const char *warning_string = NULL, size_t offset = 0) : field(fid) { const Realm::RegionInstance instance = region.get_instance_info(LEGION_WRITE_DISCARD, fid,actual_field_size, &bounds, Internal::NT_TemplateHelper::encode_tag<1,T>(), warning_string, silence_warnings, true/*generic accessor*/, check_field_size); if (!Realm::GenericAccessor<FT,1,T>::is_compatible(instance, fid, bounds.bounds)) region.report_incompatible_accessor("GenericAccessor", instance, fid); accessor = Realm::GenericAccessor<FT,1,T>(instance, fid, bounds.bounds, offset); bounds.bounds = source_bounds.intersection(bounds.bounds); } public: inline FT read(const Point<1,T>& p) const { if (!bounds.contains(p)) PhysicalRegion::fail_bounds_check(DomainPoint(p), field, LEGION_READ_ONLY); return accessor.read(p); } inline void write(const Point<1,T>& p, FT val) const { if (!bounds.contains(p)) PhysicalRegion::fail_bounds_check(DomainPoint(p), field, LEGION_WRITE_DISCARD); accessor.write(p, val); } inline ArraySyntax::AccessorRefHelper<FT,LEGION_WRITE_DISCARD> operator[](const Point<1,T>& p) const { if (!bounds.contains(p)) PhysicalRegion::fail_bounds_check(DomainPoint(p), field, LEGION_READ_WRITE); return ArraySyntax::AccessorRefHelper<FT,LEGION_WRITE_DISCARD>( accessor[p]); } public: mutable Realm::GenericAccessor<FT,1,T> accessor; FieldID field; DomainT<1,T> bounds; public: typedef FT value_type; typedef FT& reference; typedef const FT& const_reference; static const int dim = 1; }; // Write-only FieldAccessor specialization template<typename FT, int N, typename T, bool CB> class FieldAccessor<LEGION_WRITE_ONLY,FT,N,T, Realm::GenericAccessor<FT,N,T>,CB> { public: FieldAccessor(void) { } FieldAccessor(const PhysicalRegion &region, FieldID fid, size_t actual_field_size = sizeof(FT), #ifdef DEBUG_LEGION bool check_field_size = true, #else bool check_field_size = false, #endif bool silence_warnings = false, const char *warning_string = NULL, size_t offset = 0) { DomainT<N,T> is; const Realm::RegionInstance instance = region.get_instance_info(LEGION_WRITE_DISCARD, fid, actual_field_size, &is,Internal::NT_TemplateHelper::encode_tag<N,T>(),warning_string, silence_warnings, true/*generic accessor*/, check_field_size); if (!Realm::GenericAccessor<FT,N,T>::is_compatible(instance, fid, is.bounds)) region.report_incompatible_accessor("GenericAccessor", instance, fid); accessor = Realm::GenericAccessor<FT,N,T>(instance, fid, is.bounds, offset); } FieldAccessor(const PhysicalRegion &region, FieldID fid, const Rect<N,T> source_bounds, size_t actual_field_size = sizeof(FT), #ifdef DEBUG_LEGION bool check_field_size = true, #else bool check_field_size = false, #endif bool silence_warnings = false, const char *warning_string = NULL, size_t offset = 0) { DomainT<N,T> is; const Realm::RegionInstance instance = region.get_instance_info(LEGION_WRITE_DISCARD, fid, actual_field_size, &is,Internal::NT_TemplateHelper::encode_tag<N,T>(),warning_string, silence_warnings, true/*generic accessor*/, check_field_size); if (!Realm::GenericAccessor<FT,N,T>::is_compatible(instance, fid, source_bounds)) region.report_incompatible_accessor("GenericAccessor", instance, fid); accessor = Realm::GenericAccessor<FT,N,T>(instance, fid, source_bounds, offset); } public: inline void write(const Point<N,T>& p, FT val) const { accessor.write(p, val); } inline ArraySyntax::AccessorRefHelper<FT,LEGION_WRITE_DISCARD> operator[](const Point<N,T>& p) const { return ArraySyntax::AccessorRefHelper<FT,LEGION_WRITE_DISCARD>( accessor[p]); } inline ArraySyntax::GenericSyntaxHelper< FieldAccessor<LEGION_WRITE_DISCARD,FT,N,T, Realm::GenericAccessor<FT,N,T>,CB>,FT,N,T,2,LEGION_WRITE_DISCARD> operator[](T index) const { return ArraySyntax::GenericSyntaxHelper< FieldAccessor<LEGION_WRITE_DISCARD,FT,N,T, Realm::GenericAccessor<FT,N,T>,CB>,FT,N,T,2,LEGION_WRITE_DISCARD>( *this, Point<1,T>(index)); } public: mutable Realm::GenericAccessor<FT,N,T> accessor; public: typedef FT value_type; typedef FT& reference; typedef const FT& const_reference; static const int dim = 1; }; // Write-only FieldAccessor specialization // with bounds checks template<typename FT, int N, typename T> class FieldAccessor<LEGION_WRITE_ONLY,FT,N,T, Realm::GenericAccessor<FT,N,T>,true> { public: // No CUDA support due to PhysicalRegion constructor FieldAccessor(void) { } FieldAccessor(const PhysicalRegion &region, FieldID fid, size_t actual_field_size = sizeof(FT), #ifdef DEBUG_LEGION bool check_field_size = true, #else bool check_field_size = false, #endif bool silence_warnings = false, const char *warning_string = NULL, size_t offset = 0) : field(fid) { const Realm::RegionInstance instance = region.get_instance_info(LEGION_WRITE_DISCARD, fid, actual_field_size, &bounds, Internal::NT_TemplateHelper::encode_tag<N,T>(), warning_string, silence_warnings, true/*generic accessor*/, check_field_size); if (!Realm::GenericAccessor<FT,N,T>::is_compatible(instance, fid, bounds.bounds)) region.report_incompatible_accessor("GenericAccessor", instance, fid); accessor = Realm::GenericAccessor<FT,N,T>(instance, fid, bounds.bounds, offset); } FieldAccessor(const PhysicalRegion &region, FieldID fid, const Rect<N,T> source_bounds, size_t actual_field_size = sizeof(FT), #ifdef DEBUG_LEGION bool check_field_size = true, #else bool check_field_size = false, #endif bool silence_warnings = false, const char *warning_string = NULL, size_t offset = 0) : field(fid) { const Realm::RegionInstance instance = region.get_instance_info(LEGION_WRITE_DISCARD, fid, actual_field_size, &bounds, Internal::NT_TemplateHelper::encode_tag<N,T>(), warning_string, silence_warnings, true/*generic accessor*/, check_field_size); if (!Realm::GenericAccessor<FT,N,T>::is_compatible(instance, fid, source_bounds)) region.report_incompatible_accessor("GenericAccessor", instance, fid); accessor = Realm::GenericAccessor<FT,N,T>(instance, fid, source_bounds, offset); bounds.bounds = source_bounds.intersection(bounds.bound); } public: inline void write(const Point<N,T>& p, FT val) const { if (!bounds.contains(p)) PhysicalRegion::fail_bounds_check(DomainPoint(p), field, LEGION_WRITE_DISCARD); accessor.write(p, val); } inline ArraySyntax::AccessorRefHelper<FT,LEGION_WRITE_DISCARD> operator[](const Point<N,T>& p) const { if (!bounds.contains(p)) PhysicalRegion::fail_bounds_check(DomainPoint(p), field, LEGION_READ_WRITE); return ArraySyntax::AccessorRefHelper<FT,LEGION_WRITE_DISCARD>( accessor[p]); } inline ArraySyntax::GenericSyntaxHelper< FieldAccessor<LEGION_WRITE_DISCARD,FT,N,T, Realm::GenericAccessor<FT,N,T>,true>,FT,N,T,2,LEGION_WRITE_DISCARD> operator[](T index) const { return ArraySyntax::GenericSyntaxHelper< FieldAccessor<LEGION_WRITE_DISCARD,FT,N,T, Realm::GenericAccessor<FT,N,T>,true>,FT,N,T,2,LEGION_WRITE_DISCARD>( *this, Point<1,T>(index)); } public: mutable Realm::GenericAccessor<FT,N,T> accessor; FieldID field; DomainT<N,T> bounds; public: typedef FT value_type; typedef FT& reference; typedef const FT& const_reference; static const int dim = N; }; // Write-only FieldAccessor specialization with // N == 1 to avoid array ambiguity template<typename FT, typename T, bool CB> class FieldAccessor<LEGION_WRITE_ONLY,FT,1,T, Realm::GenericAccessor<FT,1,T>,CB> { public: FieldAccessor(void) { } FieldAccessor(const PhysicalRegion &region, FieldID fid, size_t actual_field_size = sizeof(FT), #ifdef DEBUG_LEGION bool check_field_size = true, #else bool check_field_size = false, #endif bool silence_warnings = false, const char *warning_string = NULL, size_t offset = 0) { DomainT<1,T> is; const Realm::RegionInstance instance = region.get_instance_info(LEGION_WRITE_DISCARD, fid, actual_field_size, &is,Internal::NT_TemplateHelper::encode_tag<1,T>(),warning_string, silence_warnings, true/*generic accessor*/, check_field_size); if (!Realm::GenericAccessor<FT,1,T>::is_compatible(instance, fid, is.bounds)) region.report_incompatible_accessor("GenericAccessor", instance, fid); accessor = Realm::GenericAccessor<FT,1,T>(instance, fid, is.bounds, offset); } FieldAccessor(const PhysicalRegion &region, FieldID fid, const Rect<1,T> source_bounds, size_t actual_field_size = sizeof(FT), #ifdef DEBUG_LEGION bool check_field_size = true, #else bool check_field_size = false, #endif bool silence_warnings = false, const char *warning_string = NULL, size_t offset = 0) { DomainT<1,T> is; const Realm::RegionInstance instance = region.get_instance_info(LEGION_WRITE_DISCARD, fid, actual_field_size, &is,Internal::NT_TemplateHelper::encode_tag<1,T>(),warning_string, silence_warnings, true/*generic accessor*/, check_field_size); if (!Realm::GenericAccessor<FT,1,T>::is_compatible(instance, fid, source_bounds)) region.report_incompatible_accessor("GenericAccessor", instance, fid); accessor = Realm::GenericAccessor<FT,1,T>(instance, fid, source_bounds, offset); } public: inline void write(const Point<1,T>& p, FT val) const { accessor.write(p, val); } inline ArraySyntax::AccessorRefHelper<FT,LEGION_WRITE_DISCARD> operator[](const Point<1,T>& p) const { return ArraySyntax::AccessorRefHelper<FT,LEGION_WRITE_DISCARD>( accessor[p]); } public: mutable Realm::GenericAccessor<FT,1,T> accessor; public: typedef FT value_type; typedef FT& reference; typedef const FT& const_reference; static const int dim = 1; }; // Write-only FieldAccessor specialization with // N == 1 to avoid array ambiguity and bounds checks template<typename FT, typename T> class FieldAccessor<LEGION_WRITE_ONLY,FT,1,T, Realm::GenericAccessor<FT,1,T>,true> { public: FieldAccessor(void) { } FieldAccessor(const PhysicalRegion &region, FieldID fid, size_t actual_field_size = sizeof(FT), #ifdef DEBUG_LEGION bool check_field_size = true, #else bool check_field_size = false, #endif bool silence_warnings = false, const char *warning_string = NULL, size_t offset = 0) : field(fid) { const Realm::RegionInstance instance = region.get_instance_info(LEGION_WRITE_DISCARD, fid, actual_field_size, &bounds, Internal::NT_TemplateHelper::encode_tag<1,T>(), warning_string, silence_warnings, true/*generic accessor*/, check_field_size); if (!Realm::GenericAccessor<FT,1,T>::is_compatible(instance, fid, bounds.bounds)) region.report_incompatible_accessor("GenericAccessor", instance, fid); accessor = Realm::GenericAccessor<FT,1,T>(instance, fid, bounds.bounds, offset); } FieldAccessor(const PhysicalRegion &region, FieldID fid, const Rect<1,T> source_bounds, size_t actual_field_size = sizeof(FT), #ifdef DEBUG_LEGION bool check_field_size = true, #else bool check_field_size = false, #endif bool silence_warnings = false, const char *warning_string = NULL, size_t offset = 0) : field(fid) { const Realm::RegionInstance instance = region.get_instance_info(LEGION_WRITE_DISCARD, fid, actual_field_size, &bounds, Internal::NT_TemplateHelper::encode_tag<1,T>(), warning_string, silence_warnings, true/*generic accessor*/, check_field_size); if (!Realm::GenericAccessor<FT,1,T>::is_compatible(instance, fid, source_bounds)) region.report_incompatible_accessor("GenericAccessor", instance, fid); accessor = Realm::GenericAccessor<FT,1,T>(instance, fid, source_bounds, offset); bounds.bounds = source_bounds.intersection(bounds.bounds); } public: inline void write(const Point<1,T>& p, FT val) const { if (!bounds.contains(p)) PhysicalRegion::fail_bounds_check(DomainPoint(p), field, LEGION_WRITE_DISCARD); accessor.write(p, val); } inline ArraySyntax::AccessorRefHelper<FT,LEGION_WRITE_DISCARD> operator[](const Point<1,T>& p) const { if (!bounds.contains(p)) PhysicalRegion::fail_bounds_check(DomainPoint(p), field, LEGION_READ_WRITE); return ArraySyntax::AccessorRefHelper<FT,LEGION_WRITE_DISCARD>( accessor[p]); } public: mutable Realm::GenericAccessor<FT,1,T> accessor; FieldID field; DomainT<1,T> bounds; public: typedef FT value_type; typedef FT& reference; typedef const FT& const_reference; static const int dim = 1; }; // Special namespace for providing bounds check help for affine accessors namespace AffineBounds { // A helper class for testing bounds for affine accessors // which might have a transform associated with them // We should never use the base version of this, only the specializations template<int N, typename T> class Tester { public: Tester(void) : M(0) { } Tester(const DomainT<N,T> b) : bounds(b), M(N), has_source(false), has_transform(false) { } Tester(const DomainT<N,T> b, const Rect<N,T> s) : bounds(b), source(s), M(N), has_source(true), has_transform(false) { } template<int M2> Tester(const DomainT<M2,T> b, const AffineTransform<M2,N,T> t) : bounds(b), transform(t), M(M2), has_source(false), has_transform(!t.is_identity()) { LEGION_STATIC_ASSERT(M2 <= LEGION_MAX_DIM, "Accessor DIM larger than LEGION_MAX_DIM"); } template<int M2> Tester(const DomainT<M2,T> b, const Rect<N,T> s, const AffineTransform<M2,N,T> t) : bounds(b), transform(t), source(s), M(M2), has_source(true), has_transform(!t.is_identity()) { LEGION_STATIC_ASSERT(M2 <= LEGION_MAX_DIM, "Accessor DIM larger than LEGION_MAX_DIM"); } public: __CUDA_HD__ inline bool contains(const Point<N,T> &p) const { if (has_source && !source.contains(p)) return false; #ifdef __CUDA_ARCH__ check_gpu_warning(); // Note that in CUDA this function is likely being inlined // everywhere and we can't afford to instantiate templates // for every single dimension so do things untyped if (!has_transform) { // This is imprecise because we can't see the // Realm index space on the GPU const Rect<N,T> b = bounds.bounds<N,T>(); return b.contains(p); } else return bounds.contains_bounds_only(transform[DomainPoint(p)]); #else if (!has_transform) { const DomainT<N,T> b = bounds; return b.contains(p); } switch (M) { #define DIMFUNC(DIM) \ case DIM: \ { \ const DomainT<DIM,T> b = bounds; \ const AffineTransform<DIM,N,T> t = transform; \ return b.contains(t[p]); \ } LEGION_FOREACH_N(DIMFUNC) #undef DIMFUNC default: assert(false); } return false; #endif } __CUDA_HD__ inline bool contains_all(const Rect<N,T> &r) const { if (has_source && !source.contains(r)) return false; #ifdef __CUDA_ARCH__ check_gpu_warning(); // Note that in CUDA this function is likely being inlined // everywhere and we can't afford to instantiate templates // for every single dimension so do things untyped if (has_transform) { for (PointInRectIterator<N,T> itr(r); itr(); itr++) if (!bounds.contains_bounds_only(transform[DomainPoint(*itr)])) return false; return true; } else { // This is imprecise because we can't see the // Realm index space on the GPU const Rect<N,T> b = bounds.bounds<N,T>(); return b.contains(r); } #else if (!has_transform) { const DomainT<N,T> b = bounds; return b.contains_all(r); } // If we have a transform then we have to do each point separately switch (M) { #define DIMFUNC(DIM) \ case DIM: \ { \ const DomainT<DIM,T> b = bounds; \ const AffineTransform<DIM,N,T> t = transform; \ for (PointInRectIterator<N,T> itr(r); itr(); itr++) \ if (!b.contains(t[*itr])) \ return false; \ return true; \ } LEGION_FOREACH_N(DIMFUNC) #undef DIMFUNC default: assert(false); } return false; #endif } private: __CUDA_HD__ inline void check_gpu_warning(void) const { #if 0 #ifdef __CUDA_ARCH__ bool need_warning = !bounds.dense(); if (need_warning) printf("WARNING: GPU bounds check is imprecise!\n"); #endif #endif } private: Domain bounds; DomainAffineTransform transform; Rect<N,T> source; int M; bool has_source; bool has_transform; }; }; // Some helper methods for accessors and deferred buffers namespace Internal { template<int N, typename T> __CUDA_HD__ static inline bool is_dense_layout(const Rect<N,T> &bounds, const size_t strides[N], size_t field_size) { ptrdiff_t exp_offset = field_size; int used_mask = 0; // keep track of the dimensions we've already matched static_assert((N <= (8*sizeof(used_mask))), "Mask dim exceeded"); for (int i = 0; i < N; i++) { bool found = false; for (int j = 0; j < N; j++) { if ((used_mask >> j) & 1) continue; if (strides[j] != exp_offset) continue; found = true; // It's possible other dimensions can have the same strides if // there are multiple dimensions with extents of size 1. At most // one dimension can have an extent >1 though int nontrivial = (bounds.lo[j] < bounds.hi[j]) ? j : -1; for (int k = j+1; k < N; k++) { if ((used_mask >> k) & 1) continue; if (strides[k] == exp_offset) { if (bounds.lo[k] < bounds.hi[k]) { // if we already saw a non-trivial dimension this is bad if (nontrivial >= 0) return false; else nontrivial = k; } used_mask |= (1 << k); i++; } } used_mask |= (1 << j); if (nontrivial >= 0) exp_offset *= (bounds.hi[nontrivial] - bounds.lo[nontrivial] + 1); break; } if (!found) return false; } return true; } // Same method as above but for realm points from affine accessors template<int N, typename T> __CUDA_HD__ static inline bool is_dense_layout(const Rect<N,T> &bounds, const Realm::Point<N,size_t> &strides, size_t field_size) { size_t exp_offset = field_size; int used_mask = 0; // keep track of the dimensions we've already matched static_assert((N <= (8*sizeof(used_mask))), "Mask dim exceeded"); for (int i = 0; i < N; i++) { bool found = false; for (int j = 0; j < N; j++) { if ((used_mask >> j) & 1) continue; if (strides[j] != exp_offset) continue; found = true; // It's possible other dimensions can have the same strides if // there are multiple dimensions with extents of size 1. At most // one dimension can have an extent >1 though int nontrivial = (bounds.lo[j] < bounds.hi[j]) ? j : -1; for (int k = j+1; k < N; k++) { if ((used_mask >> k) & 1) continue; if (strides[k] == exp_offset) { if (bounds.lo[k] < bounds.hi[k]) { // if we already saw a non-trivial dimension this is bad if (nontrivial >= 0) return false; else nontrivial = k; } used_mask |= (1 << k); i++; } } used_mask |= (1 << j); if (nontrivial >= 0) exp_offset *= (bounds.hi[nontrivial] - bounds.lo[nontrivial] + 1); break; } if (!found) return false; } return true; } } //////////////////////////////////////////////////////////// // Specializations for Affine Accessors //////////////////////////////////////////////////////////// // Read-only FieldAccessor specialization template<typename FT, int N, typename T, bool CB> class FieldAccessor<LEGION_READ_ONLY,FT,N,T, Realm::AffineAccessor<FT,N,T>,CB> { public: __CUDA_HD__ FieldAccessor(void) { } FieldAccessor(const PhysicalRegion &region, FieldID fid, size_t actual_field_size = sizeof(FT), #ifdef DEBUG_LEGION bool check_field_size = true, #else bool check_field_size = false, #endif bool silence_warnings = false, const char *warning_string = NULL, size_t offset = 0) { DomainT<N,T> is; const Realm::RegionInstance instance = region.get_instance_info(LEGION_READ_ONLY, fid, actual_field_size,&is, Internal::NT_TemplateHelper::encode_tag<N,T>(), warning_string, silence_warnings, false/*generic accessor*/, check_field_size); if (!Realm::AffineAccessor<FT,N,T>::is_compatible(instance, fid, is.bounds)) region.report_incompatible_accessor("AffineAccessor", instance, fid); accessor = Realm::AffineAccessor<FT,N,T>(instance, fid, is.bounds, offset); } // With explicit bounds FieldAccessor(const PhysicalRegion &region, FieldID fid, const Rect<N,T> source_bounds, size_t actual_field_size = sizeof(FT), #ifdef DEBUG_LEGION bool check_field_size = true, #else bool check_field_size = false, #endif bool silence_warnings = false, const char *warning_string = NULL, size_t offset = 0) { DomainT<N,T> is; const Realm::RegionInstance instance = region.get_instance_info(LEGION_READ_ONLY, fid, actual_field_size,&is, Internal::NT_TemplateHelper::encode_tag<N,T>(), warning_string, silence_warnings, false/*generic accessor*/, check_field_size); if (!Realm::AffineAccessor<FT,N,T>::is_compatible(instance, fid, source_bounds)) region.report_incompatible_accessor("AffineAccessor", instance, fid); accessor = Realm::AffineAccessor<FT,N,T>(instance, fid, source_bounds, offset); } // With explicit transform template<int M> FieldAccessor(const PhysicalRegion &region, FieldID fid, const AffineTransform<M,N,T> transform, size_t actual_field_size = sizeof(FT), #ifdef DEBUG_LEGION bool check_field_size = true, #else bool check_field_size = false, #endif bool silence_warnings = false, const char *warning_string = NULL, size_t offset = 0) { DomainT<M,T> is; const Realm::RegionInstance instance = region.get_instance_info(LEGION_READ_ONLY, fid, actual_field_size,&is, Internal::NT_TemplateHelper::encode_tag<M,T>(), warning_string, silence_warnings, false/*generic accessor*/, check_field_size); if (!Realm::AffineAccessor<FT,N,T>::is_compatible(instance, transform.transform, transform.offset, fid)) region.report_incompatible_accessor("AffineAccessor", instance, fid); accessor = Realm::AffineAccessor<FT,N,T>(instance, transform.transform, transform.offset, fid, offset); } // With explicit transform and bounds template<int M> FieldAccessor(const PhysicalRegion &region, FieldID fid, const AffineTransform<M,N,T> transform, const Rect<N,T> source_bounds, size_t actual_field_size = sizeof(FT), #ifdef DEBUG_LEGION bool check_field_size = true, #else bool check_field_size = false, #endif bool silence_warnings = false, const char *warning_string = NULL, size_t offset = 0) { DomainT<M,T> is; const Realm::RegionInstance instance = region.get_instance_info(LEGION_READ_ONLY, fid, actual_field_size,&is, Internal::NT_TemplateHelper::encode_tag<M,T>(), warning_string, silence_warnings, false/*generic accessor*/, check_field_size); if (!Realm::AffineAccessor<FT,N,T>::is_compatible(instance, transform.transform, transform.offset, fid, source_bounds)) region.report_incompatible_accessor("AffineAccessor", instance, fid); accessor = Realm::AffineAccessor<FT,N,T>(instance, transform.transform, transform.offset, fid, source_bounds, offset); } public: __CUDA_HD__ inline FT read(const Point<N,T>& p) const { return accessor.read(p); } __CUDA_HD__ inline const FT* ptr(const Point<N,T>& p) const { return accessor.ptr(p); } __CUDA_HD__ inline const FT* ptr(const Rect<N,T>& r, size_t field_size = sizeof(FT)) const { #ifdef __CUDA_ARCH__ assert(Internal::is_dense_layout(r, accessor.strides, field_size)); #else if (!Internal::is_dense_layout(r, accessor.strides, field_size)) { fprintf(stderr, "ERROR: Illegal request for pointer of non-dense rectangle\n"); #ifdef DEBUG_LEGION assert(false); #else exit(ERROR_NON_DENSE_RECTANGLE); #endif } #endif return accessor.ptr(r.lo); } __CUDA_HD__ inline const FT* ptr(const Rect<N,T>& r, size_t strides[N], size_t field_size = sizeof(FT)) const { for (int i = 0; i < N; i++) strides[i] = accessor.strides[i] / field_size; return accessor.ptr(r.lo); } __CUDA_HD__ inline const FT& operator[](const Point<N,T>& p) const { return accessor[p]; } __CUDA_HD__ inline ArraySyntax::AffineSyntaxHelper< FieldAccessor<LEGION_READ_ONLY,FT,N,T, Realm::AffineAccessor<FT,N,T>,CB>,FT,N,T,2,LEGION_READ_ONLY> operator[](T index) const { return ArraySyntax::AffineSyntaxHelper< FieldAccessor<LEGION_READ_ONLY,FT,N,T, Realm::AffineAccessor<FT,N,T>,CB>,FT,N,T,2,LEGION_READ_ONLY>( *this, Point<1,T>(index)); } public: Realm::AffineAccessor<FT,N,T> accessor; public: typedef FT value_type; typedef FT& reference; typedef const FT& const_reference; static const int dim = N; }; // Read-only FieldAccessor specialization // with bounds checks template<typename FT, int N, typename T> class FieldAccessor<LEGION_READ_ONLY,FT,N,T, Realm::AffineAccessor<FT,N,T>,true> { public: // No CUDA support due to PhysicalRegion constructor FieldAccessor(void) { } FieldAccessor(const PhysicalRegion &region, FieldID fid, size_t actual_field_size = sizeof(FT), #ifdef DEBUG_LEGION bool check_field_size = true, #else bool check_field_size = false, #endif bool silence_warnings = false, const char *warning_string = NULL, size_t offset = 0) : field(fid) { DomainT<N,T> is; const Realm::RegionInstance instance = region.get_instance_info(LEGION_READ_ONLY, fid, actual_field_size,&is, Internal::NT_TemplateHelper::encode_tag<N,T>(), warning_string, silence_warnings, false/*generic accessor*/, check_field_size); if (!Realm::AffineAccessor<FT,N,T>::is_compatible(instance, fid, is.bounds)) region.report_incompatible_accessor("AffineAccessor", instance, fid); accessor = Realm::AffineAccessor<FT,N,T>(instance, fid, is.bounds, offset); bounds = AffineBounds::Tester<N,T>(is); } // With explicit bounds FieldAccessor(const PhysicalRegion &region, FieldID fid, const Rect<N,T> source_bounds, size_t actual_field_size = sizeof(FT), #ifdef DEBUG_LEGION bool check_field_size = true, #else bool check_field_size = false, #endif bool silence_warnings = false, const char *warning_string = NULL, size_t offset = 0) : field(fid) { DomainT<N,T> is; const Realm::RegionInstance instance = region.get_instance_info(LEGION_READ_ONLY, fid, actual_field_size,&is, Internal::NT_TemplateHelper::encode_tag<N,T>(), warning_string, silence_warnings, false/*generic accessor*/, check_field_size); if (!Realm::AffineAccessor<FT,N,T>::is_compatible(instance, fid, source_bounds)) region.report_incompatible_accessor("AffineAccessor", instance, fid); accessor = Realm::AffineAccessor<FT,N,T>(instance, fid, source_bounds, offset); bounds = AffineBounds::Tester<N,T>(is, source_bounds); } // With explicit transform template<int M> FieldAccessor(const PhysicalRegion &region, FieldID fid, const AffineTransform<M,N,T> transform, size_t actual_field_size = sizeof(FT), #ifdef DEBUG_LEGION bool check_field_size = true, #else bool check_field_size = false, #endif bool silence_warnings = false, const char *warning_string = NULL, size_t offset = 0) : field(fid) { DomainT<M,T> is; const Realm::RegionInstance instance = region.get_instance_info(LEGION_READ_ONLY, fid, actual_field_size,&is, Internal::NT_TemplateHelper::encode_tag<M,T>(), warning_string, silence_warnings, false/*generic accessor*/, check_field_size); if (!Realm::AffineAccessor<FT,N,T>::is_compatible(instance, transform.transform, transform.offset, fid)) region.report_incompatible_accessor("AffineAccessor", instance, fid); accessor = Realm::AffineAccessor<FT,N,T>(instance, transform.transform, transform.offset, fid, offset); bounds = AffineBounds::Tester<N,T>(is, transform); } // With explicit transform and bounds template<int M> FieldAccessor(const PhysicalRegion &region, FieldID fid, const AffineTransform<M,N,T> transform, const Rect<N,T> source_bounds, size_t actual_field_size = sizeof(FT), #ifdef DEBUG_LEGION bool check_field_size = true, #else bool check_field_size = false, #endif bool silence_warnings = false, const char *warning_string = NULL, size_t offset = 0) : field(fid) { DomainT<M,T> is; const Realm::RegionInstance instance = region.get_instance_info(LEGION_READ_ONLY, fid, actual_field_size,&is, Internal::NT_TemplateHelper::encode_tag<M,T>(), warning_string, silence_warnings, false/*generic accessor*/, check_field_size); if (!Realm::AffineAccessor<FT,N,T>::is_compatible(instance, transform.transform, transform.offset, fid, source_bounds)) region.report_incompatible_accessor("AffineAccessor", instance, fid); accessor = Realm::AffineAccessor<FT,N,T>(instance, transform.transform, transform.offset, fid, source_bounds, offset); bounds = AffineBounds::Tester<N,T>(is, source_bounds, transform); } public: __CUDA_HD__ inline FT read(const Point<N,T>& p) const { #ifdef __CUDA_ARCH__ assert(bounds.contains(p)); #else if (!bounds.contains(p)) PhysicalRegion::fail_bounds_check(DomainPoint(p), field, LEGION_READ_ONLY); #endif return accessor.read(p); } __CUDA_HD__ inline const FT* ptr(const Point<N,T>& p) const { #ifdef __CUDA_ARCH__ assert(bounds.contains(p)); #else if (!bounds.contains(p)) PhysicalRegion::fail_bounds_check(DomainPoint(p), field, LEGION_READ_ONLY); #endif return accessor.ptr(p); } __CUDA_HD__ inline const FT* ptr(const Rect<N,T>& r, size_t field_size = sizeof(FT)) const { #ifdef __CUDA_ARCH__ assert(bounds.contains_all(r)); assert(Internal::is_dense_layout(r, accessor.strides, field_size)); #else if (!bounds.contains_all(r)) PhysicalRegion::fail_bounds_check(Domain(r), field, LEGION_READ_ONLY); if (!Internal::is_dense_layout(r, accessor.strides, field_size)) { fprintf(stderr, "ERROR: Illegal request for pointer of non-dense rectangle\n"); #ifdef DEBUG_LEGION assert(false); #else exit(ERROR_NON_DENSE_RECTANGLE); #endif } #endif return accessor.ptr(r.lo); } __CUDA_HD__ inline const FT* ptr(const Rect<N,T>& r, size_t strides[N], size_t field_size = sizeof(FT)) const { #ifdef __CUDA_ARCH__ assert(bounds.contains_all(r)); #else if (!bounds.contains_all(r)) PhysicalRegion::fail_bounds_check(Domain(r), field, LEGION_READ_ONLY); #endif for (int i = 0; i < N; i++) strides[i] = accessor.strides[i] / field_size; return accessor.ptr(r.lo); } __CUDA_HD__ inline const FT& operator[](const Point<N,T>& p) const { #ifdef __CUDA_ARCH__ assert(bounds.contains(p)); #else if (!bounds.contains(p)) PhysicalRegion::fail_bounds_check(DomainPoint(p), field, LEGION_READ_ONLY); #endif return accessor[p]; } __CUDA_HD__ inline ArraySyntax::AffineSyntaxHelper< FieldAccessor<LEGION_READ_ONLY,FT,N,T, Realm::AffineAccessor<FT,N,T>,true>,FT,N,T,2,LEGION_READ_ONLY> operator[](T index) const { return ArraySyntax::AffineSyntaxHelper< FieldAccessor<LEGION_READ_ONLY,FT,N,T, Realm::AffineAccessor<FT,N,T>,true>,FT,N,T,2,LEGION_READ_ONLY>( *this, Point<1,T>(index)); } public: Realm::AffineAccessor<FT,N,T> accessor; FieldID field; AffineBounds::Tester<N,T> bounds; public: typedef FT value_type; typedef FT& reference; typedef const FT& const_reference; static const int dim = N; }; // Read-only FieldAccessor specialization // with N==1 to avoid array ambiguity template<typename FT, typename T, bool CB> class FieldAccessor<LEGION_READ_ONLY,FT,1,T, Realm::AffineAccessor<FT,1,T>,CB> { public: __CUDA_HD__ FieldAccessor(void) { } FieldAccessor(const PhysicalRegion &region, FieldID fid, size_t actual_field_size = sizeof(FT), #ifdef DEBUG_LEGION bool check_field_size = true, #else bool check_field_size = false, #endif bool silence_warnings = false, const char *warning_string = NULL, size_t offset = 0) { DomainT<1,T> is; const Realm::RegionInstance instance = region.get_instance_info(LEGION_READ_ONLY, fid, actual_field_size,&is, Internal::NT_TemplateHelper::encode_tag<1,T>(), warning_string, silence_warnings, false/*generic accessor*/, check_field_size); if (!Realm::AffineAccessor<FT,1,T>::is_compatible(instance, fid, is.bounds)) region.report_incompatible_accessor("AffineAccessor", instance, fid); accessor = Realm::AffineAccessor<FT,1,T>(instance, fid, is.bounds, offset); } // With explicit bounds FieldAccessor(const PhysicalRegion &region, FieldID fid, const Rect<1,T> source_bounds, size_t actual_field_size = sizeof(FT), #ifdef DEBUG_LEGION bool check_field_size = true, #else bool check_field_size = false, #endif bool silence_warnings = false, const char *warning_string = NULL, size_t offset = 0) { DomainT<1,T> is; const Realm::RegionInstance instance = region.get_instance_info(LEGION_READ_ONLY, fid, actual_field_size,&is, Internal::NT_TemplateHelper::encode_tag<1,T>(), warning_string, silence_warnings, false/*generic accessor*/, check_field_size); if (!Realm::AffineAccessor<FT,1,T>::is_compatible(instance, fid, source_bounds)) region.report_incompatible_accessor("AffineAccessor", instance, fid); accessor = Realm::AffineAccessor<FT,1,T>(instance, fid, source_bounds, offset); } // With explicit transform template<int M> FieldAccessor(const PhysicalRegion &region, FieldID fid, const AffineTransform<M,1,T> transform, size_t actual_field_size = sizeof(FT), #ifdef DEBUG_LEGION bool check_field_size = true, #else bool check_field_size = false, #endif bool silence_warnings = false, const char *warning_string = NULL, size_t offset = 0) { DomainT<M,T> is; const Realm::RegionInstance instance = region.get_instance_info(LEGION_READ_ONLY, fid, actual_field_size,&is, Internal::NT_TemplateHelper::encode_tag<M,T>(), warning_string, silence_warnings, false/*generic accessor*/, check_field_size); if (!Realm::AffineAccessor<FT,1,T>::is_compatible(instance, transform.transform, transform.offset, fid)) region.report_incompatible_accessor("AffineAccessor", instance, fid); accessor = Realm::AffineAccessor<FT,1,T>(instance, transform.transform, transform.offset, fid, offset); } // With explicit transform and bounds template<int M> FieldAccessor(const PhysicalRegion &region, FieldID fid, const AffineTransform<M,1,T> transform, const Rect<1,T> source_bounds, size_t actual_field_size = sizeof(FT), #ifdef DEBUG_LEGION bool check_field_size = true, #else bool check_field_size = false, #endif bool silence_warnings = false, const char *warning_string = NULL, size_t offset = 0) { DomainT<M,T> is; const Realm::RegionInstance instance = region.get_instance_info(LEGION_READ_ONLY, fid, actual_field_size,&is, Internal::NT_TemplateHelper::encode_tag<M,T>(), warning_string, silence_warnings, false/*generic accessor*/, check_field_size); if (!Realm::AffineAccessor<FT,1,T>::is_compatible(instance, transform.transform, transform.offset, fid, source_bounds)) region.report_incompatible_accessor("AffineAccessor", instance, fid); accessor = Realm::AffineAccessor<FT,1,T>(instance, transform.transform, transform.offset, fid, source_bounds, offset); } public: __CUDA_HD__ inline FT read(const Point<1,T>& p) const { return accessor.read(p); } __CUDA_HD__ inline const FT* ptr(const Point<1,T>& p) const { return accessor.ptr(p); } __CUDA_HD__ inline const FT* ptr(const Rect<1,T>& r, size_t field_size = sizeof(FT)) const { #ifdef __CUDA_ARCH__ assert(Internal::is_dense_layout(r, accessor.strides, field_size)); #else if (!Internal::is_dense_layout(r, accessor.strides, field_size)) { fprintf(stderr, "ERROR: Illegal request for pointer of non-dense rectangle\n"); #ifdef DEBUG_LEGION assert(false); #else exit(ERROR_NON_DENSE_RECTANGLE); #endif } #endif return accessor.ptr(r.lo); } __CUDA_HD__ inline const FT* ptr(const Rect<1,T>& r, size_t strides[1], size_t field_size = sizeof(FT)) const { strides[0] = accessor.strides[0] / field_size; return accessor.ptr(r.lo); } __CUDA_HD__ inline const FT& operator[](const Point<1,T>& p) const { return accessor[p]; } public: Realm::AffineAccessor<FT,1,T> accessor; public: typedef FT value_type; typedef FT& reference; typedef const FT& const_reference; static const int dim = 1; }; // Read-only FieldAccessor specialization // with N==1 to avoid array ambiguity and bounds checks template<typename FT, typename T> class FieldAccessor<LEGION_READ_ONLY,FT,1,T, Realm::AffineAccessor<FT,1,T>,true> { public: // No CUDA support due to PhysicalRegion constructor FieldAccessor(void) { } FieldAccessor(const PhysicalRegion &region, FieldID fid, size_t actual_field_size = sizeof(FT), #ifdef DEBUG_LEGION bool check_field_size = true, #else bool check_field_size = false, #endif bool silence_warnings = false, const char *warning_string = NULL, size_t offset = 0) : field(fid) { DomainT<1,T> is; const Realm::RegionInstance instance = region.get_instance_info(LEGION_READ_ONLY, fid, actual_field_size,&is, Internal::NT_TemplateHelper::encode_tag<1,T>(), warning_string, silence_warnings, false/*generic accessor*/, check_field_size); if (!Realm::AffineAccessor<FT,1,T>::is_compatible(instance, fid, is.bounds)) region.report_incompatible_accessor("AffineAccessor", instance, fid); accessor = Realm::AffineAccessor<FT,1,T>(instance, fid, is.bounds, offset); bounds = AffineBounds::Tester<1,T>(is); } // With explicit bounds FieldAccessor(const PhysicalRegion &region, FieldID fid, const Rect<1,T> source_bounds, size_t actual_field_size = sizeof(FT), #ifdef DEBUG_LEGION bool check_field_size = true, #else bool check_field_size = false, #endif bool silence_warnings = false, const char *warning_string = NULL, size_t offset = 0) : field(fid) { DomainT<1,T> is; const Realm::RegionInstance instance = region.get_instance_info(LEGION_READ_ONLY, fid, actual_field_size,&is, Internal::NT_TemplateHelper::encode_tag<1,T>(), warning_string, silence_warnings, false/*generic accessor*/, check_field_size); if (!Realm::AffineAccessor<FT,1,T>::is_compatible(instance, fid, source_bounds)) region.report_incompatible_accessor("AffineAccessor", instance, fid); accessor = Realm::AffineAccessor<FT,1,T>(instance, fid, source_bounds, offset); bounds = AffineBounds::Tester<1,T>(is, source_bounds); } // With explicit transform template<int M> FieldAccessor(const PhysicalRegion &region, FieldID fid, const AffineTransform<M,1,T> transform, size_t actual_field_size = sizeof(FT), #ifdef DEBUG_LEGION bool check_field_size = true, #else bool check_field_size = false, #endif bool silence_warnings = false, const char *warning_string = NULL, size_t offset = 0) : field(fid) { DomainT<M,T> is; const Realm::RegionInstance instance = region.get_instance_info(LEGION_READ_ONLY, fid, actual_field_size,&is, Internal::NT_TemplateHelper::encode_tag<M,T>(), warning_string, silence_warnings, false/*generic accessor*/, check_field_size); if (!Realm::AffineAccessor<FT,1,T>::is_compatible(instance, transform.transform, transform.offset, fid)) region.report_incompatible_accessor("AffineAccessor", instance, fid); accessor = Realm::AffineAccessor<FT,1,T>(instance, transform.transform, transform.offset, fid, offset); bounds = AffineBounds::Tester<1,T>(is, transform); } // With explicit transform and bounds template<int M> FieldAccessor(const PhysicalRegion &region, FieldID fid, const AffineTransform<M,1,T> transform, const Rect<1,T> source_bounds, size_t actual_field_size = sizeof(FT), #ifdef DEBUG_LEGION bool check_field_size = true, #else bool check_field_size = false, #endif bool silence_warnings = false, const char *warning_string = NULL, size_t offset = 0) : field(fid) { DomainT<M,T> is; const Realm::RegionInstance instance = region.get_instance_info(LEGION_READ_ONLY, fid, actual_field_size,&is, Internal::NT_TemplateHelper::encode_tag<M,T>(), warning_string, silence_warnings, false/*generic accessor*/, check_field_size); if (!Realm::AffineAccessor<FT,1,T>::is_compatible(instance, transform.transform, transform.offset, fid, source_bounds)) region.report_incompatible_accessor("AffineAccessor", instance, fid); accessor = Realm::AffineAccessor<FT,1,T>(instance, transform.transform, transform.offset, fid, source_bounds, offset); bounds = AffineBounds::Tester<1,T>(is, source_bounds, transform); } public: __CUDA_HD__ inline FT read(const Point<1,T>& p) const { #ifdef __CUDA_ARCH__ assert(bounds.contains(p)); #else if (!bounds.contains(p)) PhysicalRegion::fail_bounds_check(DomainPoint(p), field, LEGION_READ_ONLY); #endif return accessor.read(p); } __CUDA_HD__ inline const FT* ptr(const Point<1,T>& p) const { #ifdef __CUDA_ARCH__ assert(bounds.contains(p)); #else if (!bounds.contains(p)) PhysicalRegion::fail_bounds_check(DomainPoint(p), field, LEGION_READ_ONLY); #endif return accessor.ptr(p); } __CUDA_HD__ inline const FT* ptr(const Rect<1,T>& r, size_t field_size = sizeof(FT)) const { #ifdef __CUDA_ARCH__ assert(bounds.contains_all(r)); assert(Internal::is_dense_layout(r, accessor.strides, field_size)); #else if (!bounds.contains_all(r)) PhysicalRegion::fail_bounds_check(Domain(r), field, LEGION_READ_ONLY); if (!Internal::is_dense_layout(r, accessor.strides, field_size)) { fprintf(stderr, "ERROR: Illegal request for pointer of non-dense rectangle\n"); #ifdef DEBUG_LEGION assert(false); #else exit(ERROR_NON_DENSE_RECTANGLE); #endif } #endif return accessor.ptr(r.lo); } __CUDA_HD__ inline const FT* ptr(const Rect<1,T>& r, size_t strides[1], size_t field_size = sizeof(FT)) const { #ifdef __CUDA_ARCH__ assert(bounds.contains_all(r)); #else if (!bounds.contains_all(r)) PhysicalRegion::fail_bounds_check(Domain(r), field, LEGION_READ_ONLY); #endif strides[0] = accessor.strides[0] / field_size; return accessor.ptr(r.lo); } __CUDA_HD__ inline const FT& operator[](const Point<1,T>& p) const { #ifdef __CUDA_ARCH__ assert(bounds.contains(p)); #else if (!bounds.contains(p)) PhysicalRegion::fail_bounds_check(DomainPoint(p), field, LEGION_READ_ONLY); #endif return accessor[p]; } public: Realm::AffineAccessor<FT,1,T> accessor; FieldID field; AffineBounds::Tester<1,T> bounds; public: typedef FT value_type; typedef FT& reference; typedef const FT& const_reference; static const int dim = 1; }; // Read-write FieldAccessor specialization template<typename FT, int N, typename T, bool CB> class FieldAccessor<LEGION_READ_WRITE,FT,N,T, Realm::AffineAccessor<FT,N,T>,CB> { public: __CUDA_HD__ FieldAccessor(void) { } FieldAccessor(const PhysicalRegion &region, FieldID fid, size_t actual_field_size = sizeof(FT), #ifdef DEBUG_LEGION bool check_field_size = true, #else bool check_field_size = false, #endif bool silence_warnings = false, const char *warning_string = NULL, size_t offset = 0) { DomainT<N,T> is; const Realm::RegionInstance instance = region.get_instance_info(LEGION_READ_WRITE, fid,actual_field_size,&is, Internal::NT_TemplateHelper::encode_tag<N,T>(), warning_string, silence_warnings, false/*generic accessor*/, check_field_size); if (!Realm::AffineAccessor<FT,N,T>::is_compatible(instance, fid, is.bounds)) region.report_incompatible_accessor("AffineAccessor", instance, fid); accessor = Realm::AffineAccessor<FT,N,T>(instance, fid, is.bounds, offset); } // With explicit bounds FieldAccessor(const PhysicalRegion &region, FieldID fid, const Rect<N,T> source_bounds, size_t actual_field_size = sizeof(FT), #ifdef DEBUG_LEGION bool check_field_size = true, #else bool check_field_size = false, #endif bool silence_warnings = false, const char *warning_string = NULL, size_t offset = 0) { DomainT<N,T> is; const Realm::RegionInstance instance = region.get_instance_info(LEGION_READ_WRITE, fid,actual_field_size,&is, Internal::NT_TemplateHelper::encode_tag<N,T>(), warning_string, silence_warnings, false/*generic accessor*/, check_field_size); if (!Realm::AffineAccessor<FT,N,T>::is_compatible(instance, fid, source_bounds)) region.report_incompatible_accessor("AffineAccessor", instance, fid); accessor = Realm::AffineAccessor<FT,N,T>(instance, fid, source_bounds, offset); } // With explicit transform template<int M> FieldAccessor(const PhysicalRegion &region, FieldID fid, const AffineTransform<M,N,T> transform, size_t actual_field_size = sizeof(FT), #ifdef DEBUG_LEGION bool check_field_size = true, #else bool check_field_size = false, #endif bool silence_warnings = false, const char *warning_string = NULL, size_t offset = 0) { DomainT<M,T> is; const Realm::RegionInstance instance = region.get_instance_info(LEGION_READ_WRITE, fid,actual_field_size,&is, Internal::NT_TemplateHelper::encode_tag<M,T>(), warning_string, silence_warnings, false/*generic accessor*/, check_field_size); if (!Realm::AffineAccessor<FT,N,T>::is_compatible(instance, transform.transform, transform.offset, fid)) region.report_incompatible_accessor("AffineAccessor", instance, fid); accessor = Realm::AffineAccessor<FT,N,T>(instance, transform.transform, transform.offset, fid, offset); } // With explicit transform and bounds template<int M> FieldAccessor(const PhysicalRegion &region, FieldID fid, const AffineTransform<M,N,T> transform, const Rect<N,T> source_bounds, size_t actual_field_size = sizeof(FT), #ifdef DEBUG_LEGION bool check_field_size = true, #else bool check_field_size = false, #endif bool silence_warnings = false, const char *warning_string = NULL, size_t offset = 0) { DomainT<M,T> is; const Realm::RegionInstance instance = region.get_instance_info(LEGION_READ_WRITE, fid,actual_field_size,&is, Internal::NT_TemplateHelper::encode_tag<M,T>(), warning_string, silence_warnings, false/*generic accessor*/, check_field_size); if (!Realm::AffineAccessor<FT,N,T>::is_compatible(instance, transform.transform, transform.offset, fid, source_bounds)) region.report_incompatible_accessor("AffineAccessor", instance, fid); accessor = Realm::AffineAccessor<FT,N,T>(instance, transform.transform, transform.offset, fid, source_bounds, offset); } public: __CUDA_HD__ inline FT read(const Point<N,T>& p) const { return accessor.read(p); } __CUDA_HD__ inline void write(const Point<N,T>& p, FT val) const { accessor.write(p, val); } __CUDA_HD__ inline FT* ptr(const Point<N,T>& p) const { return accessor.ptr(p); } __CUDA_HD__ inline FT* ptr(const Rect<N,T>& r, size_t field_size = sizeof(FT)) const { #ifdef __CUDA_ARCH__ assert(Internal::is_dense_layout(r, accessor.strides, field_size)); #else if (!Internal::is_dense_layout(r, accessor.strides, field_size)) { fprintf(stderr, "ERROR: Illegal request for pointer of non-dense rectangle\n"); #ifdef DEBUG_LEGION assert(false); #else exit(ERROR_NON_DENSE_RECTANGLE); #endif } #endif return accessor.ptr(r.lo); } __CUDA_HD__ inline FT* ptr(const Rect<N,T>& r, size_t strides[N], size_t field_size = sizeof(FT)) const { for (int i = 0; i < N; i++) strides[i] = accessor.strides[i] / field_size; return accessor.ptr(r.lo); } __CUDA_HD__ inline FT& operator[](const Point<N,T>& p) const { return accessor[p]; } __CUDA_HD__ inline ArraySyntax::AffineSyntaxHelper< FieldAccessor<LEGION_READ_WRITE,FT,N,T, Realm::AffineAccessor<FT,N,T>,CB>,FT,N,T,2,LEGION_READ_WRITE> operator[](T index) const { return ArraySyntax::AffineSyntaxHelper< FieldAccessor<LEGION_READ_WRITE,FT,N,T, Realm::AffineAccessor<FT,N,T>,CB>,FT,N,T,2,LEGION_READ_WRITE>( *this, Point<1,T>(index)); } template<typename REDOP, bool EXCLUSIVE> __CUDA_HD__ inline void reduce(const Point<N,T>& p, typename REDOP::RHS val) const { REDOP::template apply<EXCLUSIVE>(accessor[p], val); } public: Realm::AffineAccessor<FT,N,T> accessor; public: typedef FT value_type; typedef FT& reference; typedef const FT& const_reference; static const int dim = N; }; // Read-write FieldAccessor specialization // with bounds checks template<typename FT, int N, typename T> class FieldAccessor<LEGION_READ_WRITE,FT,N,T, Realm::AffineAccessor<FT,N,T>,true> { public: // No CUDA support due to PhysicalRegion constructor FieldAccessor(void) { } FieldAccessor(const PhysicalRegion &region, FieldID fid, size_t actual_field_size = sizeof(FT), #ifdef DEBUG_LEGION bool check_field_size = true, #else bool check_field_size = false, #endif bool silence_warnings = false, const char *warning_string = NULL, size_t offset = 0) : field(fid) { DomainT<N,T> is; const Realm::RegionInstance instance = region.get_instance_info(LEGION_READ_WRITE, fid,actual_field_size,&is, Internal::NT_TemplateHelper::encode_tag<N,T>(), warning_string, silence_warnings, false/*generic accessor*/, check_field_size); if (!Realm::AffineAccessor<FT,N,T>::is_compatible(instance, fid, is.bounds)) region.report_incompatible_accessor("AffineAccessor", instance, fid); accessor = Realm::AffineAccessor<FT,N,T>(instance, fid, is.bounds, offset); bounds = AffineBounds::Tester<N,T>(is); } // With explicit bounds FieldAccessor(const PhysicalRegion &region, FieldID fid, const Rect<N,T> source_bounds, size_t actual_field_size = sizeof(FT), #ifdef DEBUG_LEGION bool check_field_size = true, #else bool check_field_size = false, #endif bool silence_warnings = false, const char *warning_string = NULL, size_t offset = 0) : field(fid) { DomainT<N,T> is; const Realm::RegionInstance instance = region.get_instance_info(LEGION_READ_WRITE, fid,actual_field_size,&is, Internal::NT_TemplateHelper::encode_tag<N,T>(), warning_string, silence_warnings, false/*generic accessor*/, check_field_size); if (!Realm::AffineAccessor<FT,N,T>::is_compatible(instance, fid, source_bounds)) region.report_incompatible_accessor("AffineAccessor", instance, fid); accessor = Realm::AffineAccessor<FT,N,T>(instance, fid, source_bounds, offset); bounds = AffineBounds::Tester<N,T>(is, source_bounds); } // With explicit transform template<int M> FieldAccessor(const PhysicalRegion &region, FieldID fid, const AffineTransform<M,N,T> transform, size_t actual_field_size = sizeof(FT), #ifdef DEBUG_LEGION bool check_field_size = true, #else bool check_field_size = false, #endif bool silence_warnings = false, const char *warning_string = NULL, size_t offset = 0) : field(fid) { DomainT<M,T> is; const Realm::RegionInstance instance = region.get_instance_info(LEGION_READ_WRITE, fid,actual_field_size,&is, Internal::NT_TemplateHelper::encode_tag<M,T>(), warning_string, silence_warnings, false/*generic accessor*/, check_field_size); if (!Realm::AffineAccessor<FT,N,T>::is_compatible(instance, transform.transform, transform.offset, fid)) region.report_incompatible_accessor("AffineAccessor", instance, fid); accessor = Realm::AffineAccessor<FT,N,T>(instance, transform.transform, transform.offset, fid, offset); bounds = AffineBounds::Tester<N,T>(is, transform); } // With explicit transform and bounds template<int M> FieldAccessor(const PhysicalRegion &region, FieldID fid, const AffineTransform<M,N,T> transform, const Rect<N,T> source_bounds, size_t actual_field_size = sizeof(FT), #ifdef DEBUG_LEGION bool check_field_size = true, #else bool check_field_size = false, #endif bool silence_warnings = false, const char *warning_string = NULL, size_t offset = 0) : field(fid) { DomainT<M,T> is; const Realm::RegionInstance instance = region.get_instance_info(LEGION_READ_WRITE, fid,actual_field_size,&is, Internal::NT_TemplateHelper::encode_tag<M,T>(), warning_string, silence_warnings, false/*generic accessor*/, check_field_size); if (!Realm::AffineAccessor<FT,N,T>::is_compatible(instance, transform.transform, transform.offset, fid, source_bounds)) region.report_incompatible_accessor("AffineAccessor", instance, fid); accessor = Realm::AffineAccessor<FT,N,T>(instance, transform.transform, transform.offset, fid, source_bounds, offset); bounds = AffineBounds::Tester<N,T>(is, source_bounds, transform); } public: __CUDA_HD__ inline FT read(const Point<N,T>& p) const { #ifdef __CUDA_ARCH__ assert(bounds.contains(p)); #else if (!bounds.contains(p)) PhysicalRegion::fail_bounds_check(DomainPoint(p), field, LEGION_READ_ONLY); #endif return accessor.read(p); } __CUDA_HD__ inline void write(const Point<N,T>& p, FT val) const { #ifdef __CUDA_ARCH__ assert(bounds.contains(p)); #else if (!bounds.contains(p)) PhysicalRegion::fail_bounds_check(DomainPoint(p), field, LEGION_WRITE_DISCARD); #endif accessor.write(p, val); } __CUDA_HD__ inline FT* ptr(const Point<N,T>& p) const { #ifdef __CUDA_ARCH__ assert(bounds.contains(p)); #else if (!bounds.contains(p)) PhysicalRegion::fail_bounds_check(DomainPoint(p), field, LEGION_READ_WRITE); #endif return accessor.ptr(p); } __CUDA_HD__ inline FT* ptr(const Rect<N,T>& r, size_t field_size = sizeof(FT)) const { #ifdef __CUDA_ARCH__ assert(bounds.contains_all(r)); assert(Internal::is_dense_layout(r, accessor.strides, field_size)); #else if (!bounds.contains_all(r)) PhysicalRegion::fail_bounds_check(Domain(r), field, LEGION_READ_WRITE); if (!Internal::is_dense_layout(r, accessor.strides, field_size)) { fprintf(stderr, "ERROR: Illegal request for pointer of non-dense rectangle\n"); #ifdef DEBUG_LEGION assert(false); #else exit(ERROR_NON_DENSE_RECTANGLE); #endif } #endif return accessor.ptr(r.lo); } __CUDA_HD__ inline FT* ptr(const Rect<N,T>& r, size_t strides[N], size_t field_size = sizeof(FT)) const { #ifdef __CUDA_ARCH__ assert(bounds.contains_all(r)); #else if (!bounds.contains_all(r)) PhysicalRegion::fail_bounds_check(Domain(r), field, LEGION_READ_WRITE); #endif for (int i = 0; i < N; i++) strides[i] = accessor.strides[i] / field_size; return accessor.ptr(r.lo); } __CUDA_HD__ inline FT& operator[](const Point<N,T>& p) const { #ifdef __CUDA_ARCH__ assert(bounds.contains(p)); #else if (!bounds.contains(p)) PhysicalRegion::fail_bounds_check(DomainPoint(p), field, LEGION_READ_WRITE); #endif return accessor[p]; } __CUDA_HD__ inline ArraySyntax::AffineSyntaxHelper< FieldAccessor<LEGION_READ_WRITE,FT,N,T, Realm::AffineAccessor<FT,N,T>,true>,FT,N,T,2,LEGION_READ_WRITE> operator[](T index) const { return ArraySyntax::AffineSyntaxHelper< FieldAccessor<LEGION_READ_WRITE,FT,N,T, Realm::AffineAccessor<FT,N,T>,true>,FT,N,T,2,LEGION_READ_WRITE>( *this, Point<1,T>(index)); } template<typename REDOP, bool EXCLUSIVE> __CUDA_HD__ inline void reduce(const Point<N,T>& p, typename REDOP::RHS val) const { #ifdef __CUDA_ARCH__ assert(bounds.contains(p)); #else if (!bounds.contains(p)) PhysicalRegion::fail_bounds_check(DomainPoint(p), field, LEGION_REDUCE); #endif REDOP::template apply<EXCLUSIVE>(accessor[p], val); } public: Realm::AffineAccessor<FT,N,T> accessor; FieldID field; AffineBounds::Tester<N,T> bounds; public: typedef FT value_type; typedef FT& reference; typedef const FT& const_reference; static const int dim = N; }; // Read-write FieldAccessor specialization // with N==1 to avoid array ambiguity template<typename FT, typename T, bool CB> class FieldAccessor<LEGION_READ_WRITE,FT,1,T, Realm::AffineAccessor<FT,1,T>,CB> { public: __CUDA_HD__ FieldAccessor(void) { } FieldAccessor(const PhysicalRegion &region, FieldID fid, size_t actual_field_size = sizeof(FT), #ifdef DEBUG_LEGION bool check_field_size = true, #else bool check_field_size = false, #endif bool silence_warnings = false, const char *warning_string = NULL, size_t offset = 0) { DomainT<1,T> is; const Realm::RegionInstance instance = region.get_instance_info(LEGION_READ_WRITE, fid,actual_field_size,&is, Internal::NT_TemplateHelper::encode_tag<1,T>(), warning_string, silence_warnings, false/*generic accessor*/, check_field_size); if (!Realm::AffineAccessor<FT,1,T>::is_compatible(instance, fid, is.bounds)) region.report_incompatible_accessor("AffineAccessor", instance, fid); accessor = Realm::AffineAccessor<FT,1,T>(instance, fid, is.bounds, offset); } // With explicit bounds FieldAccessor(const PhysicalRegion &region, FieldID fid, const Rect<1,T> source_bounds, size_t actual_field_size = sizeof(FT), #ifdef DEBUG_LEGION bool check_field_size = true, #else bool check_field_size = false, #endif bool silence_warnings = false, const char *warning_string = NULL, size_t offset = 0) { DomainT<1,T> is; const Realm::RegionInstance instance = region.get_instance_info(LEGION_READ_WRITE, fid,actual_field_size,&is, Internal::NT_TemplateHelper::encode_tag<1,T>(), warning_string, silence_warnings, false/*generic accessor*/, check_field_size); if (!Realm::AffineAccessor<FT,1,T>::is_compatible(instance, fid, source_bounds)) region.report_incompatible_accessor("AffineAccessor", instance, fid); accessor = Realm::AffineAccessor<FT,1,T>(instance, fid, source_bounds, offset); } // With explicit transform template<int M> FieldAccessor(const PhysicalRegion &region, FieldID fid, const AffineTransform<M,1,T> transform, size_t actual_field_size = sizeof(FT), #ifdef DEBUG_LEGION bool check_field_size = true, #else bool check_field_size = false, #endif bool silence_warnings = false, const char *warning_string = NULL, size_t offset = 0) { DomainT<M,T> is; const Realm::RegionInstance instance = region.get_instance_info(LEGION_READ_WRITE, fid,actual_field_size,&is, Internal::NT_TemplateHelper::encode_tag<M,T>(), warning_string, silence_warnings, false/*generic accessor*/, check_field_size); if (!Realm::AffineAccessor<FT,1,T>::is_compatible(instance, transform.transform, transform.offset, fid)) region.report_incompatible_accessor("AffineAccessor", instance, fid); accessor = Realm::AffineAccessor<FT,1,T>(instance, transform.transform, transform.offset, fid, offset); } // With explicit transform and bounds template<int M> FieldAccessor(const PhysicalRegion &region, FieldID fid, const AffineTransform<M,1,T> transform, const Rect<1,T> source_bounds, size_t actual_field_size = sizeof(FT), #ifdef DEBUG_LEGION bool check_field_size = true, #else bool check_field_size = false, #endif bool silence_warnings = false, const char *warning_string = NULL, size_t offset = 0) { DomainT<M,T> is; const Realm::RegionInstance instance = region.get_instance_info(LEGION_READ_WRITE, fid,actual_field_size,&is, Internal::NT_TemplateHelper::encode_tag<M,T>(), warning_string, silence_warnings, false/*generic accessor*/, check_field_size); if (!Realm::AffineAccessor<FT,1,T>::is_compatible(instance, transform.transform, transform.offset, fid, source_bounds)) region.report_incompatible_accessor("AffineAccessor", instance, fid); accessor = Realm::AffineAccessor<FT,1,T>(instance, transform.transform, transform.offset, fid, source_bounds, offset); } public: __CUDA_HD__ inline FT read(const Point<1,T>& p) const { return accessor.read(p); } __CUDA_HD__ inline void write(const Point<1,T>& p, FT val) const { accessor.write(p, val); } __CUDA_HD__ inline FT* ptr(const Point<1,T>& p) const { return accessor.ptr(p); } __CUDA_HD__ inline FT* ptr(const Rect<1,T>& r, size_t field_size = sizeof(FT)) const { #ifdef __CUDA_ARCH__ assert(Internal::is_dense_layout(r, accessor.strides, field_size)); #else if (!Internal::is_dense_layout(r, accessor.strides, field_size)) { fprintf(stderr, "ERROR: Illegal request for pointer of non-dense rectangle\n"); #ifdef DEBUG_LEGION assert(false); #else exit(ERROR_NON_DENSE_RECTANGLE); #endif } #endif return accessor.ptr(r.lo); } __CUDA_HD__ inline FT* ptr(const Rect<1,T>& r, size_t strides[1], size_t field_size = sizeof(FT)) const { strides[0] = accessor.strides[0] / field_size; return accessor.ptr(r.lo); } __CUDA_HD__ inline FT& operator[](const Point<1,T>& p) const { return accessor[p]; } template<typename REDOP, bool EXCLUSIVE> __CUDA_HD__ inline void reduce(const Point<1,T>& p, typename REDOP::RHS val) const { REDOP::template apply<EXCLUSIVE>(accessor[p], val); } public: Realm::AffineAccessor<FT,1,T> accessor; public: typedef FT value_type; typedef FT& reference; typedef const FT& const_reference; static const int dim = 1; }; // Read-write FieldAccessor specialization // with N==1 to avoid array ambiguity and bounds checks template<typename FT, typename T> class FieldAccessor<LEGION_READ_WRITE,FT,1,T, Realm::AffineAccessor<FT,1,T>,true> { public: // No CUDA support due to PhysicalRegion constructor FieldAccessor(void) { } FieldAccessor(const PhysicalRegion &region, FieldID fid, size_t actual_field_size = sizeof(FT), #ifdef DEBUG_LEGION bool check_field_size = true, #else bool check_field_size = false, #endif bool silence_warnings = false, const char *warning_string = NULL, size_t offset = 0) : field(fid) { DomainT<1,T> is; const Realm::RegionInstance instance = region.get_instance_info(LEGION_READ_WRITE, fid,actual_field_size,&is, Internal::NT_TemplateHelper::encode_tag<1,T>(), warning_string, silence_warnings, false/*generic accessor*/, check_field_size); if (!Realm::AffineAccessor<FT,1,T>::is_compatible(instance, fid, is.bounds)) region.report_incompatible_accessor("AffineAccessor", instance, fid); accessor = Realm::AffineAccessor<FT,1,T>(instance, fid, is.bounds, offset); bounds = AffineBounds::Tester<1,T>(is); } // With explicit bounds FieldAccessor(const PhysicalRegion &region, FieldID fid, const Rect<1,T> source_bounds, size_t actual_field_size = sizeof(FT), #ifdef DEBUG_LEGION bool check_field_size = true, #else bool check_field_size = false, #endif bool silence_warnings = false, const char *warning_string = NULL, size_t offset = 0) : field(fid) { DomainT<1,T> is; const Realm::RegionInstance instance = region.get_instance_info(LEGION_READ_WRITE, fid,actual_field_size,&is, Internal::NT_TemplateHelper::encode_tag<1,T>(), warning_string, silence_warnings, false/*generic accessor*/, check_field_size); if (!Realm::AffineAccessor<FT,1,T>::is_compatible(instance, fid, source_bounds)) region.report_incompatible_accessor("AffineAccessor", instance, fid); accessor = Realm::AffineAccessor<FT,1,T>(instance, fid, source_bounds, offset); bounds = AffineBounds::Tester<1,T>(is, source_bounds); } // With explicit transform template<int M> FieldAccessor(const PhysicalRegion &region, FieldID fid, const AffineTransform<M,1,T> transform, size_t actual_field_size = sizeof(FT), #ifdef DEBUG_LEGION bool check_field_size = true, #else bool check_field_size = false, #endif bool silence_warnings = false, const char *warning_string = NULL, size_t offset = 0) : field(fid) { DomainT<M,T> is; const Realm::RegionInstance instance = region.get_instance_info(LEGION_READ_WRITE, fid,actual_field_size,&is, Internal::NT_TemplateHelper::encode_tag<M,T>(), warning_string, silence_warnings, false/*generic accessor*/, check_field_size); if (!Realm::AffineAccessor<FT,1,T>::is_compatible(instance, transform.transform, transform.offset, fid)) region.report_incompatible_accessor("AffineAccessor", instance, fid); accessor = Realm::AffineAccessor<FT,1,T>(instance, transform.transform, transform.offset, fid, offset); bounds = AffineBounds::Tester<1,T>(is, transform); } // With explicit transform and bounds template<int M> FieldAccessor(const PhysicalRegion &region, FieldID fid, const AffineTransform<M,1,T> transform, const Rect<1,T> source_bounds, size_t actual_field_size = sizeof(FT), #ifdef DEBUG_LEGION bool check_field_size = true, #else bool check_field_size = false, #endif bool silence_warnings = false, const char *warning_string = NULL, size_t offset = 0) : field(fid) { DomainT<M,T> is; const Realm::RegionInstance instance = region.get_instance_info(LEGION_READ_WRITE, fid,actual_field_size,&is, Internal::NT_TemplateHelper::encode_tag<M,T>(), warning_string, silence_warnings, false/*generic accessor*/, check_field_size); if (!Realm::AffineAccessor<FT,1,T>::is_compatible(instance, transform.transform, transform.offset, fid, source_bounds)) region.report_incompatible_accessor("AffineAccessor", instance, fid); accessor = Realm::AffineAccessor<FT,1,T>(instance, transform.transform, transform.offset, fid, source_bounds, offset); bounds = AffineBounds::Tester<1,T>(is, source_bounds, transform); } public: __CUDA_HD__ inline FT read(const Point<1,T>& p) const { #ifdef __CUDA_ARCH__ assert(bounds.contains(p)); #else if (!bounds.contains(p)) PhysicalRegion::fail_bounds_check(DomainPoint(p), field, LEGION_READ_ONLY); #endif return accessor.read(p); } __CUDA_HD__ inline void write(const Point<1,T>& p, FT val) const { #ifdef __CUDA_ARCH__ assert(bounds.contains(p)); #else if (!bounds.contains(p)) PhysicalRegion::fail_bounds_check(DomainPoint(p), field, LEGION_WRITE_DISCARD); #endif accessor.write(p, val); } __CUDA_HD__ inline FT* ptr(const Point<1,T>& p) const { #ifdef __CUDA_ARCH__ assert(bounds.contains(p)); #else if (!bounds.contains(p)) PhysicalRegion::fail_bounds_check(DomainPoint(p), field, LEGION_READ_WRITE); #endif return accessor.ptr(p); } __CUDA_HD__ inline FT* ptr(const Rect<1,T>& r, size_t field_size = sizeof(FT)) const { #ifdef __CUDA_ARCH__ assert(bounds.contains_all(r)); assert(Internal::is_dense_layout(r, accessor.strides, field_size)); #else if (!bounds.contains_all(r)) PhysicalRegion::fail_bounds_check(Domain(r), field, LEGION_READ_WRITE); if (!Internal::is_dense_layout(r, accessor.strides, field_size)) { fprintf(stderr, "ERROR: Illegal request for pointer of non-dense rectangle\n"); #ifdef DEBUG_LEGION assert(false); #else exit(ERROR_NON_DENSE_RECTANGLE); #endif } #endif return accessor.ptr(r.lo); } __CUDA_HD__ inline FT* ptr(const Rect<1,T>& r, size_t strides[1], size_t field_size = sizeof(FT)) const { #ifdef __CUDA_ARCH__ assert(bounds.contains_all(r)); #else if (!bounds.contains_all(r)) PhysicalRegion::fail_bounds_check(Domain(r), field, LEGION_READ_WRITE); #endif strides[0] = accessor.strides[0] / field_size; return accessor.ptr(r.lo); } __CUDA_HD__ inline FT& operator[](const Point<1,T>& p) const { #ifdef __CUDA_ARCH__ assert(bounds.contains(p)); #else if (!bounds.contains(p)) PhysicalRegion::fail_bounds_check(DomainPoint(p), field, LEGION_READ_WRITE); #endif return accessor[p]; } template<typename REDOP, bool EXCLUSIVE> __CUDA_HD__ inline void reduce(const Point<1,T>& p, typename REDOP::RHS val) const { #ifdef __CUDA_ARCH__ assert(bounds.contains(p)); #else if (!bounds.contains(p)) PhysicalRegion::fail_bounds_check(DomainPoint(p), field, LEGION_REDUCE); #endif REDOP::template apply<EXCLUSIVE>(accessor[p], val); } public: Realm::AffineAccessor<FT,1,T> accessor; FieldID field; AffineBounds::Tester<1,T> bounds; public: typedef FT value_type; typedef FT& reference; typedef const FT& const_reference; static const int dim = 1; }; // Write-discard FieldAccessor specialization template<typename FT, int N, typename T, bool CB> class FieldAccessor<LEGION_WRITE_DISCARD,FT,N,T, Realm::AffineAccessor<FT,N,T>,CB> { public: __CUDA_HD__ FieldAccessor(void) { } FieldAccessor(const PhysicalRegion &region, FieldID fid, size_t actual_field_size = sizeof(FT), #ifdef DEBUG_LEGION bool check_field_size = true, #else bool check_field_size = false, #endif bool silence_warnings = false, const char *warning_string = NULL, size_t offset = 0) { DomainT<N,T> is; const Realm::RegionInstance instance = region.get_instance_info(LEGION_WRITE_DISCARD, fid, actual_field_size, &is,Internal::NT_TemplateHelper::encode_tag<N,T>(),warning_string, silence_warnings, false/*generic accessor*/, check_field_size); if (!Realm::AffineAccessor<FT,N,T>::is_compatible(instance, fid, is.bounds)) region.report_incompatible_accessor("AffineAccessor", instance, fid); accessor = Realm::AffineAccessor<FT,N,T>(instance, fid, is.bounds, offset); } // With explicit bounds FieldAccessor(const PhysicalRegion &region, FieldID fid, const Rect<N,T> source_bounds, size_t actual_field_size = sizeof(FT), #ifdef DEBUG_LEGION bool check_field_size = true, #else bool check_field_size = false, #endif bool silence_warnings = false, const char *warning_string = NULL, size_t offset = 0) { DomainT<N,T> is; const Realm::RegionInstance instance = region.get_instance_info(LEGION_WRITE_DISCARD, fid, actual_field_size, &is,Internal::NT_TemplateHelper::encode_tag<N,T>(),warning_string, silence_warnings, false/*generic accessor*/, check_field_size); if (!Realm::AffineAccessor<FT,N,T>::is_compatible(instance, fid, source_bounds)) region.report_incompatible_accessor("AffineAccessor", instance, fid); accessor = Realm::AffineAccessor<FT,N,T>(instance, fid, source_bounds, offset); } // With explicit transform template<int M> FieldAccessor(const PhysicalRegion &region, FieldID fid, const AffineTransform<M,N,T> transform, size_t actual_field_size = sizeof(FT), #ifdef DEBUG_LEGION bool check_field_size = true, #else bool check_field_size = false, #endif bool silence_warnings = false, const char *warning_string = NULL, size_t offset = 0) { DomainT<M,T> is; const Realm::RegionInstance instance = region.get_instance_info(LEGION_WRITE_DISCARD, fid, actual_field_size, &is,Internal::NT_TemplateHelper::encode_tag<M,T>(),warning_string, silence_warnings, false/*generic accessor*/, check_field_size); if (!Realm::AffineAccessor<FT,N,T>::is_compatible(instance, transform.transform, transform.offset, fid)) region.report_incompatible_accessor("AffineAccessor", instance, fid); accessor = Realm::AffineAccessor<FT,N,T>(instance, transform.transform, transform.offset, fid, offset); } // With explicit transform and bounds template<int M> FieldAccessor(const PhysicalRegion &region, FieldID fid, const AffineTransform<M,N,T> transform, const Rect<N,T> source_bounds, size_t actual_field_size = sizeof(FT), #ifdef DEBUG_LEGION bool check_field_size = true, #else bool check_field_size = false, #endif bool silence_warnings = false, const char *warning_string = NULL, size_t offset = 0) { DomainT<M,T> is; const Realm::RegionInstance instance = region.get_instance_info(LEGION_WRITE_DISCARD, fid, actual_field_size, &is,Internal::NT_TemplateHelper::encode_tag<M,T>(),warning_string, silence_warnings, false/*generic accessor*/, check_field_size); if (!Realm::AffineAccessor<FT,N,T>::is_compatible(instance, transform.transform, transform.offset, fid, source_bounds)) region.report_incompatible_accessor("AffineAccessor", instance, fid); accessor = Realm::AffineAccessor<FT,N,T>(instance, transform.transform, transform.offset, fid, source_bounds, offset); } public: __CUDA_HD__ inline FT read(const Point<N,T>& p) const { return accessor.read(p); } __CUDA_HD__ inline void write(const Point<N,T>& p, FT val) const { accessor.write(p, val); } __CUDA_HD__ inline FT* ptr(const Point<N,T>& p) const { return accessor.ptr(p); } __CUDA_HD__ inline FT* ptr(const Rect<N,T>& r, size_t field_size = sizeof(FT)) const { #ifdef __CUDA_ARCH__ assert(Internal::is_dense_layout(r, accessor.strides, field_size)); #else if (!Internal::is_dense_layout(r, accessor.strides, field_size)) { fprintf(stderr, "ERROR: Illegal request for pointer of non-dense rectangle\n"); #ifdef DEBUG_LEGION assert(false); #else exit(ERROR_NON_DENSE_RECTANGLE); #endif } #endif return accessor.ptr(r.lo); } __CUDA_HD__ inline FT* ptr(const Rect<N,T>& r, size_t strides[N], size_t field_size = sizeof(FT)) const { for (int i = 0; i < N; i++) strides[i] = accessor.strides[i] / field_size; return accessor.ptr(r.lo); } __CUDA_HD__ inline FT& operator[](const Point<N,T>& p) const { return accessor[p]; } __CUDA_HD__ inline ArraySyntax::AffineSyntaxHelper< FieldAccessor<LEGION_WRITE_DISCARD,FT,N,T, Realm::AffineAccessor<FT,N,T>,CB>,FT,N,T,2,LEGION_WRITE_DISCARD> operator[](T index) const { return ArraySyntax::AffineSyntaxHelper< FieldAccessor<LEGION_WRITE_DISCARD,FT,N,T, Realm::AffineAccessor<FT,N,T>,CB>,FT,N,T,2,LEGION_WRITE_DISCARD>( *this, Point<1,T>(index)); } public: Realm::AffineAccessor<FT,N,T> accessor; public: typedef FT value_type; typedef FT& reference; typedef const FT& const_reference; static const int dim = N; }; // Write-discard FieldAccessor specialization // with bounds checks template<typename FT, int N, typename T> class FieldAccessor<LEGION_WRITE_DISCARD,FT,N,T, Realm::AffineAccessor<FT,N,T>,true> { public: // No CUDA support due to PhysicalRegion constructor FieldAccessor(void) { } FieldAccessor(const PhysicalRegion &region, FieldID fid, size_t actual_field_size = sizeof(FT), #ifdef DEBUG_LEGION bool check_field_size = true, #else bool check_field_size = false, #endif bool silence_warnings = false, const char *warning_string = NULL, size_t offset = 0) : field(fid) { DomainT<N,T> is; const Realm::RegionInstance instance = region.get_instance_info(LEGION_WRITE_DISCARD, fid, actual_field_size, &is,Internal::NT_TemplateHelper::encode_tag<N,T>(),warning_string, silence_warnings, false/*generic accessor*/, check_field_size); if (!Realm::AffineAccessor<FT,N,T>::is_compatible(instance, fid, is.bounds)) region.report_incompatible_accessor("AffineAccessor", instance, fid); accessor = Realm::AffineAccessor<FT,N,T>(instance, fid, is.bounds, offset); bounds = AffineBounds::Tester<N,T>(is); } // With explicit bounds FieldAccessor(const PhysicalRegion &region, FieldID fid, const Rect<N,T> source_bounds, size_t actual_field_size = sizeof(FT), #ifdef DEBUG_LEGION bool check_field_size = true, #else bool check_field_size = false, #endif bool silence_warnings = false, const char *warning_string = NULL, size_t offset = 0) : field(fid) { DomainT<N,T> is; const Realm::RegionInstance instance = region.get_instance_info(LEGION_WRITE_DISCARD, fid, actual_field_size, &is,Internal::NT_TemplateHelper::encode_tag<N,T>(),warning_string, silence_warnings, false/*generic accessor*/, check_field_size); if (!Realm::AffineAccessor<FT,N,T>::is_compatible(instance, fid, source_bounds)) region.report_incompatible_accessor("AffineAccessor", instance, fid); accessor = Realm::AffineAccessor<FT,N,T>(instance, fid, source_bounds, offset); bounds = AffineBounds::Tester<N,T>(is, source_bounds); } // With explicit transform template<int M> FieldAccessor(const PhysicalRegion &region, FieldID fid, const AffineTransform<M,N,T> transform, size_t actual_field_size = sizeof(FT), #ifdef DEBUG_LEGION bool check_field_size = true, #else bool check_field_size = false, #endif bool silence_warnings = false, const char *warning_string = NULL, size_t offset = 0) : field(fid) { DomainT<M,T> is; const Realm::RegionInstance instance = region.get_instance_info(LEGION_WRITE_DISCARD, fid, actual_field_size, &is,Internal::NT_TemplateHelper::encode_tag<M,T>(),warning_string, silence_warnings, false/*generic accessor*/, check_field_size); if (!Realm::AffineAccessor<FT,N,T>::is_compatible(instance, transform.transform, transform.offset, fid)) region.report_incompatible_accessor("AffineAccessor", instance, fid); accessor = Realm::AffineAccessor<FT,N,T>(instance, transform.transform, transform.offset, fid, offset); bounds = AffineBounds::Tester<N,T>(is, transform); } // With explicit transform and bounds template<int M> FieldAccessor(const PhysicalRegion &region, FieldID fid, const AffineTransform<M,N,T> transform, const Rect<N,T> source_bounds, size_t actual_field_size = sizeof(FT), #ifdef DEBUG_LEGION bool check_field_size = true, #else bool check_field_size = false, #endif bool silence_warnings = false, const char *warning_string = NULL, size_t offset = 0) : field(fid) { DomainT<M,T> is; const Realm::RegionInstance instance = region.get_instance_info(LEGION_WRITE_DISCARD, fid, actual_field_size, &is,Internal::NT_TemplateHelper::encode_tag<M,T>(),warning_string, silence_warnings, false/*generic accessor*/, check_field_size); if (!Realm::AffineAccessor<FT,N,T>::is_compatible(instance, transform.transform, transform.offset, fid, source_bounds)) region.report_incompatible_accessor("AffineAccessor", instance, fid); accessor = Realm::AffineAccessor<FT,N,T>(instance, transform.transform, transform.offset, fid, source_bounds, offset); bounds = AffineBounds::Tester<N,T>(is, source_bounds, transform); } public: __CUDA_HD__ inline FT read(const Point<N,T>& p) const { #ifdef __CUDA_ARCH__ assert(bounds.contains(p)); #else if (!bounds.contains(p)) PhysicalRegion::fail_bounds_check(DomainPoint(p), field, LEGION_READ_ONLY); #endif return accessor.read(p); } __CUDA_HD__ inline void write(const Point<N,T>& p, FT val) const { #ifdef __CUDA_ARCH__ assert(bounds.contains(p)); #else if (!bounds.contains(p)) PhysicalRegion::fail_bounds_check(DomainPoint(p), field, LEGION_WRITE_DISCARD); #endif accessor.write(p, val); } __CUDA_HD__ inline FT* ptr(const Point<N,T>& p) const { #ifdef __CUDA_ARCH__ assert(bounds.contains(p)); #else if (!bounds.contains(p)) PhysicalRegion::fail_bounds_check(DomainPoint(p), field, LEGION_READ_WRITE); #endif return accessor.ptr(p); } __CUDA_HD__ inline FT* ptr(const Rect<N,T>& r, size_t field_size = sizeof(FT)) const { #ifdef __CUDA_ARCH__ assert(bounds.contains_all(r)); assert(Internal::is_dense_layout(r, accessor.strides, field_size)); #else if (!bounds.contains_all(r)) PhysicalRegion::fail_bounds_check(Domain(r), field, LEGION_READ_WRITE); if (!Internal::is_dense_layout(r, accessor.strides, field_size)) { fprintf(stderr, "ERROR: Illegal request for pointer of non-dense rectangle\n"); #ifdef DEBUG_LEGION assert(false); #else exit(ERROR_NON_DENSE_RECTANGLE); #endif } #endif return accessor.ptr(r.lo); } __CUDA_HD__ inline FT* ptr(const Rect<N,T>& r, size_t strides[N], size_t field_size = sizeof(FT)) const { #ifdef __CUDA_ARCH__ assert(bounds.contains_all(r)); #else if (!bounds.contains_all(r)) PhysicalRegion::fail_bounds_check(Domain(r), field, LEGION_READ_WRITE); #endif for (int i = 0; i < N; i++) strides[i] = accessor.strides[i] / field_size; return accessor.ptr(r.lo); } __CUDA_HD__ inline FT& operator[](const Point<N,T>& p) const { #ifdef __CUDA_ARCH__ assert(bounds.contains(p)); #else if (!bounds.contains(p)) PhysicalRegion::fail_bounds_check(DomainPoint(p), field, LEGION_READ_WRITE); #endif return accessor[p]; } __CUDA_HD__ inline ArraySyntax::AffineSyntaxHelper< FieldAccessor<LEGION_WRITE_DISCARD,FT,N,T, Realm::AffineAccessor<FT,N,T>,true>,FT,N,T,2,LEGION_WRITE_DISCARD> operator[](T index) const { return ArraySyntax::AffineSyntaxHelper< FieldAccessor<LEGION_WRITE_DISCARD,FT,N,T, Realm::AffineAccessor<FT,N,T>,true>,FT,N,T,2,LEGION_WRITE_DISCARD>( *this, Point<1,T>(index)); } public: Realm::AffineAccessor<FT,N,T> accessor; FieldID field; AffineBounds::Tester<N,T> bounds; public: typedef FT value_type; typedef FT& reference; typedef const FT& const_reference; static const int dim = N; }; // Write-discard FieldAccessor specialization with // N == 1 to avoid array ambiguity template<typename FT, typename T, bool CB> class FieldAccessor<LEGION_WRITE_DISCARD,FT,1,T, Realm::AffineAccessor<FT,1,T>,CB> { public: __CUDA_HD__ FieldAccessor(void) { } FieldAccessor(const PhysicalRegion &region, FieldID fid, size_t actual_field_size = sizeof(FT), #ifdef DEBUG_LEGION bool check_field_size = true, #else bool check_field_size = false, #endif bool silence_warnings = false, const char *warning_string = NULL, size_t offset = 0) { DomainT<1,T> is; const Realm::RegionInstance instance = region.get_instance_info(LEGION_WRITE_DISCARD, fid, actual_field_size, &is,Internal::NT_TemplateHelper::encode_tag<1,T>(),warning_string, silence_warnings, false/*generic accessor*/, check_field_size); if (!Realm::AffineAccessor<FT,1,T>::is_compatible(instance, fid, is.bounds)) region.report_incompatible_accessor("AffineAccessor", instance, fid); accessor = Realm::AffineAccessor<FT,1,T>(instance, fid, is.bounds, offset); } // With explicit bounds FieldAccessor(const PhysicalRegion &region, FieldID fid, const Rect<1,T> source_bounds, size_t actual_field_size = sizeof(FT), #ifdef DEBUG_LEGION bool check_field_size = true, #else bool check_field_size = false, #endif bool silence_warnings = false, const char *warning_string = NULL, size_t offset = 0) { DomainT<1,T> is; const Realm::RegionInstance instance = region.get_instance_info(LEGION_WRITE_DISCARD, fid, actual_field_size, &is,Internal::NT_TemplateHelper::encode_tag<1,T>(),warning_string, silence_warnings, false/*generic accessor*/, check_field_size); if (!Realm::AffineAccessor<FT,1,T>::is_compatible(instance, fid, source_bounds)) region.report_incompatible_accessor("AffineAccessor", instance, fid); accessor = Realm::AffineAccessor<FT,1,T>(instance, fid, source_bounds, offset); } // With explicit transform template<int M> FieldAccessor(const PhysicalRegion &region, FieldID fid, const AffineTransform<M,1,T> transform, size_t actual_field_size = sizeof(FT), #ifdef DEBUG_LEGION bool check_field_size = true, #else bool check_field_size = false, #endif bool silence_warnings = false, const char *warning_string = NULL, size_t offset = 0) { DomainT<M,T> is; const Realm::RegionInstance instance = region.get_instance_info(LEGION_WRITE_DISCARD, fid, actual_field_size, &is,Internal::NT_TemplateHelper::encode_tag<M,T>(),warning_string, silence_warnings, false/*generic accessor*/, check_field_size); if (!Realm::AffineAccessor<FT,1,T>::is_compatible(instance, transform.transform, transform.offset, fid)) region.report_incompatible_accessor("AffineAccessor", instance, fid); accessor = Realm::AffineAccessor<FT,1,T>(instance, transform.transform, transform.offset, fid, offset); } // With explicit transform and bounds template<int M> FieldAccessor(const PhysicalRegion &region, FieldID fid, const AffineTransform<M,1,T> transform, const Rect<1,T> source_bounds, size_t actual_field_size = sizeof(FT), #ifdef DEBUG_LEGION bool check_field_size = true, #else bool check_field_size = false, #endif bool silence_warnings = false, const char *warning_string = NULL, size_t offset = 0) { DomainT<M,T> is; const Realm::RegionInstance instance = region.get_instance_info(LEGION_WRITE_DISCARD, fid, actual_field_size, &is,Internal::NT_TemplateHelper::encode_tag<M,T>(),warning_string, silence_warnings, false/*generic accessor*/, check_field_size); if (!Realm::AffineAccessor<FT,1,T>::is_compatible(instance, transform.transform, transform.offset, fid, source_bounds)) region.report_incompatible_accessor("AffineAccessor", instance, fid); accessor = Realm::AffineAccessor<FT,1,T>(instance, transform.transform, transform.offset, fid, source_bounds, offset); } public: __CUDA_HD__ inline FT read(const Point<1,T>& p) const { return accessor.read(p); } __CUDA_HD__ inline void write(const Point<1,T>& p, FT val) const { accessor.write(p, val); } __CUDA_HD__ inline FT* ptr(const Point<1,T>& p) const { return accessor.ptr(p); } __CUDA_HD__ inline FT* ptr(const Rect<1,T>& r, size_t field_size = sizeof(FT)) const { #ifdef __CUDA_ARCH__ assert(Internal::is_dense_layout(r, accessor.strides, field_size)); #else if (!Internal::is_dense_layout(r, accessor.strides, field_size)) { fprintf(stderr, "ERROR: Illegal request for pointer of non-dense rectangle\n"); #ifdef DEBUG_LEGION assert(false); #else exit(ERROR_NON_DENSE_RECTANGLE); #endif } #endif return accessor.ptr(r.lo); } __CUDA_HD__ inline FT* ptr(const Rect<1,T>& r, size_t strides[1], size_t field_size = sizeof(FT)) const { strides[0] = accessor.strides[0] / field_size; return accessor.ptr(r.lo); } __CUDA_HD__ inline FT& operator[](const Point<1,T>& p) const { return accessor[p]; } public: Realm::AffineAccessor<FT,1,T> accessor; public: typedef FT value_type; typedef FT& reference; typedef const FT& const_reference; static const int dim = 1; }; // Write-discard FieldAccessor specialization with // N == 1 to avoid array ambiguity and bounds checks template<typename FT, typename T> class FieldAccessor<LEGION_WRITE_DISCARD,FT,1,T, Realm::AffineAccessor<FT,1,T>,true> { public: // No CUDA support due to PhysicalRegion constructor FieldAccessor(void) { } FieldAccessor(const PhysicalRegion &region, FieldID fid, size_t actual_field_size = sizeof(FT), #ifdef DEBUG_LEGION bool check_field_size = true, #else bool check_field_size = false, #endif bool silence_warnings = false, const char *warning_string = NULL, size_t offset = 0) : field(fid) { DomainT<1,T> is; const Realm::RegionInstance instance = region.get_instance_info(LEGION_WRITE_DISCARD, fid, actual_field_size, &is,Internal::NT_TemplateHelper::encode_tag<1,T>(),warning_string, silence_warnings, false/*generic accessor*/, check_field_size); if (!Realm::AffineAccessor<FT,1,T>::is_compatible(instance, fid, is.bounds)) region.report_incompatible_accessor("AffineAccessor", instance, fid); accessor = Realm::AffineAccessor<FT,1,T>(instance, fid, is.bounds, offset); bounds = AffineBounds::Tester<1,T>(is); } // With explicit bounds FieldAccessor(const PhysicalRegion &region, FieldID fid, const Rect<1,T> source_bounds, size_t actual_field_size = sizeof(FT), #ifdef DEBUG_LEGION bool check_field_size = true, #else bool check_field_size = false, #endif bool silence_warnings = false, const char *warning_string = NULL, size_t offset = 0) : field(fid) { DomainT<1,T> is; const Realm::RegionInstance instance = region.get_instance_info(LEGION_WRITE_DISCARD, fid, actual_field_size, &is,Internal::NT_TemplateHelper::encode_tag<1,T>(),warning_string, silence_warnings, false/*generic accessor*/, check_field_size); if (!Realm::AffineAccessor<FT,1,T>::is_compatible(instance, fid, source_bounds)) region.report_incompatible_accessor("AffineAccessor", instance, fid); accessor = Realm::AffineAccessor<FT,1,T>(instance, fid, source_bounds, offset); bounds = AffineBounds::Tester<1,T>(is, source_bounds); } // With explicit transform template<int M> FieldAccessor(const PhysicalRegion &region, FieldID fid, const AffineTransform<M,1,T> transform, size_t actual_field_size = sizeof(FT), #ifdef DEBUG_LEGION bool check_field_size = true, #else bool check_field_size = false, #endif bool silence_warnings = false, const char *warning_string = NULL, size_t offset = 0) : field(fid) { DomainT<M,T> is; const Realm::RegionInstance instance = region.get_instance_info(LEGION_WRITE_DISCARD, fid, actual_field_size, &is,Internal::NT_TemplateHelper::encode_tag<M,T>(),warning_string, silence_warnings, false/*generic accessor*/, check_field_size); if (!Realm::AffineAccessor<FT,1,T>::is_compatible(instance, transform.transform, transform.offset, fid)) region.report_incompatible_accessor("AffineAccessor", instance, fid); accessor = Realm::AffineAccessor<FT,1,T>(instance, transform.transform, transform.offset, fid, offset); bounds = AffineBounds::Tester<1,T>(is, transform); } // With explicit transform and bounds template<int M> FieldAccessor(const PhysicalRegion &region, FieldID fid, const AffineTransform<M,1,T> transform, const Rect<1,T> source_bounds, size_t actual_field_size = sizeof(FT), #ifdef DEBUG_LEGION bool check_field_size = true, #else bool check_field_size = false, #endif bool silence_warnings = false, const char *warning_string = NULL, size_t offset = 0) : field(fid) { DomainT<M,T> is; const Realm::RegionInstance instance = region.get_instance_info(LEGION_WRITE_DISCARD, fid, actual_field_size, &is,Internal::NT_TemplateHelper::encode_tag<M,T>(),warning_string, silence_warnings, false/*generic accessor*/, check_field_size); if (!Realm::AffineAccessor<FT,1,T>::is_compatible(instance, transform.transform, transform.offset, fid, source_bounds)) region.report_incompatible_accessor("AffineAccessor", instance, fid); accessor = Realm::AffineAccessor<FT,1,T>(instance, transform.transform, transform.offset, fid, source_bounds, offset); bounds = AffineBounds::Tester<1,T>(is, source_bounds, transform); } public: __CUDA_HD__ inline FT read(const Point<1,T>& p) const { #ifdef __CUDA_ARCH__ assert(bounds.contains(p)); #else if (!bounds.contains(p)) PhysicalRegion::fail_bounds_check(DomainPoint(p), field, LEGION_READ_ONLY); #endif return accessor.read(p); } __CUDA_HD__ inline void write(const Point<1,T>& p, FT val) const { #ifdef __CUDA_ARCH__ assert(bounds.contains(p)); #else if (!bounds.contains(p)) PhysicalRegion::fail_bounds_check(DomainPoint(p), field, LEGION_WRITE_DISCARD); #endif accessor.write(p, val); } __CUDA_HD__ inline FT* ptr(const Point<1,T>& p) const { #ifdef __CUDA_ARCH__ assert(bounds.contains(p)); #else if (!bounds.contains(p)) PhysicalRegion::fail_bounds_check(DomainPoint(p), field, LEGION_READ_WRITE); #endif return accessor.ptr(p); } __CUDA_HD__ inline FT* ptr(const Rect<1,T>& r, size_t field_size = sizeof(FT)) const { #ifdef __CUDA_ARCH__ assert(bounds.contains_all(r)); assert(Internal::is_dense_layout(r, accessor.strides, field_size)); #else if (!bounds.contains_all(r)) PhysicalRegion::fail_bounds_check(Domain(r), field, LEGION_READ_WRITE); if (!Internal::is_dense_layout(r, accessor.strides, field_size)) { fprintf(stderr, "ERROR: Illegal request for pointer of non-dense rectangle\n"); #ifdef DEBUG_LEGION assert(false); #else exit(ERROR_NON_DENSE_RECTANGLE); #endif } #endif return accessor.ptr(r.lo); } __CUDA_HD__ inline FT* ptr(const Rect<1,T>& r, size_t strides[1], size_t field_size = sizeof(FT)) const { #ifdef __CUDA_ARCH__ assert(bounds.contains_all(r)); #else if (!bounds.contains_all(r)) PhysicalRegion::fail_bounds_check(Domain(r), field, LEGION_READ_WRITE); #endif strides[0] = accessor.strides[0] / field_size; return accessor.ptr(r.lo); } __CUDA_HD__ inline FT& operator[](const Point<1,T>& p) const { #ifdef __CUDA_ARCH__ assert(bounds.contains(p)); #else if (!bounds.contains(p)) PhysicalRegion::fail_bounds_check(DomainPoint(p), field, LEGION_READ_WRITE); #endif return accessor[p]; } public: Realm::AffineAccessor<FT,1,T> accessor; FieldID field; AffineBounds::Tester<1,T> bounds; public: typedef FT value_type; typedef FT& reference; typedef const FT& const_reference; static const int dim = 1; }; // Write-only FieldAccessor specialization template<typename FT, int N, typename T, bool CB> class FieldAccessor<LEGION_WRITE_ONLY,FT,N,T, Realm::AffineAccessor<FT,N,T>,CB> { public: __CUDA_HD__ FieldAccessor(void) { } FieldAccessor(const PhysicalRegion &region, FieldID fid, size_t actual_field_size = sizeof(FT), #ifdef DEBUG_LEGION bool check_field_size = true, #else bool check_field_size = false, #endif bool silence_warnings = false, const char *warning_string = NULL, size_t offset = 0) { DomainT<N,T> is; const Realm::RegionInstance instance = region.get_instance_info(LEGION_WRITE_DISCARD, fid, actual_field_size, &is,Internal::NT_TemplateHelper::encode_tag<N,T>(),warning_string, silence_warnings, false/*generic accessor*/, check_field_size); if (!Realm::AffineAccessor<FT,N,T>::is_compatible(instance, fid, is.bounds)) region.report_incompatible_accessor("AffineAccessor", instance, fid); accessor = Realm::AffineAccessor<FT,N,T>(instance, fid, is.bounds, offset); } // With explicit bounds FieldAccessor(const PhysicalRegion &region, FieldID fid, const Rect<N,T> source_bounds, size_t actual_field_size = sizeof(FT), #ifdef DEBUG_LEGION bool check_field_size = true, #else bool check_field_size = false, #endif bool silence_warnings = false, const char *warning_string = NULL, size_t offset = 0) { DomainT<N,T> is; const Realm::RegionInstance instance = region.get_instance_info(LEGION_WRITE_DISCARD, fid, actual_field_size, &is,Internal::NT_TemplateHelper::encode_tag<N,T>(),warning_string, silence_warnings, false/*generic accessor*/, check_field_size); if (!Realm::AffineAccessor<FT,N,T>::is_compatible(instance, fid, source_bounds)) region.report_incompatible_accessor("AffineAccessor", instance, fid); accessor = Realm::AffineAccessor<FT,N,T>(instance, fid, source_bounds, offset); } // With explicit transform template<int M> FieldAccessor(const PhysicalRegion &region, FieldID fid, const AffineTransform<M,N,T> transform, size_t actual_field_size = sizeof(FT), #ifdef DEBUG_LEGION bool check_field_size = true, #else bool check_field_size = false, #endif bool silence_warnings = false, const char *warning_string = NULL, size_t offset = 0) { DomainT<M,T> is; const Realm::RegionInstance instance = region.get_instance_info(LEGION_WRITE_DISCARD, fid, actual_field_size, &is,Internal::NT_TemplateHelper::encode_tag<M,T>(),warning_string, silence_warnings, false/*generic accessor*/, check_field_size); if (!Realm::AffineAccessor<FT,N,T>::is_compatible(instance, transform.transform, transform.offset, fid)) region.report_incompatible_accessor("AffineAccessor", instance, fid); accessor = Realm::AffineAccessor<FT,N,T>(instance, transform.transform, transform.offset, fid, offset); } // With explicit transform and bounds template<int M> FieldAccessor(const PhysicalRegion &region, FieldID fid, const AffineTransform<M,N,T> transform, const Rect<N,T> source_bounds, size_t actual_field_size = sizeof(FT), #ifdef DEBUG_LEGION bool check_field_size = true, #else bool check_field_size = false, #endif bool silence_warnings = false, const char *warning_string = NULL, size_t offset = 0) { DomainT<M,T> is; const Realm::RegionInstance instance = region.get_instance_info(LEGION_WRITE_DISCARD, fid, actual_field_size, &is,Internal::NT_TemplateHelper::encode_tag<M,T>(),warning_string, silence_warnings, false/*generic accessor*/, check_field_size); if (!Realm::AffineAccessor<FT,N,T>::is_compatible(instance, transform.transform, transform.offset, fid, source_bounds)) region.report_incompatible_accessor("AffineAccessor", instance, fid); accessor = Realm::AffineAccessor<FT,N,T>(instance, transform.transform, transform.offset, fid, source_bounds, offset); } public: __CUDA_HD__ inline void write(const Point<N,T>& p, FT val) const { accessor.write(p, val); } __CUDA_HD__ inline FT* ptr(const Point<N,T>& p) const { return accessor.ptr(p); } __CUDA_HD__ inline FT* ptr(const Rect<N,T>& r, size_t field_size = sizeof(FT)) const { #ifdef __CUDA_ARCH__ assert(Internal::is_dense_layout(r, accessor.strides, field_size)); #else if (!Internal::is_dense_layout(r, accessor.strides, field_size)) { fprintf(stderr, "ERROR: Illegal request for pointer of non-dense rectangle\n"); #ifdef DEBUG_LEGION assert(false); #else exit(ERROR_NON_DENSE_RECTANGLE); #endif } #endif return accessor.ptr(r.lo); } __CUDA_HD__ inline FT* ptr(const Rect<N,T>& r, size_t strides[N], size_t field_size = sizeof(FT)) const { for (int i = 0; i < N; i++) strides[i] = accessor.strides[i] / field_size; return accessor.ptr(r.lo); } __CUDA_HD__ inline FT& operator[](const Point<N,T>& p) const { return accessor[p]; } __CUDA_HD__ inline ArraySyntax::AffineSyntaxHelper< FieldAccessor<LEGION_WRITE_DISCARD,FT,N,T, Realm::AffineAccessor<FT,N,T>,CB>,FT,N,T,2,LEGION_WRITE_DISCARD> operator[](T index) const { return ArraySyntax::AffineSyntaxHelper< FieldAccessor<LEGION_WRITE_DISCARD,FT,N,T, Realm::AffineAccessor<FT,N,T>,CB>,FT,N,T,2,LEGION_WRITE_DISCARD>( *this, Point<1,T>(index)); } public: Realm::AffineAccessor<FT,N,T> accessor; public: typedef FT value_type; typedef FT& reference; typedef const FT& const_reference; static const int dim = N; }; // Write-only FieldAccessor specialization // with bounds checks template<typename FT, int N, typename T> class FieldAccessor<LEGION_WRITE_ONLY,FT,N,T, Realm::AffineAccessor<FT,N,T>,true> { public: // No CUDA support due to PhysicalRegion constructor FieldAccessor(void) { } FieldAccessor(const PhysicalRegion &region, FieldID fid, size_t actual_field_size = sizeof(FT), #ifdef DEBUG_LEGION bool check_field_size = true, #else bool check_field_size = false, #endif bool silence_warnings = false, const char *warning_string = NULL, size_t offset = 0) : field(fid) { DomainT<N,T> is; const Realm::RegionInstance instance = region.get_instance_info(LEGION_WRITE_DISCARD, fid, actual_field_size, &is,Internal::NT_TemplateHelper::encode_tag<N,T>(),warning_string, silence_warnings, false/*generic accessor*/, check_field_size); if (!Realm::AffineAccessor<FT,N,T>::is_compatible(instance, fid, is.bounds)) region.report_incompatible_accessor("AffineAccessor", instance, fid); accessor = Realm::AffineAccessor<FT,N,T>(instance, fid, is.bounds, offset); bounds = AffineBounds::Tester<N,T>(is); } // With explicit bounds FieldAccessor(const PhysicalRegion &region, FieldID fid, const Rect<N,T> source_bounds, size_t actual_field_size = sizeof(FT), #ifdef DEBUG_LEGION bool check_field_size = true, #else bool check_field_size = false, #endif bool silence_warnings = false, const char *warning_string = NULL, size_t offset = 0) : field(fid) { DomainT<N,T> is; const Realm::RegionInstance instance = region.get_instance_info(LEGION_WRITE_DISCARD, fid, actual_field_size, &is,Internal::NT_TemplateHelper::encode_tag<N,T>(),warning_string, silence_warnings, false/*generic accessor*/, check_field_size); if (!Realm::AffineAccessor<FT,N,T>::is_compatible(instance, fid, source_bounds)) region.report_incompatible_accessor("AffineAccessor", instance, fid); accessor = Realm::AffineAccessor<FT,N,T>(instance, fid, source_bounds, offset); bounds = AffineBounds::Tester<N,T>(is, source_bounds); } // With explicit transform template<int M> FieldAccessor(const PhysicalRegion &region, FieldID fid, const AffineTransform<M,N,T> transform, size_t actual_field_size = sizeof(FT), #ifdef DEBUG_LEGION bool check_field_size = true, #else bool check_field_size = false, #endif bool silence_warnings = false, const char *warning_string = NULL, size_t offset = 0) : field(fid) { DomainT<M,T> is; const Realm::RegionInstance instance = region.get_instance_info(LEGION_WRITE_DISCARD, fid, actual_field_size, &is,Internal::NT_TemplateHelper::encode_tag<M,T>(),warning_string, silence_warnings, false/*generic accessor*/, check_field_size); accessor = Realm::AffineAccessor<FT,N,T>(instance, transform.transform, transform.offset, fid, offset); bounds = AffineBounds::Tester<N,T>(is, transform); } // With explicit transform and bounds template<int M> FieldAccessor(const PhysicalRegion &region, FieldID fid, const AffineTransform<M,N,T> transform, const Rect<N,T> source_bounds, size_t actual_field_size = sizeof(FT), #ifdef DEBUG_LEGION bool check_field_size = true, #else bool check_field_size = false, #endif bool silence_warnings = false, const char *warning_string = NULL, size_t offset = 0) : field(fid) { DomainT<M,T> is; const Realm::RegionInstance instance = region.get_instance_info(LEGION_WRITE_DISCARD, fid, actual_field_size, &is,Internal::NT_TemplateHelper::encode_tag<M,T>(),warning_string, silence_warnings, false/*generic accessor*/, check_field_size); if (!Realm::AffineAccessor<FT,N,T>::is_compatible(instance, transform.transform, transform.offset, fid)) region.report_incompatible_accessor("AffineAccessor", instance, fid); accessor = Realm::AffineAccessor<FT,N,T>(instance, transform.transform, transform.offset, fid, source_bounds, offset); bounds = AffineBounds::Tester<N,T>(is, source_bounds, transform); } public: __CUDA_HD__ inline void write(const Point<N,T>& p, FT val) const { #ifdef __CUDA_ARCH__ assert(bounds.contains(p)); #else if (!bounds.contains(p)) PhysicalRegion::fail_bounds_check(DomainPoint(p), field, LEGION_WRITE_DISCARD); #endif accessor.write(p, val); } __CUDA_HD__ inline FT* ptr(const Point<N,T>& p) const { #ifdef __CUDA_ARCH__ assert(bounds.contains(p)); #else if (!bounds.contains(p)) PhysicalRegion::fail_bounds_check(DomainPoint(p), field, LEGION_READ_WRITE); #endif return accessor.ptr(p); } __CUDA_HD__ inline FT* ptr(const Rect<N,T>& r, size_t field_size = sizeof(FT)) const { #ifdef __CUDA_ARCH__ assert(bounds.contains_all(r)); assert(Internal::is_dense_layout(r, accessor.strides, field_size)); #else if (!bounds.contains_all(r)) PhysicalRegion::fail_bounds_check(Domain(r), field, LEGION_READ_WRITE); if (!Internal::is_dense_layout(r, accessor.strides, field_size)) { fprintf(stderr, "ERROR: Illegal request for pointer of non-dense rectangle\n"); #ifdef DEBUG_LEGION assert(false); #else exit(ERROR_NON_DENSE_RECTANGLE); #endif } #endif return accessor.ptr(r.lo); } __CUDA_HD__ inline FT* ptr(const Rect<N,T>& r, size_t strides[N], size_t field_size = sizeof(FT)) const { #ifdef __CUDA_ARCH__ assert(bounds.contains_all(r)); #else if (!bounds.contains_all(r)) PhysicalRegion::fail_bounds_check(Domain(r), field, LEGION_READ_WRITE); #endif for (int i = 0; i < N; i++) strides[i] = accessor.strides[i] / field_size; return accessor.ptr(r.lo); } __CUDA_HD__ inline FT& operator[](const Point<N,T>& p) const { #ifdef __CUDA_ARCH__ assert(bounds.contains(p)); #else if (!bounds.contains(p)) PhysicalRegion::fail_bounds_check(DomainPoint(p), field, LEGION_READ_WRITE); #endif return accessor[p]; } __CUDA_HD__ inline ArraySyntax::AffineSyntaxHelper< FieldAccessor<LEGION_WRITE_DISCARD,FT,N,T, Realm::AffineAccessor<FT,N,T>,true>,FT,N,T,2,LEGION_WRITE_DISCARD> operator[](T index) const { return ArraySyntax::AffineSyntaxHelper< FieldAccessor<LEGION_WRITE_DISCARD,FT,N,T, Realm::AffineAccessor<FT,N,T>,true>,FT,N,T,2,LEGION_WRITE_DISCARD>( *this, Point<1,T>(index)); } public: Realm::AffineAccessor<FT,N,T> accessor; FieldID field; AffineBounds::Tester<N,T> bounds; public: typedef FT value_type; typedef FT& reference; typedef const FT& const_reference; static const int dim = N; }; // Write-only FieldAccessor specialization with // N == 1 to avoid array ambiguity template<typename FT, typename T, bool CB> class FieldAccessor<LEGION_WRITE_ONLY,FT,1,T, Realm::AffineAccessor<FT,1,T>,CB> { public: __CUDA_HD__ FieldAccessor(void) { } FieldAccessor(const PhysicalRegion &region, FieldID fid, size_t actual_field_size = sizeof(FT), #ifdef DEBUG_LEGION bool check_field_size = true, #else bool check_field_size = false, #endif bool silence_warnings = false, const char *warning_string = NULL, size_t offset = 0) { DomainT<1,T> is; const Realm::RegionInstance instance = region.get_instance_info(LEGION_WRITE_DISCARD, fid, actual_field_size, &is,Internal::NT_TemplateHelper::encode_tag<1,T>(),warning_string, silence_warnings, false/*generic accessor*/, check_field_size); if (!Realm::AffineAccessor<FT,1,T>::is_compatible(instance, fid, is.bounds)) region.report_incompatible_accessor("AffineAccessor", instance, fid); accessor = Realm::AffineAccessor<FT,1,T>(instance, fid, is.bounds, offset); } // With explicit bounds FieldAccessor(const PhysicalRegion &region, FieldID fid, const Rect<1,T> source_bounds, size_t actual_field_size = sizeof(FT), #ifdef DEBUG_LEGION bool check_field_size = true, #else bool check_field_size = false, #endif bool silence_warnings = false, const char *warning_string = NULL, size_t offset = 0) { DomainT<1,T> is; const Realm::RegionInstance instance = region.get_instance_info(LEGION_WRITE_DISCARD, fid, actual_field_size, &is,Internal::NT_TemplateHelper::encode_tag<1,T>(),warning_string, silence_warnings, false/*generic accessor*/, check_field_size); if (!Realm::AffineAccessor<FT,1,T>::is_compatible(instance, fid, source_bounds)) region.report_incompatible_accessor("AffineAccessor", instance, fid); accessor = Realm::AffineAccessor<FT,1,T>(instance, fid, source_bounds, offset); } // With explicit transform template<int M> FieldAccessor(const PhysicalRegion &region, FieldID fid, const AffineTransform<M,1,T> transform, size_t actual_field_size = sizeof(FT), #ifdef DEBUG_LEGION bool check_field_size = true, #else bool check_field_size = false, #endif bool silence_warnings = false, const char *warning_string = NULL, size_t offset = 0) { DomainT<M,T> is; const Realm::RegionInstance instance = region.get_instance_info(LEGION_WRITE_DISCARD, fid, actual_field_size, &is,Internal::NT_TemplateHelper::encode_tag<M,T>(),warning_string, silence_warnings, false/*generic accessor*/, check_field_size); if (!Realm::AffineAccessor<FT,1,T>::is_compatible(instance, transform.transform, transform.offset, fid)) region.report_incompatible_accessor("AffineAccessor", instance, fid); accessor = Realm::AffineAccessor<FT,1,T>(instance, transform.transform, transform.offset, fid, offset); } // With explicit transform and bounds template<int M> FieldAccessor(const PhysicalRegion &region, FieldID fid, const AffineTransform<M,1,T> transform, const Rect<1,T> source_bounds, size_t actual_field_size = sizeof(FT), #ifdef DEBUG_LEGION bool check_field_size = true, #else bool check_field_size = false, #endif bool silence_warnings = false, const char *warning_string = NULL, size_t offset = 0) { DomainT<M,T> is; const Realm::RegionInstance instance = region.get_instance_info(LEGION_WRITE_DISCARD, fid, actual_field_size, &is,Internal::NT_TemplateHelper::encode_tag<M,T>(),warning_string, silence_warnings, false/*generic accessor*/, check_field_size); if (!Realm::AffineAccessor<FT,1,T>::is_compatible(instance, transform.transform, transform.offset, fid, source_bounds)) region.report_incompatible_accessor("AffineAccessor", instance, fid); accessor = Realm::AffineAccessor<FT,1,T>(instance, transform.transform, transform.offset, fid, source_bounds, offset); } public: __CUDA_HD__ inline void write(const Point<1,T>& p, FT val) const { accessor.write(p, val); } __CUDA_HD__ inline FT* ptr(const Point<1,T>& p) const { return accessor.ptr(p); } __CUDA_HD__ inline FT* ptr(const Rect<1,T>& r, size_t field_size = sizeof(FT)) const { #ifdef __CUDA_ARCH__ assert(Internal::is_dense_layout(r, accessor.strides, field_size)); #else if (!Internal::is_dense_layout(r, accessor.strides, field_size)) { fprintf(stderr, "ERROR: Illegal request for pointer of non-dense rectangle\n"); #ifdef DEBUG_LEGION assert(false); #else exit(ERROR_NON_DENSE_RECTANGLE); #endif } #endif return accessor.ptr(r.lo); } __CUDA_HD__ inline FT* ptr(const Rect<1,T>& r, size_t strides[1], size_t field_size = sizeof(FT)) const { strides[0] = accessor.strides[0] / field_size; return accessor.ptr(r.lo); } __CUDA_HD__ inline FT& operator[](const Point<1,T>& p) const { return accessor[p]; } public: Realm::AffineAccessor<FT,1,T> accessor; public: typedef FT value_type; typedef FT& reference; typedef const FT& const_reference; static const int dim = 1; }; // Write-only FieldAccessor specialization with // N == 1 to avoid array ambiguity and bounds checks template<typename FT, typename T> class FieldAccessor<LEGION_WRITE_ONLY,FT,1,T, Realm::AffineAccessor<FT,1,T>,true> { public: // No CUDA support due to PhysicalRegion constructor FieldAccessor(void) { } FieldAccessor(const PhysicalRegion &region, FieldID fid, size_t actual_field_size = sizeof(FT), #ifdef DEBUG_LEGION bool check_field_size = true, #else bool check_field_size = false, #endif bool silence_warnings = false, const char *warning_string = NULL, size_t offset = 0) : field(fid) { DomainT<1,T> is; const Realm::RegionInstance instance = region.get_instance_info(LEGION_WRITE_DISCARD, fid, actual_field_size, &is,Internal::NT_TemplateHelper::encode_tag<1,T>(),warning_string, silence_warnings, false/*generic accessor*/, check_field_size); if (!Realm::AffineAccessor<FT,1,T>::is_compatible(instance, fid, is.bounds)) region.report_incompatible_accessor("AffineAccessor", instance, fid); accessor = Realm::AffineAccessor<FT,1,T>(instance, fid, is.bounds, offset); bounds = AffineBounds::Tester<1,T>(is); } // With explicit bounds FieldAccessor(const PhysicalRegion &region, FieldID fid, const Rect<1,T> source_bounds, size_t actual_field_size = sizeof(FT), #ifdef DEBUG_LEGION bool check_field_size = true, #else bool check_field_size = false, #endif bool silence_warnings = false, const char *warning_string = NULL, size_t offset = 0) : field(fid) { DomainT<1,T> is; const Realm::RegionInstance instance = region.get_instance_info(LEGION_WRITE_DISCARD, fid, actual_field_size, &is,Internal::NT_TemplateHelper::encode_tag<1,T>(),warning_string, silence_warnings, false/*generic accessor*/, check_field_size); if (!Realm::AffineAccessor<FT,1,T>::is_compatible(instance, fid, source_bounds)) region.report_incompatible_accessor("AffineAccessor", instance, fid); accessor = Realm::AffineAccessor<FT,1,T>(instance, fid, source_bounds, offset); bounds = AffineBounds::Tester<1,T>(is, source_bounds); } // With explicit transform template<int M> FieldAccessor(const PhysicalRegion &region, FieldID fid, const AffineTransform<M,1,T> transform, size_t actual_field_size = sizeof(FT), #ifdef DEBUG_LEGION bool check_field_size = true, #else bool check_field_size = false, #endif bool silence_warnings = false, const char *warning_string = NULL, size_t offset = 0) : field(fid) { DomainT<M,T> is; const Realm::RegionInstance instance = region.get_instance_info(LEGION_WRITE_DISCARD, fid, actual_field_size, &is,Internal::NT_TemplateHelper::encode_tag<M,T>(),warning_string, silence_warnings, false/*generic accessor*/, check_field_size); if (!Realm::AffineAccessor<FT,1,T>::is_compatible(instance, transform.transform, transform.offset, fid)) region.report_incompatible_accessor("AffineAccessor", instance, fid); accessor = Realm::AffineAccessor<FT,1,T>(instance, transform.transform, transform.offset, fid, offset); bounds = AffineBounds::Tester<1,T>(is, transform); } // With explicit transform and bounds template<int M> FieldAccessor(const PhysicalRegion &region, FieldID fid, const AffineTransform<M,1,T> transform, const Rect<1,T> source_bounds, size_t actual_field_size = sizeof(FT), #ifdef DEBUG_LEGION bool check_field_size = true, #else bool check_field_size = false, #endif bool silence_warnings = false, const char *warning_string = NULL, size_t offset = 0) : field(fid) { DomainT<M,T> is; const Realm::RegionInstance instance = region.get_instance_info(LEGION_WRITE_DISCARD, fid, actual_field_size, &is,Internal::NT_TemplateHelper::encode_tag<M,T>(),warning_string, silence_warnings, false/*generic accessor*/, check_field_size); if (!Realm::AffineAccessor<FT,1,T>::is_compatible(instance, transform.transform, transform.offset, fid, source_bounds)) region.report_incompatible_accessor("AffineAccessor", instance, fid); accessor = Realm::AffineAccessor<FT,1,T>(instance, transform.transform, transform.offset, fid, source_bounds, offset); bounds = AffineBounds::Tester<1,T>(is, source_bounds, transform); } public: __CUDA_HD__ inline void write(const Point<1,T>& p, FT val) const { #ifdef __CUDA_ARCH__ assert(bounds.contains(p)); #else if (!bounds.contains(p)) PhysicalRegion::fail_bounds_check(DomainPoint(p), field, LEGION_WRITE_DISCARD); #endif accessor.write(p, val); } __CUDA_HD__ inline FT* ptr(const Point<1,T>& p) const { #ifdef __CUDA_ARCH__ assert(bounds.contains(p)); #else if (!bounds.contains(p)) PhysicalRegion::fail_bounds_check(DomainPoint(p), field, LEGION_READ_WRITE); #endif return accessor.ptr(p); } __CUDA_HD__ inline FT* ptr(const Rect<1,T>& r, size_t field_size = sizeof(FT)) const { #ifdef __CUDA_ARCH__ assert(bounds.contains_all(r)); assert(Internal::is_dense_layout(r, accessor.strides, field_size)); #else if (!bounds.contains_all(r)) PhysicalRegion::fail_bounds_check(Domain(r), field, LEGION_READ_WRITE); if (!Internal::is_dense_layout(r, accessor.strides, field_size)) { fprintf(stderr, "ERROR: Illegal request for pointer of non-dense rectangle\n"); #ifdef DEBUG_LEGION assert(false); #else exit(ERROR_NON_DENSE_RECTANGLE); #endif } #endif return accessor.ptr(r.lo); } __CUDA_HD__ inline FT* ptr(const Rect<1,T>& r, size_t strides[1], size_t field_size = sizeof(FT)) const { #ifdef __CUDA_ARCH__ assert(bounds.contains_all(r)); #else if (!bounds.contains_all(r)) PhysicalRegion::fail_bounds_check(Domain(r), field, LEGION_READ_WRITE); #endif strides[0] = accessor.strides[0] / field_size; return accessor.ptr(r.lo); } __CUDA_HD__ inline FT& operator[](const Point<1,T>& p) const { #ifdef __CUDA_ARCH__ assert(bounds.contains(p)); #else if (!bounds.contains(p)) PhysicalRegion::fail_bounds_check(DomainPoint(p), field, LEGION_READ_WRITE); #endif return accessor[p]; } public: Realm::AffineAccessor<FT,1,T> accessor; FieldID field; AffineBounds::Tester<1,T> bounds; public: typedef FT value_type; typedef FT& reference; typedef const FT& const_reference; static const int dim = 1; }; // Reduce FieldAccessor specialization template<typename REDOP, bool EXCLUSIVE, int N, typename T, bool CB> class ReductionAccessor<REDOP,EXCLUSIVE,N,T, Realm::AffineAccessor<typename REDOP::RHS,N,T>,CB> { public: __CUDA_HD__ ReductionAccessor(void) { } ReductionAccessor(const PhysicalRegion &region, FieldID fid, ReductionOpID redop, bool silence_warnings = false, const char *warning_string = NULL, size_t offset = 0) { DomainT<N,T> is; const Realm::RegionInstance instance = region.get_instance_info(LEGION_REDUCE,fid,sizeof(typename REDOP::RHS), &is, Internal::NT_TemplateHelper::encode_tag<N,T>(), warning_string, silence_warnings, false/*generic accessor*/, false/*check field size*/, redop); if (!Realm::AffineAccessor<typename REDOP::RHS,N,T>::is_compatible( instance, fid, is.bounds)) region.report_incompatible_accessor("AffineAccessor", instance, fid); accessor = Realm::AffineAccessor<typename REDOP::RHS,N,T>( instance, fid, is.bounds, offset); } // With explicit bounds ReductionAccessor(const PhysicalRegion &region, FieldID fid, ReductionOpID redop, const Rect<N,T> source_bounds, bool silence_warnings = false, const char *warning_string = NULL, size_t offset = 0) { DomainT<N,T> is; const Realm::RegionInstance instance = region.get_instance_info(LEGION_REDUCE,fid,sizeof(typename REDOP::RHS), &is, Internal::NT_TemplateHelper::encode_tag<N,T>(), warning_string, silence_warnings, false/*generic accessor*/, false/*check field size*/, redop); if (!Realm::AffineAccessor<typename REDOP::RHS,N,T>::is_compatible( instance, fid, source_bounds)) region.report_incompatible_accessor("AffineAccessor", instance, fid); accessor = Realm::AffineAccessor<typename REDOP::RHS,N,T>( instance, fid, source_bounds, offset); } // With explicit transform template<int M> ReductionAccessor(const PhysicalRegion &region, FieldID fid, ReductionOpID redop, const AffineTransform<M,N,T> transform, bool silence_warnings = false, const char *warning_string = NULL, size_t offset = 0) { DomainT<M,T> is; const Realm::RegionInstance instance = region.get_instance_info(LEGION_REDUCE,fid,sizeof(typename REDOP::RHS), &is, Internal::NT_TemplateHelper::encode_tag<M,T>(), warning_string, silence_warnings, false/*generic accessor*/, false/*check field size*/, redop); if (!Realm::AffineAccessor<typename REDOP::RHS,N,T>::is_compatible( instance, transform.transform, transform.offset, fid)) region.report_incompatible_accessor("AffineAccessor", instance, fid); accessor = Realm::AffineAccessor<typename REDOP::RHS,N,T>(instance, transform.transform, transform.offset, fid, offset); } // With explicit transform and bounds template<int M> ReductionAccessor(const PhysicalRegion &region, FieldID fid, ReductionOpID redop, const AffineTransform<M,N,T> transform, const Rect<N,T> source_bounds, bool silence_warnings = false, const char *warning_string = NULL, size_t offset = 0) { DomainT<M,T> is; const Realm::RegionInstance instance = region.get_instance_info(LEGION_REDUCE,fid,sizeof(typename REDOP::RHS), &is, Internal::NT_TemplateHelper::encode_tag<M,T>(), warning_string, silence_warnings, false/*generic accessor*/, false/*check field size*/, redop); if (!Realm::AffineAccessor<typename REDOP::RHS,N,T>::is_compatible( instance,transform.transform,transform.offset,fid,source_bounds)) region.report_incompatible_accessor("AffineAccessor", instance, fid); accessor = Realm::AffineAccessor<typename REDOP::RHS,N,T>(instance, transform.transform, transform.offset, fid, source_bounds, offset); } public: __CUDA_HD__ inline void reduce(const Point<N,T>& p, typename REDOP::RHS val) const { REDOP::template fold<EXCLUSIVE>(accessor[p], val); } __CUDA_HD__ inline typename REDOP::RHS* ptr(const Point<N,T>& p) const { return accessor.ptr(p); } __CUDA_HD__ inline typename REDOP::RHS* ptr(const Rect<N,T>& r, size_t field_size = sizeof(typename REDOP::RHS)) const { #ifdef __CUDA_ARCH__ assert(Internal::is_dense_layout(r, accessor.strides, field_size)); #else if (!Internal::is_dense_layout(r, accessor.strides, field_size)) { fprintf(stderr, "ERROR: Illegal request for pointer of non-dense rectangle\n"); #ifdef DEBUG_LEGION assert(false); #else exit(ERROR_NON_DENSE_RECTANGLE); #endif } #endif return accessor.ptr(r.lo); } __CUDA_HD__ inline typename REDOP::RHS* ptr(const Rect<N,T>& r, size_t strides[N], size_t field_size = sizeof(typename REDOP::RHS)) const { for (int i = 0; i < N; i++) strides[i] = accessor.strides[i] / field_size; return accessor.ptr(r.lo); } __CUDA_HD__ inline ArraySyntax::ReductionHelper<ReductionAccessor<REDOP,EXCLUSIVE,N, T,Realm::AffineAccessor<typename REDOP::RHS,N,T>,CB>, typename REDOP::RHS,N,T> operator[](const Point<N,T>& p) const { return ArraySyntax::ReductionHelper<ReductionAccessor<REDOP,EXCLUSIVE, N,T,Realm::AffineAccessor<typename REDOP::RHS,N,T>,CB>, typename REDOP::RHS,N,T>(*this, p); } __CUDA_HD__ inline ArraySyntax::AffineSyntaxHelper<ReductionAccessor<REDOP,EXCLUSIVE, N,T,Realm::AffineAccessor<typename REDOP::RHS,N,T>,CB>, typename REDOP::RHS,N,T,2,LEGION_REDUCE> operator[](T index) const { return ArraySyntax::AffineSyntaxHelper<ReductionAccessor<REDOP, EXCLUSIVE,N,T,Realm::AffineAccessor<typename REDOP::RHS,N,T>,CB>, typename REDOP::RHS,N,T,2,LEGION_REDUCE>( *this, Point<1,T>(index)); } public: Realm::AffineAccessor<typename REDOP::RHS,N,T> accessor; public: typedef typename REDOP::RHS value_type; typedef typename REDOP::RHS& reference; typedef const typename REDOP::RHS& const_reference; static const int dim = N; }; // Reduce ReductionAccessor specialization with bounds checks template<typename REDOP, bool EXCLUSIVE, int N, typename T> class ReductionAccessor<REDOP,EXCLUSIVE,N,T, Realm::AffineAccessor<typename REDOP::RHS,N,T>,true> { public: // No CUDA support due to PhysicalRegion constructor ReductionAccessor(void) { } ReductionAccessor(const PhysicalRegion &region, FieldID fid, ReductionOpID redop, bool silence_warnings = false, const char *warning_string = NULL, size_t offset = 0) : field(fid) { DomainT<N,T> is; const Realm::RegionInstance instance = region.get_instance_info(LEGION_REDUCE,fid,sizeof(typename REDOP::RHS), &is, Internal::NT_TemplateHelper::encode_tag<N,T>(), warning_string, silence_warnings, false/*generic accessor*/, false/*check field size*/, redop); if (!Realm::AffineAccessor<typename REDOP::RHS,N,T>::is_compatible( instance, fid, is.bounds)) region.report_incompatible_accessor("AffineAccessor", instance, fid); accessor = Realm::AffineAccessor<typename REDOP::RHS,N,T>( instance, fid, is.bounds, offset); bounds = AffineBounds::Tester<N,T>(is); } // With explicit bounds ReductionAccessor(const PhysicalRegion &region, FieldID fid, ReductionOpID redop, const Rect<N,T> source_bounds, bool silence_warnings = false, const char *warning_string = NULL, size_t offset = 0) : field(fid) { DomainT<N,T> is; const Realm::RegionInstance instance = region.get_instance_info(LEGION_REDUCE,fid,sizeof(typename REDOP::RHS), &is, Internal::NT_TemplateHelper::encode_tag<N,T>(), warning_string, silence_warnings, false/*generic accessor*/, false/*check field size*/, redop); if (!Realm::AffineAccessor<typename REDOP::RHS,N,T>::is_compatible( instance, fid, source_bounds)) region.report_incompatible_accessor("AffineAccessor", instance, fid); accessor = Realm::AffineAccessor<typename REDOP::RHS,N,T>( instance, fid, source_bounds, offset); bounds = AffineBounds::Tester<N,T>(is, source_bounds); } // With explicit transform template<int M> ReductionAccessor(const PhysicalRegion &region, FieldID fid, ReductionOpID redop, const AffineTransform<M,N,T> transform, bool silence_warnings = false, const char *warning_string = NULL, size_t offset = 0) : field(fid) { DomainT<M,T> is; const Realm::RegionInstance instance = region.get_instance_info(LEGION_REDUCE,fid,sizeof(typename REDOP::RHS), &is, Internal::NT_TemplateHelper::encode_tag<M,T>(), warning_string, silence_warnings, false/*generic accessor*/, false/*check field size*/, redop); if (!Realm::AffineAccessor<typename REDOP::RHS,N,T>::is_compatible( instance, transform.transform, transform.offset, fid)) region.report_incompatible_accessor("AffineAccessor", instance, fid); accessor = Realm::AffineAccessor<typename REDOP::RHS,N,T>( instance, transform.transform, transform.offset, fid, offset); bounds = AffineBounds::Tester<N,T>(is, transform); } // With explicit transform and bounds template<int M> ReductionAccessor(const PhysicalRegion &region, FieldID fid, ReductionOpID redop, const AffineTransform<M,N,T> transform, const Rect<N,T> source_bounds, bool silence_warnings = false, const char *warning_string = NULL, size_t offset = 0) : field(fid) { DomainT<M,T> is; const Realm::RegionInstance instance = region.get_instance_info(LEGION_REDUCE,fid,sizeof(typename REDOP::RHS), &is, Internal::NT_TemplateHelper::encode_tag<M,T>(), warning_string, silence_warnings, false/*generic accessor*/, false/*check field size*/, redop); if (!Realm::AffineAccessor<typename REDOP::RHS,N,T>::is_compatible( instance,transform.transform,transform.offset,fid,source_bounds)) region.report_incompatible_accessor("AffineAccessor", instance, fid); accessor = Realm::AffineAccessor<typename REDOP::RHS,N,T>(instance, transform.transform, transform.offset, fid, source_bounds, offset); bounds = AffineBounds::Tester<N,T>(is, source_bounds, transform); } public: __CUDA_HD__ inline void reduce(const Point<N,T>& p, typename REDOP::RHS val) const { #ifdef __CUDA_ARCH__ assert(bounds.contains(p)); #else if (!bounds.contains(p)) PhysicalRegion::fail_bounds_check(DomainPoint(p), field, LEGION_REDUCE); #endif REDOP::template fold<EXCLUSIVE>(accessor[p], val); } __CUDA_HD__ inline typename REDOP::RHS* ptr(const Point<N,T>& p) const { #ifdef __CUDA_ARCH__ assert(bounds.contains(p)); #else if (!bounds.contains(p)) PhysicalRegion::fail_bounds_check(DomainPoint(p), field, LEGION_REDUCE); #endif return accessor.ptr(p); } __CUDA_HD__ inline typename REDOP::RHS* ptr(const Rect<N,T>& r, size_t field_size = sizeof(typename REDOP::RHS)) const { #ifdef __CUDA_ARCH__ assert(bounds.contains_all(r)); assert(Internal::is_dense_layout(r, accessor.strides, field_size)); #else if (!bounds.contains_all(r)) PhysicalRegion::fail_bounds_check(Domain(r), field, LEGION_REDUCE); if (!Internal::is_dense_layout(r, accessor.strides, field_size)) { fprintf(stderr, "ERROR: Illegal request for pointer of non-dense rectangle\n"); #ifdef DEBUG_LEGION assert(false); #else exit(ERROR_NON_DENSE_RECTANGLE); #endif } #endif return accessor.ptr(r.lo); } __CUDA_HD__ inline typename REDOP::RHS* ptr(const Rect<N,T>& r, size_t strides[N], size_t field_size = sizeof(typename REDOP::RHS)) const { #ifdef __CUDA_ARCH__ assert(bounds.contains_all(r)); #else if (!bounds.contains_all(r)) PhysicalRegion::fail_bounds_check(Domain(r), field, LEGION_REDUCE); #endif for (int i = 0; i < N; i++) strides[i] = accessor.strides[i] / field_size; return accessor.ptr(r.lo); } __CUDA_HD__ inline ArraySyntax::ReductionHelper<ReductionAccessor<REDOP,EXCLUSIVE,N, T,Realm::AffineAccessor<typename REDOP::RHS,N,T>,true>, typename REDOP::RHS,N,T> operator[](const Point<N,T>& p) const { return ArraySyntax::ReductionHelper<ReductionAccessor<REDOP,EXCLUSIVE, N,T,Realm::AffineAccessor<typename REDOP::RHS,N,T>,true>, typename REDOP::RHS,N,T>(*this, p); } __CUDA_HD__ inline ArraySyntax::AffineSyntaxHelper<ReductionAccessor<REDOP,EXCLUSIVE, N,T, Realm::AffineAccessor<typename REDOP::RHS,N,T>,true>, typename REDOP::RHS,N,T,2,LEGION_REDUCE> operator[](T index) const { return ArraySyntax::AffineSyntaxHelper<ReductionAccessor<REDOP, EXCLUSIVE,N,T,Realm::AffineAccessor<typename REDOP::RHS,N,T>,true>, typename REDOP::RHS,N,T,2,LEGION_REDUCE>( *this, Point<1,T>(index)); } public: Realm::AffineAccessor<typename REDOP::RHS,N,T> accessor; FieldID field; AffineBounds::Tester<N,T> bounds; public: typedef typename REDOP::RHS value_type; typedef typename REDOP::RHS& reference; typedef const typename REDOP::RHS& const_reference; static const int dim = N; }; // Reduce Field Accessor specialization with N==1 // to avoid array ambiguity template<typename REDOP, bool EXCLUSIVE, typename T, bool CB> class ReductionAccessor<REDOP,EXCLUSIVE,1,T, Realm::AffineAccessor<typename REDOP::RHS,1,T>,CB> { public: __CUDA_HD__ ReductionAccessor(void) { } ReductionAccessor(const PhysicalRegion &region, FieldID fid, ReductionOpID redop, bool silence_warnings = false, const char *warning_string = NULL, size_t offset = 0) { DomainT<1,T> is; const Realm::RegionInstance instance = region.get_instance_info(LEGION_REDUCE,fid,sizeof(typename REDOP::RHS), &is, Internal::NT_TemplateHelper::encode_tag<1,T>(), warning_string, silence_warnings, false/*generic accessor*/, false/*check field size*/, redop); if (!Realm::AffineAccessor<typename REDOP::RHS,1,T>::is_compatible( instance, fid, is.bounds)) region.report_incompatible_accessor("AffineAccessor", instance, fid); accessor = Realm::AffineAccessor<typename REDOP::RHS,1,T>( instance, fid, is.bounds, offset); } // With explicit bounds ReductionAccessor(const PhysicalRegion &region, FieldID fid, ReductionOpID redop, const Rect<1,T> source_bounds, bool silence_warnings = false, const char *warning_string = NULL, size_t offset = 0) { DomainT<1,T> is; const Realm::RegionInstance instance = region.get_instance_info(LEGION_REDUCE,fid,sizeof(typename REDOP::RHS), &is, Internal::NT_TemplateHelper::encode_tag<1,T>(), warning_string, silence_warnings, false/*generic accessor*/, false/*check field size*/, redop); if (!Realm::AffineAccessor<typename REDOP::RHS,1,T>::is_compatible( instance, fid, source_bounds)) region.report_incompatible_accessor("AffineAccessor", instance, fid); accessor = Realm::AffineAccessor<typename REDOP::RHS,1,T>( instance, fid, source_bounds, offset); } // With explicit transform template<int M> ReductionAccessor(const PhysicalRegion &region, FieldID fid, ReductionOpID redop, const AffineTransform<M,1,T> transform, bool silence_warnings = false, const char *warning_string = NULL, size_t offset = 0) { DomainT<M,T> is; const Realm::RegionInstance instance = region.get_instance_info(LEGION_REDUCE,fid,sizeof(typename REDOP::RHS), &is, Internal::NT_TemplateHelper::encode_tag<M,T>(), warning_string, silence_warnings, false/*generic accessor*/, false/*check field size*/, redop); if (!Realm::AffineAccessor<typename REDOP::RHS,1,T>::is_compatible( instance, transform.transform, transform.offset, fid)) region.report_incompatible_accessor("AffineAccessor", instance, fid); accessor = Realm::AffineAccessor<typename REDOP::RHS,1,T>( instance, transform.transform, transform.offset, fid, offset); } // With explicit transform and bounds template<int M> ReductionAccessor(const PhysicalRegion &region, FieldID fid, ReductionOpID redop, const AffineTransform<M,1,T> transform, const Rect<1,T> source_bounds, bool silence_warnings = false, const char *warning_string = NULL, size_t offset = 0) { DomainT<M,T> is; const Realm::RegionInstance instance = region.get_instance_info(LEGION_REDUCE,fid,sizeof(typename REDOP::RHS), &is, Internal::NT_TemplateHelper::encode_tag<M,T>(), warning_string, silence_warnings, false/*generic accessor*/, false/*check field size*/, redop); if (!Realm::AffineAccessor<typename REDOP::RHS,1,T>::is_compatible( instance,transform.transform,transform.offset,fid,source_bounds)) region.report_incompatible_accessor("AffineAccessor", instance, fid); accessor = Realm::AffineAccessor<typename REDOP::RHS,1,T>(instance, transform.transform, transform.offset, fid, source_bounds, offset); } public: __CUDA_HD__ inline void reduce(const Point<1,T>& p, typename REDOP::RHS val) const { REDOP::template fold<EXCLUSIVE>(accessor[p], val); } __CUDA_HD__ inline typename REDOP::RHS* ptr(const Point<1,T>& p) const { return accessor.ptr(p); } __CUDA_HD__ inline typename REDOP::RHS* ptr(const Rect<1,T>& r, size_t field_size = sizeof(typename REDOP::RHS)) const { #ifdef __CUDA_ARCH__ assert(Internal::is_dense_layout(r, accessor.strides, field_size)); #else if (!Internal::is_dense_layout(r, accessor.strides, field_size)) { fprintf(stderr, "ERROR: Illegal request for pointer of non-dense rectangle\n"); #ifdef DEBUG_LEGION assert(false); #else exit(ERROR_NON_DENSE_RECTANGLE); #endif } #endif return accessor.ptr(r.lo); } __CUDA_HD__ inline typename REDOP::RHS* ptr(const Rect<1,T>& r, size_t strides[1], size_t field_size = sizeof(typename REDOP::RHS)) const { strides[0] = accessor.strides[0] / field_size; return accessor.ptr(r.lo); } __CUDA_HD__ inline ArraySyntax::ReductionHelper<ReductionAccessor<REDOP,EXCLUSIVE,1, T,Realm::AffineAccessor<typename REDOP::RHS,1,T>,CB>, typename REDOP::RHS,1,T> operator[](const Point<1,T>& p) const { return ArraySyntax::ReductionHelper<ReductionAccessor<REDOP,EXCLUSIVE, 1,T,Realm::AffineAccessor<typename REDOP::RHS,1,T>,CB>, typename REDOP::RHS,1,T>(*this, p); } public: Realm::AffineAccessor<typename REDOP::RHS,1,T> accessor; public: typedef typename REDOP::RHS value_type; typedef typename REDOP::RHS& reference; typedef const typename REDOP::RHS& const_reference; static const int dim = 1; }; // Reduce Field Accessor specialization with N==1 // to avoid array ambiguity and bounds checks template<typename REDOP, bool EXCLUSIVE, typename T> class ReductionAccessor<REDOP,EXCLUSIVE,1,T, Realm::AffineAccessor<typename REDOP::RHS,1,T>,true> { public: // No CUDA support due to PhysicalRegion constructor ReductionAccessor(void) { } ReductionAccessor(const PhysicalRegion &region, FieldID fid, ReductionOpID redop, bool silence_warnings = false, const char *warning_string = NULL, size_t offset = 0) : field(fid) { DomainT<1,T> is; const Realm::RegionInstance instance = region.get_instance_info(LEGION_REDUCE,fid,sizeof(typename REDOP::RHS), &is, Internal::NT_TemplateHelper::encode_tag<1,T>(), warning_string, silence_warnings, false/*generic accessor*/, false/*check field size*/, redop); if (!Realm::AffineAccessor<typename REDOP::RHS,1,T>::is_compatible( instance, fid, is.bounds)) region.report_incompatible_accessor("AffineAccessor", instance, fid); accessor = Realm::AffineAccessor<typename REDOP::RHS,1,T>( instance, fid, is.bounds, offset); bounds = AffineBounds::Tester<1,T>(is); } // With explicit bounds ReductionAccessor(const PhysicalRegion &region, FieldID fid, ReductionOpID redop, const Rect<1,T> source_bounds, bool silence_warnings = false, const char *warning_string = NULL, size_t offset = 0) : field(fid) { DomainT<1,T> is; const Realm::RegionInstance instance = region.get_instance_info(LEGION_REDUCE,fid,sizeof(typename REDOP::RHS), &is, Internal::NT_TemplateHelper::encode_tag<1,T>(), warning_string, silence_warnings, false/*generic accessor*/, false/*check field size*/, redop); if (!Realm::AffineAccessor<typename REDOP::RHS,1,T>::is_compatible( instance, fid, source_bounds)) region.report_incompatible_accessor("AffineAccessor", instance, fid); accessor = Realm::AffineAccessor<typename REDOP::RHS,1,T>( instance, fid, source_bounds, offset); bounds = AffineBounds::Tester<1,T>(is, source_bounds); } // With explicit transform template<int M> ReductionAccessor(const PhysicalRegion &region, FieldID fid, ReductionOpID redop, const AffineTransform<M,1,T> transform, bool silence_warnings = false, const char *warning_string = NULL, size_t offset = 0) : field(fid) { DomainT<M,T> is; const Realm::RegionInstance instance = region.get_instance_info(LEGION_REDUCE,fid,sizeof(typename REDOP::RHS), &is, Internal::NT_TemplateHelper::encode_tag<M,T>(), warning_string, silence_warnings, false/*generic accessor*/, false/*check field size*/, redop); if (!Realm::AffineAccessor<typename REDOP::RHS,1,T>::is_compatible( instance, transform.transform, transform.offset, fid)) region.report_incompatible_accessor("AffineAccessor", instance, fid); accessor = Realm::AffineAccessor<typename REDOP::RHS,1,T>(instance, transform.transform, transform.offset, fid, offset); bounds = AffineBounds::Tester<1,T>(is, transform); } // With explicit transform and bounds template<int M> ReductionAccessor(const PhysicalRegion &region, FieldID fid, ReductionOpID redop, const AffineTransform<M,1,T> transform, const Rect<1,T> source_bounds, bool silence_warnings = false, const char *warning_string = NULL, size_t offset = 0) : field(fid) { DomainT<M,T> is; const Realm::RegionInstance instance = region.get_instance_info(LEGION_REDUCE,fid,sizeof(typename REDOP::RHS), &is, Internal::NT_TemplateHelper::encode_tag<M,T>(), warning_string, silence_warnings, false/*generic accessor*/, false/*check field size*/, redop); if (!Realm::AffineAccessor<typename REDOP::RHS,1,T>::is_compatible( instance,transform.transform,transform.offset,fid,source_bounds)) region.report_incompatible_accessor("AffineAccessor", instance, fid); accessor = Realm::AffineAccessor<typename REDOP::RHS,1,T>(instance, transform.transform, transform.offset, fid, source_bounds, offset); bounds = AffineBounds::Tester<1,T>(is, source_bounds, transform); } public: __CUDA_HD__ inline void reduce(const Point<1,T>& p, typename REDOP::RHS val) const { #ifdef __CUDA_ARCH__ assert(bounds.contains(p)); #else if (!bounds.contains(p)) PhysicalRegion::fail_bounds_check(DomainPoint(p), field, LEGION_REDUCE); #endif REDOP::template fold<EXCLUSIVE>(accessor[p], val); } __CUDA_HD__ inline typename REDOP::RHS* ptr(const Point<1,T>& p) const { #ifdef __CUDA_ARCH__ assert(bounds.contains(p)); #else if (!bounds.contains(p)) PhysicalRegion::fail_bounds_check(DomainPoint(p), field, LEGION_REDUCE); #endif return accessor.ptr(p); } __CUDA_HD__ inline typename REDOP::RHS* ptr(const Rect<1,T>& r, size_t field_size = sizeof(typename REDOP::RHS)) const { #ifdef __CUDA_ARCH__ assert(bounds.contains_all(r)); assert(Internal::is_dense_layout(r, accessor.strides, field_size)); #else if (!bounds.contains_all(r)) PhysicalRegion::fail_bounds_check(Domain(r), field, LEGION_REDUCE); if (!Internal::is_dense_layout(r, accessor.strides, field_size)) { fprintf(stderr, "ERROR: Illegal request for pointer of non-dense rectangle\n"); #ifdef DEBUG_LEGION assert(false); #else exit(ERROR_NON_DENSE_RECTANGLE); #endif } #endif return accessor.ptr(r.lo); } __CUDA_HD__ inline typename REDOP::RHS* ptr(const Rect<1,T>& r, size_t strides[1], size_t field_size = sizeof(typename REDOP::RHS)) const { #ifdef __CUDA_ARCH__ assert(bounds.contains_all(r)); #else if (!bounds.contains_all(r)) PhysicalRegion::fail_bounds_check(Domain(r), field, LEGION_REDUCE); #endif strides[0] = accessor.strides[0] / field_size; return accessor.ptr(r.lo); } __CUDA_HD__ inline ArraySyntax::ReductionHelper<ReductionAccessor<REDOP,EXCLUSIVE,1, T,Realm::AffineAccessor<typename REDOP::RHS,1,T>,true>, typename REDOP::RHS,1,T> operator[](const Point<1,T>& p) const { return ArraySyntax::ReductionHelper<ReductionAccessor<REDOP,EXCLUSIVE, 1,T,Realm::AffineAccessor<typename REDOP::RHS,1,T>,true>, typename REDOP::RHS,1,T>(*this, p); } public: Realm::AffineAccessor<typename REDOP::RHS,1,T> accessor; FieldID field; AffineBounds::Tester<1,T> bounds; public: typedef typename REDOP::RHS value_type; typedef typename REDOP::RHS& reference; typedef const typename REDOP::RHS& const_reference; static const int dim = 1; }; //////////////////////////////////////////////////////////// // Specializations for Multi Affine Accessors //////////////////////////////////////////////////////////// // Read-only FieldAccessor specialization template<typename FT, int N, typename T, bool CB> class FieldAccessor<LEGION_READ_ONLY,FT,N,T, Realm::MultiAffineAccessor<FT,N,T>,CB> { public: __CUDA_HD__ FieldAccessor(void) { } FieldAccessor(const PhysicalRegion &region, FieldID fid, size_t actual_field_size = sizeof(FT), #ifdef DEBUG_LEGION bool check_field_size = true, #else bool check_field_size = false, #endif bool silence_warnings = false, const char *warning_string = NULL, size_t offset = 0) { DomainT<N,T> is; const Realm::RegionInstance instance = region.get_instance_info(LEGION_READ_ONLY, fid, actual_field_size,&is, Internal::NT_TemplateHelper::encode_tag<N,T>(), warning_string, silence_warnings, false/*generic accessor*/, check_field_size); if (!Realm::MultiAffineAccessor<FT,N,T>::is_compatible(instance, fid, is.bounds)) region.report_incompatible_accessor("MultiAffineAccessor", instance, fid); accessor = Realm::MultiAffineAccessor<FT,N,T>(instance, fid, is.bounds, offset); } // With explicit bounds FieldAccessor(const PhysicalRegion &region, FieldID fid, const Rect<N,T> source_bounds, size_t actual_field_size = sizeof(FT), #ifdef DEBUG_LEGION bool check_field_size = true, #else bool check_field_size = false, #endif bool silence_warnings = false, const char *warning_string = NULL, size_t offset = 0) { DomainT<N,T> is; const Realm::RegionInstance instance = region.get_instance_info(LEGION_READ_ONLY, fid, actual_field_size,&is, Internal::NT_TemplateHelper::encode_tag<N,T>(), warning_string, silence_warnings, false/*generic accessor*/, check_field_size); if (!Realm::MultiAffineAccessor<FT,N,T>::is_compatible(instance, fid, source_bounds)) region.report_incompatible_accessor("MultiAffineAccessor", instance, fid); accessor = Realm::MultiAffineAccessor<FT,N,T>(instance, fid, source_bounds, offset); } public: __CUDA_HD__ inline FT read(const Point<N,T>& p) const { return accessor.read(p); } __CUDA_HD__ inline const FT* ptr(const Point<N,T>& p) const { return accessor.ptr(p); } __CUDA_HD__ inline const FT* ptr(const Rect<N,T>& r, size_t field_size = sizeof(FT)) const { size_t strides[N]; FT *result = accessor.ptr(r, strides); #ifdef __CUDA_ARCH__ assert(result != NULL); assert(Internal::is_dense_layout(r, strides, field_size)); #else if (result == NULL) { fprintf(stderr, "ERROR: Illegal request for pointer of rectangle " "not contained within the bounds of a piece\n"); #ifdef DEBUG_LEGION assert(false); #else exit(ERROR_NON_PIECE_RECTANGLE); #endif } if (!Internal::is_dense_layout(r, strides, field_size)) { fprintf(stderr, "ERROR: Illegal request for pointer of non-dense rectangle\n"); #ifdef DEBUG_LEGION assert(false); #else exit(ERROR_NON_DENSE_RECTANGLE); #endif } #endif return result; } __CUDA_HD__ inline const FT* ptr(const Rect<N,T>& r, size_t strides[N], size_t field_size = sizeof(FT)) const { FT *result = accessor.ptr(r, strides); #ifdef __CUDA_ARCH__ assert(result != NULL); #else if (result == NULL) { fprintf(stderr, "ERROR: Illegal request for pointer of rectangle " "not contained within the bounds of a piece\n"); #ifdef DEBUG_LEGION assert(false); #else exit(ERROR_NON_PIECE_RECTANGLE); #endif } #endif for (int i = 0; i < N; i++) strides[i] /= field_size; return result; } __CUDA_HD__ inline const FT& operator[](const Point<N,T>& p) const { return accessor[p]; } __CUDA_HD__ inline ArraySyntax::AffineSyntaxHelper< FieldAccessor<LEGION_READ_ONLY,FT,N,T, Realm::MultiAffineAccessor<FT,N,T>,CB>,FT,N,T,2,LEGION_READ_ONLY> operator[](T index) const { return ArraySyntax::AffineSyntaxHelper< FieldAccessor<LEGION_READ_ONLY,FT,N,T, Realm::MultiAffineAccessor<FT,N,T>,CB>,FT,N,T,2,LEGION_READ_ONLY>( *this, Point<1,T>(index)); } public: Realm::MultiAffineAccessor<FT,N,T> accessor; public: typedef FT value_type; typedef FT& reference; typedef const FT& const_reference; static const int dim = N; }; // Read-only FieldAccessor specialization // with bounds checks template<typename FT, int N, typename T> class FieldAccessor<LEGION_READ_ONLY,FT,N,T, Realm::MultiAffineAccessor<FT,N,T>,true> { public: // No CUDA support due to PhysicalRegion constructor FieldAccessor(void) { } FieldAccessor(const PhysicalRegion &region, FieldID fid, size_t actual_field_size = sizeof(FT), #ifdef DEBUG_LEGION bool check_field_size = true, #else bool check_field_size = false, #endif bool silence_warnings = false, const char *warning_string = NULL, size_t offset = 0) : field(fid) { DomainT<N,T> is; const Realm::RegionInstance instance = region.get_instance_info(LEGION_READ_ONLY, fid, actual_field_size,&is, Internal::NT_TemplateHelper::encode_tag<N,T>(), warning_string, silence_warnings, false/*generic accessor*/, check_field_size); if (!Realm::MultiAffineAccessor<FT,N,T>::is_compatible(instance, fid, is.bounds)) region.report_incompatible_accessor("MultiAffineAccessor", instance, fid); accessor = Realm::MultiAffineAccessor<FT,N,T>(instance, fid, is.bounds, offset); bounds = AffineBounds::Tester<N,T>(is); } // With explicit bounds FieldAccessor(const PhysicalRegion &region, FieldID fid, const Rect<N,T> source_bounds, size_t actual_field_size = sizeof(FT), #ifdef DEBUG_LEGION bool check_field_size = true, #else bool check_field_size = false, #endif bool silence_warnings = false, const char *warning_string = NULL, size_t offset = 0) : field(fid) { DomainT<N,T> is; const Realm::RegionInstance instance = region.get_instance_info(LEGION_READ_ONLY, fid, actual_field_size,&is, Internal::NT_TemplateHelper::encode_tag<N,T>(), warning_string, silence_warnings, false/*generic accessor*/, check_field_size); if (!Realm::MultiAffineAccessor<FT,N,T>::is_compatible(instance, fid, source_bounds)) region.report_incompatible_accessor("MultiAffineAccessor", instance, fid); accessor = Realm::MultiAffineAccessor<FT,N,T>(instance, fid, source_bounds, offset); bounds = AffineBounds::Tester<N,T>(is, source_bounds); } public: __CUDA_HD__ inline FT read(const Point<N,T>& p) const { #ifdef __CUDA_ARCH__ assert(bounds.contains(p)); #else if (!bounds.contains(p)) PhysicalRegion::fail_bounds_check(DomainPoint(p), field, LEGION_READ_ONLY); #endif return accessor.read(p); } __CUDA_HD__ inline const FT* ptr(const Point<N,T>& p) const { #ifdef __CUDA_ARCH__ assert(bounds.contains(p)); #else if (!bounds.contains(p)) PhysicalRegion::fail_bounds_check(DomainPoint(p), field, LEGION_READ_ONLY); #endif return accessor.ptr(p); } __CUDA_HD__ inline const FT* ptr(const Rect<N,T>& r, size_t field_size = sizeof(FT)) const { size_t strides[N]; FT *result = accessor.ptr(r, strides); #ifdef __CUDA_ARCH__ assert(bounds.contains_all(r)); assert(result != NULL); assert(Internal::is_dense_layout(r, strides, field_size)); #else if (!bounds.contains_all(r)) PhysicalRegion::fail_bounds_check(Domain(r), field, LEGION_READ_ONLY); if (result == NULL) { fprintf(stderr, "ERROR: Illegal request for pointer of rectangle " "not contained within the bounds of a piece\n"); #ifdef DEBUG_LEGION assert(false); #else exit(ERROR_NON_PIECE_RECTANGLE); #endif } if (!Internal::is_dense_layout(r, strides, field_size)) { fprintf(stderr, "ERROR: Illegal request for pointer of non-dense rectangle\n"); #ifdef DEBUG_LEGION assert(false); #else exit(ERROR_NON_DENSE_RECTANGLE); #endif } #endif return result; } __CUDA_HD__ inline const FT* ptr(const Rect<N,T>& r, size_t strides[N], size_t field_size = sizeof(FT)) const { FT *result = accessor.prt(r, strides); #ifdef __CUDA_ARCH__ assert(bounds.contains_all(r)); assert(result != NULL); #else if (!bounds.contains_all(r)) PhysicalRegion::fail_bounds_check(Domain(r), field, LEGION_READ_ONLY); if (result == NULL) { fprintf(stderr, "ERROR: Illegal request for pointer of rectangle " "not contained within the bounds of a piece\n"); #ifdef DEBUG_LEGION assert(false); #else exit(ERROR_NON_PIECE_RECTANGLE); #endif } #endif for (int i = 0; i < N; i++) strides[i] /= field_size; return result; } __CUDA_HD__ inline const FT& operator[](const Point<N,T>& p) const { #ifdef __CUDA_ARCH__ assert(bounds.contains(p)); #else if (!bounds.contains(p)) PhysicalRegion::fail_bounds_check(DomainPoint(p), field, LEGION_READ_ONLY); #endif return accessor[p]; } __CUDA_HD__ inline ArraySyntax::AffineSyntaxHelper< FieldAccessor<LEGION_READ_ONLY,FT,N,T, Realm::MultiAffineAccessor<FT,N,T>,true>,FT,N,T,2,LEGION_READ_ONLY> operator[](T index) const { return ArraySyntax::AffineSyntaxHelper< FieldAccessor<LEGION_READ_ONLY,FT,N,T, Realm::MultiAffineAccessor<FT,N,T>,true>,FT,N,T,2,LEGION_READ_ONLY>( *this, Point<1,T>(index)); } public: Realm::MultiAffineAccessor<FT,N,T> accessor; FieldID field; AffineBounds::Tester<N,T> bounds; public: typedef FT value_type; typedef FT& reference; typedef const FT& const_reference; static const int dim = N; }; // Read-only FieldAccessor specialization // with N==1 to avoid array ambiguity template<typename FT, typename T, bool CB> class FieldAccessor<LEGION_READ_ONLY,FT,1,T, Realm::MultiAffineAccessor<FT,1,T>,CB> { public: __CUDA_HD__ FieldAccessor(void) { } FieldAccessor(const PhysicalRegion &region, FieldID fid, size_t actual_field_size = sizeof(FT), #ifdef DEBUG_LEGION bool check_field_size = true, #else bool check_field_size = false, #endif bool silence_warnings = false, const char *warning_string = NULL, size_t offset = 0) { DomainT<1,T> is; const Realm::RegionInstance instance = region.get_instance_info(LEGION_READ_ONLY, fid, actual_field_size,&is, Internal::NT_TemplateHelper::encode_tag<1,T>(), warning_string, silence_warnings, false/*generic accessor*/, check_field_size); if (!Realm::MultiAffineAccessor<FT,1,T>::is_compatible(instance, fid, is.bounds)) region.report_incompatible_accessor("MultiAffineAccessor", instance, fid); accessor = Realm::MultiAffineAccessor<FT,1,T>(instance, fid, is.bounds, offset); } // With explicit bounds FieldAccessor(const PhysicalRegion &region, FieldID fid, const Rect<1,T> source_bounds, size_t actual_field_size = sizeof(FT), #ifdef DEBUG_LEGION bool check_field_size = true, #else bool check_field_size = false, #endif bool silence_warnings = false, const char *warning_string = NULL, size_t offset = 0) { DomainT<1,T> is; const Realm::RegionInstance instance = region.get_instance_info(LEGION_READ_ONLY, fid, actual_field_size,&is, Internal::NT_TemplateHelper::encode_tag<1,T>(), warning_string, silence_warnings, false/*generic accessor*/, check_field_size); if (!Realm::MultiAffineAccessor<FT,1,T>::is_compatible(instance, fid, source_bounds)) region.report_incompatible_accessor("MultiAffineAccessor", instance, fid); accessor = Realm::MultiAffineAccessor<FT,1,T>(instance, fid, source_bounds, offset); } public: __CUDA_HD__ inline FT read(const Point<1,T>& p) const { return accessor.read(p); } __CUDA_HD__ inline const FT* ptr(const Point<1,T>& p) const { return accessor.ptr(p); } __CUDA_HD__ inline const FT* ptr(const Rect<1,T>& r, size_t field_size = sizeof(FT)) const { size_t strides[1]; FT *result = accessor.ptr(r, strides); #ifdef __CUDA_ARCH__ assert(result != NULL); assert(Internal::is_dense_layout(r, strides, field_size)); #else if (result == NULL) { fprintf(stderr, "ERROR: Illegal request for pointer of rectangle " "not contained within the bounds of a piece\n"); #ifdef DEBUG_LEGION assert(false); #else exit(ERROR_NON_PIECE_RECTANGLE); #endif } if (!Internal::is_dense_layout(r, strides, field_size)) { fprintf(stderr, "ERROR: Illegal request for pointer of non-dense rectangle\n"); #ifdef DEBUG_LEGION assert(false); #else exit(ERROR_NON_DENSE_RECTANGLE); #endif } #endif return result; } __CUDA_HD__ inline const FT* ptr(const Rect<1,T>& r, size_t strides[1], size_t field_size = sizeof(FT)) const { FT *result = accessor.ptr(r, strides); #ifdef __CUDA_ARCH__ assert(result != NULL); #else if (result == NULL) { fprintf(stderr, "ERROR: Illegal request for pointer of rectangle " "not contained within the bounds of a piece\n"); #ifdef DEBUG_LEGION assert(false); #else exit(ERROR_NON_PIECE_RECTANGLE); #endif } #endif strides[0] /= field_size; return result; } __CUDA_HD__ inline const FT& operator[](const Point<1,T>& p) const { return accessor[p]; } public: Realm::MultiAffineAccessor<FT,1,T> accessor; public: typedef FT value_type; typedef FT& reference; typedef const FT& const_reference; static const int dim = 1; }; // Read-only FieldAccessor specialization // with N==1 to avoid array ambiguity and bounds checks template<typename FT, typename T> class FieldAccessor<LEGION_READ_ONLY,FT,1,T, Realm::MultiAffineAccessor<FT,1,T>,true> { public: // No CUDA support due to PhysicalRegion constructor FieldAccessor(void) { } FieldAccessor(const PhysicalRegion &region, FieldID fid, size_t actual_field_size = sizeof(FT), #ifdef DEBUG_LEGION bool check_field_size = true, #else bool check_field_size = false, #endif bool silence_warnings = false, const char *warning_string = NULL, size_t offset = 0) : field(fid) { DomainT<1,T> is; const Realm::RegionInstance instance = region.get_instance_info(LEGION_READ_ONLY, fid, actual_field_size,&is, Internal::NT_TemplateHelper::encode_tag<1,T>(), warning_string, silence_warnings, false/*generic accessor*/, check_field_size); if (!Realm::MultiAffineAccessor<FT,1,T>::is_compatible(instance, fid, is.bounds)) region.report_incompatible_accessor("MultiAffineAccessor", instance, fid); accessor = Realm::MultiAffineAccessor<FT,1,T>(instance, fid, is.bounds, offset); bounds = AffineBounds::Tester<1,T>(is); } // With explicit bounds FieldAccessor(const PhysicalRegion &region, FieldID fid, const Rect<1,T> source_bounds, size_t actual_field_size = sizeof(FT), #ifdef DEBUG_LEGION bool check_field_size = true, #else bool check_field_size = false, #endif bool silence_warnings = false, const char *warning_string = NULL, size_t offset = 0) : field(fid) { DomainT<1,T> is; const Realm::RegionInstance instance = region.get_instance_info(LEGION_READ_ONLY, fid, actual_field_size,&is, Internal::NT_TemplateHelper::encode_tag<1,T>(), warning_string, silence_warnings, false/*generic accessor*/, check_field_size); if (!Realm::MultiAffineAccessor<FT,1,T>::is_compatible(instance, fid, source_bounds)) region.report_incompatible_accessor("MultiAffineAccessor", instance, fid); accessor = Realm::MultiAffineAccessor<FT,1,T>(instance, fid, source_bounds, offset); bounds = AffineBounds::Tester<1,T>(is, source_bounds); } public: __CUDA_HD__ inline FT read(const Point<1,T>& p) const { #ifdef __CUDA_ARCH__ assert(bounds.contains(p)); #else if (!bounds.contains(p)) PhysicalRegion::fail_bounds_check(DomainPoint(p), field, LEGION_READ_ONLY); #endif return accessor.read(p); } __CUDA_HD__ inline const FT* ptr(const Point<1,T>& p) const { #ifdef __CUDA_ARCH__ assert(bounds.contains(p)); #else if (!bounds.contains(p)) PhysicalRegion::fail_bounds_check(DomainPoint(p), field, LEGION_READ_ONLY); #endif return accessor.ptr(p); } __CUDA_HD__ inline const FT* ptr(const Rect<1,T>& r, size_t field_size = sizeof(FT)) const { size_t strides[1]; FT *result = accessor.ptr(r, strides); #ifdef __CUDA_ARCH__ assert(bounds.contains_all(r)); assert(result != NULL); assert(Internal::is_dense_layout(r, strides, field_size)); #else if (!bounds.contains_all(r)) PhysicalRegion::fail_bounds_check(Domain(r), field, LEGION_READ_ONLY); if (result == NULL) { fprintf(stderr, "ERROR: Illegal request for pointer of rectangle " "not contained within the bounds of a piece\n"); #ifdef DEBUG_LEGION assert(false); #else exit(ERROR_NON_PIECE_RECTANGLE); #endif } if (!Internal::is_dense_layout(r, strides, field_size)) { fprintf(stderr, "ERROR: Illegal request for pointer of non-dense rectangle\n"); #ifdef DEBUG_LEGION assert(false); #else exit(ERROR_NON_DENSE_RECTANGLE); #endif } #endif return result; } __CUDA_HD__ inline const FT* ptr(const Rect<1,T>& r, size_t strides[1], size_t field_size = sizeof(FT)) const { FT *result = accessor.ptr(r, strides); #ifdef __CUDA_ARCH__ assert(bounds.contains_all(r)); assert(result != NULL); #else if (!bounds.contains_all(r)) PhysicalRegion::fail_bounds_check(Domain(r), field, LEGION_READ_ONLY); if (result == NULL) { fprintf(stderr, "ERROR: Illegal request for pointer of rectangle " "not contained within the bounds of a piece\n"); #ifdef DEBUG_LEGION assert(false); #else exit(ERROR_NON_PIECE_RECTANGLE); #endif } #endif strides[0] /= field_size; return result; } __CUDA_HD__ inline const FT& operator[](const Point<1,T>& p) const { #ifdef __CUDA_ARCH__ assert(bounds.contains(p)); #else if (!bounds.contains(p)) PhysicalRegion::fail_bounds_check(DomainPoint(p), field, LEGION_READ_ONLY); #endif return accessor[p]; } public: Realm::MultiAffineAccessor<FT,1,T> accessor; FieldID field; AffineBounds::Tester<1,T> bounds; public: typedef FT value_type; typedef FT& reference; typedef const FT& const_reference; static const int dim = 1; }; // Read-write FieldAccessor specialization template<typename FT, int N, typename T, bool CB> class FieldAccessor<LEGION_READ_WRITE,FT,N,T, Realm::MultiAffineAccessor<FT,N,T>,CB> { public: __CUDA_HD__ FieldAccessor(void) { } FieldAccessor(const PhysicalRegion &region, FieldID fid, size_t actual_field_size = sizeof(FT), #ifdef DEBUG_LEGION bool check_field_size = true, #else bool check_field_size = false, #endif bool silence_warnings = false, const char *warning_string = NULL, size_t offset = 0) { DomainT<N,T> is; const Realm::RegionInstance instance = region.get_instance_info(LEGION_READ_WRITE, fid,actual_field_size,&is, Internal::NT_TemplateHelper::encode_tag<N,T>(), warning_string, silence_warnings, false/*generic accessor*/, check_field_size); if (!Realm::MultiAffineAccessor<FT,N,T>::is_compatible(instance, fid, is.bounds)) region.report_incompatible_accessor("MultiAffineAccessor", instance, fid); accessor = Realm::MultiAffineAccessor<FT,N,T>(instance, fid, is.bounds, offset); } // With explicit bounds FieldAccessor(const PhysicalRegion &region, FieldID fid, const Rect<N,T> source_bounds, size_t actual_field_size = sizeof(FT), #ifdef DEBUG_LEGION bool check_field_size = true, #else bool check_field_size = false, #endif bool silence_warnings = false, const char *warning_string = NULL, size_t offset = 0) { DomainT<N,T> is; const Realm::RegionInstance instance = region.get_instance_info(LEGION_READ_WRITE, fid,actual_field_size,&is, Internal::NT_TemplateHelper::encode_tag<N,T>(), warning_string, silence_warnings, false/*generic accessor*/, check_field_size); if (!Realm::MultiAffineAccessor<FT,N,T>::is_compatible(instance, fid, source_bounds)) region.report_incompatible_accessor("MultiAffineAccessor", instance, fid); accessor = Realm::MultiAffineAccessor<FT,N,T>(instance, fid, source_bounds, offset); } public: __CUDA_HD__ inline FT read(const Point<N,T>& p) const { return accessor.read(p); } __CUDA_HD__ inline void write(const Point<N,T>& p, FT val) const { accessor.write(p, val); } __CUDA_HD__ inline FT* ptr(const Point<N,T>& p) const { return accessor.ptr(p); } __CUDA_HD__ inline FT* ptr(const Rect<N,T>& r, size_t field_size = sizeof(FT)) const { size_t strides[N]; FT *result = accessor.ptr(r, strides); #ifdef __CUDA_ARCH__ assert(result != NULL); assert(Internal::is_dense_layout(r, strides, field_size)); #else if (result == NULL) { fprintf(stderr, "ERROR: Illegal request for pointer of rectangle " "not contained within the bounds of a piece\n"); #ifdef DEBUG_LEGION assert(false); #else exit(ERROR_NON_PIECE_RECTANGLE); #endif } if (!Internal::is_dense_layout(r, strides, field_size)) { fprintf(stderr, "ERROR: Illegal request for pointer of non-dense rectangle\n"); #ifdef DEBUG_LEGION assert(false); #else exit(ERROR_NON_DENSE_RECTANGLE); #endif } #endif return result; } __CUDA_HD__ inline FT* ptr(const Rect<N,T>& r, size_t strides[N], size_t field_size = sizeof(FT)) const { FT *result = accessor.ptr(r, strides); #ifdef __CUDA_ARCH__ assert(result != NULL); #else if (result == NULL) { fprintf(stderr, "ERROR: Illegal request for pointer of rectangle " "not contained within the bounds of a piece\n"); #ifdef DEBUG_LEGION assert(false); #else exit(ERROR_NON_PIECE_RECTANGLE); #endif } #endif for (int i = 0; i < N; i++) strides[i] /= field_size; return result; } __CUDA_HD__ inline FT& operator[](const Point<N,T>& p) const { return accessor[p]; } __CUDA_HD__ inline ArraySyntax::AffineSyntaxHelper< FieldAccessor<LEGION_READ_WRITE,FT,N,T, Realm::MultiAffineAccessor<FT,N,T>,CB>,FT,N,T,2,LEGION_READ_WRITE> operator[](T index) const { return ArraySyntax::AffineSyntaxHelper< FieldAccessor<LEGION_READ_WRITE,FT,N,T, Realm::MultiAffineAccessor<FT,N,T>,CB>,FT,N,T,2,LEGION_READ_WRITE>( *this, Point<1,T>(index)); } template<typename REDOP, bool EXCLUSIVE> __CUDA_HD__ inline void reduce(const Point<N,T>& p, typename REDOP::RHS val) const { REDOP::template apply<EXCLUSIVE>(accessor[p], val); } public: Realm::MultiAffineAccessor<FT,N,T> accessor; public: typedef FT value_type; typedef FT& reference; typedef const FT& const_reference; static const int dim = N; }; // Read-write FieldAccessor specialization // with bounds checks template<typename FT, int N, typename T> class FieldAccessor<LEGION_READ_WRITE,FT,N,T, Realm::MultiAffineAccessor<FT,N,T>,true> { public: // No CUDA support due to PhysicalRegion constructor FieldAccessor(void) { } FieldAccessor(const PhysicalRegion &region, FieldID fid, size_t actual_field_size = sizeof(FT), #ifdef DEBUG_LEGION bool check_field_size = true, #else bool check_field_size = false, #endif bool silence_warnings = false, const char *warning_string = NULL, size_t offset = 0) : field(fid) { DomainT<N,T> is; const Realm::RegionInstance instance = region.get_instance_info(LEGION_READ_WRITE, fid,actual_field_size,&is, Internal::NT_TemplateHelper::encode_tag<N,T>(), warning_string, silence_warnings, false/*generic accessor*/, check_field_size); if (!Realm::MultiAffineAccessor<FT,N,T>::is_compatible(instance, fid, is.bounds)) region.report_incompatible_accessor("MultiAffineAccessor", instance, fid); accessor = Realm::MultiAffineAccessor<FT,N,T>(instance, fid, is.bounds, offset); bounds = AffineBounds::Tester<N,T>(is); } // With explicit bounds FieldAccessor(const PhysicalRegion &region, FieldID fid, const Rect<N,T> source_bounds, size_t actual_field_size = sizeof(FT), #ifdef DEBUG_LEGION bool check_field_size = true, #else bool check_field_size = false, #endif bool silence_warnings = false, const char *warning_string = NULL, size_t offset = 0) : field(fid) { DomainT<N,T> is; const Realm::RegionInstance instance = region.get_instance_info(LEGION_READ_WRITE, fid,actual_field_size,&is, Internal::NT_TemplateHelper::encode_tag<N,T>(), warning_string, silence_warnings, false/*generic accessor*/, check_field_size); if (!Realm::MultiAffineAccessor<FT,N,T>::is_compatible(instance, fid, source_bounds)) region.report_incompatible_accessor("MultiAffineAccessor", instance, fid); accessor = Realm::MultiAffineAccessor<FT,N,T>(instance, fid, source_bounds, offset); bounds = AffineBounds::Tester<N,T>(is, source_bounds); } public: __CUDA_HD__ inline FT read(const Point<N,T>& p) const { #ifdef __CUDA_ARCH__ assert(bounds.contains(p)); #else if (!bounds.contains(p)) PhysicalRegion::fail_bounds_check(DomainPoint(p), field, LEGION_READ_ONLY); #endif return accessor.read(p); } __CUDA_HD__ inline void write(const Point<N,T>& p, FT val) const { #ifdef __CUDA_ARCH__ assert(bounds.contains(p)); #else if (!bounds.contains(p)) PhysicalRegion::fail_bounds_check(DomainPoint(p), field, LEGION_WRITE_DISCARD); #endif accessor.write(p, val); } __CUDA_HD__ inline FT* ptr(const Point<N,T>& p) const { #ifdef __CUDA_ARCH__ assert(bounds.contains(p)); #else if (!bounds.contains(p)) PhysicalRegion::fail_bounds_check(DomainPoint(p), field, LEGION_READ_WRITE); #endif return accessor.ptr(p); } __CUDA_HD__ inline FT* ptr(const Rect<N,T>& r, size_t field_size = sizeof(FT)) const { size_t strides[N]; FT *result = accessor.ptr(r, strides); #ifdef __CUDA_ARCH__ assert(bounds.contains_all(r)); assert(result != NULL); assert(Internal::is_dense_layout(r, strides, field_size)); #else if (!bounds.contains_all(r)) PhysicalRegion::fail_bounds_check(Domain(r), field, LEGION_READ_WRITE); if (result == NULL) { fprintf(stderr, "ERROR: Illegal request for pointer of rectangle " "not contained within the bounds of a piece\n"); #ifdef DEBUG_LEGION assert(false); #else exit(ERROR_NON_PIECE_RECTANGLE); #endif } if (!Internal::is_dense_layout(r, strides, field_size)) { fprintf(stderr, "ERROR: Illegal request for pointer of non-dense rectangle\n"); #ifdef DEBUG_LEGION assert(false); #else exit(ERROR_NON_DENSE_RECTANGLE); #endif } #endif return result; } __CUDA_HD__ inline FT* ptr(const Rect<N,T>& r, size_t strides[N], size_t field_size = sizeof(FT)) const { FT *result = accessor.ptr(r, strides); #ifdef __CUDA_ARCH__ assert(bounds.contains_all(r)); assert(result != NULL); #else if (!bounds.contains_all(r)) PhysicalRegion::fail_bounds_check(Domain(r), field, LEGION_READ_WRITE); if (result == NULL) { fprintf(stderr, "ERROR: Illegal request for pointer of rectangle " "not contained within the bounds of a piece\n"); #ifdef DEBUG_LEGION assert(false); #else exit(ERROR_NON_PIECE_RECTANGLE); #endif } #endif for (int i = 0; i < N; i++) strides[i] /= field_size; return result; } __CUDA_HD__ inline FT& operator[](const Point<N,T>& p) const { #ifdef __CUDA_ARCH__ assert(bounds.contains(p)); #else if (!bounds.contains(p)) PhysicalRegion::fail_bounds_check(DomainPoint(p), field, LEGION_READ_WRITE); #endif return accessor[p]; } __CUDA_HD__ inline ArraySyntax::AffineSyntaxHelper< FieldAccessor<LEGION_READ_WRITE,FT,N,T, Realm::MultiAffineAccessor<FT,N,T>,true>,FT,N,T,2,LEGION_READ_WRITE> operator[](T index) const { return ArraySyntax::AffineSyntaxHelper< FieldAccessor<LEGION_READ_WRITE,FT,N,T, Realm::MultiAffineAccessor<FT,N,T>,true>,FT,N,T,2,LEGION_READ_WRITE>( *this, Point<1,T>(index)); } template<typename REDOP, bool EXCLUSIVE> __CUDA_HD__ inline void reduce(const Point<N,T>& p, typename REDOP::RHS val) const { #ifdef __CUDA_ARCH__ assert(bounds.contains(p)); #else if (!bounds.contains(p)) PhysicalRegion::fail_bounds_check(DomainPoint(p), field, LEGION_REDUCE); #endif REDOP::template apply<EXCLUSIVE>(accessor[p], val); } public: Realm::MultiAffineAccessor<FT,N,T> accessor; FieldID field; AffineBounds::Tester<N,T> bounds; public: typedef FT value_type; typedef FT& reference; typedef const FT& const_reference; static const int dim = N; }; // Read-write FieldAccessor specialization // with N==1 to avoid array ambiguity template<typename FT, typename T, bool CB> class FieldAccessor<LEGION_READ_WRITE,FT,1,T, Realm::MultiAffineAccessor<FT,1,T>,CB> { public: __CUDA_HD__ FieldAccessor(void) { } FieldAccessor(const PhysicalRegion &region, FieldID fid, size_t actual_field_size = sizeof(FT), #ifdef DEBUG_LEGION bool check_field_size = true, #else bool check_field_size = false, #endif bool silence_warnings = false, const char *warning_string = NULL, size_t offset = 0) { DomainT<1,T> is; const Realm::RegionInstance instance = region.get_instance_info(LEGION_READ_WRITE, fid,actual_field_size,&is, Internal::NT_TemplateHelper::encode_tag<1,T>(), warning_string, silence_warnings, false/*generic accessor*/, check_field_size); if (!Realm::MultiAffineAccessor<FT,1,T>::is_compatible(instance, fid, is.bounds)) region.report_incompatible_accessor("MultiAffineAccessor", instance, fid); accessor = Realm::MultiAffineAccessor<FT,1,T>(instance, fid, is.bounds, offset); } // With explicit bounds FieldAccessor(const PhysicalRegion &region, FieldID fid, const Rect<1,T> source_bounds, size_t actual_field_size = sizeof(FT), #ifdef DEBUG_LEGION bool check_field_size = true, #else bool check_field_size = false, #endif bool silence_warnings = false, const char *warning_string = NULL, size_t offset = 0) { DomainT<1,T> is; const Realm::RegionInstance instance = region.get_instance_info(LEGION_READ_WRITE, fid,actual_field_size,&is, Internal::NT_TemplateHelper::encode_tag<1,T>(), warning_string, silence_warnings, false/*generic accessor*/, check_field_size); if (!Realm::MultiAffineAccessor<FT,1,T>::is_compatible(instance, fid, source_bounds)) region.report_incompatible_accessor("MultiAffineAccessor", instance, fid); accessor = Realm::MultiAffineAccessor<FT,1,T>(instance, fid, source_bounds, offset); } public: __CUDA_HD__ inline FT read(const Point<1,T>& p) const { return accessor.read(p); } __CUDA_HD__ inline void write(const Point<1,T>& p, FT val) const { accessor.write(p, val); } __CUDA_HD__ inline FT* ptr(const Point<1,T>& p) const { return accessor.ptr(p); } __CUDA_HD__ inline FT* ptr(const Rect<1,T>& r, size_t field_size = sizeof(FT)) const { size_t strides[1]; FT *result = accessor.ptr(r, strides); #ifdef __CUDA_ARCH__ assert(result != NULL); assert(Internal::is_dense_layout(r, strides, field_size)); #else if (result == NULL) { fprintf(stderr, "ERROR: Illegal request for pointer of rectangle " "not contained within the bounds of a piece\n"); #ifdef DEBUG_LEGION assert(false); #else exit(ERROR_NON_PIECE_RECTANGLE); #endif } if (!Internal::is_dense_layout(r, strides, field_size)) { fprintf(stderr, "ERROR: Illegal request for pointer of non-dense rectangle\n"); #ifdef DEBUG_LEGION assert(false); #else exit(ERROR_NON_DENSE_RECTANGLE); #endif } #endif return result; } __CUDA_HD__ inline FT* ptr(const Rect<1,T>& r, size_t strides[1], size_t field_size = sizeof(FT)) const { FT *result = accessor.ptr(r, strides); #ifdef __CUDA_ARCH__ assert(result != NULL); #else if (result == NULL) { fprintf(stderr, "ERROR: Illegal request for pointer of rectangle " "not contained within the bounds of a piece\n"); #ifdef DEBUG_LEGION assert(false); #else exit(ERROR_NON_PIECE_RECTANGLE); #endif } #endif strides[0] /= field_size; return result; } __CUDA_HD__ inline FT& operator[](const Point<1,T>& p) const { return accessor[p]; } template<typename REDOP, bool EXCLUSIVE> __CUDA_HD__ inline void reduce(const Point<1,T>& p, typename REDOP::RHS val) const { REDOP::template apply<EXCLUSIVE>(accessor[p], val); } public: Realm::MultiAffineAccessor<FT,1,T> accessor; public: typedef FT value_type; typedef FT& reference; typedef const FT& const_reference; static const int dim = 1; }; // Read-write FieldAccessor specialization // with N==1 to avoid array ambiguity and bounds checks template<typename FT, typename T> class FieldAccessor<LEGION_READ_WRITE,FT,1,T, Realm::MultiAffineAccessor<FT,1,T>,true> { public: // No CUDA support due to PhysicalRegion constructor FieldAccessor(void) { } FieldAccessor(const PhysicalRegion &region, FieldID fid, size_t actual_field_size = sizeof(FT), #ifdef DEBUG_LEGION bool check_field_size = true, #else bool check_field_size = false, #endif bool silence_warnings = false, const char *warning_string = NULL, size_t offset = 0) : field(fid) { DomainT<1,T> is; const Realm::RegionInstance instance = region.get_instance_info(LEGION_READ_WRITE, fid,actual_field_size,&is, Internal::NT_TemplateHelper::encode_tag<1,T>(), warning_string, silence_warnings, false/*generic accessor*/, check_field_size); if (!Realm::MultiAffineAccessor<FT,1,T>::is_compatible(instance, fid, is.bounds)) region.report_incompatible_accessor("MultiAffineAccessor", instance, fid); accessor = Realm::MultiAffineAccessor<FT,1,T>(instance, fid, is.bounds, offset); bounds = AffineBounds::Tester<1,T>(is); } // With explicit bounds FieldAccessor(const PhysicalRegion &region, FieldID fid, const Rect<1,T> source_bounds, size_t actual_field_size = sizeof(FT), #ifdef DEBUG_LEGION bool check_field_size = true, #else bool check_field_size = false, #endif bool silence_warnings = false, const char *warning_string = NULL, size_t offset = 0) : field(fid) { DomainT<1,T> is; const Realm::RegionInstance instance = region.get_instance_info(LEGION_READ_WRITE, fid,actual_field_size,&is, Internal::NT_TemplateHelper::encode_tag<1,T>(), warning_string, silence_warnings, false/*generic accessor*/, check_field_size); if (!Realm::MultiAffineAccessor<FT,1,T>::is_compatible(instance, fid, source_bounds)) region.report_incompatible_accessor("MultiAffineAccessor", instance, fid); accessor = Realm::MultiAffineAccessor<FT,1,T>(instance, fid, source_bounds, offset); bounds = AffineBounds::Tester<1,T>(is, source_bounds); } public: __CUDA_HD__ inline FT read(const Point<1,T>& p) const { #ifdef __CUDA_ARCH__ assert(bounds.contains(p)); #else if (!bounds.contains(p)) PhysicalRegion::fail_bounds_check(DomainPoint(p), field, LEGION_READ_ONLY); #endif return accessor.read(p); } __CUDA_HD__ inline void write(const Point<1,T>& p, FT val) const { #ifdef __CUDA_ARCH__ assert(bounds.contains(p)); #else if (!bounds.contains(p)) PhysicalRegion::fail_bounds_check(DomainPoint(p), field, LEGION_WRITE_DISCARD); #endif accessor.write(p, val); } __CUDA_HD__ inline FT* ptr(const Point<1,T>& p) const { #ifdef __CUDA_ARCH__ assert(bounds.contains(p)); #else if (!bounds.contains(p)) PhysicalRegion::fail_bounds_check(DomainPoint(p), field, LEGION_READ_WRITE); #endif return accessor.ptr(p); } __CUDA_HD__ inline FT* ptr(const Rect<1,T>& r, size_t field_size = sizeof(FT)) const { size_t strides[1]; FT *result = accessor.ptr(r, strides); #ifdef __CUDA_ARCH__ assert(bounds.contains_all(r)); assert(result != NULL); assert(Internal::is_dense_layout(r, strides, field_size)); #else if (!bounds.contains_all(r)) PhysicalRegion::fail_bounds_check(Domain(r), field, LEGION_READ_WRITE); if (result == NULL) { fprintf(stderr, "ERROR: Illegal request for pointer of rectangle " "not contained within the bounds of a piece\n"); #ifdef DEBUG_LEGION assert(false); #else exit(ERROR_NON_PIECE_RECTANGLE); #endif } if (!Internal::is_dense_layout(r, strides, field_size)) { fprintf(stderr, "ERROR: Illegal request for pointer of non-dense rectangle\n"); #ifdef DEBUG_LEGION assert(false); #else exit(ERROR_NON_DENSE_RECTANGLE); #endif } #endif return result; } __CUDA_HD__ inline FT* ptr(const Rect<1,T>& r, size_t strides[1], size_t field_size = sizeof(FT)) const { FT *result = accessor.ptr(r, strides); #ifdef __CUDA_ARCH__ assert(bounds.contains_all(r)); assert(result != NULL); #else if (!bounds.contains_all(r)) PhysicalRegion::fail_bounds_check(Domain(r), field, LEGION_READ_WRITE); if (result == NULL) { fprintf(stderr, "ERROR: Illegal request for pointer of rectangle " "not contained within the bounds of a piece\n"); #ifdef DEBUG_LEGION assert(false); #else exit(ERROR_NON_PIECE_RECTANGLE); #endif } #endif strides[0] /= field_size; return result; } __CUDA_HD__ inline FT& operator[](const Point<1,T>& p) const { #ifdef __CUDA_ARCH__ assert(bounds.contains(p)); #else if (!bounds.contains(p)) PhysicalRegion::fail_bounds_check(DomainPoint(p), field, LEGION_READ_WRITE); #endif return accessor[p]; } template<typename REDOP, bool EXCLUSIVE> __CUDA_HD__ inline void reduce(const Point<1,T>& p, typename REDOP::RHS val) const { #ifdef __CUDA_ARCH__ assert(bounds.contains(p)); #else if (!bounds.contains(p)) PhysicalRegion::fail_bounds_check(DomainPoint(p), field, LEGION_REDUCE); #endif REDOP::template apply<EXCLUSIVE>(accessor[p], val); } public: Realm::MultiAffineAccessor<FT,1,T> accessor; FieldID field; AffineBounds::Tester<1,T> bounds; public: typedef FT value_type; typedef FT& reference; typedef const FT& const_reference; static const int dim = 1; }; // Write-discard FieldAccessor specialization template<typename FT, int N, typename T, bool CB> class FieldAccessor<LEGION_WRITE_DISCARD,FT,N,T, Realm::MultiAffineAccessor<FT,N,T>,CB> { public: __CUDA_HD__ FieldAccessor(void) { } FieldAccessor(const PhysicalRegion &region, FieldID fid, size_t actual_field_size = sizeof(FT), #ifdef DEBUG_LEGION bool check_field_size = true, #else bool check_field_size = false, #endif bool silence_warnings = false, const char *warning_string = NULL, size_t offset = 0) { DomainT<N,T> is; const Realm::RegionInstance instance = region.get_instance_info(LEGION_WRITE_DISCARD, fid, actual_field_size, &is,Internal::NT_TemplateHelper::encode_tag<N,T>(),warning_string, silence_warnings, false/*generic accessor*/, check_field_size); if (!Realm::MultiAffineAccessor<FT,N,T>::is_compatible(instance, fid, is.bounds)) region.report_incompatible_accessor("MultiAffineAccessor", instance, fid); accessor = Realm::MultiAffineAccessor<FT,N,T>(instance, fid, is.bounds, offset); } // With explicit bounds FieldAccessor(const PhysicalRegion &region, FieldID fid, const Rect<N,T> source_bounds, size_t actual_field_size = sizeof(FT), #ifdef DEBUG_LEGION bool check_field_size = true, #else bool check_field_size = false, #endif bool silence_warnings = false, const char *warning_string = NULL, size_t offset = 0) { DomainT<N,T> is; const Realm::RegionInstance instance = region.get_instance_info(LEGION_WRITE_DISCARD, fid, actual_field_size, &is,Internal::NT_TemplateHelper::encode_tag<N,T>(),warning_string, silence_warnings, false/*generic accessor*/, check_field_size); if (!Realm::MultiAffineAccessor<FT,N,T>::is_compatible(instance, fid, source_bounds)) region.report_incompatible_accessor("MultiAffineAccessor", instance, fid); accessor = Realm::MultiAffineAccessor<FT,N,T>(instance, fid, source_bounds, offset); } public: __CUDA_HD__ inline FT read(const Point<N,T>& p) const { return accessor.read(p); } __CUDA_HD__ inline void write(const Point<N,T>& p, FT val) const { accessor.write(p, val); } __CUDA_HD__ inline FT* ptr(const Point<N,T>& p) const { return accessor.ptr(p); } __CUDA_HD__ inline FT* ptr(const Rect<N,T>& r, size_t field_size = sizeof(FT)) const { size_t strides[N]; FT *result = accessor.ptr(r, strides); #ifdef __CUDA_ARCH__ assert(result != NULL); assert(Internal::is_dense_layout(r, strides, field_size)); #else if (result == NULL) { fprintf(stderr, "ERROR: Illegal request for pointer of rectangle " "not contained within the bounds of a piece\n"); #ifdef DEBUG_LEGION assert(false); #else exit(ERROR_NON_PIECE_RECTANGLE); #endif } if (!Internal::is_dense_layout(r, strides, field_size)) { fprintf(stderr, "ERROR: Illegal request for pointer of non-dense rectangle\n"); #ifdef DEBUG_LEGION assert(false); #else exit(ERROR_NON_DENSE_RECTANGLE); #endif } #endif return result; } __CUDA_HD__ inline FT* ptr(const Rect<N,T>& r, size_t strides[N], size_t field_size = sizeof(FT)) const { FT *result = accessor.ptr(r, strides); #ifdef __CUDA_ARCH__ assert(result != NULL); #else if (result == NULL) { fprintf(stderr, "ERROR: Illegal request for pointer of rectangle " "not contained within the bounds of a piece\n"); #ifdef DEBUG_LEGION assert(false); #else exit(ERROR_NON_PIECE_RECTANGLE); #endif } #endif for (int i = 0; i < N; i++) strides[i] /= field_size; return result; } __CUDA_HD__ inline FT& operator[](const Point<N,T>& p) const { return accessor[p]; } __CUDA_HD__ inline ArraySyntax::AffineSyntaxHelper< FieldAccessor<LEGION_WRITE_DISCARD,FT,N,T, Realm::MultiAffineAccessor<FT,N,T>,CB>,FT,N,T,2,LEGION_WRITE_DISCARD> operator[](T index) const { return ArraySyntax::AffineSyntaxHelper< FieldAccessor<LEGION_WRITE_DISCARD,FT,N,T, Realm::MultiAffineAccessor<FT,N,T>,CB>,FT,N,T,2,LEGION_WRITE_DISCARD>( *this, Point<1,T>(index)); } public: Realm::MultiAffineAccessor<FT,N,T> accessor; public: typedef FT value_type; typedef FT& reference; typedef const FT& const_reference; static const int dim = N; }; // Write-discard FieldAccessor specialization // with bounds checks template<typename FT, int N, typename T> class FieldAccessor<LEGION_WRITE_DISCARD,FT,N,T, Realm::MultiAffineAccessor<FT,N,T>,true> { public: // No CUDA support due to PhysicalRegion constructor FieldAccessor(void) { } FieldAccessor(const PhysicalRegion &region, FieldID fid, size_t actual_field_size = sizeof(FT), #ifdef DEBUG_LEGION bool check_field_size = true, #else bool check_field_size = false, #endif bool silence_warnings = false, const char *warning_string = NULL, size_t offset = 0) : field(fid) { DomainT<N,T> is; const Realm::RegionInstance instance = region.get_instance_info(LEGION_WRITE_DISCARD, fid, actual_field_size, &is,Internal::NT_TemplateHelper::encode_tag<N,T>(),warning_string, silence_warnings, false/*generic accessor*/, check_field_size); if (!Realm::MultiAffineAccessor<FT,N,T>::is_compatible(instance, fid, is.bounds)) region.report_incompatible_accessor("MultiAffineAccessor", instance, fid); accessor = Realm::MultiAffineAccessor<FT,N,T>(instance, fid, is.bounds, offset); bounds = AffineBounds::Tester<N,T>(is); } // With explicit bounds FieldAccessor(const PhysicalRegion &region, FieldID fid, const Rect<N,T> source_bounds, size_t actual_field_size = sizeof(FT), #ifdef DEBUG_LEGION bool check_field_size = true, #else bool check_field_size = false, #endif bool silence_warnings = false, const char *warning_string = NULL, size_t offset = 0) : field(fid) { DomainT<N,T> is; const Realm::RegionInstance instance = region.get_instance_info(LEGION_WRITE_DISCARD, fid, actual_field_size, &is,Internal::NT_TemplateHelper::encode_tag<N,T>(),warning_string, silence_warnings, false/*generic accessor*/, check_field_size); if (!Realm::MultiAffineAccessor<FT,N,T>::is_compatible(instance, fid, source_bounds)) region.report_incompatible_accessor("MultiAffineAccessor", instance, fid); accessor = Realm::MultiAffineAccessor<FT,N,T>(instance, fid, source_bounds, offset); bounds = AffineBounds::Tester<N,T>(is, source_bounds); } public: __CUDA_HD__ inline FT read(const Point<N,T>& p) const { #ifdef __CUDA_ARCH__ assert(bounds.contains(p)); #else if (!bounds.contains(p)) PhysicalRegion::fail_bounds_check(DomainPoint(p), field, LEGION_READ_ONLY); #endif return accessor.read(p); } __CUDA_HD__ inline void write(const Point<N,T>& p, FT val) const { #ifdef __CUDA_ARCH__ assert(bounds.contains(p)); #else if (!bounds.contains(p)) PhysicalRegion::fail_bounds_check(DomainPoint(p), field, LEGION_WRITE_DISCARD); #endif accessor.write(p, val); } __CUDA_HD__ inline FT* ptr(const Point<N,T>& p) const { #ifdef __CUDA_ARCH__ assert(bounds.contains(p)); #else if (!bounds.contains(p)) PhysicalRegion::fail_bounds_check(DomainPoint(p), field, LEGION_READ_WRITE); #endif return accessor.ptr(p); } __CUDA_HD__ inline FT* ptr(const Rect<N,T>& r, size_t field_size = sizeof(FT)) const { size_t strides[N]; FT *result = accessor.ptr(r, strides); #ifdef __CUDA_ARCH__ assert(bounds.contains_all(r)); assert(result != NULL); assert(Internal::is_dense_layout(r, strides, field_size)); #else if (!bounds.contains_all(r)) PhysicalRegion::fail_bounds_check(Domain(r), field, LEGION_READ_WRITE); if (result == NULL) { fprintf(stderr, "ERROR: Illegal request for pointer of rectangle " "not contained within the bounds of a piece\n"); #ifdef DEBUG_LEGION assert(false); #else exit(ERROR_NON_PIECE_RECTANGLE); #endif } if (!Internal::is_dense_layout(r, strides, field_size)) { fprintf(stderr, "ERROR: Illegal request for pointer of non-dense rectangle\n"); #ifdef DEBUG_LEGION assert(false); #else exit(ERROR_NON_DENSE_RECTANGLE); #endif } #endif return result; } __CUDA_HD__ inline FT* ptr(const Rect<N,T>& r, size_t strides[N], size_t field_size = sizeof(FT)) const { FT *result = accessor.ptr(r, strides); #ifdef __CUDA_ARCH__ assert(bounds.contains_all(r)); assert(result != NULL); #else if (!bounds.contains_all(r)) PhysicalRegion::fail_bounds_check(Domain(r), field, LEGION_READ_WRITE); if (result == NULL) { fprintf(stderr, "ERROR: Illegal request for pointer of rectangle " "not contained within the bounds of a piece\n"); #ifdef DEBUG_LEGION assert(false); #else exit(ERROR_NON_PIECE_RECTANGLE); #endif } #endif for (int i = 0; i < N; i++) strides[i] /= field_size; return result; } __CUDA_HD__ inline FT& operator[](const Point<N,T>& p) const { #ifdef __CUDA_ARCH__ assert(bounds.contains(p)); #else if (!bounds.contains(p)) PhysicalRegion::fail_bounds_check(DomainPoint(p), field, LEGION_READ_WRITE); #endif return accessor[p]; } __CUDA_HD__ inline ArraySyntax::AffineSyntaxHelper< FieldAccessor<LEGION_WRITE_DISCARD,FT,N,T, Realm::MultiAffineAccessor<FT,N,T>,true>,FT,N,T,2,LEGION_WRITE_DISCARD> operator[](T index) const { return ArraySyntax::AffineSyntaxHelper< FieldAccessor<LEGION_WRITE_DISCARD,FT,N,T, Realm::MultiAffineAccessor<FT,N,T>,true>,FT,N,T,2, LEGION_WRITE_DISCARD>(*this, Point<1,T>(index)); } public: Realm::MultiAffineAccessor<FT,N,T> accessor; FieldID field; AffineBounds::Tester<N,T> bounds; public: typedef FT value_type; typedef FT& reference; typedef const FT& const_reference; static const int dim = N; }; // Write-discard FieldAccessor specialization with // N == 1 to avoid array ambiguity template<typename FT, typename T, bool CB> class FieldAccessor<LEGION_WRITE_DISCARD,FT,1,T, Realm::MultiAffineAccessor<FT,1,T>,CB> { public: __CUDA_HD__ FieldAccessor(void) { } FieldAccessor(const PhysicalRegion &region, FieldID fid, size_t actual_field_size = sizeof(FT), #ifdef DEBUG_LEGION bool check_field_size = true, #else bool check_field_size = false, #endif bool silence_warnings = false, const char *warning_string = NULL, size_t offset = 0) { DomainT<1,T> is; const Realm::RegionInstance instance = region.get_instance_info(LEGION_WRITE_DISCARD, fid, actual_field_size, &is,Internal::NT_TemplateHelper::encode_tag<1,T>(),warning_string, silence_warnings, false/*generic accessor*/, check_field_size); if (!Realm::MultiAffineAccessor<FT,1,T>::is_compatible(instance, fid, is.bounds)) region.report_incompatible_accessor("MultiAffineAccessor", instance, fid); accessor = Realm::MultiAffineAccessor<FT,1,T>(instance, fid, is.bounds, offset); } // With explicit bounds FieldAccessor(const PhysicalRegion &region, FieldID fid, const Rect<1,T> source_bounds, size_t actual_field_size = sizeof(FT), #ifdef DEBUG_LEGION bool check_field_size = true, #else bool check_field_size = false, #endif bool silence_warnings = false, const char *warning_string = NULL, size_t offset = 0) { DomainT<1,T> is; const Realm::RegionInstance instance = region.get_instance_info(LEGION_WRITE_DISCARD, fid, actual_field_size, &is,Internal::NT_TemplateHelper::encode_tag<1,T>(),warning_string, silence_warnings, false/*generic accessor*/, check_field_size); if (!Realm::MultiAffineAccessor<FT,1,T>::is_compatible(instance, fid, source_bounds)) region.report_incompatible_accessor("MultiAffineAccessor", instance, fid); accessor = Realm::MultiAffineAccessor<FT,1,T>(instance, fid, source_bounds, offset); } public: __CUDA_HD__ inline FT read(const Point<1,T>& p) const { return accessor.read(p); } __CUDA_HD__ inline void write(const Point<1,T>& p, FT val) const { accessor.write(p, val); } __CUDA_HD__ inline FT* ptr(const Point<1,T>& p) const { return accessor.ptr(p); } __CUDA_HD__ inline FT* ptr(const Rect<1,T>& r, size_t field_size = sizeof(FT)) const { size_t strides[1]; FT *result = accessor.ptr(r, strides); #ifdef __CUDA_ARCH__ assert(result != NULL); assert(Internal::is_dense_layout(r, strides, field_size)); #else if (result == NULL) { fprintf(stderr, "ERROR: Illegal request for pointer of rectangle " "not contained within the bounds of a piece\n"); #ifdef DEBUG_LEGION assert(false); #else exit(ERROR_NON_PIECE_RECTANGLE); #endif } if (!Internal::is_dense_layout(r, strides, field_size)) { fprintf(stderr, "ERROR: Illegal request for pointer of non-dense rectangle\n"); #ifdef DEBUG_LEGION assert(false); #else exit(ERROR_NON_DENSE_RECTANGLE); #endif } #endif return result; } __CUDA_HD__ inline FT* ptr(const Rect<1,T>& r, size_t strides[1], size_t field_size = sizeof(FT)) const { FT *result = accessor.ptr(r, strides); #ifdef __CUDA_ARCH__ assert(result != NULL); #else if (result == NULL) { fprintf(stderr, "ERROR: Illegal request for pointer of rectangle " "not contained within the bounds of a piece\n"); #ifdef DEBUG_LEGION assert(false); #else exit(ERROR_NON_PIECE_RECTANGLE); #endif } #endif strides[0] /= field_size; return result; } __CUDA_HD__ inline FT& operator[](const Point<1,T>& p) const { return accessor[p]; } public: Realm::MultiAffineAccessor<FT,1,T> accessor; public: typedef FT value_type; typedef FT& reference; typedef const FT& const_reference; static const int dim = 1; }; // Write-discard FieldAccessor specialization with // N == 1 to avoid array ambiguity and bounds checks template<typename FT, typename T> class FieldAccessor<LEGION_WRITE_DISCARD,FT,1,T, Realm::MultiAffineAccessor<FT,1,T>,true> { public: // No CUDA support due to PhysicalRegion constructor FieldAccessor(void) { } FieldAccessor(const PhysicalRegion &region, FieldID fid, size_t actual_field_size = sizeof(FT), #ifdef DEBUG_LEGION bool check_field_size = true, #else bool check_field_size = false, #endif bool silence_warnings = false, const char *warning_string = NULL, size_t offset = 0) : field(fid) { DomainT<1,T> is; const Realm::RegionInstance instance = region.get_instance_info(LEGION_WRITE_DISCARD, fid, actual_field_size, &is,Internal::NT_TemplateHelper::encode_tag<1,T>(),warning_string, silence_warnings, false/*generic accessor*/, check_field_size); if (!Realm::MultiAffineAccessor<FT,1,T>::is_compatible(instance, fid, is.bounds)) region.report_incompatible_accessor("MultiAffineAccessor", instance, fid); accessor = Realm::MultiAffineAccessor<FT,1,T>(instance, fid, is.bounds, offset); bounds = AffineBounds::Tester<1,T>(is); } // With explicit bounds FieldAccessor(const PhysicalRegion &region, FieldID fid, const Rect<1,T> source_bounds, size_t actual_field_size = sizeof(FT), #ifdef DEBUG_LEGION bool check_field_size = true, #else bool check_field_size = false, #endif bool silence_warnings = false, const char *warning_string = NULL, size_t offset = 0) : field(fid) { DomainT<1,T> is; const Realm::RegionInstance instance = region.get_instance_info(LEGION_WRITE_DISCARD, fid, actual_field_size, &is,Internal::NT_TemplateHelper::encode_tag<1,T>(),warning_string, silence_warnings, false/*generic accessor*/, check_field_size); if (!Realm::MultiAffineAccessor<FT,1,T>::is_compatible(instance, fid, source_bounds)) region.report_incompatible_accessor("MultiAffineAccessor", instance, fid); accessor = Realm::MultiAffineAccessor<FT,1,T>(instance, fid, source_bounds, offset); bounds = AffineBounds::Tester<1,T>(is, source_bounds); } public: __CUDA_HD__ inline FT read(const Point<1,T>& p) const { #ifdef __CUDA_ARCH__ assert(bounds.contains(p)); #else if (!bounds.contains(p)) PhysicalRegion::fail_bounds_check(DomainPoint(p), field, LEGION_READ_ONLY); #endif return accessor.read(p); } __CUDA_HD__ inline void write(const Point<1,T>& p, FT val) const { #ifdef __CUDA_ARCH__ assert(bounds.contains(p)); #else if (!bounds.contains(p)) PhysicalRegion::fail_bounds_check(DomainPoint(p), field, LEGION_WRITE_DISCARD); #endif accessor.write(p, val); } __CUDA_HD__ inline FT* ptr(const Point<1,T>& p) const { #ifdef __CUDA_ARCH__ assert(bounds.contains(p)); #else if (!bounds.contains(p)) PhysicalRegion::fail_bounds_check(DomainPoint(p), field, LEGION_READ_WRITE); #endif return accessor.ptr(p); } __CUDA_HD__ inline FT* ptr(const Rect<1,T>& r, size_t field_size = sizeof(FT)) const { size_t strides[1]; FT *result = accessor.ptr(r, strides); #ifdef __CUDA_ARCH__ assert(bounds.contains_all(r)); assert(result != NULL); assert(Internal::is_dense_layout(r, strides, field_size)); #else if (!bounds.contains_all(r)) PhysicalRegion::fail_bounds_check(Domain(r), field, LEGION_READ_WRITE); if (result == NULL) { fprintf(stderr, "ERROR: Illegal request for pointer of rectangle " "not contained within the bounds of a piece\n"); #ifdef DEBUG_LEGION assert(false); #else exit(ERROR_NON_PIECE_RECTANGLE); #endif } if (!Internal::is_dense_layout(r, strides, field_size)) { fprintf(stderr, "ERROR: Illegal request for pointer of non-dense rectangle\n"); #ifdef DEBUG_LEGION assert(false); #else exit(ERROR_NON_DENSE_RECTANGLE); #endif } #endif return result; } __CUDA_HD__ inline FT* ptr(const Rect<1,T>& r, size_t strides[1], size_t field_size = sizeof(FT)) const { FT *result = accessor.ptr(r, strides); #ifdef __CUDA_ARCH__ assert(bounds.contains_all(r)); assert(result != NULL); #else if (!bounds.contains_all(r)) PhysicalRegion::fail_bounds_check(Domain(r), field, LEGION_READ_WRITE); if (result == NULL) { fprintf(stderr, "ERROR: Illegal request for pointer of rectangle " "not contained within the bounds of a piece\n"); #ifdef DEBUG_LEGION assert(false); #else exit(ERROR_NON_PIECE_RECTANGLE); #endif } #endif strides[0] /= field_size; return result; } __CUDA_HD__ inline FT& operator[](const Point<1,T>& p) const { #ifdef __CUDA_ARCH__ assert(bounds.contains(p)); #else if (!bounds.contains(p)) PhysicalRegion::fail_bounds_check(DomainPoint(p), field, LEGION_READ_WRITE); #endif return accessor[p]; } public: Realm::MultiAffineAccessor<FT,1,T> accessor; FieldID field; AffineBounds::Tester<1,T> bounds; public: typedef FT value_type; typedef FT& reference; typedef const FT& const_reference; static const int dim = 1; }; // Write-only FieldAccessor specialization template<typename FT, int N, typename T, bool CB> class FieldAccessor<LEGION_WRITE_ONLY,FT,N,T, Realm::MultiAffineAccessor<FT,N,T>,CB> { public: __CUDA_HD__ FieldAccessor(void) { } FieldAccessor(const PhysicalRegion &region, FieldID fid, size_t actual_field_size = sizeof(FT), #ifdef DEBUG_LEGION bool check_field_size = true, #else bool check_field_size = false, #endif bool silence_warnings = false, const char *warning_string = NULL, size_t offset = 0) { DomainT<N,T> is; const Realm::RegionInstance instance = region.get_instance_info(LEGION_WRITE_DISCARD, fid, actual_field_size, &is,Internal::NT_TemplateHelper::encode_tag<N,T>(),warning_string, silence_warnings, false/*generic accessor*/, check_field_size); if (!Realm::MultiAffineAccessor<FT,N,T>::is_compatible(instance, fid, is.bounds)) region.report_incompatible_accessor("MultiAffineAccessor", instance, fid); accessor = Realm::MultiAffineAccessor<FT,N,T>(instance, fid, is.bounds, offset); } // With explicit bounds FieldAccessor(const PhysicalRegion &region, FieldID fid, const Rect<N,T> source_bounds, size_t actual_field_size = sizeof(FT), #ifdef DEBUG_LEGION bool check_field_size = true, #else bool check_field_size = false, #endif bool silence_warnings = false, const char *warning_string = NULL, size_t offset = 0) { DomainT<N,T> is; const Realm::RegionInstance instance = region.get_instance_info(LEGION_WRITE_DISCARD, fid, actual_field_size, &is,Internal::NT_TemplateHelper::encode_tag<N,T>(),warning_string, silence_warnings, false/*generic accessor*/, check_field_size); if (!Realm::MultiAffineAccessor<FT,N,T>::is_compatible(instance, fid, source_bounds)) region.report_incompatible_accessor("MultiAffineAccessor", instance, fid); accessor = Realm::MultiAffineAccessor<FT,N,T>(instance, fid, source_bounds, offset); } public: __CUDA_HD__ inline void write(const Point<N,T>& p, FT val) const { accessor.write(p, val); } __CUDA_HD__ inline FT* ptr(const Point<N,T>& p) const { return accessor.ptr(p); } __CUDA_HD__ inline FT* ptr(const Rect<N,T>& r, size_t field_size = sizeof(FT)) const { size_t strides[N]; FT *result = accessor.ptr(r, strides); #ifdef __CUDA_ARCH__ assert(result != NULL); assert(Internal::is_dense_layout(r, strides, field_size)); #else if (result == NULL) { fprintf(stderr, "ERROR: Illegal request for pointer of rectangle " "not contained within the bounds of a piece\n"); #ifdef DEBUG_LEGION assert(false); #else exit(ERROR_NON_PIECE_RECTANGLE); #endif } if (!Internal::is_dense_layout(r, strides, field_size)) { fprintf(stderr, "ERROR: Illegal request for pointer of non-dense rectangle\n"); #ifdef DEBUG_LEGION assert(false); #else exit(ERROR_NON_DENSE_RECTANGLE); #endif } #endif return result; } __CUDA_HD__ inline FT* ptr(const Rect<N,T>& r, size_t strides[N], size_t field_size = sizeof(FT)) const { FT *result = accessor.ptr(r, strides); #ifdef __CUDA_ARCH__ assert(result != NULL); #else if (result == NULL) { fprintf(stderr, "ERROR: Illegal request for pointer of rectangle " "not contained within the bounds of a piece\n"); #ifdef DEBUG_LEGION assert(false); #else exit(ERROR_NON_PIECE_RECTANGLE); #endif } #endif for (int i = 0; i < N; i++) strides[i] /= field_size; return result; } __CUDA_HD__ inline FT& operator[](const Point<N,T>& p) const { return accessor[p]; } __CUDA_HD__ inline ArraySyntax::AffineSyntaxHelper< FieldAccessor<LEGION_WRITE_DISCARD,FT,N,T, Realm::MultiAffineAccessor<FT,N,T>,CB>,FT,N,T,2,LEGION_WRITE_DISCARD> operator[](T index) const { return ArraySyntax::AffineSyntaxHelper< FieldAccessor<LEGION_WRITE_DISCARD,FT,N,T, Realm::MultiAffineAccessor<FT,N,T>,CB>,FT,N,T,2,LEGION_WRITE_DISCARD>( *this, Point<1,T>(index)); } public: Realm::MultiAffineAccessor<FT,N,T> accessor; public: typedef FT value_type; typedef FT& reference; typedef const FT& const_reference; static const int dim = N; }; // Write-only FieldAccessor specialization // with bounds checks template<typename FT, int N, typename T> class FieldAccessor<LEGION_WRITE_ONLY,FT,N,T, Realm::MultiAffineAccessor<FT,N,T>,true> { public: // No CUDA support due to PhysicalRegion constructor FieldAccessor(void) { } FieldAccessor(const PhysicalRegion &region, FieldID fid, size_t actual_field_size = sizeof(FT), #ifdef DEBUG_LEGION bool check_field_size = true, #else bool check_field_size = false, #endif bool silence_warnings = false, const char *warning_string = NULL, size_t offset = 0) : field(fid) { DomainT<N,T> is; const Realm::RegionInstance instance = region.get_instance_info(LEGION_WRITE_DISCARD, fid, actual_field_size, &is,Internal::NT_TemplateHelper::encode_tag<N,T>(),warning_string, silence_warnings, false/*generic accessor*/, check_field_size); if (!Realm::MultiAffineAccessor<FT,N,T>::is_compatible(instance, fid, is.bounds)) region.report_incompatible_accessor("MultiAffineAccessor", instance, fid); accessor = Realm::MultiAffineAccessor<FT,N,T>(instance, fid, is.bounds, offset); bounds = AffineBounds::Tester<N,T>(is); } // With explicit bounds FieldAccessor(const PhysicalRegion &region, FieldID fid, const Rect<N,T> source_bounds, size_t actual_field_size = sizeof(FT), #ifdef DEBUG_LEGION bool check_field_size = true, #else bool check_field_size = false, #endif bool silence_warnings = false, const char *warning_string = NULL, size_t offset = 0) : field(fid) { DomainT<N,T> is; const Realm::RegionInstance instance = region.get_instance_info(LEGION_WRITE_DISCARD, fid, actual_field_size, &is,Internal::NT_TemplateHelper::encode_tag<N,T>(),warning_string, silence_warnings, false/*generic accessor*/, check_field_size); if (!Realm::MultiAffineAccessor<FT,N,T>::is_compatible(instance, fid, source_bounds)) region.report_incompatible_accessor("MultiAffineAccessor", instance, fid); accessor = Realm::MultiAffineAccessor<FT,N,T>(instance, fid, source_bounds, offset); bounds = AffineBounds::Tester<N,T>(is, source_bounds); } public: __CUDA_HD__ inline void write(const Point<N,T>& p, FT val) const { #ifdef __CUDA_ARCH__ assert(bounds.contains(p)); #else if (!bounds.contains(p)) PhysicalRegion::fail_bounds_check(DomainPoint(p), field, LEGION_WRITE_DISCARD); #endif accessor.write(p, val); } __CUDA_HD__ inline FT* ptr(const Point<N,T>& p) const { #ifdef __CUDA_ARCH__ assert(bounds.contains(p)); #else if (!bounds.contains(p)) PhysicalRegion::fail_bounds_check(DomainPoint(p), field, LEGION_READ_WRITE); #endif return accessor.ptr(p); } __CUDA_HD__ inline FT* ptr(const Rect<N,T>& r, size_t field_size = sizeof(FT)) const { size_t strides[N]; FT *result = accessor.ptr(r, strides); #ifdef __CUDA_ARCH__ assert(bounds.contains_all(r)); assert(result != NULL); assert(Internal::is_dense_layout(r, strides, field_size)); #else if (!bounds.contains_all(r)) PhysicalRegion::fail_bounds_check(Domain(r), field, LEGION_READ_WRITE); if (result == NULL) { fprintf(stderr, "ERROR: Illegal request for pointer of rectangle " "not contained within the bounds of a piece\n"); #ifdef DEBUG_LEGION assert(false); #else exit(ERROR_NON_PIECE_RECTANGLE); #endif } if (!Internal::is_dense_layout(r, strides, field_size)) { fprintf(stderr, "ERROR: Illegal request for pointer of non-dense rectangle\n"); #ifdef DEBUG_LEGION assert(false); #else exit(ERROR_NON_DENSE_RECTANGLE); #endif } #endif return result; } __CUDA_HD__ inline FT* ptr(const Rect<N,T>& r, size_t strides[N], size_t field_size = sizeof(FT)) const { FT *result = accessor.ptr(r, strides); #ifdef __CUDA_ARCH__ assert(bounds.contains_all(r)); assert(result != NULL); #else if (!bounds.contains_all(r)) PhysicalRegion::fail_bounds_check(Domain(r), field, LEGION_READ_WRITE); if (result == NULL) { fprintf(stderr, "ERROR: Illegal request for pointer of rectangle " "not contained within the bounds of a piece\n"); #ifdef DEBUG_LEGION assert(false); #else exit(ERROR_NON_PIECE_RECTANGLE); #endif } #endif for (int i = 0; i < N; i++) strides[i] /= field_size; return result; } __CUDA_HD__ inline FT& operator[](const Point<N,T>& p) const { #ifdef __CUDA_ARCH__ assert(bounds.contains(p)); #else if (!bounds.contains(p)) PhysicalRegion::fail_bounds_check(DomainPoint(p), field, LEGION_READ_WRITE); #endif return accessor[p]; } __CUDA_HD__ inline ArraySyntax::AffineSyntaxHelper< FieldAccessor<LEGION_WRITE_DISCARD,FT,N,T, Realm::MultiAffineAccessor<FT,N,T>,true>,FT,N,T,2,LEGION_WRITE_DISCARD> operator[](T index) const { return ArraySyntax::AffineSyntaxHelper< FieldAccessor<LEGION_WRITE_DISCARD,FT,N,T, Realm::MultiAffineAccessor<FT,N,T>,true>,FT,N,T,2, LEGION_WRITE_DISCARD>(*this, Point<1,T>(index)); } public: Realm::MultiAffineAccessor<FT,N,T> accessor; FieldID field; AffineBounds::Tester<N,T> bounds; public: typedef FT value_type; typedef FT& reference; typedef const FT& const_reference; static const int dim = N; }; // Write-only FieldAccessor specialization with // N == 1 to avoid array ambiguity template<typename FT, typename T, bool CB> class FieldAccessor<LEGION_WRITE_ONLY,FT,1,T, Realm::MultiAffineAccessor<FT,1,T>,CB> { public: __CUDA_HD__ FieldAccessor(void) { } FieldAccessor(const PhysicalRegion &region, FieldID fid, size_t actual_field_size = sizeof(FT), #ifdef DEBUG_LEGION bool check_field_size = true, #else bool check_field_size = false, #endif bool silence_warnings = false, const char *warning_string = NULL, size_t offset = 0) { DomainT<1,T> is; const Realm::RegionInstance instance = region.get_instance_info(LEGION_WRITE_DISCARD, fid, actual_field_size, &is,Internal::NT_TemplateHelper::encode_tag<1,T>(),warning_string, silence_warnings, false/*generic accessor*/, check_field_size); if (!Realm::MultiAffineAccessor<FT,1,T>::is_compatible(instance, fid, is.bounds)) region.report_incompatible_accessor("MultiAffineAccessor", instance, fid); accessor = Realm::MultiAffineAccessor<FT,1,T>(instance, fid, is.bounds, offset); } // With explicit bounds FieldAccessor(const PhysicalRegion &region, FieldID fid, const Rect<1,T> source_bounds, size_t actual_field_size = sizeof(FT), #ifdef DEBUG_LEGION bool check_field_size = true, #else bool check_field_size = false, #endif bool silence_warnings = false, const char *warning_string = NULL, size_t offset = 0) { DomainT<1,T> is; const Realm::RegionInstance instance = region.get_instance_info(LEGION_WRITE_DISCARD, fid, actual_field_size, &is,Internal::NT_TemplateHelper::encode_tag<1,T>(),warning_string, silence_warnings, false/*generic accessor*/, check_field_size); if (!Realm::MultiAffineAccessor<FT,1,T>::is_compatible(instance, fid, source_bounds)) region.report_incompatible_accessor("MultiAffineAccessor", instance, fid); accessor = Realm::MultiAffineAccessor<FT,1,T>(instance, fid, source_bounds, offset); } public: __CUDA_HD__ inline void write(const Point<1,T>& p, FT val) const { accessor.write(p, val); } __CUDA_HD__ inline FT* ptr(const Point<1,T>& p) const { return accessor.ptr(p); } __CUDA_HD__ inline FT* ptr(const Rect<1,T>& r, size_t field_size = sizeof(FT)) const { size_t strides[1]; FT *result = accessor.ptr(r, strides); #ifdef __CUDA_ARCH__ assert(result != NULL); assert(Internal::is_dense_layout(r, strides, field_size)); #else if (result == NULL) { fprintf(stderr, "ERROR: Illegal request for pointer of rectangle " "not contained within the bounds of a piece\n"); #ifdef DEBUG_LEGION assert(false); #else exit(ERROR_NON_PIECE_RECTANGLE); #endif } if (!Internal::is_dense_layout(r, strides, field_size)) { fprintf(stderr, "ERROR: Illegal request for pointer of non-dense rectangle\n"); #ifdef DEBUG_LEGION assert(false); #else exit(ERROR_NON_DENSE_RECTANGLE); #endif } #endif return accessor.ptr(r.lo); } __CUDA_HD__ inline FT* ptr(const Rect<1,T>& r, size_t strides[1], size_t field_size = sizeof(FT)) const { FT *result = accessor.ptr(r, strides); #ifdef __CUDA_ARCH__ assert(result != NULL); #else if (result == NULL) { fprintf(stderr, "ERROR: Illegal request for pointer of rectangle " "not contained within the bounds of a piece\n"); #ifdef DEBUG_LEGION assert(false); #else exit(ERROR_NON_PIECE_RECTANGLE); #endif } #endif strides[0] /= field_size; return accessor.ptr(r.lo); } __CUDA_HD__ inline FT& operator[](const Point<1,T>& p) const { return accessor[p]; } public: Realm::MultiAffineAccessor<FT,1,T> accessor; public: typedef FT value_type; typedef FT& reference; typedef const FT& const_reference; static const int dim = 1; }; // Write-only FieldAccessor specialization with // N == 1 to avoid array ambiguity and bounds checks template<typename FT, typename T> class FieldAccessor<LEGION_WRITE_ONLY,FT,1,T, Realm::MultiAffineAccessor<FT,1,T>,true> { public: // No CUDA support due to PhysicalRegion constructor FieldAccessor(void) { } FieldAccessor(const PhysicalRegion &region, FieldID fid, size_t actual_field_size = sizeof(FT), #ifdef DEBUG_LEGION bool check_field_size = true, #else bool check_field_size = false, #endif bool silence_warnings = false, const char *warning_string = NULL, size_t offset = 0) : field(fid) { DomainT<1,T> is; const Realm::RegionInstance instance = region.get_instance_info(LEGION_WRITE_DISCARD, fid, actual_field_size, &is,Internal::NT_TemplateHelper::encode_tag<1,T>(),warning_string, silence_warnings, false/*generic accessor*/, check_field_size); if (!Realm::MultiAffineAccessor<FT,1,T>::is_compatible(instance, fid, is.bounds)) region.report_incompatible_accessor("MultiAffineAccessor", instance, fid); accessor = Realm::MultiAffineAccessor<FT,1,T>(instance, fid, is.bounds, offset); bounds = AffineBounds::Tester<1,T>(is); } // With explicit bounds FieldAccessor(const PhysicalRegion &region, FieldID fid, const Rect<1,T> source_bounds, size_t actual_field_size = sizeof(FT), #ifdef DEBUG_LEGION bool check_field_size = true, #else bool check_field_size = false, #endif bool silence_warnings = false, const char *warning_string = NULL, size_t offset = 0) : field(fid) { DomainT<1,T> is; const Realm::RegionInstance instance = region.get_instance_info(LEGION_WRITE_DISCARD, fid, actual_field_size, &is,Internal::NT_TemplateHelper::encode_tag<1,T>(),warning_string, silence_warnings, false/*generic accessor*/, check_field_size); if (!Realm::MultiAffineAccessor<FT,1,T>::is_compatible(instance, fid, source_bounds)) region.report_incompatible_accessor("MultiAffineAccessor", instance, fid); accessor = Realm::MultiAffineAccessor<FT,1,T>(instance, fid, source_bounds, offset); bounds = AffineBounds::Tester<1,T>(is, source_bounds); } public: __CUDA_HD__ inline void write(const Point<1,T>& p, FT val) const { #ifdef __CUDA_ARCH__ assert(bounds.contains(p)); #else if (!bounds.contains(p)) PhysicalRegion::fail_bounds_check(DomainPoint(p), field, LEGION_WRITE_DISCARD); #endif accessor.write(p, val); } __CUDA_HD__ inline FT* ptr(const Point<1,T>& p) const { #ifdef __CUDA_ARCH__ assert(bounds.contains(p)); #else if (!bounds.contains(p)) PhysicalRegion::fail_bounds_check(DomainPoint(p), field, LEGION_READ_WRITE); #endif return accessor.ptr(p); } __CUDA_HD__ inline FT* ptr(const Rect<1,T>& r, size_t field_size = sizeof(FT)) const { size_t strides[1]; FT *result = accessor.ptr(r, strides); #ifdef __CUDA_ARCH__ assert(bounds.contains_all(r)); assert(result != NULL); assert(Internal::is_dense_layout(r, strides, field_size)); #else if (!bounds.contains_all(r)) PhysicalRegion::fail_bounds_check(Domain(r), field, LEGION_READ_WRITE); if (result == NULL) { fprintf(stderr, "ERROR: Illegal request for pointer of rectangle " "not contained within the bounds of a piece\n"); #ifdef DEBUG_LEGION assert(false); #else exit(ERROR_NON_PIECE_RECTANGLE); #endif } if (!Internal::is_dense_layout(r, strides, field_size)) { fprintf(stderr, "ERROR: Illegal request for pointer of non-dense rectangle\n"); #ifdef DEBUG_LEGION assert(false); #else exit(ERROR_NON_DENSE_RECTANGLE); #endif } #endif return result; } __CUDA_HD__ inline FT* ptr(const Rect<1,T>& r, size_t strides[1], size_t field_size = sizeof(FT)) const { FT *result = accessor.ptr(r, strides); #ifdef __CUDA_ARCH__ assert(bounds.contains_all(r)); assert(result != NULL); #else if (!bounds.contains_all(r)) PhysicalRegion::fail_bounds_check(Domain(r), field, LEGION_READ_WRITE); if (result == NULL) { fprintf(stderr, "ERROR: Illegal request for pointer of rectangle " "not contained within the bounds of a piece\n"); #ifdef DEBUG_LEGION assert(false); #else exit(ERROR_NON_PIECE_RECTANGLE); #endif } #endif strides[0] /= field_size; return result; } __CUDA_HD__ inline FT& operator[](const Point<1,T>& p) const { #ifdef __CUDA_ARCH__ assert(bounds.contains(p)); #else if (!bounds.contains(p)) PhysicalRegion::fail_bounds_check(DomainPoint(p), field, LEGION_READ_WRITE); #endif return accessor[p]; } public: Realm::MultiAffineAccessor<FT,1,T> accessor; FieldID field; AffineBounds::Tester<1,T> bounds; public: typedef FT value_type; typedef FT& reference; typedef const FT& const_reference; static const int dim = 1; }; // Reduce FieldAccessor specialization template<typename REDOP, bool EXCLUSIVE, int N, typename T, bool CB> class ReductionAccessor<REDOP,EXCLUSIVE,N,T, Realm::MultiAffineAccessor<typename REDOP::RHS,N,T>,CB> { public: __CUDA_HD__ ReductionAccessor(void) { } ReductionAccessor(const PhysicalRegion &region, FieldID fid, ReductionOpID redop, bool silence_warnings = false, const char *warning_string = NULL, size_t offset = 0) { DomainT<N,T> is; const Realm::RegionInstance instance = region.get_instance_info(LEGION_REDUCE,fid,sizeof(typename REDOP::RHS), &is, Internal::NT_TemplateHelper::encode_tag<N,T>(), warning_string, silence_warnings, false/*generic accessor*/, false/*check field size*/, redop); if (!Realm::MultiAffineAccessor<typename REDOP::RHS,N,T>::is_compatible( instance, fid, is.bounds)) region.report_incompatible_accessor("MultiAffineAccessor", instance, fid); accessor = Realm::MultiAffineAccessor<typename REDOP::RHS,N,T>( instance, fid, is.bounds, offset); } // With explicit bounds ReductionAccessor(const PhysicalRegion &region, FieldID fid, ReductionOpID redop, const Rect<N,T> source_bounds, bool silence_warnings = false, const char *warning_string = NULL, size_t offset = 0) { DomainT<N,T> is; const Realm::RegionInstance instance = region.get_instance_info(LEGION_REDUCE,fid,sizeof(typename REDOP::RHS), &is, Internal::NT_TemplateHelper::encode_tag<N,T>(), warning_string, silence_warnings, false/*generic accessor*/, false/*check field size*/, redop); if (!Realm::MultiAffineAccessor<typename REDOP::RHS,N,T>::is_compatible( instance, fid, source_bounds)) region.report_incompatible_accessor("MultiAffineAccessor", instance, fid); accessor = Realm::MultiAffineAccessor<typename REDOP::RHS,N,T>( instance, fid, source_bounds, offset); } public: __CUDA_HD__ inline void reduce(const Point<N,T>& p, typename REDOP::RHS val) const { REDOP::template fold<EXCLUSIVE>(accessor[p], val); } __CUDA_HD__ inline typename REDOP::RHS* ptr(const Point<N,T>& p) const { return accessor.ptr(p); } __CUDA_HD__ inline typename REDOP::RHS* ptr(const Rect<N,T>& r, size_t field_size = sizeof(typename REDOP::RHS)) const { size_t strides[N]; typename REDOP::RHS *result = accessor.ptr(r, strides); #ifdef __CUDA_ARCH__ assert(result != NULL); assert(Internal::is_dense_layout(r, strides, field_size)); #else if (result == NULL) { fprintf(stderr, "ERROR: Illegal request for pointer of rectangle " "not contained within the bounds of a piece\n"); #ifdef DEBUG_LEGION assert(false); #else exit(ERROR_NON_PIECE_RECTANGLE); #endif } if (!Internal::is_dense_layout(r, strides, field_size)) { fprintf(stderr, "ERROR: Illegal request for pointer of non-dense rectangle\n"); #ifdef DEBUG_LEGION assert(false); #else exit(ERROR_NON_DENSE_RECTANGLE); #endif } #endif return result; } __CUDA_HD__ inline typename REDOP::RHS* ptr(const Rect<N,T>& r, size_t strides[N], size_t field_size = sizeof(typename REDOP::RHS)) const { typename REDOP::RHS *result = accessor.ptr(r, strides); #ifdef __CUDA_ARCH__ assert(result != NULL); #else if (result == NULL) { fprintf(stderr, "ERROR: Illegal request for pointer of rectangle " "not contained within the bounds of a piece\n"); #ifdef DEBUG_LEGION assert(false); #else exit(ERROR_NON_PIECE_RECTANGLE); #endif } #endif for (int i = 0; i < N; i++) strides[i] /= field_size; return result; } __CUDA_HD__ inline ArraySyntax::ReductionHelper<ReductionAccessor<REDOP,EXCLUSIVE,N, T,Realm::MultiAffineAccessor<typename REDOP::RHS,N,T>,CB>, typename REDOP::RHS,N,T> operator[](const Point<N,T>& p) const { return ArraySyntax::ReductionHelper<ReductionAccessor<REDOP,EXCLUSIVE, N,T,Realm::MultiAffineAccessor<typename REDOP::RHS,N,T>,CB>, typename REDOP::RHS,N,T>(*this, p); } __CUDA_HD__ inline ArraySyntax::AffineSyntaxHelper<ReductionAccessor<REDOP,EXCLUSIVE, N,T,Realm::MultiAffineAccessor<typename REDOP::RHS,N,T>,CB>, typename REDOP::RHS,N,T,2,LEGION_REDUCE> operator[](T index) const { return ArraySyntax::AffineSyntaxHelper<ReductionAccessor<REDOP, EXCLUSIVE,N,T,Realm::MultiAffineAccessor<typename REDOP::RHS,N,T>,CB>, typename REDOP::RHS,N,T,2,LEGION_REDUCE>( *this, Point<1,T>(index)); } public: Realm::MultiAffineAccessor<typename REDOP::RHS,N,T> accessor; public: typedef typename REDOP::RHS value_type; typedef typename REDOP::RHS& reference; typedef const typename REDOP::RHS& const_reference; static const int dim = N; }; // Reduce ReductionAccessor specialization with bounds checks template<typename REDOP, bool EXCLUSIVE, int N, typename T> class ReductionAccessor<REDOP,EXCLUSIVE,N,T, Realm::MultiAffineAccessor<typename REDOP::RHS,N,T>,true> { public: // No CUDA support due to PhysicalRegion constructor ReductionAccessor(void) { } ReductionAccessor(const PhysicalRegion &region, FieldID fid, ReductionOpID redop, bool silence_warnings = false, const char *warning_string = NULL, size_t offset = 0) : field(fid) { DomainT<N,T> is; const Realm::RegionInstance instance = region.get_instance_info(LEGION_REDUCE,fid,sizeof(typename REDOP::RHS), &is, Internal::NT_TemplateHelper::encode_tag<N,T>(), warning_string, silence_warnings, false/*generic accessor*/, false/*check field size*/, redop); if (!Realm::MultiAffineAccessor<typename REDOP::RHS,N,T>::is_compatible( instance, fid, is.bounds)) region.report_incompatible_accessor("MultiAffineAccessor", instance, fid); accessor = Realm::MultiAffineAccessor<typename REDOP::RHS,N,T>( instance, fid, is.bounds, offset); bounds = AffineBounds::Tester<N,T>(is); } // With explicit bounds ReductionAccessor(const PhysicalRegion &region, FieldID fid, ReductionOpID redop, const Rect<N,T> source_bounds, bool silence_warnings = false, const char *warning_string = NULL, size_t offset = 0) : field(fid) { DomainT<N,T> is; const Realm::RegionInstance instance = region.get_instance_info(LEGION_REDUCE,fid,sizeof(typename REDOP::RHS), &is, Internal::NT_TemplateHelper::encode_tag<N,T>(), warning_string, silence_warnings, false/*generic accessor*/, false/*check field size*/, redop); if (!Realm::MultiAffineAccessor<typename REDOP::RHS,N,T>::is_compatible( instance, fid, source_bounds)) region.report_incompatible_accessor("MultiAffineAccessor", instance, fid); accessor = Realm::MultiAffineAccessor<typename REDOP::RHS,N,T>( instance, fid, source_bounds, offset); bounds = AffineBounds::Tester<N,T>(is, source_bounds); } public: __CUDA_HD__ inline void reduce(const Point<N,T>& p, typename REDOP::RHS val) const { #ifdef __CUDA_ARCH__ assert(bounds.contains(p)); #else if (!bounds.contains(p)) PhysicalRegion::fail_bounds_check(DomainPoint(p), field, LEGION_REDUCE); #endif REDOP::template fold<EXCLUSIVE>(accessor[p], val); } __CUDA_HD__ inline typename REDOP::RHS* ptr(const Point<N,T>& p) const { #ifdef __CUDA_ARCH__ assert(bounds.contains(p)); #else if (!bounds.contains(p)) PhysicalRegion::fail_bounds_check(DomainPoint(p), field, LEGION_REDUCE); #endif return accessor.ptr(p); } __CUDA_HD__ inline typename REDOP::RHS* ptr(const Rect<N,T>& r, size_t field_size = sizeof(typename REDOP::RHS)) const { size_t strides[N]; typename REDOP::RHS *result = accessor.ptr(r, strides); #ifdef __CUDA_ARCH__ assert(bounds.contains_all(r)); assert(result != NULL); assert(Internal::is_dense_layout(r, strides, field_size)); #else if (!bounds.contains_all(r)) PhysicalRegion::fail_bounds_check(Domain(r), field, LEGION_REDUCE); if (result == NULL) { fprintf(stderr, "ERROR: Illegal request for pointer of rectangle " "not contained within the bounds of a piece\n"); #ifdef DEBUG_LEGION assert(false); #else exit(ERROR_NON_PIECE_RECTANGLE); #endif } if (!Internal::is_dense_layout(r, strides, field_size)) { fprintf(stderr, "ERROR: Illegal request for pointer of non-dense rectangle\n"); #ifdef DEBUG_LEGION assert(false); #else exit(ERROR_NON_DENSE_RECTANGLE); #endif } #endif return result; } __CUDA_HD__ inline typename REDOP::RHS* ptr(const Rect<N,T>& r, size_t strides[N], size_t field_size = sizeof(typename REDOP::RHS)) const { typename REDOP::RHS *result = accessor.ptr(r, strides); #ifdef __CUDA_ARCH__ assert(bounds.contains_all(r)); assert(result != NULL); #else if (!bounds.contains_all(r)) PhysicalRegion::fail_bounds_check(Domain(r), field, LEGION_REDUCE); if (result == NULL) { fprintf(stderr, "ERROR: Illegal request for pointer of rectangle " "not contained within the bounds of a piece\n"); #ifdef DEBUG_LEGION assert(false); #else exit(ERROR_NON_PIECE_RECTANGLE); #endif } #endif for (int i = 0; i < N; i++) strides[i] /= field_size; return result; } __CUDA_HD__ inline ArraySyntax::ReductionHelper<ReductionAccessor<REDOP,EXCLUSIVE,N, T,Realm::MultiAffineAccessor<typename REDOP::RHS,N,T>,true>, typename REDOP::RHS,N,T> operator[](const Point<N,T>& p) const { return ArraySyntax::ReductionHelper<ReductionAccessor<REDOP,EXCLUSIVE, N,T,Realm::MultiAffineAccessor<typename REDOP::RHS,N,T>,true>, typename REDOP::RHS,N,T>(*this, p); } __CUDA_HD__ inline ArraySyntax::AffineSyntaxHelper<ReductionAccessor<REDOP,EXCLUSIVE, N,T, Realm::MultiAffineAccessor<typename REDOP::RHS,N,T>,true>, typename REDOP::RHS,N,T,2,LEGION_REDUCE> operator[](T index) const { return ArraySyntax::AffineSyntaxHelper<ReductionAccessor<REDOP, EXCLUSIVE,N,T,Realm::MultiAffineAccessor<typename REDOP::RHS,N,T>, true>,typename REDOP::RHS,N,T,2,LEGION_REDUCE>( *this, Point<1,T>(index)); } public: Realm::MultiAffineAccessor<typename REDOP::RHS,N,T> accessor; FieldID field; AffineBounds::Tester<N,T> bounds; public: typedef typename REDOP::RHS value_type; typedef typename REDOP::RHS& reference; typedef const typename REDOP::RHS& const_reference; static const int dim = N; }; // Reduce Field Accessor specialization with N==1 // to avoid array ambiguity template<typename REDOP, bool EXCLUSIVE, typename T, bool CB> class ReductionAccessor<REDOP,EXCLUSIVE,1,T, Realm::MultiAffineAccessor<typename REDOP::RHS,1,T>,CB> { public: __CUDA_HD__ ReductionAccessor(void) { } ReductionAccessor(const PhysicalRegion &region, FieldID fid, ReductionOpID redop, bool silence_warnings = false, const char *warning_string = NULL, size_t offset = 0) { DomainT<1,T> is; const Realm::RegionInstance instance = region.get_instance_info(LEGION_REDUCE,fid,sizeof(typename REDOP::RHS), &is, Internal::NT_TemplateHelper::encode_tag<1,T>(), warning_string, silence_warnings, false/*generic accessor*/, false/*check field size*/, redop); if (!Realm::MultiAffineAccessor<typename REDOP::RHS,1,T>::is_compatible( instance, fid, is.bounds)) region.report_incompatible_accessor("MultiAffineAccessor", instance, fid); accessor = Realm::MultiAffineAccessor<typename REDOP::RHS,1,T>( instance, fid, is.bounds, offset); } // With explicit bounds ReductionAccessor(const PhysicalRegion &region, FieldID fid, ReductionOpID redop, const Rect<1,T> source_bounds, bool silence_warnings = false, const char *warning_string = NULL, size_t offset = 0) { DomainT<1,T> is; const Realm::RegionInstance instance = region.get_instance_info(LEGION_REDUCE,fid,sizeof(typename REDOP::RHS), &is, Internal::NT_TemplateHelper::encode_tag<1,T>(), warning_string, silence_warnings, false/*generic accessor*/, false/*check field size*/, redop); if (!Realm::MultiAffineAccessor<typename REDOP::RHS,1,T>::is_compatible( instance, fid, source_bounds)) region.report_incompatible_accessor("MultiAffineAccessor", instance, fid); accessor = Realm::MultiAffineAccessor<typename REDOP::RHS,1,T>( instance, fid, source_bounds, offset); } public: __CUDA_HD__ inline void reduce(const Point<1,T>& p, typename REDOP::RHS val) const { REDOP::template fold<EXCLUSIVE>(accessor[p], val); } __CUDA_HD__ inline typename REDOP::RHS* ptr(const Point<1,T>& p) const { return accessor.ptr(p); } __CUDA_HD__ inline typename REDOP::RHS* ptr(const Rect<1,T>& r, size_t field_size = sizeof(typename REDOP::RHS)) const { size_t strides[1]; typename REDOP::RHS *result = accessor.ptr(r, strides); #ifdef __CUDA_ARCH__ assert(result != NULL); assert(Internal::is_dense_layout(r, strides, field_size)); #else if (result == NULL) { fprintf(stderr, "ERROR: Illegal request for pointer of rectangle " "not contained within the bounds of a piece\n"); #ifdef DEBUG_LEGION assert(false); #else exit(ERROR_NON_PIECE_RECTANGLE); #endif } if (!Internal::is_dense_layout(r, strides, field_size)) { fprintf(stderr, "ERROR: Illegal request for pointer of non-dense rectangle\n"); #ifdef DEBUG_LEGION assert(false); #else exit(ERROR_NON_DENSE_RECTANGLE); #endif } #endif return result; } __CUDA_HD__ inline typename REDOP::RHS* ptr(const Rect<1,T>& r, size_t strides[1], size_t field_size = sizeof(typename REDOP::RHS)) const { typename REDOP::RHS *result = accessor.ptr(r, strides); #ifdef __CUDA_ARCH__ assert(result != NULL); #else if (result == NULL) { fprintf(stderr, "ERROR: Illegal request for pointer of rectangle " "not contained within the bounds of a piece\n"); #ifdef DEBUG_LEGION assert(false); #else exit(ERROR_NON_PIECE_RECTANGLE); #endif } #endif strides[0] /= field_size; return result; } __CUDA_HD__ inline ArraySyntax::ReductionHelper<ReductionAccessor<REDOP,EXCLUSIVE,1, T,Realm::MultiAffineAccessor<typename REDOP::RHS,1,T>,CB>, typename REDOP::RHS,1,T> operator[](const Point<1,T>& p) const { return ArraySyntax::ReductionHelper<ReductionAccessor<REDOP,EXCLUSIVE, 1,T,Realm::MultiAffineAccessor<typename REDOP::RHS,1,T>,CB>, typename REDOP::RHS,1,T>(*this, p); } public: Realm::MultiAffineAccessor<typename REDOP::RHS,1,T> accessor; public: typedef typename REDOP::RHS value_type; typedef typename REDOP::RHS& reference; typedef const typename REDOP::RHS& const_reference; static const int dim = 1; }; // Reduce Field Accessor specialization with N==1 // to avoid array ambiguity and bounds checks template<typename REDOP, bool EXCLUSIVE, typename T> class ReductionAccessor<REDOP,EXCLUSIVE,1,T, Realm::MultiAffineAccessor<typename REDOP::RHS,1,T>,true> { public: // No CUDA support due to PhysicalRegion constructor ReductionAccessor(void) { } ReductionAccessor(const PhysicalRegion &region, FieldID fid, ReductionOpID redop, bool silence_warnings = false, const char *warning_string = NULL, size_t offset = 0) : field(fid) { DomainT<1,T> is; const Realm::RegionInstance instance = region.get_instance_info(LEGION_REDUCE,fid,sizeof(typename REDOP::RHS), &is, Internal::NT_TemplateHelper::encode_tag<1,T>(), warning_string, silence_warnings, false/*generic accessor*/, false/*check field size*/, redop); if (!Realm::MultiAffineAccessor<typename REDOP::RHS,1,T>::is_compatible( instance, fid, is.bounds)) region.report_incompatible_accessor("MultiAffineAccessor", instance, fid); accessor = Realm::MultiAffineAccessor<typename REDOP::RHS,1,T>( instance, fid, is.bounds, offset); bounds = AffineBounds::Tester<1,T>(is); } // With explicit bounds ReductionAccessor(const PhysicalRegion &region, FieldID fid, ReductionOpID redop, const Rect<1,T> source_bounds, bool silence_warnings = false, const char *warning_string = NULL, size_t offset = 0) : field(fid) { DomainT<1,T> is; const Realm::RegionInstance instance = region.get_instance_info(LEGION_REDUCE,fid,sizeof(typename REDOP::RHS), &is, Internal::NT_TemplateHelper::encode_tag<1,T>(), warning_string, silence_warnings, false/*generic accessor*/, false/*check field size*/, redop); if (!Realm::MultiAffineAccessor<typename REDOP::RHS,1,T>::is_compatible( instance, fid, source_bounds)) region.report_incompatible_accessor("MultiAffineAccessor", instance, fid); accessor = Realm::MultiAffineAccessor<typename REDOP::RHS,1,T>( instance, fid, source_bounds, offset); bounds = AffineBounds::Tester<1,T>(is, source_bounds); } public: __CUDA_HD__ inline void reduce(const Point<1,T>& p, typename REDOP::RHS val) const { #ifdef __CUDA_ARCH__ assert(bounds.contains(p)); #else if (!bounds.contains(p)) PhysicalRegion::fail_bounds_check(DomainPoint(p), field, LEGION_REDUCE); #endif REDOP::template fold<EXCLUSIVE>(accessor[p], val); } __CUDA_HD__ inline typename REDOP::RHS* ptr(const Point<1,T>& p) const { #ifdef __CUDA_ARCH__ assert(bounds.contains(p)); #else if (!bounds.contains(p)) PhysicalRegion::fail_bounds_check(DomainPoint(p), field, LEGION_REDUCE); #endif return accessor.ptr(p); } __CUDA_HD__ inline typename REDOP::RHS* ptr(const Rect<1,T>& r, size_t field_size = sizeof(typename REDOP::RHS)) const { size_t strides[1]; typename REDOP::RHS *result = accessor.ptr(r, strides); #ifdef __CUDA_ARCH__ assert(bounds.contains_all(r)); assert(result != NULL); assert(Internal::is_dense_layout(r, strides, field_size)); #else if (!bounds.contains_all(r)) PhysicalRegion::fail_bounds_check(Domain(r), field, LEGION_REDUCE); if (result == NULL) { fprintf(stderr, "ERROR: Illegal request for pointer of rectangle " "not contained within the bounds of a piece\n"); #ifdef DEBUG_LEGION assert(false); #else exit(ERROR_NON_PIECE_RECTANGLE); #endif } if (!Internal::is_dense_layout(r, strides, field_size)) { fprintf(stderr, "ERROR: Illegal request for pointer of non-dense rectangle\n"); #ifdef DEBUG_LEGION assert(false); #else exit(ERROR_NON_DENSE_RECTANGLE); #endif } #endif return result; } __CUDA_HD__ inline typename REDOP::RHS* ptr(const Rect<1,T>& r, size_t strides[1], size_t field_size = sizeof(typename REDOP::RHS)) const { typename REDOP::RHS *result = accessor.ptr(r, strides); #ifdef __CUDA_ARCH__ assert(bounds.contains_all(r)); assert(result != NULL); #else if (!bounds.contains_all(r)) PhysicalRegion::fail_bounds_check(Domain(r), field, LEGION_REDUCE); if (result == NULL) { fprintf(stderr, "ERROR: Illegal request for pointer of rectangle " "not contained within the bounds of a piece\n"); #ifdef DEBUG_LEGION assert(false); #else exit(ERROR_NON_PIECE_RECTANGLE); #endif } #endif strides[0] /= field_size; return result; } __CUDA_HD__ inline ArraySyntax::ReductionHelper<ReductionAccessor<REDOP,EXCLUSIVE,1, T,Realm::MultiAffineAccessor<typename REDOP::RHS,1,T>,true>, typename REDOP::RHS,1,T> operator[](const Point<1,T>& p) const { return ArraySyntax::ReductionHelper<ReductionAccessor<REDOP,EXCLUSIVE, 1,T,Realm::MultiAffineAccessor<typename REDOP::RHS,1,T>,true>, typename REDOP::RHS,1,T>(*this, p); } public: Realm::MultiAffineAccessor<typename REDOP::RHS,1,T> accessor; FieldID field; AffineBounds::Tester<1,T> bounds; public: typedef typename REDOP::RHS value_type; typedef typename REDOP::RHS& reference; typedef const typename REDOP::RHS& const_reference; static const int dim = 1; }; //////////////////////////////////////////////////////////// // Multi Region Accessor with Generic Accessors //////////////////////////////////////////////////////////// // Multi-Accessor, generic, N, bounds checks and/or privilege checks template<typename FT, int N, typename T, bool CB, bool CP, int MR> class MultiRegionAccessor<FT,N,T,Realm::GenericAccessor<FT,N,T>,CB,CP,MR> { public: MultiRegionAccessor(void) { } public: template<typename InputIterator> MultiRegionAccessor(InputIterator start, InputIterator stop, FieldID fid, size_t actual_field_size = sizeof(FT), #ifdef DEBUG_LEGION bool check_field_size = true, #else bool check_field_size = false, #endif bool silence_warnings = false, const char *warning_string = NULL, size_t offset = 0) : field(fid) { if (start == stop) return; const PhysicalRegion &region = *start; region_privileges[0] = region.get_privilege(); const Realm::RegionInstance instance = region.get_instance_info( region_privileges[0], fid, actual_field_size, &region_bounds[0], Internal::NT_TemplateHelper::encode_tag<N,T>(), warning_string, silence_warnings, true/*generic accessor*/, check_field_size); Rect<N,T> bounds = region_bounds[0].bounds; unsigned idx = 1; while (++start != stop) { assert(idx < MR); region_privileges[idx] = start->get_privilege(); const Realm::RegionInstance inst = start->get_instance_info( region_privileges[idx], fid, actual_field_size, &region_bounds[idx], Internal::NT_TemplateHelper::encode_tag<N,T>(), warning_string, silence_warnings, true/*generic accessor*/, check_field_size); if (inst != instance) region.report_incompatible_multi_accessor(idx, fid, instance, inst); bounds = bounds.union_bbox(region_bounds[idx].bounds); idx++; } if (!Realm::GenericAccessor<FT,N,T>::is_compatible(instance,fid,bounds)) region.report_incompatible_accessor("GenericAccessor", instance, fid); accessor = Realm::GenericAccessor<FT,N,T>(instance, fid, bounds, offset); total_regions = idx; } template<typename InputIterator> MultiRegionAccessor(InputIterator start, InputIterator stop, const Rect<N,T> source_bounds, FieldID fid, size_t actual_field_size = sizeof(FT), #ifdef DEBUG_LEGION bool check_field_size = true, #else bool check_field_size = false, #endif bool silence_warnings = false, const char *warning_string = NULL, size_t offset = 0) : field(fid) { if (start == stop) return; const PhysicalRegion &region = *start; region_privileges[0] = region.get_privilege(); const Realm::RegionInstance instance = region.get_instance_info( region_privileges[0], fid, actual_field_size, &region_bounds[0], Internal::NT_TemplateHelper::encode_tag<N,T>(), warning_string, silence_warnings, true/*generic accessor*/, check_field_size); Rect<N,T> bounds = region_bounds[0].bounds; unsigned idx = 1; while (++start != stop) { assert(idx < MR); region_privileges[idx] = start->get_privilege(); const Realm::RegionInstance inst = start->get_instance_info( region_privileges[idx], fid, actual_field_size, &region_bounds[idx], Internal::NT_TemplateHelper::encode_tag<N,T>(), warning_string, silence_warnings, true/*generic accessor*/, check_field_size); if (inst != instance) region.report_incompatible_multi_accessor(idx, fid, instance, inst); region_bounds[idx].bounds = source_bounds.intersection(region_bounds[idx].bounds); bounds = bounds.union_bbox(region_bounds[idx].bounds); idx++; } if (!Realm::GenericAccessor<FT,N,T>::is_compatible(instance,fid,bounds)) region.report_incompatible_accessor("GenericAccessor", instance, fid); accessor = Realm::GenericAccessor<FT,N,T>(instance, fid, bounds, offset); total_regions = idx; } public: MultiRegionAccessor(const std::vector<PhysicalRegion> &regions, FieldID fid, size_t actual_field_size = sizeof(FT), #ifdef DEBUG_LEGION bool check_field_size = true, #else bool check_field_size = false, #endif bool silence_warnings = false, const char *warning_string = NULL, size_t offset = 0) : field(fid), total_regions(regions.size()) { if (regions.empty()) return; assert(regions.size() <= MR); const PhysicalRegion &region = regions.front(); region_privileges[0] = region.get_privilege(); const Realm::RegionInstance instance = region.get_instance_info(region_privileges[0], fid, actual_field_size, &region_bounds[0], Internal::NT_TemplateHelper::encode_tag<N,T>(), warning_string, silence_warnings, true/*generic accessor*/, check_field_size); Rect<N,T> bounds = region_bounds[0].bounds; for (unsigned idx = 1; idx < regions.size(); idx++) { region_privileges[idx] = regions[idx].get_privilege(); const Realm::RegionInstance inst = regions[idx].get_instance_info( region_privileges[idx], fid, actual_field_size, &region_bounds[idx], Internal::NT_TemplateHelper::encode_tag<N,T>(), warning_string, silence_warnings, true/*generic accessor*/, check_field_size); if (inst != instance) region.report_incompatible_multi_accessor(idx, fid, instance, inst); bounds = bounds.union_bbox(region_bounds[idx].bounds); } if (!Realm::GenericAccessor<FT,N,T>::is_compatible(instance,fid,bounds)) region.report_incompatible_accessor("GenericAccessor", instance, fid); accessor = Realm::GenericAccessor<FT,N,T>(instance, fid, bounds, offset); } MultiRegionAccessor(const std::vector<PhysicalRegion> &regions, const Rect<N,T> source_bounds, FieldID fid, size_t actual_field_size = sizeof(FT), #ifdef DEBUG_LEGION bool check_field_size = true, #else bool check_field_size = false, #endif bool silence_warnings = false, const char *warning_string = NULL, size_t offset = 0) : field(fid), total_regions(regions.size()) { if (regions.empty()) return; assert(regions.size() <= MR); const PhysicalRegion &region = regions.front(); region_privileges[0] = region.get_privilege(); const Realm::RegionInstance instance = region.get_instance_info(region_privileges[0], fid, actual_field_size, &region_bounds[0], Internal::NT_TemplateHelper::encode_tag<N,T>(), warning_string, silence_warnings, true/*generic accessor*/, check_field_size); region_bounds[0].bounds = source_bounds.intersection(region_bounds[0].bounds); Rect<N,T> bounds = region_bounds[0].bounds; for (unsigned idx = 1; idx < regions.size(); idx++) { region_privileges[idx] = regions[idx].get_privilege(); const Realm::RegionInstance inst = regions[idx].get_instance_info( region_privileges[idx], fid, actual_field_size, &region_bounds[idx], Internal::NT_TemplateHelper::encode_tag<N,T>(), warning_string, silence_warnings, true/*generic accessor*/, check_field_size); if (inst != instance) region.report_incompatible_multi_accessor(idx, fid, instance, inst); region_bounds[idx].bounds = source_bounds.intersection(region_bounds[idx].bounds); bounds = bounds.union_bbox(region_bounds[idx].bounds); } if (!Realm::GenericAccessor<FT,N,T>::is_compatible(instance,fid,bounds)) region.report_incompatible_accessor("GenericAccessor", instance, fid); accessor = Realm::GenericAccessor<FT,N,T>(instance, fid, bounds, offset); } public: inline FT read(const Point<N,T>& p) const { bool found = false; for (unsigned idx = 0; idx < total_regions; idx++) { if (!region_bounds[idx].contains(p)) continue; if (CP && ((region_privileges[idx] & LEGION_READ_ONLY) == 0)) PhysicalRegion::fail_privilege_check(DomainPoint(p), field, region_privileges[idx]); found = true; break; } if (!found) PhysicalRegion::fail_bounds_check(DomainPoint(p), field, region_privileges[0], true/*multi*/); return accessor.read(p); } inline void write(const Point<N,T>& p, FT val) const { bool found = false; for (unsigned idx = 0; idx < total_regions; idx++) { if (!region_bounds[idx].contains(p)) continue; if (CP && ((region_privileges[idx] & LEGION_WRITE_PRIV) == 0)) PhysicalRegion::fail_privilege_check(DomainPoint(p), field, region_privileges[idx]); found = true; break; } if (!found) PhysicalRegion::fail_bounds_check(DomainPoint(p), field, region_privileges[0], true/*multi*/); return accessor.write(p, val); } inline ArraySyntax::AccessorRefHelper<FT,LEGION_NO_ACCESS> operator[](const Point<N,T>& p) const { int index = -1; for (unsigned idx = 0; idx < total_regions; idx++) { if (!region_bounds[idx].contains(p)) continue; index = idx; break; } if (index < 0) PhysicalRegion::fail_bounds_check(DomainPoint(p), field, region_privileges[0], true/*multi*/); return ArraySyntax::AccessorRefHelper<FT,LEGION_NO_ACCESS>( accessor[p], field, DomainPoint(p), region_privileges[index]); } inline ArraySyntax::GenericSyntaxHelper<MultiRegionAccessor<FT,N,T, Realm::GenericAccessor<FT,N,T>,CB,CP,MR>,FT,N,T,2,LEGION_NO_ACCESS> operator[](T index) const { return ArraySyntax::GenericSyntaxHelper<MultiRegionAccessor<FT,N,T, Realm::GenericAccessor<FT,N,T>,CB,CP,MR>,FT,N,T,2,LEGION_NO_ACCESS>( *this, Point<1,T>(index)); } public: mutable Realm::GenericAccessor<FT,N,T> accessor; FieldID field; PrivilegeMode region_privileges[MR]; DomainT<N,T> region_bounds[MR]; unsigned total_regions; public: typedef FT value_type; typedef FT& reference; typedef const FT& const_reference; static const int dim = N; }; // Multi-Accessor, generic, 1, bounds checks and/or privilege checks template<typename FT, typename T, bool CB, bool CP, int MR> class MultiRegionAccessor<FT,1,T,Realm::GenericAccessor<FT,1,T>,CB,CP,MR> { public: MultiRegionAccessor(void) { } public: template<typename InputIterator> MultiRegionAccessor(InputIterator start, InputIterator stop, FieldID fid, size_t actual_field_size = sizeof(FT), #ifdef DEBUG_LEGION bool check_field_size = true, #else bool check_field_size = false, #endif bool silence_warnings = false, const char *warning_string = NULL, size_t offset = 0) : field(fid) { if (start == stop) return; const PhysicalRegion &region = *start; region_privileges[0] = region.get_privilege(); const Realm::RegionInstance instance = region.get_instance_info( region_privileges[0], fid, actual_field_size, &region_bounds[0], Internal::NT_TemplateHelper::encode_tag<1,T>(), warning_string, silence_warnings, true/*generic accessor*/, check_field_size); Rect<1,T> bounds = region_bounds[0].bounds; unsigned idx = 1; while (++start != stop) { assert(idx < MR); region_privileges[idx] = start->get_privilege(); const Realm::RegionInstance inst = start->get_instance_info( region_privileges[idx], fid, actual_field_size, &region_bounds[idx], Internal::NT_TemplateHelper::encode_tag<1,T>(), warning_string, silence_warnings, true/*generic accessor*/, check_field_size); if (inst != instance) region.report_incompatible_multi_accessor(idx, fid, instance, inst); bounds = bounds.union_bbox(region_bounds[idx].bounds); idx++; } if (!Realm::GenericAccessor<FT,1,T>::is_compatible(instance,fid,bounds)) region.report_incompatible_accessor("GenericAccessor", instance, fid); accessor = Realm::GenericAccessor<FT,1,T>(instance, fid, bounds, offset); total_regions = idx; } template<typename InputIterator> MultiRegionAccessor(InputIterator start, InputIterator stop, const Rect<1,T> source_bounds, FieldID fid, size_t actual_field_size = sizeof(FT), #ifdef DEBUG_LEGION bool check_field_size = true, #else bool check_field_size = false, #endif bool silence_warnings = false, const char *warning_string = NULL, size_t offset = 0) : field(fid) { if (start == stop) return; const PhysicalRegion &region = *start; region_privileges[0] = region.get_privilege(); const Realm::RegionInstance instance = region.get_instance_info( region_privileges[0], fid, actual_field_size, &region_bounds[0], Internal::NT_TemplateHelper::encode_tag<1,T>(), warning_string, silence_warnings, true/*generic accessor*/, check_field_size); Rect<1,T> bounds = region_bounds[0].bounds; unsigned idx = 1; while (++start != stop) { assert(idx < MR); region_privileges[idx] = start->get_privilege(); const Realm::RegionInstance inst = start->get_instance_info( region_privileges[idx], fid, actual_field_size, &region_bounds[idx], Internal::NT_TemplateHelper::encode_tag<1,T>(), warning_string, silence_warnings, true/*generic accessor*/, check_field_size); if (inst != instance) region.report_incompatible_multi_accessor(idx, fid, instance, inst); region_bounds[idx].bounds = source_bounds.intersection(region_bounds[idx].bounds); bounds = bounds.union_bbox(region_bounds[idx].bounds); idx++; } if (!Realm::GenericAccessor<FT,1,T>::is_compatible(instance,fid,bounds)) region.report_incompatible_accessor("GenericAccessor", instance, fid); accessor = Realm::GenericAccessor<FT,1,T>(instance, fid, bounds, offset); total_regions = idx; } public: MultiRegionAccessor(const std::vector<PhysicalRegion> &regions, FieldID fid, size_t actual_field_size = sizeof(FT), #ifdef DEBUG_LEGION bool check_field_size = true, #else bool check_field_size = false, #endif bool silence_warnings = false, const char *warning_string = NULL, size_t offset = 0) : field(fid), total_regions(regions.size()) { if (regions.empty()) return; assert(regions.size() <= MR); const PhysicalRegion &region = regions.front(); region_privileges[0] = region.get_privilege(); const Realm::RegionInstance instance = region.get_instance_info(region_privileges[0], fid, actual_field_size, &region_bounds[0], Internal::NT_TemplateHelper::encode_tag<1,T>(), warning_string, silence_warnings, true/*generic accessor*/, check_field_size); Rect<1,T> bounds = region_bounds[0].bounds; for (unsigned idx = 1; idx < regions.size(); idx++) { region_privileges[idx] = regions[idx].get_privilege(); const Realm::RegionInstance inst = regions[idx].get_instance_info( region_privileges[idx], fid, actual_field_size, &region_bounds[idx], Internal::NT_TemplateHelper::encode_tag<1,T>(), warning_string, silence_warnings, true/*generic accessor*/, check_field_size); if (inst != instance) region.report_incompatible_multi_accessor(idx, fid, instance, inst); bounds = bounds.union_bbox(region_bounds[idx].bounds); } if (!Realm::GenericAccessor<FT,1,T>::is_compatible(instance,fid,bounds)) region.report_incompatible_accessor("GenericAccessor", instance, fid); accessor = Realm::GenericAccessor<FT,1,T>(instance, fid, bounds, offset); } MultiRegionAccessor(const std::vector<PhysicalRegion> &regions, const Rect<1,T> source_bounds, FieldID fid, size_t actual_field_size = sizeof(FT), #ifdef DEBUG_LEGION bool check_field_size = true, #else bool check_field_size = false, #endif bool silence_warnings = false, const char *warning_string = NULL, size_t offset = 0) : field(fid), total_regions(regions.size()) { if (regions.empty()) return; assert(regions.size() <= MR); const PhysicalRegion &region = regions.front(); region_privileges[0] = region.get_privilege(); const Realm::RegionInstance instance = region.get_instance_info(region_privileges[0], fid, actual_field_size, &region_bounds[0], Internal::NT_TemplateHelper::encode_tag<1,T>(), warning_string, silence_warnings, true/*generic accessor*/, check_field_size); region_bounds[0].bounds = source_bounds.intersection(region_bounds[0].bounds); Rect<1,T> bounds = region_bounds[0].bounds; for (unsigned idx = 1; idx < regions.size(); idx++) { region_privileges[idx] = regions[idx].get_privilege(); const Realm::RegionInstance inst = regions[idx].get_instance_info( region_privileges[idx], fid, actual_field_size, &region_bounds[idx], Internal::NT_TemplateHelper::encode_tag<1,T>(), warning_string, silence_warnings, true/*generic accessor*/, check_field_size); if (inst != instance) region.report_incompatible_multi_accessor(idx, fid, instance, inst); region_bounds[idx].bounds = source_bounds.intersection(region_bounds[idx].bounds); bounds = bounds.union_bbox(region_bounds[idx].bounds); } if (!Realm::GenericAccessor<FT,1,T>::is_compatible(instance,fid,bounds)) region.report_incompatible_accessor("GenericAccessor", instance, fid); accessor = Realm::GenericAccessor<FT,1,T>(instance, fid, bounds, offset); } public: inline FT read(const Point<1,T>& p) const { bool found = false; for (unsigned idx = 0; idx < total_regions; idx++) { if (!region_bounds[idx].contains(p)) continue; if (CP && ((region_privileges[idx] & LEGION_READ_ONLY) == 0)) PhysicalRegion::fail_privilege_check(DomainPoint(p), field, region_privileges[idx]); found = true; break; } if (!found) PhysicalRegion::fail_bounds_check(DomainPoint(p), field, region_privileges[0], true/*multi*/); return accessor.read(p); } inline void write(const Point<1,T>& p, FT val) const { bool found = false; for (unsigned idx = 0; idx < total_regions; idx++) { if (!region_bounds[idx].contains(p)) continue; if (CP && ((region_privileges[idx] & LEGION_WRITE_PRIV) == 0)) PhysicalRegion::fail_privilege_check(DomainPoint(p), field, region_privileges[idx]); found = true; break; } if (!found) PhysicalRegion::fail_bounds_check(DomainPoint(p), field, region_privileges[0], true/*multi*/); return accessor.write(p, val); } inline ArraySyntax::AccessorRefHelper<FT,LEGION_NO_ACCESS> operator[](const Point<1,T>& p) const { int index = -1; for (unsigned idx = 0; idx < total_regions; idx++) { if (!region_bounds[idx].contains(p)) continue; index = idx; break; } if (index < 0) PhysicalRegion::fail_bounds_check(DomainPoint(p), field, region_privileges[0], true/*multi*/); return ArraySyntax::AccessorRefHelper<FT,LEGION_NO_ACCESS>( accessor[p], field, DomainPoint(p), region_privileges[index]); } public: mutable Realm::GenericAccessor<FT,1,T> accessor; FieldID field; PrivilegeMode region_privileges[MR]; DomainT<1,T> region_bounds[MR]; unsigned total_regions; public: typedef FT value_type; typedef FT& reference; typedef const FT& const_reference; static const int dim = 1; }; // Multi-Accessor, generic, N, no bounds, no privileges template<typename FT, int N, typename T, int MR> class MultiRegionAccessor<FT,N,T,Realm::GenericAccessor<FT,N,T>, false,false,MR> { public: MultiRegionAccessor(void) { } public: template<typename InputIterator> MultiRegionAccessor(InputIterator start, InputIterator stop, FieldID fid, size_t actual_field_size = sizeof(FT), #ifdef DEBUG_LEGION bool check_field_size = true, #else bool check_field_size = false, #endif bool silence_warnings = false, const char *warning_string = NULL, size_t offset = 0) { if (start == stop) return; DomainT<N,T> is; const PhysicalRegion &region = *start; const Realm::RegionInstance instance = region.get_instance_info(region.get_privilege(), fid, actual_field_size, &is, Internal::NT_TemplateHelper::encode_tag<N,T>(), warning_string, silence_warnings, true/*generic accessor*/, check_field_size); Rect<N,T> bounds = is.bounds; unsigned idx = 1; while (++start != stop) { assert(idx < MR); const Realm::RegionInstance inst = start->get_instance_info( start->get_privilege(), fid, actual_field_size, &is, Internal::NT_TemplateHelper::encode_tag<N,T>(), warning_string, silence_warnings, true/*generic accessor*/, check_field_size); if (inst != instance) region.report_incompatible_multi_accessor(idx, fid, instance, inst); bounds = bounds.union_bbox(is.bounds); idx++; } if (!Realm::GenericAccessor<FT,N,T>::is_compatible(instance,fid,bounds)) region.report_incompatible_accessor("GenericAccessor", instance, fid); accessor = Realm::GenericAccessor<FT,N,T>(instance, fid, bounds, offset); } template<typename InputIterator> MultiRegionAccessor(InputIterator start, InputIterator stop, const Rect<N,T> source_bounds, FieldID fid, size_t actual_field_size = sizeof(FT), #ifdef DEBUG_LEGION bool check_field_size = true, #else bool check_field_size = false, #endif bool silence_warnings = false, const char *warning_string = NULL, size_t offset = 0) { if (start == stop) return; DomainT<N,T> is; const PhysicalRegion &region = *start; const Realm::RegionInstance instance = region.get_instance_info(start->get_privilege(), fid, actual_field_size, &is, Internal::NT_TemplateHelper::encode_tag<N,T>(), warning_string, silence_warnings, true/*generic accessor*/, check_field_size); Rect<N,T> bounds = source_bounds.intersection(is.bounds); unsigned idx = 1; while (++start != stop) { assert(idx < MR); const Realm::RegionInstance inst = start->get_instance_info( start->get_privilege(), fid, actual_field_size, &is, Internal::NT_TemplateHelper::encode_tag<N,T>(), warning_string, silence_warnings, true/*generic accessor*/, check_field_size); if (inst != instance) region.report_incompatible_multi_accessor(idx, fid, instance, inst); bounds = bounds.union_bbox(source_bounds.intersection(is.bounds)); idx++; } if (!Realm::GenericAccessor<FT,N,T>::is_compatible(instance,fid,bounds)) region.report_incompatible_accessor("GenericAccessor", instance, fid); accessor = Realm::GenericAccessor<FT,N,T>(instance, fid, bounds, offset); } public: MultiRegionAccessor(const std::vector<PhysicalRegion> &regions, FieldID fid, size_t actual_field_size = sizeof(FT), #ifdef DEBUG_LEGION bool check_field_size = true, #else bool check_field_size = false, #endif bool silence_warnings = false, const char *warning_string = NULL, size_t offset = 0) { if (regions.empty()) return; DomainT<N,T> is; const PhysicalRegion &region = regions.front(); const Realm::RegionInstance instance = region.get_instance_info(region.get_privilege(), fid, actual_field_size, &is, Internal::NT_TemplateHelper::encode_tag<N,T>(), warning_string, silence_warnings, true/*generic accessor*/, check_field_size); Rect<N,T> bounds = is.bounds; for (unsigned idx = 1; idx < regions.size(); idx++) { const Realm::RegionInstance inst = regions[idx].get_instance_info( regions[idx].get_privilege(), fid, actual_field_size, &is, Internal::NT_TemplateHelper::encode_tag<N,T>(), warning_string, silence_warnings, true/*generic accessor*/, check_field_size); if (inst != instance) region.report_incompatible_multi_accessor(idx, fid, instance, inst); bounds = bounds.union_bbox(is.bounds); } if (!Realm::GenericAccessor<FT,N,T>::is_compatible(instance,fid,bounds)) region.report_incompatible_accessor("GenericAccessor", instance, fid); accessor = Realm::GenericAccessor<FT,N,T>(instance, fid, bounds, offset); } MultiRegionAccessor(const std::vector<PhysicalRegion> &regions, const Rect<N,T> source_bounds, FieldID fid, size_t actual_field_size = sizeof(FT), #ifdef DEBUG_LEGION bool check_field_size = true, #else bool check_field_size = false, #endif bool silence_warnings = false, const char *warning_string = NULL, size_t offset = 0) { if (regions.empty()) return; DomainT<N,T> is; const PhysicalRegion &region = regions.front(); const Realm::RegionInstance instance = region.get_instance_info(region.get_privilege(), fid, actual_field_size, &is, Internal::NT_TemplateHelper::encode_tag<N,T>(), warning_string, silence_warnings, true/*generic accessor*/, check_field_size); Rect<N,T> bounds = source_bounds.intersection(is.bounds); for (unsigned idx = 1; idx < regions.size(); idx++) { const Realm::RegionInstance inst = regions[idx].get_instance_info( regions[idx].get_privilege(), fid, actual_field_size, &is, Internal::NT_TemplateHelper::encode_tag<N,T>(), warning_string, silence_warnings, true/*generic accessor*/, check_field_size); if (inst != instance) region.report_incompatible_multi_accessor(idx, fid, instance, inst); bounds = bounds.union_bbox(source_bounds.intersection(is.bounds)); } if (!Realm::GenericAccessor<FT,N,T>::is_compatible(instance,fid,bounds)) region.report_incompatible_accessor("GenericAccessor", instance, fid); accessor = Realm::GenericAccessor<FT,N,T>(instance, fid, bounds, offset); } public: inline FT read(const Point<N,T>& p) const { return accessor.read(p); } inline void write(const Point<N,T>& p, FT val) const { return accessor.write(p, val); } inline ArraySyntax::AccessorRefHelper<FT,LEGION_READ_WRITE> operator[](const Point<N,T>& p) const { return ArraySyntax::AccessorRefHelper<FT,LEGION_READ_WRITE>( accessor[p]); } inline ArraySyntax::GenericSyntaxHelper<MultiRegionAccessor<FT,N,T, Realm::GenericAccessor<FT,N,T>,false,false,MR>, FT,N,T,2,LEGION_READ_WRITE> operator[](T index) const { return ArraySyntax::GenericSyntaxHelper<MultiRegionAccessor<FT,N,T, Realm::GenericAccessor<FT,N,T>,false,false,MR>, FT,N,T,2,LEGION_READ_WRITE>( *this, Point<1,T>(index)); } public: mutable Realm::GenericAccessor<FT,N,T> accessor; public: typedef FT value_type; typedef FT& reference; typedef const FT& const_reference; static const int dim = N; }; // Multi-Accessor, generic, 1, no bounds, no privileges template<typename FT, typename T, int MR> class MultiRegionAccessor<FT,1,T,Realm::GenericAccessor<FT,1,T>, false,false,MR> { public: MultiRegionAccessor(void) { } public: template<typename InputIterator> MultiRegionAccessor(InputIterator start, InputIterator stop, FieldID fid, size_t actual_field_size = sizeof(FT), #ifdef DEBUG_LEGION bool check_field_size = true, #else bool check_field_size = false, #endif bool silence_warnings = false, const char *warning_string = NULL, size_t offset = 0) { if (start == stop) return; DomainT<1,T> is; const PhysicalRegion &region = *start; const Realm::RegionInstance instance = region.get_instance_info(region.get_privilege(), fid, actual_field_size, &is, Internal::NT_TemplateHelper::encode_tag<1,T>(), warning_string, silence_warnings, true/*generic accessor*/, check_field_size); Rect<1,T> bounds = is.bounds; unsigned idx = 1; while (++start != stop) { assert(idx < MR); const Realm::RegionInstance inst = start->get_instance_info( start->get_privilege(), fid, actual_field_size, &is, Internal::NT_TemplateHelper::encode_tag<1,T>(), warning_string, silence_warnings, true/*generic accessor*/, check_field_size); if (inst != instance) region.report_incompatible_multi_accessor(idx, fid, instance, inst); bounds = bounds.union_bbox(is.bounds); idx++; } if (!Realm::GenericAccessor<FT,1,T>::is_compatible(instance,fid,bounds)) region.report_incompatible_accessor("GenericAccessor", instance, fid); accessor = Realm::GenericAccessor<FT,1,T>(instance, fid, bounds, offset); } template<typename InputIterator> MultiRegionAccessor(InputIterator start, InputIterator stop, const Rect<1,T> source_bounds, FieldID fid, size_t actual_field_size = sizeof(FT), #ifdef DEBUG_LEGION bool check_field_size = true, #else bool check_field_size = false, #endif bool silence_warnings = false, const char *warning_string = NULL, size_t offset = 0) { if (start == stop) return; DomainT<1,T> is; const PhysicalRegion &region = *start; const Realm::RegionInstance instance = region.get_instance_info(start->get_privilege(), fid, actual_field_size, &is, Internal::NT_TemplateHelper::encode_tag<1,T>(), warning_string, silence_warnings, true/*generic accessor*/, check_field_size); Rect<1,T> bounds = source_bounds.intersection(is.bounds); unsigned idx = 1; while (++start != stop) { assert(idx < MR); const Realm::RegionInstance inst = start->get_instance_info( start->get_privilege(), fid, actual_field_size, &is, Internal::NT_TemplateHelper::encode_tag<1,T>(), warning_string, silence_warnings, true/*generic accessor*/, check_field_size); if (inst != instance) region.report_incompatible_multi_accessor(idx, fid, instance, inst); bounds = bounds.union_bbox(source_bounds.intersection(is.bounds)); idx++; } if (!Realm::GenericAccessor<FT,1,T>::is_compatible(instance,fid,bounds)) region.report_incompatible_accessor("GenericAccessor", instance, fid); accessor = Realm::GenericAccessor<FT,1,T>(instance, fid, bounds, offset); } public: MultiRegionAccessor(const std::vector<PhysicalRegion> &regions, FieldID fid, size_t actual_field_size = sizeof(FT), #ifdef DEBUG_LEGION bool check_field_size = true, #else bool check_field_size = false, #endif bool silence_warnings = false, const char *warning_string = NULL, size_t offset = 0) { if (regions.empty()) return; DomainT<1,T> is; const PhysicalRegion &region = regions.front(); const Realm::RegionInstance instance = region.get_instance_info(region.get_privilege(), fid, actual_field_size, &is, Internal::NT_TemplateHelper::encode_tag<1,T>(), warning_string, silence_warnings, true/*generic accessor*/, check_field_size); Rect<1,T> bounds = is.bounds; for (unsigned idx = 1; idx < regions.size(); idx++) { const Realm::RegionInstance inst = regions[idx].get_instance_info( regions[idx].get_privilege(), fid, actual_field_size, &is, Internal::NT_TemplateHelper::encode_tag<1,T>(), warning_string, silence_warnings, true/*generic accessor*/, check_field_size); if (inst != instance) region.report_incompatible_multi_accessor(idx, fid, instance, inst); bounds = bounds.union_bbox(is.bounds); } if (!Realm::GenericAccessor<FT,1,T>::is_compatible(instance,fid,bounds)) region.report_incompatible_accessor("GenericAccessor", instance, fid); accessor = Realm::GenericAccessor<FT,1,T>(instance, fid, bounds, offset); } MultiRegionAccessor(const std::vector<PhysicalRegion> &regions, const Rect<1,T> source_bounds, FieldID fid, size_t actual_field_size = sizeof(FT), #ifdef DEBUG_LEGION bool check_field_size = true, #else bool check_field_size = false, #endif bool silence_warnings = false, const char *warning_string = NULL, size_t offset = 0) { if (regions.empty()) return; DomainT<1,T> is; const PhysicalRegion &region = regions.front(); const Realm::RegionInstance instance = region.get_instance_info(region.get_privilege(), fid, actual_field_size, &is, Internal::NT_TemplateHelper::encode_tag<1,T>(), warning_string, silence_warnings, true/*generic accessor*/, check_field_size); Rect<1,T> bounds = source_bounds.intersection(is.bounds); for (unsigned idx = 1; idx < regions.size(); idx++) { const Realm::RegionInstance inst = regions[idx].get_instance_info( regions[idx].get_privilege(), fid, actual_field_size, &is, Internal::NT_TemplateHelper::encode_tag<1,T>(), warning_string, silence_warnings, true/*generic accessor*/, check_field_size); if (inst != instance) region.report_incompatible_multi_accessor(idx, fid, instance, inst); bounds = bounds.union_bbox(source_bounds.intersection(is.bounds)); } if (!Realm::GenericAccessor<FT,1,T>::is_compatible(instance,fid,bounds)) region.report_incompatible_accessor("GenericAccessor", instance, fid); accessor = Realm::GenericAccessor<FT,1,T>(instance, fid, bounds, offset); } public: inline FT read(const Point<1,T>& p) const { return accessor.read(p); } inline void write(const Point<1,T>& p, FT val) const { return accessor.write(p, val); } inline ArraySyntax::AccessorRefHelper<FT,LEGION_READ_WRITE> operator[](const Point<1,T>& p) const { return ArraySyntax::AccessorRefHelper<FT,LEGION_READ_WRITE>( accessor[p]); } public: mutable Realm::GenericAccessor<FT,1,T> accessor; public: typedef FT value_type; typedef FT& reference; typedef const FT& const_reference; static const int dim = 1; }; //////////////////////////////////////////////////////////// // Multi Region Accessor with Affine Accessors //////////////////////////////////////////////////////////// // Multi-Accessor, affine, N, with privilege checks (implies bounds checks) template<typename FT, int N, typename T, bool CB, int MR> class MultiRegionAccessor<FT,N,T,Realm::AffineAccessor<FT,N,T>,CB,true,MR> { public: MultiRegionAccessor(void) { } public: template<typename InputIterator> MultiRegionAccessor(InputIterator start, InputIterator stop, FieldID fid, size_t actual_field_size = sizeof(FT), #ifdef DEBUG_LEGION bool check_field_size = true, #else bool check_field_size = false, #endif bool silence_warnings = false, const char *warning_string = NULL, size_t offset = 0) : field(fid) { if (start == stop) return; DomainT<N,T> is; const PhysicalRegion &region = *start; region_privileges[0] = region.get_privilege(); const Realm::RegionInstance instance = region.get_instance_info(region_privileges[0], fid, actual_field_size, &is, Internal::NT_TemplateHelper::encode_tag<N,T>(), warning_string, silence_warnings, false/*generic accessor*/, check_field_size); region_bounds[0] = AffineBounds::Tester<N,T>(is); Rect<N,T> bounds = is.bounds; unsigned idx = 1; while (++start != stop) { assert(idx < MR); region_privileges[idx] = start->get_privilege(); const Realm::RegionInstance inst = start->get_instance_info( region_privileges[idx], fid, actual_field_size, &is, Internal::NT_TemplateHelper::encode_tag<N,T>(), warning_string, silence_warnings, false/*generic accessor*/, check_field_size); if (inst != instance) region.report_incompatible_multi_accessor(idx, fid, instance, inst); region_bounds[idx] = AffineBounds::Tester<N,T>(is); bounds = bounds.union_bbox(is.bounds); idx++; } if (!Realm::AffineAccessor<FT,N,T>::is_compatible(instance,fid,bounds)) region.report_incompatible_accessor("AffineAccessor", instance, fid); accessor = Realm::AffineAccessor<FT,N,T>(instance, fid, bounds, offset); total_regions = idx; } template<typename InputIterator> MultiRegionAccessor(InputIterator start, InputIterator stop, const Rect<N,T> source_bounds, FieldID fid, size_t actual_field_size = sizeof(FT), #ifdef DEBUG_LEGION bool check_field_size = true, #else bool check_field_size = false, #endif bool silence_warnings = false, const char *warning_string = NULL, size_t offset = 0) : field(fid) { if (start == stop) return; DomainT<N,T> is; const PhysicalRegion &region = *start; region_privileges[0] = region.get_privilege(); const Realm::RegionInstance instance = region.get_instance_info(region_privileges[0], fid, actual_field_size, &is, Internal::NT_TemplateHelper::encode_tag<N,T>(), warning_string, silence_warnings, false/*generic accessor*/, check_field_size); region_bounds[0] = AffineBounds::Tester<N,T>(is, source_bounds); Rect<N,T> bounds = source_bounds.intersection(is.bounds); unsigned idx = 1; while (++start != stop) { assert(idx < MR); region_privileges[idx] = start->get_privilege(); const Realm::RegionInstance inst = start->get_instance_info( region_privileges[idx], fid, actual_field_size, &is, Internal::NT_TemplateHelper::encode_tag<N,T>(), warning_string, silence_warnings, false/*generic accessor*/, check_field_size); if (inst != instance) region.report_incompatible_multi_accessor(idx, fid, instance, inst); region_bounds[idx] = AffineBounds::Tester<N,T>(is, source_bounds); bounds = bounds.union_bbox(source_bounds.inersection(is.bounds)); idx++; } if (!Realm::AffineAccessor<FT,N,T>::is_compatible(instance,fid,bounds)) region.report_incompatible_accessor("AffineAccessor", instance, fid); accessor = Realm::AffineAccessor<FT,N,T>(instance, fid, bounds, offset); total_regions = idx; } template<int M, typename InputIterator> MultiRegionAccessor(InputIterator start, InputIterator stop, const AffineTransform<M,N,T> transform, FieldID fid, size_t actual_field_size = sizeof(FT), #ifdef DEBUG_LEGION bool check_field_size = true, #else bool check_field_size = false, #endif bool silence_warnings = false, const char *warning_string = NULL, size_t offset = 0) : field(fid) { if (start == stop) return; DomainT<N,T> is; const PhysicalRegion &region = *start; region_privileges[0] = region.get_privilege(); const Realm::RegionInstance instance = region.get_instance_info(region_privileges[0], fid, actual_field_size, &is, Internal::NT_TemplateHelper::encode_tag<N,T>(), warning_string, silence_warnings, false/*generic accessor*/, check_field_size); region_bounds[0] = AffineBounds::Tester<N,T>(is, transform); Rect<N,T> bounds = is.bounds; unsigned idx = 1; while (++start != stop) { assert(idx < MR); region_privileges[idx] = start->get_privilege(); const Realm::RegionInstance inst = start->get_instance_info( region_privileges[idx], fid, actual_field_size, &is, Internal::NT_TemplateHelper::encode_tag<N,T>(), warning_string, silence_warnings, false/*generic accessor*/, check_field_size); if (inst != instance) region.report_incompatible_multi_accessor(idx, fid, instance, inst); region_bounds[idx] = AffineBounds::Tester<N,T>(is, transform); bounds = bounds.union_bbox(is.bounds); idx++; } if (!Realm::AffineAccessor<FT,N,T>::is_compatible(instance, transform.transform, transform.offset, fid, bounds)) region.report_incompatible_accessor("AffineAccessor", instance, fid); accessor = Realm::AffineAccessor<FT,N,T>(instance, transform.transform, transform.offset, fid, bounds, offset); total_regions = idx; } template<int M, typename InputIterator> MultiRegionAccessor(InputIterator start, InputIterator stop, const AffineTransform<M,N,T> transform, const Rect<N,T> source_bounds, FieldID fid, // The actual field size in case it is different from the // one being used in FT and we still want to check it size_t actual_field_size = sizeof(FT), #ifdef DEBUG_LEGION bool check_field_size = true, #else bool check_field_size = false, #endif bool silence_warnings = false, const char *warning_string = NULL, size_t offset = 0) : field(fid) { if (start == stop) return; DomainT<N,T> is; const PhysicalRegion &region = *start; region_privileges[0] = region.get_privilege(); const Realm::RegionInstance instance = region.get_instance_info(region_privileges[0], fid, actual_field_size, &is, Internal::NT_TemplateHelper::encode_tag<N,T>(), warning_string, silence_warnings, false/*generic accessor*/, check_field_size); region_bounds[0] =AffineBounds::Tester<N,T>(is,source_bounds,transform); Rect<N,T> bounds = source_bounds.intersection(is.bounds); unsigned idx = 1; while (++start != stop) { assert(idx < MR); region_privileges[idx] = start->get_privilege(); const Realm::RegionInstance inst = start->get_instance_info( region_privileges[idx], fid, actual_field_size, &is, Internal::NT_TemplateHelper::encode_tag<N,T>(), warning_string, silence_warnings, false/*generic accessor*/, check_field_size); if (inst != instance) region.report_incompatible_multi_accessor(idx, fid, instance, inst); region_bounds[idx] = AffineBounds::Tester<N,T>(is, transform, source_bounds); bounds = bounds.union_bbox(source_bounds.inersection(is.bounds)); idx++; } if (!Realm::AffineAccessor<FT,N,T>::is_compatible(instance, transform.transform, transform.offset, fid, bounds)) region.report_incompatible_accessor("AffineAccessor", instance, fid); accessor = Realm::AffineAccessor<FT,N,T>(instance, transform.transform, transform.offset, fid, bounds, offset); total_regions = idx; } public: MultiRegionAccessor(const std::vector<PhysicalRegion> &regions, FieldID fid, size_t actual_field_size = sizeof(FT), #ifdef DEBUG_LEGION bool check_field_size = true, #else bool check_field_size = false, #endif bool silence_warnings = false, const char *warning_string = NULL, size_t offset = 0) : field(fid), total_regions(regions.size()) { if (regions.empty()) return; DomainT<N,T> is; const PhysicalRegion &region = regions.front(); region_privileges[0] = region.get_privilege(); const Realm::RegionInstance instance = region.get_instance_info(region_privileges[0], fid, actual_field_size, &is, Internal::NT_TemplateHelper::encode_tag<N,T>(), warning_string, silence_warnings, false/*generic accessor*/, check_field_size); region_bounds[0] = AffineBounds::Tester<N,T>(is); Rect<N,T> bounds = is.bounds; for (unsigned idx = 1; idx < regions.size(); idx++) { region_privileges[idx] = regions[idx].get_privilege(); const Realm::RegionInstance inst = regions[idx].get_instance_info( region_privileges[idx], fid, actual_field_size, &is, Internal::NT_TemplateHelper::encode_tag<N,T>(), warning_string, silence_warnings, false/*generic accessor*/, check_field_size); if (inst != instance) region.report_incompatible_multi_accessor(idx, fid, instance, inst); region_bounds[idx] = AffineBounds::Tester<N,T>(is); bounds = bounds.union_bbox(is.bounds); } if (!Realm::AffineAccessor<FT,N,T>::is_compatible(instance,fid,bounds)) region.report_incompatible_accessor("AffineAccessor", instance, fid); accessor = Realm::AffineAccessor<FT,N,T>(instance, fid, bounds, offset); } MultiRegionAccessor(const std::vector<PhysicalRegion> &regions, const Rect<N,T> source_bounds, FieldID fid, size_t actual_field_size = sizeof(FT), #ifdef DEBUG_LEGION bool check_field_size = true, #else bool check_field_size = false, #endif bool silence_warnings = false, const char *warning_string = NULL, size_t offset = 0) : field(fid), total_regions(regions.size()) { if (regions.empty()) return; DomainT<N,T> is; const PhysicalRegion &region = regions.front(); region_privileges[0] = region.get_privilege(); const Realm::RegionInstance instance = region.get_instance_info(region_privileges[0], fid, actual_field_size, &is, Internal::NT_TemplateHelper::encode_tag<N,T>(), warning_string, silence_warnings, false/*generic accessor*/, check_field_size); region_bounds[0] = AffineBounds::Tester<N,T>(is, source_bounds); Rect<N,T> bounds = source_bounds.intersection(is.bounds); for (unsigned idx = 1; idx < regions.size(); idx++) { region_privileges[idx] = regions[idx].get_privilege(); const Realm::RegionInstance inst = regions[idx].get_instance_info( region_privileges[idx], fid, actual_field_size, &is, Internal::NT_TemplateHelper::encode_tag<N,T>(), warning_string, silence_warnings, false/*generic accessor*/, check_field_size); if (inst != instance) region.report_incompatible_multi_accessor(idx, fid, instance, inst); region_bounds[idx] = AffineBounds::Tester<N,T>(is, source_bounds); bounds = bounds.union_bbox(source_bounds.inersection(is.bounds)); } if (!Realm::AffineAccessor<FT,N,T>::is_compatible(instance,fid,bounds)) region.report_incompatible_accessor("AffineAccessor", instance, fid); accessor = Realm::AffineAccessor<FT,N,T>(instance, fid, bounds, offset); } template<int M> MultiRegionAccessor(const std::vector<PhysicalRegion> &regions, const AffineTransform<M,N,T> transform, FieldID fid, size_t actual_field_size = sizeof(FT), #ifdef DEBUG_LEGION bool check_field_size = true, #else bool check_field_size = false, #endif bool silence_warnings = false, const char *warning_string = NULL, size_t offset = 0) : field(fid), total_regions(regions.size()) { if (regions.empty()) return; DomainT<N,T> is; const PhysicalRegion &region = regions.front(); region_privileges[0] = region.get_privilege(); const Realm::RegionInstance instance = region.get_instance_info(region_privileges[0], fid, actual_field_size, &is, Internal::NT_TemplateHelper::encode_tag<N,T>(), warning_string, silence_warnings, false/*generic accessor*/, check_field_size); region_bounds[0] = AffineBounds::Tester<N,T>(is, transform); Rect<N,T> bounds = is.bounds; for (unsigned idx = 1; idx < regions.size(); idx++) { region_privileges[idx] = regions[idx].get_privilege(); const Realm::RegionInstance inst = regions[idx].get_instance_info( region_privileges[idx], fid, actual_field_size, &is, Internal::NT_TemplateHelper::encode_tag<N,T>(), warning_string, silence_warnings, false/*generic accessor*/, check_field_size); if (inst != instance) region.report_incompatible_multi_accessor(idx, fid, instance, inst); region_bounds[idx] = AffineBounds::Tester<N,T>(is, transform); bounds = bounds.union_bbox(is.bounds); } if (!Realm::AffineAccessor<FT,N,T>::is_compatible(instance, transform.transform, transform.offset, fid, bounds)) region.report_incompatible_accessor("AffineAccessor", instance, fid); accessor = Realm::AffineAccessor<FT,N,T>(instance, transform.transform, transform.offset, fid, bounds, offset); } template<int M> MultiRegionAccessor(const std::vector<PhysicalRegion> &regions, const AffineTransform<M,N,T> transform, const Rect<N,T> source_bounds, FieldID fid, // The actual field size in case it is different from the // one being used in FT and we still want to check it size_t actual_field_size = sizeof(FT), #ifdef DEBUG_LEGION bool check_field_size = true, #else bool check_field_size = false, #endif bool silence_warnings = false, const char *warning_string = NULL, size_t offset = 0) : field(fid), total_regions(regions.size()) { if (regions.empty()) return; DomainT<N,T> is; const PhysicalRegion &region = regions.front(); region_privileges[0] = region.get_privilege(); const Realm::RegionInstance instance = region.get_instance_info(region_privileges[0], fid, actual_field_size, &is, Internal::NT_TemplateHelper::encode_tag<N,T>(), warning_string, silence_warnings, false/*generic accessor*/, check_field_size); region_bounds[0] =AffineBounds::Tester<N,T>(is,source_bounds,transform); Rect<N,T> bounds = source_bounds.intersection(is.bounds); for (unsigned idx = 1; idx < regions.size(); idx++) { region_privileges[idx] = regions[idx].get_privilege(); const Realm::RegionInstance inst = regions[idx].get_instance_info( region_privileges[idx], fid, actual_field_size, &is, Internal::NT_TemplateHelper::encode_tag<N,T>(), warning_string, silence_warnings, false/*generic accessor*/, check_field_size); if (inst != instance) region.report_incompatible_multi_accessor(idx, fid, instance, inst); region_bounds[idx] = AffineBounds::Tester<N,T>(is, transform, source_bounds); bounds = bounds.union_bbox(source_bounds.inersection(is.bounds)); } if (!Realm::AffineAccessor<FT,N,T>::is_compatible(instance, transform.transform, transform.offset, fid, bounds)) region.report_incompatible_accessor("AffineAccessor", instance, fid); accessor = Realm::AffineAccessor<FT,N,T>(instance, transform.transform, transform.offset, fid, bounds, offset); } public: __CUDA_HD__ inline FT read(const Point<N,T>& p) const { bool found = false; for (unsigned idx = 0; idx < total_regions; idx++) { if (!region_bounds[idx].contains(p)) continue; if ((region_privileges[idx] & LEGION_READ_ONLY) == 0) { #ifdef __CUDA_ARCH__ // bounds checks are not precise for CUDA so keep going to // see if there is another region that has it with the privileges continue; #else PhysicalRegion::fail_privilege_check(DomainPoint(p), field, region_privileges[idx]); #endif } found = true; break; } #ifdef __CUDA_ARCH__ assert(found); #else if (!found) PhysicalRegion::fail_bounds_check(DomainPoint(p), field, region_privileges[0], true/*multi*/); #endif return accessor.read(p); } __CUDA_HD__ inline void write(const Point<N,T>& p, FT val) const { bool found = false; for (unsigned idx = 0; idx < total_regions; idx++) { if (!region_bounds[idx].contains(p)) continue; if ((region_privileges[idx] & LEGION_WRITE_PRIV) == 0) { #ifdef __CUDA_ARCH__ // bounds checks are not precise for CUDA so keep going to // see if there is another region that has it with the privileges continue; #else PhysicalRegion::fail_privilege_check(DomainPoint(p), field, region_privileges[idx]); #endif } found = true; break; } #ifdef __CUDA_ARCH__ assert(found); #else if (!found) PhysicalRegion::fail_bounds_check(DomainPoint(p), field, region_privileges[0], true/*multi*/); #endif return accessor.write(p, val); } __CUDA_HD__ inline ArraySyntax::AffineRefHelper<FT> operator[](const Point<N,T>& p) const { int index = -1; for (unsigned idx = 0; idx < total_regions; idx++) { if (!region_bounds[idx].contains(p)) continue; index = idx; break; } #ifdef __CUDA_ARCH__ assert(index >= 0); #else if (index < 0) PhysicalRegion::fail_bounds_check(DomainPoint(p), field, region_privileges[0], true/*multi*/); #endif return ArraySyntax::AffineRefHelper<FT>(accessor[p], field, DomainPoint(p), region_privileges[index]); } __CUDA_HD__ inline ArraySyntax::AffineSyntaxHelper<MultiRegionAccessor<FT,N,T, Realm::AffineAccessor<FT,N,T>,CB,true,MR>,FT,N,T,2,LEGION_NO_ACCESS> operator[](T index) const { return ArraySyntax::AffineSyntaxHelper<MultiRegionAccessor<FT,N,T, Realm::AffineAccessor<FT,N,T>,CB,true,MR>,FT,N,T,2,LEGION_NO_ACCESS>( *this, Point<1,T>(index)); } template<typename REDOP, bool EXCLUSIVE> __CUDA_HD__ inline void reduce(const Point<N,T>& p, typename REDOP::RHS val) const { bool found = false; for (unsigned idx = 0; idx < total_regions; idx++) { if (!region_bounds[idx].contains(p)) continue; if ((region_privileges[idx] & LEGION_REDUCE_PRIV) == 0) { #ifdef __CUDA_ARCH__ // bounds checks are not precise for CUDA so keep going to // see if there is another region that has it with the privileges continue; #else PhysicalRegion::fail_privilege_check(DomainPoint(p), field, region_privileges[idx]); #endif } found = true; break; } #ifdef __CUDA_ARCH__ assert(found); #else if (!found) PhysicalRegion::fail_bounds_check(DomainPoint(p), field, region_privileges[0], true/*multi*/); #endif REDOP::template apply<EXCLUSIVE>(accessor[p], val); } public: Realm::AffineAccessor<FT,N,T> accessor; FieldID field; PrivilegeMode region_privileges[MR]; AffineBounds::Tester<N,T> region_bounds[MR]; unsigned total_regions; public: typedef FT value_type; typedef FT& reference; typedef const FT& const_reference; static const int dim = N; }; // Multi-Accessor, affine, 1, with privilege checks (implies bounds checks) template<typename FT, typename T, bool CB, int MR> class MultiRegionAccessor<FT,1,T,Realm::AffineAccessor<FT,1,T>,CB,true,MR> { public: MultiRegionAccessor(void) { } public: template<typename InputIterator> MultiRegionAccessor(InputIterator start, InputIterator stop, FieldID fid, size_t actual_field_size = sizeof(FT), #ifdef DEBUG_LEGION bool check_field_size = true, #else bool check_field_size = false, #endif bool silence_warnings = false, const char *warning_string = NULL, size_t offset = 0) : field(fid) { if (start == stop) return; DomainT<1,T> is; const PhysicalRegion &region = *start; region_privileges[0] = region.get_privilege(); const Realm::RegionInstance instance = region.get_instance_info(region_privileges[0], fid, actual_field_size, &is, Internal::NT_TemplateHelper::encode_tag<1,T>(), warning_string, silence_warnings, false/*generic accessor*/, check_field_size); region_bounds[0] = AffineBounds::Tester<1,T>(is); Rect<1,T> bounds = is.bounds; unsigned idx = 1; while (++start != stop) { assert(idx < MR); region_privileges[idx] = start->get_privilege(); const Realm::RegionInstance inst = start->get_instance_info( region_privileges[idx], fid, actual_field_size, &is, Internal::NT_TemplateHelper::encode_tag<1,T>(), warning_string, silence_warnings, false/*generic accessor*/, check_field_size); if (inst != instance) region.report_incompatible_multi_accessor(idx, fid, instance, inst); region_bounds[idx] = AffineBounds::Tester<1,T>(is); bounds = bounds.union_bbox(is.bounds); idx++; } if (!Realm::AffineAccessor<FT,1,T>::is_compatible(instance,fid,bounds)) region.report_incompatible_accessor("AffineAccessor", instance, fid); accessor = Realm::AffineAccessor<FT,1,T>(instance, fid, bounds, offset); total_regions = idx; } template<typename InputIterator> MultiRegionAccessor(InputIterator start, InputIterator stop, const Rect<1,T> source_bounds, FieldID fid, size_t actual_field_size = sizeof(FT), #ifdef DEBUG_LEGION bool check_field_size = true, #else bool check_field_size = false, #endif bool silence_warnings = false, const char *warning_string = NULL, size_t offset = 0) : field(fid) { if (start == stop) return; DomainT<1,T> is; const PhysicalRegion &region = *start; region_privileges[0] = region.get_privilege(); const Realm::RegionInstance instance = region.get_instance_info(region_privileges[0], fid, actual_field_size, &is, Internal::NT_TemplateHelper::encode_tag<1,T>(), warning_string, silence_warnings, false/*generic accessor*/, check_field_size); region_bounds[0] = AffineBounds::Tester<1,T>(is, source_bounds); Rect<1,T> bounds = source_bounds.intersection(is.bounds); unsigned idx = 1; while (++start != stop) { assert(idx < MR); region_privileges[idx] = start->get_privilege(); const Realm::RegionInstance inst = start->get_instance_info( region_privileges[idx], fid, actual_field_size, &is, Internal::NT_TemplateHelper::encode_tag<1,T>(), warning_string, silence_warnings, false/*generic accessor*/, check_field_size); if (inst != instance) region.report_incompatible_multi_accessor(idx, fid, instance, inst); region_bounds[idx] = AffineBounds::Tester<1,T>(is, source_bounds); bounds = bounds.union_bbox(source_bounds.inersection(is.bounds)); idx++; } if (!Realm::AffineAccessor<FT,1,T>::is_compatible(instance,fid,bounds)) region.report_incompatible_accessor("AffineAccessor", instance, fid); accessor = Realm::AffineAccessor<FT,1,T>(instance, fid, bounds, offset); total_regions = idx; } template<int M, typename InputIterator> MultiRegionAccessor(InputIterator start, InputIterator stop, const AffineTransform<M,1,T> transform, FieldID fid, size_t actual_field_size = sizeof(FT), #ifdef DEBUG_LEGION bool check_field_size = true, #else bool check_field_size = false, #endif bool silence_warnings = false, const char *warning_string = NULL, size_t offset = 0) : field(fid) { if (start == stop) return; DomainT<1,T> is; const PhysicalRegion &region = *start; region_privileges[0] = region.get_privilege(); const Realm::RegionInstance instance = region.get_instance_info(region_privileges[0], fid, actual_field_size, &is, Internal::NT_TemplateHelper::encode_tag<1,T>(), warning_string, silence_warnings, false/*generic accessor*/, check_field_size); region_bounds[0] = AffineBounds::Tester<1,T>(is, transform); Rect<1,T> bounds = is.bounds; unsigned idx = 1; while (++start != stop) { assert(idx < MR); region_privileges[idx] = start->get_privilege(); const Realm::RegionInstance inst = start->get_instance_info( region_privileges[idx], fid, actual_field_size, &is, Internal::NT_TemplateHelper::encode_tag<1,T>(), warning_string, silence_warnings, false/*generic accessor*/, check_field_size); if (inst != instance) region.report_incompatible_multi_accessor(idx, fid, instance, inst); region_bounds[idx] = AffineBounds::Tester<1,T>(is, transform); bounds = bounds.union_bbox(is.bounds); idx++; } if (!Realm::AffineAccessor<FT,1,T>::is_compatible(instance, transform.transform, transform.offset, fid, bounds)) region.report_incompatible_accessor("AffineAccessor", instance, fid); accessor = Realm::AffineAccessor<FT,1,T>(instance, transform.transform, transform.offset, fid, bounds, offset); total_regions = idx; } template<int M, typename InputIterator> MultiRegionAccessor(InputIterator start, InputIterator stop, const AffineTransform<M,1,T> transform, const Rect<1,T> source_bounds, FieldID fid, // The actual field size in case it is different from the // one being used in FT and we still want to check it size_t actual_field_size = sizeof(FT), #ifdef DEBUG_LEGION bool check_field_size = true, #else bool check_field_size = false, #endif bool silence_warnings = false, const char *warning_string = NULL, size_t offset = 0) : field(fid) { if (start == stop) return; DomainT<1,T> is; const PhysicalRegion &region = *start; region_privileges[0] = region.get_privilege(); const Realm::RegionInstance instance = region.get_instance_info(region_privileges[0], fid, actual_field_size, &is, Internal::NT_TemplateHelper::encode_tag<1,T>(), warning_string, silence_warnings, false/*generic accessor*/, check_field_size); region_bounds[0] =AffineBounds::Tester<1,T>(is,source_bounds,transform); Rect<1,T> bounds = source_bounds.intersection(is.bounds); unsigned idx = 1; while (++start != stop) { assert(idx < MR); region_privileges[idx] = start->get_privilege(); const Realm::RegionInstance inst = start->get_instance_info( region_privileges[idx], fid, actual_field_size, &is, Internal::NT_TemplateHelper::encode_tag<1,T>(), warning_string, silence_warnings, false/*generic accessor*/, check_field_size); if (inst != instance) region.report_incompatible_multi_accessor(idx, fid, instance, inst); region_bounds[idx] = AffineBounds::Tester<1,T>(is, transform, source_bounds); bounds = bounds.union_bbox(source_bounds.inersection(is.bounds)); idx++; } if (!Realm::AffineAccessor<FT,1,T>::is_compatible(instance, transform.transform, transform.offset, fid, bounds)) region.report_incompatible_accessor("AffineAccessor", instance, fid); accessor = Realm::AffineAccessor<FT,1,T>(instance, transform.transform, transform.offset, fid, bounds, offset); total_regions = idx; } public: MultiRegionAccessor(const std::vector<PhysicalRegion> &regions, FieldID fid, size_t actual_field_size = sizeof(FT), #ifdef DEBUG_LEGION bool check_field_size = true, #else bool check_field_size = false, #endif bool silence_warnings = false, const char *warning_string = NULL, size_t offset = 0) : field(fid), total_regions(regions.size()) { if (regions.empty()) return; DomainT<1,T> is; const PhysicalRegion &region = regions.front(); region_privileges[0] = region.get_privilege(); const Realm::RegionInstance instance = region.get_instance_info(region_privileges[0], fid, actual_field_size, &is, Internal::NT_TemplateHelper::encode_tag<1,T>(), warning_string, silence_warnings, false/*generic accessor*/, check_field_size); region_bounds[0] = AffineBounds::Tester<1,T>(is); Rect<1,T> bounds = is.bounds; for (unsigned idx = 1; idx < regions.size(); idx++) { region_privileges[idx] = regions[idx].get_privilege(); const Realm::RegionInstance inst = regions[idx].get_instance_info( region_privileges[idx], fid, actual_field_size, &is, Internal::NT_TemplateHelper::encode_tag<1,T>(), warning_string, silence_warnings, false/*generic accessor*/, check_field_size); if (inst != instance) region.report_incompatible_multi_accessor(idx, fid, instance, inst); region_bounds[idx] = AffineBounds::Tester<1,T>(is); bounds = bounds.union_bbox(is.bounds); } if (!Realm::AffineAccessor<FT,1,T>::is_compatible(instance,fid,bounds)) region.report_incompatible_accessor("AffineAccessor", instance, fid); accessor = Realm::AffineAccessor<FT,1,T>(instance, fid, bounds, offset); } MultiRegionAccessor(const std::vector<PhysicalRegion> &regions, const Rect<1,T> source_bounds, FieldID fid, size_t actual_field_size = sizeof(FT), #ifdef DEBUG_LEGION bool check_field_size = true, #else bool check_field_size = false, #endif bool silence_warnings = false, const char *warning_string = NULL, size_t offset = 0) : field(fid), total_regions(regions.size()) { if (regions.empty()) return; DomainT<1,T> is; const PhysicalRegion &region = regions.front(); region_privileges[0] = region.get_privilege(); const Realm::RegionInstance instance = region.get_instance_info(region_privileges[0], fid, actual_field_size, &is, Internal::NT_TemplateHelper::encode_tag<1,T>(), warning_string, silence_warnings, false/*generic accessor*/, check_field_size); region_bounds[0] = AffineBounds::Tester<1,T>(is, source_bounds); Rect<1,T> bounds = source_bounds.intersection(is.bounds); for (unsigned idx = 1; idx < regions.size(); idx++) { region_privileges[idx] = regions[idx].get_privilege(); const Realm::RegionInstance inst = regions[idx].get_instance_info( region_privileges[idx], fid, actual_field_size, &is, Internal::NT_TemplateHelper::encode_tag<1,T>(), warning_string, silence_warnings, false/*generic accessor*/, check_field_size); if (inst != instance) region.report_incompatible_multi_accessor(idx, fid, instance, inst); region_bounds[idx] = AffineBounds::Tester<1,T>(is, source_bounds); bounds = bounds.union_bbox(source_bounds.inersection(is.bounds)); } if (!Realm::AffineAccessor<FT,1,T>::is_compatible(instance,fid,bounds)) region.report_incompatible_accessor("AffineAccessor", instance, fid); accessor = Realm::AffineAccessor<FT,1,T>(instance, fid, bounds, offset); } template<int M> MultiRegionAccessor(const std::vector<PhysicalRegion> &regions, const AffineTransform<M,1,T> transform, FieldID fid, size_t actual_field_size = sizeof(FT), #ifdef DEBUG_LEGION bool check_field_size = true, #else bool check_field_size = false, #endif bool silence_warnings = false, const char *warning_string = NULL, size_t offset = 0) : field(fid), total_regions(regions.size()) { if (regions.empty()) return; DomainT<1,T> is; const PhysicalRegion &region = regions.front(); region_privileges[0] = region.get_privilege(); const Realm::RegionInstance instance = region.get_instance_info(region_privileges[0], fid, actual_field_size, &is, Internal::NT_TemplateHelper::encode_tag<1,T>(), warning_string, silence_warnings, false/*generic accessor*/, check_field_size); region_bounds[0] = AffineBounds::Tester<1,T>(is, transform); Rect<1,T> bounds = is.bounds; for (unsigned idx = 1; idx < regions.size(); idx++) { region_privileges[idx] = regions[idx].get_privilege(); const Realm::RegionInstance inst = regions[idx].get_instance_info( region_privileges[idx], fid, actual_field_size, &is, Internal::NT_TemplateHelper::encode_tag<1,T>(), warning_string, silence_warnings, false/*generic accessor*/, check_field_size); if (inst != instance) region.report_incompatible_multi_accessor(idx, fid, instance, inst); region_bounds[idx] = AffineBounds::Tester<1,T>(is, transform); bounds = bounds.union_bbox(is.bounds); } if (!Realm::AffineAccessor<FT,1,T>::is_compatible(instance, transform.transform, transform.offset, fid, bounds)) region.report_incompatible_accessor("AffineAccessor", instance, fid); accessor = Realm::AffineAccessor<FT,1,T>(instance, transform.transform, transform.offset, fid, bounds, offset); } template<int M> MultiRegionAccessor(const std::vector<PhysicalRegion> &regions, const AffineTransform<M,1,T> transform, const Rect<1,T> source_bounds, FieldID fid, // The actual field size in case it is different from the // one being used in FT and we still want to check it size_t actual_field_size = sizeof(FT), #ifdef DEBUG_LEGION bool check_field_size = true, #else bool check_field_size = false, #endif bool silence_warnings = false, const char *warning_string = NULL, size_t offset = 0) : field(fid), total_regions(regions.size()) { if (regions.empty()) return; DomainT<1,T> is; const PhysicalRegion &region = regions.front(); region_privileges[0] = region.get_privilege(); const Realm::RegionInstance instance = region.get_instance_info(region_privileges[0], fid, actual_field_size, &is, Internal::NT_TemplateHelper::encode_tag<1,T>(), warning_string, silence_warnings, false/*generic accessor*/, check_field_size); region_bounds[0] =AffineBounds::Tester<1,T>(is,source_bounds,transform); Rect<1,T> bounds = source_bounds.intersection(is.bounds); for (unsigned idx = 1; idx < regions.size(); idx++) { region_privileges[idx] = regions[idx].get_privilege(); const Realm::RegionInstance inst = regions[idx].get_instance_info( region_privileges[idx], fid, actual_field_size, &is, Internal::NT_TemplateHelper::encode_tag<1,T>(), warning_string, silence_warnings, false/*generic accessor*/, check_field_size); if (inst != instance) region.report_incompatible_multi_accessor(idx, fid, instance, inst); region_bounds[idx] = AffineBounds::Tester<1,T>(is, transform, source_bounds); bounds = bounds.union_bbox(source_bounds.inersection(is.bounds)); } if (!Realm::AffineAccessor<FT,1,T>::is_compatible(instance, transform.transform, transform.offset, fid, bounds)) region.report_incompatible_accessor("AffineAccessor", instance, fid); accessor = Realm::AffineAccessor<FT,1,T>(instance, transform.transform, transform.offset, fid, bounds, offset); } public: __CUDA_HD__ inline FT read(const Point<1,T>& p) const { bool found = false; for (unsigned idx = 0; idx < total_regions; idx++) { if (!region_bounds[idx].contains(p)) continue; if ((region_privileges[idx] & LEGION_READ_ONLY) == 0) { #ifdef __CUDA_ARCH__ // bounds checks are not precise for CUDA so keep going to // see if there is another region that has it with the privileges continue; #else PhysicalRegion::fail_privilege_check(DomainPoint(p), field, region_privileges[idx]); #endif } found = true; break; } #ifdef __CUDA_ARCH__ assert(found); #else if (!found) PhysicalRegion::fail_bounds_check(DomainPoint(p), field, region_privileges[0], true/*multi*/); #endif return accessor.read(p); } __CUDA_HD__ inline void write(const Point<1,T>& p, FT val) const { bool found = false; for (unsigned idx = 0; idx < total_regions; idx++) { if (!region_bounds[idx].contains(p)) continue; if ((region_privileges[idx] & LEGION_WRITE_PRIV) == 0) { #ifdef __CUDA_ARCH__ // bounds checks are not precise for CUDA so keep going to // see if there is another region that has it with the privileges continue; #else PhysicalRegion::fail_privilege_check(DomainPoint(p), field, region_privileges[idx]); #endif } found = true; break; } #ifdef __CUDA_ARCH__ assert(found); #else if (!found) PhysicalRegion::fail_bounds_check(DomainPoint(p), field, region_privileges[0], true/*multi*/); #endif return accessor.write(p, val); } __CUDA_HD__ inline ArraySyntax::AffineRefHelper<FT> operator[](const Point<1,T>& p) const { int index = -1; for (unsigned idx = 0; idx < total_regions; idx++) { if (!region_bounds[idx].contains(p)) continue; index = idx; break; } #ifdef __CUDA_ARCH__ assert(index >= 0); #else if (index < 0) PhysicalRegion::fail_bounds_check(DomainPoint(p), field, region_privileges[0], true/*multi*/); #endif return ArraySyntax::AffineRefHelper<FT>(accessor[p], field, DomainPoint(p), region_privileges[index]); } template<typename REDOP, bool EXCLUSIVE> __CUDA_HD__ inline void reduce(const Point<1,T>& p, typename REDOP::RHS val) const { bool found = false; for (unsigned idx = 0; idx < total_regions; idx++) { if (!region_bounds[idx].contains(p)) continue; if ((region_privileges[idx] & LEGION_REDUCE_PRIV) == 0) { #ifdef __CUDA_ARCH__ // bounds checks are not precise for CUDA so keep going to // see if there is another region that has it with the privileges continue; #else PhysicalRegion::fail_privilege_check(DomainPoint(p), field, region_privileges[idx]); #endif } found = true; break; } #ifdef __CUDA_ARCH__ assert(found); #else if (!found) PhysicalRegion::fail_bounds_check(DomainPoint(p), field, region_privileges[0], true/*multi*/); #endif REDOP::template apply<EXCLUSIVE>(accessor[p], val); } public: Realm::AffineAccessor<FT,1,T> accessor; FieldID field; PrivilegeMode region_privileges[MR]; AffineBounds::Tester<1,T> region_bounds[MR]; unsigned total_regions; public: typedef FT value_type; typedef FT& reference; typedef const FT& const_reference; static const int dim = 1; }; // Multi-Accessor, affine, N, bounds checks only template<typename FT, int N, typename T, int MR> class MultiRegionAccessor<FT,N,T,Realm::AffineAccessor<FT,N,T>, true/*check bounds*/,false/*check privileges*/,MR> { public: MultiRegionAccessor(void) { } public: template<typename InputIterator> MultiRegionAccessor(InputIterator start, InputIterator stop, FieldID fid, size_t actual_field_size = sizeof(FT), #ifdef DEBUG_LEGION bool check_field_size = true, #else bool check_field_size = false, #endif bool silence_warnings = false, const char *warning_string = NULL, size_t offset = 0) : field(fid) { if (start == stop) return; DomainT<N,T> is; const PhysicalRegion &region = *start; region_privileges[0] = region.get_privilege(); const Realm::RegionInstance instance = region.get_instance_info(region_privileges[0], fid, actual_field_size, &is, Internal::NT_TemplateHelper::encode_tag<N,T>(), warning_string, silence_warnings, false/*generic accessor*/, check_field_size); region_bounds[0] = AffineBounds::Tester<N,T>(is); Rect<N,T> bounds = is.bounds; unsigned idx = 0; while (++start != stop) { assert(idx < MR); region_privileges[idx] = start->get_privilege(); const Realm::RegionInstance inst = start->get_instance_info( region_privileges[idx], fid, actual_field_size, &is, Internal::NT_TemplateHelper::encode_tag<N,T>(), warning_string, silence_warnings, false/*generic accessor*/, check_field_size); if (inst != instance) region.report_incompatible_multi_accessor(idx, fid, instance, inst); region_bounds[idx] = AffineBounds::Tester<N,T>(is); bounds = bounds.union_bbox(is.bounds); idx++; } if (!Realm::AffineAccessor<FT,N,T>::is_compatible(instance,fid,bounds)) region.report_incompatible_accessor("AffineAccessor", instance, fid); accessor = Realm::AffineAccessor<FT,N,T>(instance, fid, bounds, offset); total_regions = idx; } template<typename InputIterator> MultiRegionAccessor(InputIterator start, InputIterator stop, const Rect<N,T> source_bounds, FieldID fid, size_t actual_field_size = sizeof(FT), #ifdef DEBUG_LEGION bool check_field_size = true, #else bool check_field_size = false, #endif bool silence_warnings = false, const char *warning_string = NULL, size_t offset = 0) : field(fid) { if (start == stop) return; DomainT<N,T> is; const PhysicalRegion &region = *start; region_privileges[0] = region.get_privilege(); const Realm::RegionInstance instance = region.get_instance_info(region_privileges[0], fid, actual_field_size, &is, Internal::NT_TemplateHelper::encode_tag<N,T>(), warning_string, silence_warnings, false/*generic accessor*/, check_field_size); region_bounds[0] = AffineBounds::Tester<N,T>(is, source_bounds); Rect<N,T> bounds = source_bounds.intersection(is.bounds); unsigned idx = 1; while (++start != stop) { assert(idx < MR); region_privileges[idx] = start->get_privilege(); const Realm::RegionInstance inst = start->get_instance_info( region_privileges[idx], fid, actual_field_size, &is, Internal::NT_TemplateHelper::encode_tag<N,T>(), warning_string, silence_warnings, false/*generic accessor*/, check_field_size); if (inst != instance) region.report_incompatible_multi_accessor(idx, fid, instance, inst); region_bounds[idx] = AffineBounds::Tester<N,T>(is, source_bounds); bounds = bounds.union_bbox(source_bounds.inersection(is.bounds)); idx++; } if (!Realm::AffineAccessor<FT,N,T>::is_compatible(instance,fid,bounds)) region.report_incompatible_accessor("AffineAccessor", instance, fid); accessor = Realm::AffineAccessor<FT,N,T>(instance, fid, bounds, offset); total_regions = idx; } template<int M, typename InputIterator> MultiRegionAccessor(InputIterator start, InputIterator stop, const AffineTransform<M,N,T> transform, FieldID fid, size_t actual_field_size = sizeof(FT), #ifdef DEBUG_LEGION bool check_field_size = true, #else bool check_field_size = false, #endif bool silence_warnings = false, const char *warning_string = NULL, size_t offset = 0) : field(fid) { if (start == stop) return; DomainT<N,T> is; const PhysicalRegion &region = *start; region_privileges[0] = region.get_privilege(); const Realm::RegionInstance instance = region.get_instance_info(region_privileges[0], fid, actual_field_size, &is, Internal::NT_TemplateHelper::encode_tag<N,T>(), warning_string, silence_warnings, false/*generic accessor*/, check_field_size); region_bounds[0] = AffineBounds::Tester<N,T>(is, transform); Rect<N,T> bounds = is.bounds; unsigned idx = 1; while (++start != stop) { assert(idx < MR); region_privileges[idx] = start->get_privilege(); const Realm::RegionInstance inst = start->get_instance_info( region_privileges[idx], fid, actual_field_size, &is, Internal::NT_TemplateHelper::encode_tag<N,T>(), warning_string, silence_warnings, false/*generic accessor*/, check_field_size); if (inst != instance) region.report_incompatible_multi_accessor(idx, fid, instance, inst); region_bounds[idx] = AffineBounds::Tester<N,T>(is, transform); bounds = bounds.union_bbox(is.bounds); idx++; } if (!Realm::AffineAccessor<FT,N,T>::is_compatible(instance, transform.transform, transform.offset, fid, bounds)) region.report_incompatible_accessor("AffineAccessor", instance, fid); accessor = Realm::AffineAccessor<FT,N,T>(instance, transform.transform, transform.offset, fid, bounds, offset); total_regions = idx; } template<int M, typename InputIterator> MultiRegionAccessor(InputIterator start, InputIterator stop, const AffineTransform<M,N,T> transform, const Rect<N,T> source_bounds, FieldID fid, // The actual field size in case it is different from the // one being used in FT and we still want to check it size_t actual_field_size = sizeof(FT), #ifdef DEBUG_LEGION bool check_field_size = true, #else bool check_field_size = false, #endif bool silence_warnings = false, const char *warning_string = NULL, size_t offset = 0) : field(fid) { if (start == stop) return; DomainT<N,T> is; const PhysicalRegion &region = *start; region_privileges[0] = region.get_privilege(); const Realm::RegionInstance instance = region.get_instance_info(region_privileges[0], fid, actual_field_size, &is, Internal::NT_TemplateHelper::encode_tag<N,T>(), warning_string, silence_warnings, false/*generic accessor*/, check_field_size); region_bounds[0] =AffineBounds::Tester<N,T>(is,source_bounds,transform); Rect<N,T> bounds = source_bounds.intersection(is.bounds); unsigned idx = 1; while (++start != stop) { assert(idx < MR); region_privileges[idx] = start->get_privilege(); const Realm::RegionInstance inst = start->get_instance_info( region_privileges[idx], fid, actual_field_size, &is, Internal::NT_TemplateHelper::encode_tag<N,T>(), warning_string, silence_warnings, false/*generic accessor*/, check_field_size); if (inst != instance) region.report_incompatible_multi_accessor(idx, fid, instance, inst); region_bounds[idx] = AffineBounds::Tester<N,T>(is, transform, source_bounds); bounds = bounds.union_bbox(source_bounds.inersection(is.bounds)); idx++; } if (!Realm::AffineAccessor<FT,N,T>::is_compatible(instance, transform.transform, transform.offset, fid, bounds)) region.report_incompatible_accessor("AffineAccessor", instance, fid); accessor = Realm::AffineAccessor<FT,N,T>(instance, transform.transform, transform.offset, fid, bounds, offset); total_regions = idx; } public: MultiRegionAccessor(const std::vector<PhysicalRegion> &regions, FieldID fid, size_t actual_field_size = sizeof(FT), #ifdef DEBUG_LEGION bool check_field_size = true, #else bool check_field_size = false, #endif bool silence_warnings = false, const char *warning_string = NULL, size_t offset = 0) : field(fid), total_regions(regions.size()) { if (regions.empty()) return; DomainT<N,T> is; const PhysicalRegion &region = regions.front(); region_privileges[0] = region.get_privilege(); const Realm::RegionInstance instance = region.get_instance_info(region_privileges[0], fid, actual_field_size, &is, Internal::NT_TemplateHelper::encode_tag<N,T>(), warning_string, silence_warnings, false/*generic accessor*/, check_field_size); region_bounds[0] = AffineBounds::Tester<N,T>(is); Rect<N,T> bounds = is.bounds; for (unsigned idx = 1; idx < regions.size(); idx++) { region_privileges[idx] = regions[idx].get_privilege(); const Realm::RegionInstance inst = regions[idx].get_instance_info( region_privileges[idx], fid, actual_field_size, &is, Internal::NT_TemplateHelper::encode_tag<N,T>(), warning_string, silence_warnings, false/*generic accessor*/, check_field_size); if (inst != instance) region.report_incompatible_multi_accessor(idx, fid, instance, inst); region_bounds[idx] = AffineBounds::Tester<N,T>(is); bounds = bounds.union_bbox(is.bounds); } if (!Realm::AffineAccessor<FT,N,T>::is_compatible(instance,fid,bounds)) region.report_incompatible_accessor("AffineAccessor", instance, fid); accessor = Realm::AffineAccessor<FT,N,T>(instance, fid, bounds, offset); } MultiRegionAccessor(const std::vector<PhysicalRegion> &regions, const Rect<N,T> source_bounds, FieldID fid, size_t actual_field_size = sizeof(FT), #ifdef DEBUG_LEGION bool check_field_size = true, #else bool check_field_size = false, #endif bool silence_warnings = false, const char *warning_string = NULL, size_t offset = 0) : field(fid), total_regions(regions.size()) { if (regions.empty()) return; DomainT<N,T> is; const PhysicalRegion &region = regions.front(); region_privileges[0] = region.get_privilege(); const Realm::RegionInstance instance = region.get_instance_info(region_privileges[0], fid, actual_field_size, &is, Internal::NT_TemplateHelper::encode_tag<N,T>(), warning_string, silence_warnings, false/*generic accessor*/, check_field_size); region_bounds[0] = AffineBounds::Tester<N,T>(is, source_bounds); Rect<N,T> bounds = source_bounds.intersection(is.bounds); for (unsigned idx = 1; idx < regions.size(); idx++) { region_privileges[idx] = regions[idx].get_privilege(); const Realm::RegionInstance inst = regions[idx].get_instance_info( region_privileges[idx], fid, actual_field_size, &is, Internal::NT_TemplateHelper::encode_tag<N,T>(), warning_string, silence_warnings, false/*generic accessor*/, check_field_size); if (inst != instance) region.report_incompatible_multi_accessor(idx, fid, instance, inst); region_bounds[idx] = AffineBounds::Tester<N,T>(is, source_bounds); bounds = bounds.union_bbox(source_bounds.inersection(is.bounds)); } if (!Realm::AffineAccessor<FT,N,T>::is_compatible(instance,fid,bounds)) region.report_incompatible_accessor("AffineAccessor", instance, fid); accessor = Realm::AffineAccessor<FT,N,T>(instance, fid, bounds, offset); } template<int M> MultiRegionAccessor(const std::vector<PhysicalRegion> &regions, const AffineTransform<M,N,T> transform, FieldID fid, size_t actual_field_size = sizeof(FT), #ifdef DEBUG_LEGION bool check_field_size = true, #else bool check_field_size = false, #endif bool silence_warnings = false, const char *warning_string = NULL, size_t offset = 0) : field(fid), total_regions(regions.size()) { if (regions.empty()) return; DomainT<N,T> is; const PhysicalRegion &region = regions.front(); region_privileges[0] = region.get_privilege(); const Realm::RegionInstance instance = region.get_instance_info(region_privileges[0], fid, actual_field_size, &is, Internal::NT_TemplateHelper::encode_tag<N,T>(), warning_string, silence_warnings, false/*generic accessor*/, check_field_size); region_bounds[0] = AffineBounds::Tester<N,T>(is, transform); Rect<N,T> bounds = is.bounds; for (unsigned idx = 1; idx < regions.size(); idx++) { region_privileges[idx] = regions[idx].get_privilege(); const Realm::RegionInstance inst = regions[idx].get_instance_info( region_privileges[idx], fid, actual_field_size, &is, Internal::NT_TemplateHelper::encode_tag<N,T>(), warning_string, silence_warnings, false/*generic accessor*/, check_field_size); if (inst != instance) region.report_incompatible_multi_accessor(idx, fid, instance, inst); region_bounds[idx] = AffineBounds::Tester<N,T>(is, transform); bounds = bounds.union_bbox(is.bounds); } if (!Realm::AffineAccessor<FT,N,T>::is_compatible(instance, transform.transform, transform.offset, fid, bounds)) region.report_incompatible_accessor("AffineAccessor", instance, fid); accessor = Realm::AffineAccessor<FT,N,T>(instance, transform.transform, transform.offset, fid, bounds, offset); } template<int M> MultiRegionAccessor(const std::vector<PhysicalRegion> &regions, const AffineTransform<M,N,T> transform, const Rect<N,T> source_bounds, FieldID fid, // The actual field size in case it is different from the // one being used in FT and we still want to check it size_t actual_field_size = sizeof(FT), #ifdef DEBUG_LEGION bool check_field_size = true, #else bool check_field_size = false, #endif bool silence_warnings = false, const char *warning_string = NULL, size_t offset = 0) : field(fid), total_regions(regions.size()) { if (regions.empty()) return; DomainT<N,T> is; const PhysicalRegion &region = regions.front(); region_privileges[0] = region.get_privilege(); const Realm::RegionInstance instance = region.get_instance_info(region_privileges[0], fid, actual_field_size, &is, Internal::NT_TemplateHelper::encode_tag<N,T>(), warning_string, silence_warnings, false/*generic accessor*/, check_field_size); region_bounds[0] =AffineBounds::Tester<N,T>(is,source_bounds,transform); Rect<N,T> bounds = source_bounds.intersection(is.bounds); for (unsigned idx = 1; idx < regions.size(); idx++) { region_privileges[idx] = regions[idx].get_privilege(); const Realm::RegionInstance inst = regions[idx].get_instance_info( region_privileges[idx], fid, actual_field_size, &is, Internal::NT_TemplateHelper::encode_tag<N,T>(), warning_string, silence_warnings, false/*generic accessor*/, check_field_size); if (inst != instance) region.report_incompatible_multi_accessor(idx, fid, instance, inst); region_bounds[idx] = AffineBounds::Tester<N,T>(is, transform, source_bounds); bounds = bounds.union_bbox(source_bounds.inersection(is.bounds)); } if (!Realm::AffineAccessor<FT,N,T>::is_compatible(instance, transform.transform, transform.offset, fid, bounds)) region.report_incompatible_accessor("AffineAccessor", instance, fid); accessor = Realm::AffineAccessor<FT,N,T>(instance, transform.transform, transform.offset, fid, bounds, offset); } public: __CUDA_HD__ inline FT read(const Point<N,T>& p) const { bool found = false; for (unsigned idx = 0; idx < total_regions; idx++) { if (!region_bounds[idx].contains(p)) continue; found = true; break; } #ifdef __CUDA_ARCH__ assert(found); #else if (!found) PhysicalRegion::fail_bounds_check(DomainPoint(p), field, region_privileges[0], true/*multi*/); #endif return accessor.read(p); } __CUDA_HD__ inline void write(const Point<N,T>& p, FT val) const { bool found = false; for (unsigned idx = 0; idx < total_regions; idx++) { if (!region_bounds[idx].contains(p)) continue; found = true; break; } #ifdef __CUDA_ARCH__ assert(found); #else if (!found) PhysicalRegion::fail_bounds_check(DomainPoint(p), field, region_privileges[0], true/*multi*/); #endif return accessor.write(p, val); } __CUDA_HD__ inline FT& operator[](const Point<N,T>& p) const { int index = -1; for (unsigned idx = 0; idx < total_regions; idx++) { if (!region_bounds[idx].contains(p)) continue; index = idx; break; } #ifdef __CUDA_ARCH__ assert(index >= 0); #else if (index < 0) PhysicalRegion::fail_bounds_check(DomainPoint(p), field, region_privileges[0], true/*multi*/); #endif return accessor[p]; } __CUDA_HD__ inline ArraySyntax::AffineSyntaxHelper<MultiRegionAccessor<FT,N,T, Realm::AffineAccessor<FT,N,T>,true,false,MR>, FT,N,T,2,LEGION_READ_WRITE> operator[](T index) const { return ArraySyntax::AffineSyntaxHelper<MultiRegionAccessor<FT,N,T, Realm::AffineAccessor<FT,N,T>,true,false,MR>, FT,N,T,2,LEGION_READ_WRITE>(*this, Point<1,T>(index)); } template<typename REDOP, bool EXCLUSIVE> __CUDA_HD__ inline void reduce(const Point<N,T>& p, typename REDOP::RHS val) const { bool found = false; for (unsigned idx = 0; idx < total_regions; idx++) { if (!region_bounds[idx].contains(p)) continue; found = true; break; } #ifdef __CUDA_ARCH__ assert(found); #else if (!found) PhysicalRegion::fail_bounds_check(DomainPoint(p), field, region_privileges[0], true/*multi*/); #endif REDOP::template apply<EXCLUSIVE>(accessor[p], val); } public: Realm::AffineAccessor<FT,N,T> accessor; FieldID field; PrivilegeMode region_privileges[MR]; AffineBounds::Tester<N,T> region_bounds[MR]; unsigned total_regions; public: typedef FT value_type; typedef FT& reference; typedef const FT& const_reference; static const int dim = N; }; // Multi-Accessor, affine, 1, bounds checks only template<typename FT, typename T, int MR> class MultiRegionAccessor<FT,1,T,Realm::AffineAccessor<FT,1,T>, true/*check bounds*/,false/*check privileges*/,MR> { public: MultiRegionAccessor(void) { } public: template<typename InputIterator> MultiRegionAccessor(InputIterator start, InputIterator stop, FieldID fid, size_t actual_field_size = sizeof(FT), #ifdef DEBUG_LEGION bool check_field_size = true, #else bool check_field_size = false, #endif bool silence_warnings = false, const char *warning_string = NULL, size_t offset = 0) : field(fid) { if (start == stop) return; DomainT<1,T> is; const PhysicalRegion &region = *start; region_privileges[0] = region.get_privilege(); const Realm::RegionInstance instance = region.get_instance_info(region_privileges[0], fid, actual_field_size, &is, Internal::NT_TemplateHelper::encode_tag<1,T>(), warning_string, silence_warnings, false/*generic accessor*/, check_field_size); region_bounds[0] = AffineBounds::Tester<1,T>(is); Rect<1,T> bounds = is.bounds; unsigned idx = 0; while (++start != stop) { assert(idx < MR); region_privileges[idx] = start->get_privilege(); const Realm::RegionInstance inst = start->get_instance_info( region_privileges[idx], fid, actual_field_size, &is, Internal::NT_TemplateHelper::encode_tag<1,T>(), warning_string, silence_warnings, false/*generic accessor*/, check_field_size); if (inst != instance) region.report_incompatible_multi_accessor(idx, fid, instance, inst); region_bounds[idx] = AffineBounds::Tester<1,T>(is); bounds = bounds.union_bbox(is.bounds); idx++; } if (!Realm::AffineAccessor<FT,1,T>::is_compatible(instance,fid,bounds)) region.report_incompatible_accessor("AffineAccessor", instance, fid); accessor = Realm::AffineAccessor<FT,1,T>(instance, fid, bounds, offset); total_regions = idx; } template<typename InputIterator> MultiRegionAccessor(InputIterator start, InputIterator stop, const Rect<1,T> source_bounds, FieldID fid, size_t actual_field_size = sizeof(FT), #ifdef DEBUG_LEGION bool check_field_size = true, #else bool check_field_size = false, #endif bool silence_warnings = false, const char *warning_string = NULL, size_t offset = 0) : field(fid) { if (start == stop) return; DomainT<1,T> is; const PhysicalRegion &region = *start; region_privileges[0] = region.get_privilege(); const Realm::RegionInstance instance = region.get_instance_info(region_privileges[0], fid, actual_field_size, &is, Internal::NT_TemplateHelper::encode_tag<1,T>(), warning_string, silence_warnings, false/*generic accessor*/, check_field_size); region_bounds[0] = AffineBounds::Tester<1,T>(is, source_bounds); Rect<1,T> bounds = source_bounds.intersection(is.bounds); unsigned idx = 1; while (++start != stop) { assert(idx < MR); region_privileges[idx] = start->get_privilege(); const Realm::RegionInstance inst = start->get_instance_info( region_privileges[idx], fid, actual_field_size, &is, Internal::NT_TemplateHelper::encode_tag<1,T>(), warning_string, silence_warnings, false/*generic accessor*/, check_field_size); if (inst != instance) region.report_incompatible_multi_accessor(idx, fid, instance, inst); region_bounds[idx] = AffineBounds::Tester<1,T>(is, source_bounds); bounds = bounds.union_bbox(source_bounds.inersection(is.bounds)); idx++; } if (!Realm::AffineAccessor<FT,1,T>::is_compatible(instance,fid,bounds)) region.report_incompatible_accessor("AffineAccessor", instance, fid); accessor = Realm::AffineAccessor<FT,1,T>(instance, fid, bounds, offset); total_regions = idx; } template<int M, typename InputIterator> MultiRegionAccessor(InputIterator start, InputIterator stop, const AffineTransform<M,1,T> transform, FieldID fid, size_t actual_field_size = sizeof(FT), #ifdef DEBUG_LEGION bool check_field_size = true, #else bool check_field_size = false, #endif bool silence_warnings = false, const char *warning_string = NULL, size_t offset = 0) : field(fid) { if (start == stop) return; DomainT<1,T> is; const PhysicalRegion &region = *start; region_privileges[0] = region.get_privilege(); const Realm::RegionInstance instance = region.get_instance_info(region_privileges[0], fid, actual_field_size, &is, Internal::NT_TemplateHelper::encode_tag<1,T>(), warning_string, silence_warnings, false/*generic accessor*/, check_field_size); region_bounds[0] = AffineBounds::Tester<1,T>(is, transform); Rect<1,T> bounds = is.bounds; unsigned idx = 1; while (++start != stop) { assert(idx < MR); region_privileges[idx] = start->get_privilege(); const Realm::RegionInstance inst = start->get_instance_info( region_privileges[idx], fid, actual_field_size, &is, Internal::NT_TemplateHelper::encode_tag<1,T>(), warning_string, silence_warnings, false/*generic accessor*/, check_field_size); if (inst != instance) region.report_incompatible_multi_accessor(idx, fid, instance, inst); region_bounds[idx] = AffineBounds::Tester<1,T>(is, transform); bounds = bounds.union_bbox(is.bounds); idx++; } if (!Realm::AffineAccessor<FT,1,T>::is_compatible(instance, transform.transform, transform.offset, fid, bounds)) region.report_incompatible_accessor("AffineAccessor", instance, fid); accessor = Realm::AffineAccessor<FT,1,T>(instance, transform.transform, transform.offset, fid, bounds, offset); total_regions = idx; } template<int M, typename InputIterator> MultiRegionAccessor(InputIterator start, InputIterator stop, const AffineTransform<M,1,T> transform, const Rect<1,T> source_bounds, FieldID fid, // The actual field size in case it is different from the // one being used in FT and we still want to check it size_t actual_field_size = sizeof(FT), #ifdef DEBUG_LEGION bool check_field_size = true, #else bool check_field_size = false, #endif bool silence_warnings = false, const char *warning_string = NULL, size_t offset = 0) : field(fid) { if (start == stop) return; DomainT<1,T> is; const PhysicalRegion &region = *start; region_privileges[0] = region.get_privilege(); const Realm::RegionInstance instance = region.get_instance_info(region_privileges[0], fid, actual_field_size, &is, Internal::NT_TemplateHelper::encode_tag<1,T>(), warning_string, silence_warnings, false/*generic accessor*/, check_field_size); region_bounds[0] =AffineBounds::Tester<1,T>(is,source_bounds,transform); Rect<1,T> bounds = source_bounds.intersection(is.bounds); unsigned idx = 1; while (++start != stop) { assert(idx < MR); region_privileges[idx] = start->get_privilege(); const Realm::RegionInstance inst = start->get_instance_info( region_privileges[idx], fid, actual_field_size, &is, Internal::NT_TemplateHelper::encode_tag<1,T>(), warning_string, silence_warnings, false/*generic accessor*/, check_field_size); if (inst != instance) region.report_incompatible_multi_accessor(idx, fid, instance, inst); region_bounds[idx] = AffineBounds::Tester<1,T>(is, transform, source_bounds); bounds = bounds.union_bbox(source_bounds.inersection(is.bounds)); idx++; } if (!Realm::AffineAccessor<FT,1,T>::is_compatible(instance, transform.transform, transform.offset, fid, bounds)) region.report_incompatible_accessor("AffineAccessor", instance, fid); accessor = Realm::AffineAccessor<FT,1,T>(instance, transform.transform, transform.offset, fid, bounds, offset); total_regions = idx; } public: MultiRegionAccessor(const std::vector<PhysicalRegion> &regions, FieldID fid, size_t actual_field_size = sizeof(FT), #ifdef DEBUG_LEGION bool check_field_size = true, #else bool check_field_size = false, #endif bool silence_warnings = false, const char *warning_string = NULL, size_t offset = 0) : field(fid), total_regions(regions.size()) { if (regions.empty()) return; DomainT<1,T> is; const PhysicalRegion &region = regions.front(); region_privileges[0] = region.get_privilege(); const Realm::RegionInstance instance = region.get_instance_info(region_privileges[0], fid, actual_field_size, &is, Internal::NT_TemplateHelper::encode_tag<1,T>(), warning_string, silence_warnings, false/*generic accessor*/, check_field_size); region_bounds[0] = AffineBounds::Tester<1,T>(is); Rect<1,T> bounds = is.bounds; for (unsigned idx = 1; idx < regions.size(); idx++) { region_privileges[idx] = regions[idx].get_privilege(); const Realm::RegionInstance inst = regions[idx].get_instance_info( region_privileges[idx], fid, actual_field_size, &is, Internal::NT_TemplateHelper::encode_tag<1,T>(), warning_string, silence_warnings, false/*generic accessor*/, check_field_size); if (inst != instance) region.report_incompatible_multi_accessor(idx, fid, instance, inst); region_bounds[idx] = AffineBounds::Tester<1,T>(is); bounds = bounds.union_bbox(is.bounds); } if (!Realm::AffineAccessor<FT,1,T>::is_compatible(instance,fid,bounds)) region.report_incompatible_accessor("AffineAccessor", instance, fid); accessor = Realm::AffineAccessor<FT,1,T>(instance, fid, bounds, offset); } MultiRegionAccessor(const std::vector<PhysicalRegion> &regions, const Rect<1,T> source_bounds, FieldID fid, size_t actual_field_size = sizeof(FT), #ifdef DEBUG_LEGION bool check_field_size = true, #else bool check_field_size = false, #endif bool silence_warnings = false, const char *warning_string = NULL, size_t offset = 0) : field(fid), total_regions(regions.size()) { if (regions.empty()) return; DomainT<1,T> is; const PhysicalRegion &region = regions.front(); region_privileges[0] = region.get_privilege(); const Realm::RegionInstance instance = region.get_instance_info(region_privileges[0], fid, actual_field_size, &is, Internal::NT_TemplateHelper::encode_tag<1,T>(), warning_string, silence_warnings, false/*generic accessor*/, check_field_size); region_bounds[0] = AffineBounds::Tester<1,T>(is, source_bounds); Rect<1,T> bounds = source_bounds.intersection(is.bounds); for (unsigned idx = 1; idx < regions.size(); idx++) { region_privileges[idx] = regions[idx].get_privilege(); const Realm::RegionInstance inst = regions[idx].get_instance_info( region_privileges[idx], fid, actual_field_size, &is, Internal::NT_TemplateHelper::encode_tag<1,T>(), warning_string, silence_warnings, false/*generic accessor*/, check_field_size); if (inst != instance) region.report_incompatible_multi_accessor(idx, fid, instance, inst); region_bounds[idx] = AffineBounds::Tester<1,T>(is, source_bounds); bounds = bounds.union_bbox(source_bounds.inersection(is.bounds)); } if (!Realm::AffineAccessor<FT,1,T>::is_compatible(instance,fid,bounds)) region.report_incompatible_accessor("AffineAccessor", instance, fid); accessor = Realm::AffineAccessor<FT,1,T>(instance, fid, bounds, offset); } template<int M> MultiRegionAccessor(const std::vector<PhysicalRegion> &regions, const AffineTransform<M,1,T> transform, FieldID fid, size_t actual_field_size = sizeof(FT), #ifdef DEBUG_LEGION bool check_field_size = true, #else bool check_field_size = false, #endif bool silence_warnings = false, const char *warning_string = NULL, size_t offset = 0) : field(fid), total_regions(regions.size()) { if (regions.empty()) return; DomainT<1,T> is; const PhysicalRegion &region = regions.front(); region_privileges[0] = region.get_privilege(); const Realm::RegionInstance instance = region.get_instance_info(region_privileges[0], fid, actual_field_size, &is, Internal::NT_TemplateHelper::encode_tag<1,T>(), warning_string, silence_warnings, false/*generic accessor*/, check_field_size); region_bounds[0] = AffineBounds::Tester<1,T>(is, transform); Rect<1,T> bounds = is.bounds; for (unsigned idx = 1; idx < regions.size(); idx++) { region_privileges[idx] = regions[idx].get_privilege(); const Realm::RegionInstance inst = regions[idx].get_instance_info( region_privileges[idx], fid, actual_field_size, &is, Internal::NT_TemplateHelper::encode_tag<1,T>(), warning_string, silence_warnings, false/*generic accessor*/, check_field_size); if (inst != instance) region.report_incompatible_multi_accessor(idx, fid, instance, inst); region_bounds[idx] = AffineBounds::Tester<1,T>(is, transform); bounds = bounds.union_bbox(is.bounds); } if (!Realm::AffineAccessor<FT,1,T>::is_compatible(instance, transform.transform, transform.offset, fid, bounds)) region.report_incompatible_accessor("AffineAccessor", instance, fid); accessor = Realm::AffineAccessor<FT,1,T>(instance, transform.transform, transform.offset, fid, bounds, offset); } template<int M> MultiRegionAccessor(const std::vector<PhysicalRegion> &regions, const AffineTransform<M,1,T> transform, const Rect<1,T> source_bounds, FieldID fid, // The actual field size in case it is different from the // one being used in FT and we still want to check it size_t actual_field_size = sizeof(FT), #ifdef DEBUG_LEGION bool check_field_size = true, #else bool check_field_size = false, #endif bool silence_warnings = false, const char *warning_string = NULL, size_t offset = 0) : field(fid), total_regions(regions.size()) { if (regions.empty()) return; DomainT<1,T> is; const PhysicalRegion &region = regions.front(); region_privileges[0] = region.get_privilege(); const Realm::RegionInstance instance = region.get_instance_info(region_privileges[0], fid, actual_field_size, &is, Internal::NT_TemplateHelper::encode_tag<1,T>(), warning_string, silence_warnings, false/*generic accessor*/, check_field_size); region_bounds[0] =AffineBounds::Tester<1,T>(is,source_bounds,transform); Rect<1,T> bounds = source_bounds.intersection(is.bounds); for (unsigned idx = 1; idx < regions.size(); idx++) { region_privileges[idx] = regions[idx].get_privilege(); const Realm::RegionInstance inst = regions[idx].get_instance_info( region_privileges[idx], fid, actual_field_size, &is, Internal::NT_TemplateHelper::encode_tag<1,T>(), warning_string, silence_warnings, false/*generic accessor*/, check_field_size); if (inst != instance) region.report_incompatible_multi_accessor(idx, fid, instance, inst); region_bounds[idx] = AffineBounds::Tester<1,T>(is, transform, source_bounds); bounds = bounds.union_bbox(source_bounds.inersection(is.bounds)); } if (!Realm::AffineAccessor<FT,1,T>::is_compatible(instance, transform.transform, transform.offset, fid, bounds)) region.report_incompatible_accessor("AffineAccessor", instance, fid); accessor = Realm::AffineAccessor<FT,1,T>(instance, transform.transform, transform.offset, fid, bounds, offset); } public: __CUDA_HD__ inline FT read(const Point<1,T>& p) const { bool found = false; for (unsigned idx = 0; idx < total_regions; idx++) { if (!region_bounds[idx].contains(p)) continue; found = true; break; } #ifdef __CUDA_ARCH__ assert(found); #else if (!found) PhysicalRegion::fail_bounds_check(DomainPoint(p), field, region_privileges[0], true/*multi*/); #endif return accessor.read(p); } __CUDA_HD__ inline void write(const Point<1,T>& p, FT val) const { bool found = false; for (unsigned idx = 0; idx < total_regions; idx++) { if (!region_bounds[idx].contains(p)) continue; found = true; break; } #ifdef __CUDA_ARCH__ assert(found); #else if (!found) PhysicalRegion::fail_bounds_check(DomainPoint(p), field, region_privileges[0], true/*multi*/); #endif return accessor.write(p, val); } __CUDA_HD__ inline FT& operator[](const Point<1,T>& p) const { int index = -1; for (unsigned idx = 0; idx < total_regions; idx++) { if (!region_bounds[idx].contains(p)) continue; index = idx; break; } #ifdef __CUDA_ARCH__ assert(index >= 0); #else if (index < 0) PhysicalRegion::fail_bounds_check(DomainPoint(p), field, region_privileges[0], true/*multi*/); #endif return accessor[p]; } template<typename REDOP, bool EXCLUSIVE> __CUDA_HD__ inline void reduce(const Point<1,T>& p, typename REDOP::RHS val) const { bool found = false; for (unsigned idx = 0; idx < total_regions; idx++) { if (!region_bounds[idx].contains(p)) continue; found = true; break; } #ifdef __CUDA_ARCH__ assert(found); #else if (!found) PhysicalRegion::fail_bounds_check(DomainPoint(p), field, region_privileges[0], true/*multi*/); #endif REDOP::template apply<EXCLUSIVE>(accessor[p], val); } public: Realm::AffineAccessor<FT,1,T> accessor; FieldID field; PrivilegeMode region_privileges[MR]; AffineBounds::Tester<1,T> region_bounds[MR]; unsigned total_regions; public: typedef FT value_type; typedef FT& reference; typedef const FT& const_reference; static const int dim = 1; }; // Multi-Accessor, affine, N, no bounds, no privileges template<typename FT, int N, typename T, int MR> class MultiRegionAccessor<FT,N,T,Realm::AffineAccessor<FT,N,T>, false/*check bounds*/,false/*check privileges*/,MR> { public: MultiRegionAccessor(void) { } public: template<typename InputIterator> MultiRegionAccessor(InputIterator start, InputIterator stop, FieldID fid, size_t actual_field_size = sizeof(FT), #ifdef DEBUG_LEGION bool check_field_size = true, #else bool check_field_size = false, #endif bool silence_warnings = false, const char *warning_string = NULL, size_t offset = 0) { if (start == stop) return; DomainT<N,T> is; const PhysicalRegion &region = *start; const Realm::RegionInstance instance = region.get_instance_info(region.get_privilege(), fid, actual_field_size, &is, Internal::NT_TemplateHelper::encode_tag<N,T>(), warning_string, silence_warnings, false/*generic accessor*/, check_field_size); Rect<N,T> bounds = is.bounds; unsigned idx = 1; while (++start != stop) { assert(idx < MR); const Realm::RegionInstance inst = start->get_instance_info( start->get_privilege(), fid, actual_field_size, &is, Internal::NT_TemplateHelper::encode_tag<N,T>(), warning_string, silence_warnings, false/*generic accessor*/, check_field_size); if (inst != instance) region.report_incompatible_multi_accessor(idx, fid, instance, inst); bounds = bounds.union_bbox(is.bounds); idx++; } if (!Realm::AffineAccessor<FT,N,T>::is_compatible(instance,fid,bounds)) region.report_incompatible_accessor("AffineAccessor", instance, fid); accessor = Realm::AffineAccessor<FT,N,T>(instance, fid, bounds, offset); } template<typename InputIterator> MultiRegionAccessor(InputIterator start, InputIterator stop, const Rect<N,T> source_bounds, FieldID fid, size_t actual_field_size = sizeof(FT), #ifdef DEBUG_LEGION bool check_field_size = true, #else bool check_field_size = false, #endif bool silence_warnings = false, const char *warning_string = NULL, size_t offset = 0) { if (start == stop) return; DomainT<N,T> is; const PhysicalRegion &region = *start; const Realm::RegionInstance instance = region.get_instance_info(region.get_privilege(), fid, actual_field_size, &is, Internal::NT_TemplateHelper::encode_tag<N,T>(), warning_string, silence_warnings, false/*generic accessor*/, check_field_size); Rect<N,T> bounds = source_bounds.intersection(is.bounds); unsigned idx = 1; while (++start != stop) { assert(idx < MR); const Realm::RegionInstance inst = start->get_instance_info( start->get_privilege(), fid, actual_field_size, &is, Internal::NT_TemplateHelper::encode_tag<N,T>(), warning_string, silence_warnings, false/*generic accessor*/, check_field_size); if (inst != instance) region.report_incompatible_multi_accessor(idx, fid, instance, inst); bounds = bounds.union_bbox(source_bounds.inersection(is.bounds)); idx++; } if (!Realm::AffineAccessor<FT,N,T>::is_compatible(instance,fid,bounds)) region.report_incompatible_accessor("AffineAccessor", instance, fid); accessor = Realm::AffineAccessor<FT,N,T>(instance, fid, bounds, offset); } template<int M, typename InputIterator> MultiRegionAccessor(InputIterator start, InputIterator stop, const AffineTransform<M,N,T> transform, FieldID fid, size_t actual_field_size = sizeof(FT), #ifdef DEBUG_LEGION bool check_field_size = true, #else bool check_field_size = false, #endif bool silence_warnings = false, const char *warning_string = NULL, size_t offset = 0) { if (start == stop) return; DomainT<N,T> is; const PhysicalRegion &region = *start; const Realm::RegionInstance instance = region.get_instance_info(region.get_privilege(), fid, actual_field_size, &is, Internal::NT_TemplateHelper::encode_tag<N,T>(), warning_string, silence_warnings, false/*generic accessor*/, check_field_size); Rect<N,T> bounds = is.bounds; unsigned idx = 1; while (++start != stop) { assert(idx < MR); const Realm::RegionInstance inst = start->get_instance_info( start->get_privilege(), fid, actual_field_size, &is, Internal::NT_TemplateHelper::encode_tag<N,T>(), warning_string, silence_warnings, false/*generic accessor*/, check_field_size); if (inst != instance) region.report_incompatible_multi_accessor(idx, fid, instance, inst); bounds = bounds.union_bbox(is.bounds); idx++; } if (!Realm::AffineAccessor<FT,N,T>::is_compatible(instance, transform.transform, transform.offset, fid, bounds)) region.report_incompatible_accessor("AffineAccessor", instance, fid); accessor = Realm::AffineAccessor<FT,N,T>(instance, transform.transform, transform.offset, fid, bounds, offset); } template<int M, typename InputIterator> MultiRegionAccessor(InputIterator start, InputIterator stop, const AffineTransform<M,N,T> transform, const Rect<N,T> source_bounds, FieldID fid, // The actual field size in case it is different from the // one being used in FT and we still want to check it size_t actual_field_size = sizeof(FT), #ifdef DEBUG_LEGION bool check_field_size = true, #else bool check_field_size = false, #endif bool silence_warnings = false, const char *warning_string = NULL, size_t offset = 0) { if (start == stop) return; DomainT<N,T> is; const PhysicalRegion &region = *start; const Realm::RegionInstance instance = region.get_instance_info(region.get_privilege(), fid, actual_field_size, &is, Internal::NT_TemplateHelper::encode_tag<N,T>(), warning_string, silence_warnings, false/*generic accessor*/, check_field_size); Rect<N,T> bounds = source_bounds.intersection(is.bounds); unsigned idx = 1; while (++start != stop) { assert(idx < MR); const Realm::RegionInstance inst = start->get_instance_info( start->get_privilege(), fid, actual_field_size, &is, Internal::NT_TemplateHelper::encode_tag<N,T>(), warning_string, silence_warnings, false/*generic accessor*/, check_field_size); if (inst != instance) region.report_incompatible_multi_accessor(idx, fid, instance, inst); bounds = bounds.union_bbox(source_bounds.inersection(is.bounds)); idx++; } if (!Realm::AffineAccessor<FT,N,T>::is_compatible(instance, transform.transform, transform.offset, fid, bounds)) region.report_incompatible_accessor("AffineAccessor", instance, fid); accessor = Realm::AffineAccessor<FT,N,T>(instance, transform.transform, transform.offset, fid, bounds, offset); } public: MultiRegionAccessor(const std::vector<PhysicalRegion> &regions, FieldID fid, size_t actual_field_size = sizeof(FT), #ifdef DEBUG_LEGION bool check_field_size = true, #else bool check_field_size = false, #endif bool silence_warnings = false, const char *warning_string = NULL, size_t offset = 0) { if (regions.empty()) return; DomainT<N,T> is; const PhysicalRegion &region = regions.front(); const Realm::RegionInstance instance = region.get_instance_info(region.get_privilege(), fid, actual_field_size, &is, Internal::NT_TemplateHelper::encode_tag<N,T>(), warning_string, silence_warnings, false/*generic accessor*/, check_field_size); Rect<N,T> bounds = is.bounds; for (unsigned idx = 1; idx < regions.size(); idx++) { const Realm::RegionInstance inst = regions[idx].get_instance_info( regions[idx].get_privilege(), fid, actual_field_size, &is, Internal::NT_TemplateHelper::encode_tag<N,T>(), warning_string, silence_warnings, false/*generic accessor*/, check_field_size); if (inst != instance) region.report_incompatible_multi_accessor(idx, fid, instance, inst); bounds = bounds.union_bbox(is.bounds); } if (!Realm::AffineAccessor<FT,N,T>::is_compatible(instance,fid,bounds)) region.report_incompatible_accessor("AffineAccessor", instance, fid); accessor = Realm::AffineAccessor<FT,N,T>(instance, fid, bounds, offset); } MultiRegionAccessor(const std::vector<PhysicalRegion> &regions, const Rect<N,T> source_bounds, FieldID fid, size_t actual_field_size = sizeof(FT), #ifdef DEBUG_LEGION bool check_field_size = true, #else bool check_field_size = false, #endif bool silence_warnings = false, const char *warning_string = NULL, size_t offset = 0) { if (regions.empty()) return; DomainT<N,T> is; const PhysicalRegion &region = regions.front(); const Realm::RegionInstance instance = region.get_instance_info(region.get_privilege(), fid, actual_field_size, &is, Internal::NT_TemplateHelper::encode_tag<N,T>(), warning_string, silence_warnings, false/*generic accessor*/, check_field_size); Rect<N,T> bounds = source_bounds.intersection(is.bounds); for (unsigned idx = 1; idx < regions.size(); idx++) { const Realm::RegionInstance inst = regions[idx].get_instance_info( regions[idx].get_privilege(), fid, actual_field_size, &is, Internal::NT_TemplateHelper::encode_tag<N,T>(), warning_string, silence_warnings, false/*generic accessor*/, check_field_size); if (inst != instance) region.report_incompatible_multi_accessor(idx, fid, instance, inst); bounds = bounds.union_bbox(source_bounds.inersection(is.bounds)); } if (!Realm::AffineAccessor<FT,N,T>::is_compatible(instance,fid,bounds)) region.report_incompatible_accessor("AffineAccessor", instance, fid); accessor = Realm::AffineAccessor<FT,N,T>(instance, fid, bounds, offset); } template<int M> MultiRegionAccessor(const std::vector<PhysicalRegion> &regions, const AffineTransform<M,N,T> transform, FieldID fid, size_t actual_field_size = sizeof(FT), #ifdef DEBUG_LEGION bool check_field_size = true, #else bool check_field_size = false, #endif bool silence_warnings = false, const char *warning_string = NULL, size_t offset = 0) { if (regions.empty()) return; DomainT<N,T> is; const PhysicalRegion &region = regions.front(); const Realm::RegionInstance instance = region.get_instance_info(region.get_privilege(), fid, actual_field_size, &is, Internal::NT_TemplateHelper::encode_tag<N,T>(), warning_string, silence_warnings, false/*generic accessor*/, check_field_size); Rect<N,T> bounds = is.bounds; for (unsigned idx = 1; idx < regions.size(); idx++) { const Realm::RegionInstance inst = regions[idx].get_instance_info( regions[idx].get_privilege(), fid, actual_field_size, &is, Internal::NT_TemplateHelper::encode_tag<N,T>(), warning_string, silence_warnings, false/*generic accessor*/, check_field_size); if (inst != instance) region.report_incompatible_multi_accessor(idx, fid, instance, inst); bounds = bounds.union_bbox(is.bounds); } if (!Realm::AffineAccessor<FT,N,T>::is_compatible(instance, transform.transform, transform.offset, fid, bounds)) region.report_incompatible_accessor("AffineAccessor", instance, fid); accessor = Realm::AffineAccessor<FT,N,T>(instance, transform.transform, transform.offset, fid, bounds, offset); } template<int M> MultiRegionAccessor(const std::vector<PhysicalRegion> &regions, const AffineTransform<M,N,T> transform, const Rect<N,T> source_bounds, FieldID fid, // The actual field size in case it is different from the // one being used in FT and we still want to check it size_t actual_field_size = sizeof(FT), #ifdef DEBUG_LEGION bool check_field_size = true, #else bool check_field_size = false, #endif bool silence_warnings = false, const char *warning_string = NULL, size_t offset = 0) { if (regions.empty()) return; DomainT<N,T> is; const PhysicalRegion &region = regions.front(); const Realm::RegionInstance instance = region.get_instance_info(region.get_privilege(), fid, actual_field_size, &is, Internal::NT_TemplateHelper::encode_tag<N,T>(), warning_string, silence_warnings, false/*generic accessor*/, check_field_size); Rect<N,T> bounds = source_bounds.intersection(is.bounds); for (unsigned idx = 1; idx < regions.size(); idx++) { const Realm::RegionInstance inst = regions[idx].get_instance_info( regions[idx].get_privilege(), fid, actual_field_size, &is, Internal::NT_TemplateHelper::encode_tag<N,T>(), warning_string, silence_warnings, false/*generic accessor*/, check_field_size); if (inst != instance) region.report_incompatible_multi_accessor(idx, fid, instance, inst); bounds = bounds.union_bbox(source_bounds.inersection(is.bounds)); } if (!Realm::AffineAccessor<FT,N,T>::is_compatible(instance, transform.transform, transform.offset, fid, bounds)) region.report_incompatible_accessor("AffineAccessor", instance, fid); accessor = Realm::AffineAccessor<FT,N,T>(instance, transform.transform, transform.offset, fid, bounds, offset); } public: __CUDA_HD__ inline FT read(const Point<N,T>& p) const { return accessor.read(p); } __CUDA_HD__ inline void write(const Point<N,T>& p, FT val) const { return accessor.write(p, val); } __CUDA_HD__ inline FT& operator[](const Point<N,T>& p) const { return accessor[p]; } __CUDA_HD__ inline ArraySyntax::AffineSyntaxHelper<MultiRegionAccessor<FT,N,T, Realm::AffineAccessor<FT,N,T>,false,false,MR>,FT,N,T,2,LEGION_READ_WRITE> operator[](T index) const { return ArraySyntax::AffineSyntaxHelper<MultiRegionAccessor<FT,N,T, Realm::AffineAccessor<FT,N,T>,false,false,MR>, FT,N,T,2,LEGION_READ_WRITE>(*this, Point<1,T>(index)); } template<typename REDOP, bool EXCLUSIVE> __CUDA_HD__ inline void reduce(const Point<N,T>& p, typename REDOP::RHS val) const { REDOP::template apply<EXCLUSIVE>(accessor[p], val); } public: Realm::AffineAccessor<FT,N,T> accessor; public: typedef FT value_type; typedef FT& reference; typedef const FT& const_reference; static const int dim = N; }; // Multi-Accessor, affine, 1, no bounds, no privileges template<typename FT, typename T, int MR> class MultiRegionAccessor<FT,1,T,Realm::AffineAccessor<FT,1,T>, false/*check bounds*/,false/*check privileges*/,MR> { public: MultiRegionAccessor(void) { } public: template<typename InputIterator> MultiRegionAccessor(InputIterator start, InputIterator stop, FieldID fid, size_t actual_field_size = sizeof(FT), #ifdef DEBUG_LEGION bool check_field_size = true, #else bool check_field_size = false, #endif bool silence_warnings = false, const char *warning_string = NULL, size_t offset = 0) { if (start == stop) return; DomainT<1,T> is; const PhysicalRegion &region = *start; const Realm::RegionInstance instance = region.get_instance_info(region.get_privilege(), fid, actual_field_size, &is, Internal::NT_TemplateHelper::encode_tag<1,T>(), warning_string, silence_warnings, false/*generic accessor*/, check_field_size); Rect<1,T> bounds = is.bounds; unsigned idx = 1; while (++start != stop) { assert(idx < MR); const Realm::RegionInstance inst = start->get_instance_info( start->get_privilege(), fid, actual_field_size, &is, Internal::NT_TemplateHelper::encode_tag<1,T>(), warning_string, silence_warnings, false/*generic accessor*/, check_field_size); if (inst != instance) region.report_incompatible_multi_accessor(idx, fid, instance, inst); bounds = bounds.union_bbox(is.bounds); idx++; } if (!Realm::AffineAccessor<FT,1,T>::is_compatible(instance,fid,bounds)) region.report_incompatible_accessor("AffineAccessor", instance, fid); accessor = Realm::AffineAccessor<FT,1,T>(instance, fid, bounds); } template<typename InputIterator> MultiRegionAccessor(InputIterator start, InputIterator stop, const Rect<1,T> source_bounds, FieldID fid, size_t actual_field_size = sizeof(FT), #ifdef DEBUG_LEGION bool check_field_size = true, #else bool check_field_size = false, #endif bool silence_warnings = false, const char *warning_string = NULL, size_t offset = 0) { if (start == stop) return; DomainT<1,T> is; const PhysicalRegion &region = *start; const Realm::RegionInstance instance = region.get_instance_info(region.get_privilege(), fid, actual_field_size, &is, Internal::NT_TemplateHelper::encode_tag<1,T>(), warning_string, silence_warnings, false/*generic accessor*/, check_field_size); Rect<1,T> bounds = source_bounds.intersection(is.bounds); unsigned idx = 1; while (++start != stop) { assert(idx < MR); const Realm::RegionInstance inst = start->get_instance_info( start->get_privilege(), fid, actual_field_size, &is, Internal::NT_TemplateHelper::encode_tag<1,T>(), warning_string, silence_warnings, false/*generic accessor*/, check_field_size); if (inst != instance) region.report_incompatible_multi_accessor(idx, fid, instance, inst); bounds = bounds.union_bbox(source_bounds.inersection(is.bounds)); idx++; } if (!Realm::AffineAccessor<FT,1,T>::is_compatible(instance,fid,bounds)) region.report_incompatible_accessor("AffineAccessor", instance, fid); accessor = Realm::AffineAccessor<FT,1,T>(instance, fid, bounds); } template<int M, typename InputIterator> MultiRegionAccessor(InputIterator start, InputIterator stop, const AffineTransform<M,1,T> transform, FieldID fid, size_t actual_field_size = sizeof(FT), #ifdef DEBUG_LEGION bool check_field_size = true, #else bool check_field_size = false, #endif bool silence_warnings = false, const char *warning_string = NULL, size_t offset = 0) { if (start == stop) return; DomainT<1,T> is; const PhysicalRegion &region = *start; const Realm::RegionInstance instance = region.get_instance_info(region.get_privilege(), fid, actual_field_size, &is, Internal::NT_TemplateHelper::encode_tag<1,T>(), warning_string, silence_warnings, false/*generic accessor*/, check_field_size); Rect<1,T> bounds = is.bounds; unsigned idx = 1; while (++start != stop) { assert(idx < MR); const Realm::RegionInstance inst = start->get_instance_info( start->get_privilege(), fid, actual_field_size, &is, Internal::NT_TemplateHelper::encode_tag<1,T>(), warning_string, silence_warnings, false/*generic accessor*/, check_field_size); if (inst != instance) region.report_incompatible_multi_accessor(idx, fid, instance, inst); bounds = bounds.union_bbox(is.bounds); idx++; } if (!Realm::AffineAccessor<FT,1,T>::is_compatible(instance, transform.transform, transform.offset, fid, bounds)) region.report_incompatible_accessor("AffineAccessor", instance, fid); accessor = Realm::AffineAccessor<FT,1,T>(instance, transform.transform, transform.offset, fid, bounds); } template<int M, typename InputIterator> MultiRegionAccessor(InputIterator start, InputIterator stop, const AffineTransform<M,1,T> transform, const Rect<1,T> source_bounds, FieldID fid, // The actual field size in case it is different from the // one being used in FT and we still want to check it size_t actual_field_size = sizeof(FT), #ifdef DEBUG_LEGION bool check_field_size = true, #else bool check_field_size = false, #endif bool silence_warnings = false, const char *warning_string = NULL, size_t offset = 0) { if (start == stop) return; DomainT<1,T> is; const PhysicalRegion &region = *start; const Realm::RegionInstance instance = region.get_instance_info(region.get_privilege(), fid, actual_field_size, &is, Internal::NT_TemplateHelper::encode_tag<1,T>(), warning_string, silence_warnings, false/*generic accessor*/, check_field_size); Rect<1,T> bounds = source_bounds.intersection(is.bounds); unsigned idx = 1; while (++start != stop) { assert(idx < MR); const Realm::RegionInstance inst = start->get_instance_info( start->get_privilege(), fid, actual_field_size, &is, Internal::NT_TemplateHelper::encode_tag<1,T>(), warning_string, silence_warnings, false/*generic accessor*/, check_field_size); if (inst != instance) region.report_incompatible_multi_accessor(idx, fid, instance, inst); bounds = bounds.union_bbox(source_bounds.inersection(is.bounds)); idx++; } if (!Realm::AffineAccessor<FT,1,T>::is_compatible(instance, transform.transform, transform.offset, fid, bounds)) region.report_incompatible_accessor("AffineAccessor", instance, fid); accessor = Realm::AffineAccessor<FT,1,T>(instance, transform.transform, transform.offset, fid, bounds); } public: MultiRegionAccessor(const std::vector<PhysicalRegion> &regions, FieldID fid, size_t actual_field_size = sizeof(FT), #ifdef DEBUG_LEGION bool check_field_size = true, #else bool check_field_size = false, #endif bool silence_warnings = false, const char *warning_string = NULL, size_t offset = 0) { if (regions.empty()) return; DomainT<1,T> is; const PhysicalRegion &region = regions.front(); const Realm::RegionInstance instance = region.get_instance_info(region.get_privilege(), fid, actual_field_size, &is, Internal::NT_TemplateHelper::encode_tag<1,T>(), warning_string, silence_warnings, false/*generic accessor*/, check_field_size); Rect<1,T> bounds = is.bounds; for (unsigned idx = 1; idx < regions.size(); idx++) { const Realm::RegionInstance inst = regions[idx].get_instance_info( regions[idx].get_privilege(), fid, actual_field_size, &is, Internal::NT_TemplateHelper::encode_tag<1,T>(), warning_string, silence_warnings, false/*generic accessor*/, check_field_size); if (inst != instance) region.report_incompatible_multi_accessor(idx, fid, instance, inst); bounds = bounds.union_bbox(is.bounds); } if (!Realm::AffineAccessor<FT,1,T>::is_compatible(instance,fid,bounds)) region.report_incompatible_accessor("AffineAccessor", instance, fid); accessor = Realm::AffineAccessor<FT,1,T>(instance, fid, bounds, offset); } MultiRegionAccessor(const std::vector<PhysicalRegion> &regions, const Rect<1,T> source_bounds, FieldID fid, size_t actual_field_size = sizeof(FT), #ifdef DEBUG_LEGION bool check_field_size = true, #else bool check_field_size = false, #endif bool silence_warnings = false, const char *warning_string = NULL, size_t offset = 0) { if (regions.empty()) return; DomainT<1,T> is; const PhysicalRegion &region = regions.front(); const Realm::RegionInstance instance = region.get_instance_info(region.get_privilege(), fid, actual_field_size, &is, Internal::NT_TemplateHelper::encode_tag<1,T>(), warning_string, silence_warnings, false/*generic accessor*/, check_field_size); Rect<1,T> bounds = source_bounds.intersection(is.bounds); for (unsigned idx = 1; idx < regions.size(); idx++) { const Realm::RegionInstance inst = regions[idx].get_instance_info( regions[idx].get_privilege(), fid, actual_field_size, &is, Internal::NT_TemplateHelper::encode_tag<1,T>(), warning_string, silence_warnings, false/*generic accessor*/, check_field_size); if (inst != instance) region.report_incompatible_multi_accessor(idx, fid, instance, inst); bounds = bounds.union_bbox(source_bounds.inersection(is.bounds)); } if (!Realm::AffineAccessor<FT,1,T>::is_compatible(instance,fid,bounds)) region.report_incompatible_accessor("AffineAccessor", instance, fid); accessor = Realm::AffineAccessor<FT,1,T>(instance, fid, bounds, offset); } template<int M> MultiRegionAccessor(const std::vector<PhysicalRegion> &regions, const AffineTransform<M,1,T> transform, FieldID fid, size_t actual_field_size = sizeof(FT), #ifdef DEBUG_LEGION bool check_field_size = true, #else bool check_field_size = false, #endif bool silence_warnings = false, const char *warning_string = NULL, size_t offset = 0) { if (regions.empty()) return; DomainT<1,T> is; const PhysicalRegion &region = regions.front(); const Realm::RegionInstance instance = region.get_instance_info(region.get_privilege(), fid, actual_field_size, &is, Internal::NT_TemplateHelper::encode_tag<1,T>(), warning_string, silence_warnings, false/*generic accessor*/, check_field_size); Rect<1,T> bounds = is.bounds; for (unsigned idx = 1; idx < regions.size(); idx++) { const Realm::RegionInstance inst = regions[idx].get_instance_info( regions[idx].get_privilege(), fid, actual_field_size, &is, Internal::NT_TemplateHelper::encode_tag<1,T>(), warning_string, silence_warnings, false/*generic accessor*/, check_field_size); if (inst != instance) region.report_incompatible_multi_accessor(idx, fid, instance, inst); bounds = bounds.union_bbox(is.bounds); } if (!Realm::AffineAccessor<FT,1,T>::is_compatible(instance, transform.transform, transform.offset, fid, bounds)) region.report_incompatible_accessor("AffineAccessor", instance, fid); accessor = Realm::AffineAccessor<FT,1,T>(instance, transform.transform, transform.offset, fid, bounds, offset); } template<int M> MultiRegionAccessor(const std::vector<PhysicalRegion> &regions, const AffineTransform<M,1,T> transform, const Rect<1,T> source_bounds, FieldID fid, // The actual field size in case it is different from the // one being used in FT and we still want to check it size_t actual_field_size = sizeof(FT), #ifdef DEBUG_LEGION bool check_field_size = true, #else bool check_field_size = false, #endif bool silence_warnings = false, const char *warning_string = NULL, size_t offset = 0) { if (regions.empty()) return; DomainT<1,T> is; const PhysicalRegion &region = regions.front(); const Realm::RegionInstance instance = region.get_instance_info(region.get_privilege(), fid, actual_field_size, &is, Internal::NT_TemplateHelper::encode_tag<1,T>(), warning_string, silence_warnings, false/*generic accessor*/, check_field_size); Rect<1,T> bounds = source_bounds.intersection(is.bounds); for (unsigned idx = 1; idx < regions.size(); idx++) { const Realm::RegionInstance inst = regions[idx].get_instance_info( regions[idx].get_privilege(), fid, actual_field_size, &is, Internal::NT_TemplateHelper::encode_tag<1,T>(), warning_string, silence_warnings, false/*generic accessor*/, check_field_size); if (inst != instance) region.report_incompatible_multi_accessor(idx, fid, instance, inst); bounds = bounds.union_bbox(source_bounds.inersection(is.bounds)); } if (!Realm::AffineAccessor<FT,1,T>::is_compatible(instance, transform.transform, transform.offset, fid, bounds)) region.report_incompatible_accessor("AffineAccessor", instance, fid); accessor = Realm::AffineAccessor<FT,1,T>(instance, transform.transform, transform.offset, fid, bounds, offset); } public: __CUDA_HD__ inline FT read(const Point<1,T>& p) const { return accessor.read(p); } __CUDA_HD__ inline void write(const Point<1,T>& p, FT val) const { return accessor.write(p, val); } __CUDA_HD__ inline FT& operator[](const Point<1,T>& p) const { return accessor[p]; } template<typename REDOP, bool EXCLUSIVE> __CUDA_HD__ inline void reduce(const Point<1,T>& p, typename REDOP::RHS val) const { REDOP::template apply<EXCLUSIVE>(accessor[p], val); } public: Realm::AffineAccessor<FT,1,T> accessor; public: typedef FT value_type; typedef FT& reference; typedef const FT& const_reference; static const int dim = 1; }; //////////////////////////////////////////////////////////// // Multi Region Accessor with Multi Affine Accessors //////////////////////////////////////////////////////////// // Multi-Accessor, multi affine, N, with privilege checks // (implies bounds checks) template<typename FT, int N, typename T, bool CB, int MR> class MultiRegionAccessor<FT,N,T, Realm::MultiAffineAccessor<FT,N,T>,CB,true,MR> { public: MultiRegionAccessor(void) { } public: template<typename InputIterator> MultiRegionAccessor(InputIterator start, InputIterator stop, FieldID fid, size_t actual_field_size = sizeof(FT), #ifdef DEBUG_LEGION bool check_field_size = true, #else bool check_field_size = false, #endif bool silence_warnings = false, const char *warning_string = NULL, size_t offset = 0) : field(fid) { if (start == stop) return; DomainT<N,T> is; const PhysicalRegion &region = *start; region_privileges[0] = region.get_privilege(); const Realm::RegionInstance instance = region.get_instance_info(region_privileges[0], fid, actual_field_size, &is, Internal::NT_TemplateHelper::encode_tag<N,T>(), warning_string, silence_warnings, false/*generic accessor*/, check_field_size); region_bounds[0] = AffineBounds::Tester<N,T>(is); Rect<N,T> bounds = is.bounds; unsigned idx = 1; while (++start != stop) { assert(idx < MR); region_privileges[idx] = start->get_privilege(); const Realm::RegionInstance inst = start->get_instance_info( region_privileges[idx], fid, actual_field_size, &is, Internal::NT_TemplateHelper::encode_tag<N,T>(), warning_string, silence_warnings, false/*generic accessor*/, check_field_size); if (inst != instance) region.report_incompatible_multi_accessor(idx, fid, instance, inst); region_bounds[idx] = AffineBounds::Tester<N,T>(is); bounds = bounds.union_bbox(is.bounds); idx++; } if (!Realm::MultiAffineAccessor<FT,N,T>::is_compatible(instance, fid, bounds)) region.report_incompatible_accessor("MultiAffineAccessor", instance, fid); accessor = Realm::MultiAffineAccessor<FT,N,T>(instance, fid, bounds, offset); total_regions = idx; } template<typename InputIterator> MultiRegionAccessor(InputIterator start, InputIterator stop, const Rect<N,T> source_bounds, FieldID fid, size_t actual_field_size = sizeof(FT), #ifdef DEBUG_LEGION bool check_field_size = true, #else bool check_field_size = false, #endif bool silence_warnings = false, const char *warning_string = NULL, size_t offset = 0) : field(fid) { if (start == stop) return; DomainT<N,T> is; const PhysicalRegion &region = *start; region_privileges[0] = region.get_privilege(); const Realm::RegionInstance instance = region.get_instance_info(region_privileges[0], fid, actual_field_size, &is, Internal::NT_TemplateHelper::encode_tag<N,T>(), warning_string, silence_warnings, false/*generic accessor*/, check_field_size); region_bounds[0] = AffineBounds::Tester<N,T>(is, source_bounds); Rect<N,T> bounds = source_bounds.intersection(is.bounds); unsigned idx = 1; while (++start != stop) { assert(idx < MR); region_privileges[idx] = start->get_privilege(); const Realm::RegionInstance inst = start->get_instance_info( region_privileges[idx], fid, actual_field_size, &is, Internal::NT_TemplateHelper::encode_tag<N,T>(), warning_string, silence_warnings, false/*generic accessor*/, check_field_size); if (inst != instance) region.report_incompatible_multi_accessor(idx, fid, instance, inst); region_bounds[idx] = AffineBounds::Tester<N,T>(is, source_bounds); bounds = bounds.union_bbox(source_bounds.inersection(is.bounds)); idx++; } if (!Realm::MultiAffineAccessor<FT,N,T>::is_compatible(instance, fid, bounds)) region.report_incompatible_accessor("MultiAffineAccessor", instance, fid); accessor = Realm::MultiAffineAccessor<FT,N,T>(instance, fid, bounds, offset); total_regions = idx; } public: MultiRegionAccessor(const std::vector<PhysicalRegion> &regions, FieldID fid, size_t actual_field_size = sizeof(FT), #ifdef DEBUG_LEGION bool check_field_size = true, #else bool check_field_size = false, #endif bool silence_warnings = false, const char *warning_string = NULL, size_t offset = 0) : field(fid), total_regions(regions.size()) { if (regions.empty()) return; DomainT<N,T> is; const PhysicalRegion &region = regions.front(); region_privileges[0] = region.get_privilege(); const Realm::RegionInstance instance = region.get_instance_info(region_privileges[0], fid, actual_field_size, &is, Internal::NT_TemplateHelper::encode_tag<N,T>(), warning_string, silence_warnings, false/*generic accessor*/, check_field_size); region_bounds[0] = AffineBounds::Tester<N,T>(is); Rect<N,T> bounds = is.bounds; for (unsigned idx = 1; idx < regions.size(); idx++) { region_privileges[idx] = regions[idx].get_privilege(); const Realm::RegionInstance inst = regions[idx].get_instance_info( region_privileges[idx], fid, actual_field_size, &is, Internal::NT_TemplateHelper::encode_tag<N,T>(), warning_string, silence_warnings, false/*generic accessor*/, check_field_size); if (inst != instance) region.report_incompatible_multi_accessor(idx, fid, instance, inst); region_bounds[idx] = AffineBounds::Tester<N,T>(is); bounds = bounds.union_bbox(is.bounds); } if (!Realm::MultiAffineAccessor<FT,N,T>::is_compatible(instance, fid, bounds)) region.report_incompatible_accessor("MultiAffineAccessor", instance, fid); accessor = Realm::MultiAffineAccessor<FT,N,T>(instance, fid, bounds, offset); } MultiRegionAccessor(const std::vector<PhysicalRegion> &regions, const Rect<N,T> source_bounds, FieldID fid, size_t actual_field_size = sizeof(FT), #ifdef DEBUG_LEGION bool check_field_size = true, #else bool check_field_size = false, #endif bool silence_warnings = false, const char *warning_string = NULL, size_t offset = 0) : field(fid), total_regions(regions.size()) { if (regions.empty()) return; DomainT<N,T> is; const PhysicalRegion &region = regions.front(); region_privileges[0] = region.get_privilege(); const Realm::RegionInstance instance = region.get_instance_info(region_privileges[0], fid, actual_field_size, &is, Internal::NT_TemplateHelper::encode_tag<N,T>(), warning_string, silence_warnings, false/*generic accessor*/, check_field_size); region_bounds[0] = AffineBounds::Tester<N,T>(is, source_bounds); Rect<N,T> bounds = source_bounds.intersection(is.bounds); for (unsigned idx = 1; idx < regions.size(); idx++) { region_privileges[idx] = regions[idx].get_privilege(); const Realm::RegionInstance inst = regions[idx].get_instance_info( region_privileges[idx], fid, actual_field_size, &is, Internal::NT_TemplateHelper::encode_tag<N,T>(), warning_string, silence_warnings, false/*generic accessor*/, check_field_size); if (inst != instance) region.report_incompatible_multi_accessor(idx, fid, instance, inst); region_bounds[idx] = AffineBounds::Tester<N,T>(is, source_bounds); bounds = bounds.union_bbox(source_bounds.inersection(is.bounds)); } if (!Realm::MultiAffineAccessor<FT,N,T>::is_compatible(instance, fid, bounds)) region.report_incompatible_accessor("MultiAffineAccessor", instance, fid); accessor = Realm::MultiAffineAccessor<FT,N,T>(instance, fid, bounds, offset); } public: __CUDA_HD__ inline FT read(const Point<N,T>& p) const { bool found = false; for (unsigned idx = 0; idx < total_regions; idx++) { if (!region_bounds[idx].contains(p)) continue; if ((region_privileges[idx] & LEGION_READ_ONLY) == 0) { #ifdef __CUDA_ARCH__ // bounds checks are not precise for CUDA so keep going to // see if there is another region that has it with the privileges continue; #else PhysicalRegion::fail_privilege_check(DomainPoint(p), field, region_privileges[idx]); #endif } found = true; break; } #ifdef __CUDA_ARCH__ assert(found); #else if (!found) PhysicalRegion::fail_bounds_check(DomainPoint(p), field, region_privileges[0], true/*multi*/); #endif return accessor.read(p); } __CUDA_HD__ inline void write(const Point<N,T>& p, FT val) const { bool found = false; for (unsigned idx = 0; idx < total_regions; idx++) { if (!region_bounds[idx].contains(p)) continue; if ((region_privileges[idx] & LEGION_WRITE_PRIV) == 0) { #ifdef __CUDA_ARCH__ // bounds checks are not precise for CUDA so keep going to // see if there is another region that has it with the privileges continue; #else PhysicalRegion::fail_privilege_check(DomainPoint(p), field, region_privileges[idx]); #endif } found = true; break; } #ifdef __CUDA_ARCH__ assert(found); #else if (!found) PhysicalRegion::fail_bounds_check(DomainPoint(p), field, region_privileges[0], true/*multi*/); #endif return accessor.write(p, val); } __CUDA_HD__ inline ArraySyntax::AffineRefHelper<FT> operator[](const Point<N,T>& p) const { int index = -1; for (unsigned idx = 0; idx < total_regions; idx++) { if (!region_bounds[idx].contains(p)) continue; index = idx; break; } #ifdef __CUDA_ARCH__ assert(index >= 0); #else if (index < 0) PhysicalRegion::fail_bounds_check(DomainPoint(p), field, region_privileges[0], true/*multi*/); #endif return ArraySyntax::AffineRefHelper<FT>(accessor[p], field, DomainPoint(p), region_privileges[index]); } __CUDA_HD__ inline ArraySyntax::AffineSyntaxHelper<MultiRegionAccessor<FT,N,T, Realm::MultiAffineAccessor<FT,N,T>,CB,true,MR>,FT,N,T,2,LEGION_NO_ACCESS> operator[](T index) const { return ArraySyntax::AffineSyntaxHelper<MultiRegionAccessor<FT,N,T, Realm::MultiAffineAccessor<FT,N,T>,CB,true,MR>,FT,N,T,2, LEGION_NO_ACCESS>(*this, Point<1,T>(index)); } template<typename REDOP, bool EXCLUSIVE> __CUDA_HD__ inline void reduce(const Point<N,T>& p, typename REDOP::RHS val) const { bool found = false; for (unsigned idx = 0; idx < total_regions; idx++) { if (!region_bounds[idx].contains(p)) continue; if ((region_privileges[idx] & LEGION_REDUCE_PRIV) == 0) { #ifdef __CUDA_ARCH__ // bounds checks are not precise for CUDA so keep going to // see if there is another region that has it with the privileges continue; #else PhysicalRegion::fail_privilege_check(DomainPoint(p), field, region_privileges[idx]); #endif } found = true; break; } #ifdef __CUDA_ARCH__ assert(found); #else if (!found) PhysicalRegion::fail_bounds_check(DomainPoint(p), field, region_privileges[0], true/*multi*/); #endif REDOP::template apply<EXCLUSIVE>(accessor[p], val); } public: Realm::MultiAffineAccessor<FT,N,T> accessor; FieldID field; PrivilegeMode region_privileges[MR]; AffineBounds::Tester<N,T> region_bounds[MR]; unsigned total_regions; public: typedef FT value_type; typedef FT& reference; typedef const FT& const_reference; static const int dim = N; }; // Multi-Accessor, multi affine, 1, with privilege checks // (implies bounds checks) template<typename FT, typename T, bool CB, int MR> class MultiRegionAccessor<FT,1,T, Realm::MultiAffineAccessor<FT,1,T>,CB,true,MR> { public: MultiRegionAccessor(void) { } public: template<typename InputIterator> MultiRegionAccessor(InputIterator start, InputIterator stop, FieldID fid, size_t actual_field_size = sizeof(FT), #ifdef DEBUG_LEGION bool check_field_size = true, #else bool check_field_size = false, #endif bool silence_warnings = false, const char *warning_string = NULL, size_t offset = 0) : field(fid) { if (start == stop) return; DomainT<1,T> is; const PhysicalRegion &region = *start; region_privileges[0] = region.get_privilege(); const Realm::RegionInstance instance = region.get_instance_info(region_privileges[0], fid, actual_field_size, &is, Internal::NT_TemplateHelper::encode_tag<1,T>(), warning_string, silence_warnings, false/*generic accessor*/, check_field_size); region_bounds[0] = AffineBounds::Tester<1,T>(is); Rect<1,T> bounds = is.bounds; unsigned idx = 1; while (++start != stop) { assert(idx < MR); region_privileges[idx] = start->get_privilege(); const Realm::RegionInstance inst = start->get_instance_info( region_privileges[idx], fid, actual_field_size, &is, Internal::NT_TemplateHelper::encode_tag<1,T>(), warning_string, silence_warnings, false/*generic accessor*/, check_field_size); if (inst != instance) region.report_incompatible_multi_accessor(idx, fid, instance, inst); region_bounds[idx] = AffineBounds::Tester<1,T>(is); bounds = bounds.union_bbox(is.bounds); idx++; } if (!Realm::MultiAffineAccessor<FT,1,T>::is_compatible(instance, fid, bounds)) region.report_incompatible_accessor("MultiAffineAccessor", instance, fid); accessor = Realm::MultiAffineAccessor<FT,1,T>(instance, fid, bounds); total_regions = idx; } template<typename InputIterator> MultiRegionAccessor(InputIterator start, InputIterator stop, const Rect<1,T> source_bounds, FieldID fid, size_t actual_field_size = sizeof(FT), #ifdef DEBUG_LEGION bool check_field_size = true, #else bool check_field_size = false, #endif bool silence_warnings = false, const char *warning_string = NULL, size_t offset = 0) : field(fid) { if (start == stop) return; DomainT<1,T> is; const PhysicalRegion &region = *start; region_privileges[0] = region.get_privilege(); const Realm::RegionInstance instance = region.get_instance_info(region_privileges[0], fid, actual_field_size, &is, Internal::NT_TemplateHelper::encode_tag<1,T>(), warning_string, silence_warnings, false/*generic accessor*/, check_field_size); region_bounds[0] = AffineBounds::Tester<1,T>(is, source_bounds); Rect<1,T> bounds = source_bounds.intersection(is.bounds); unsigned idx = 1; while (++start != stop) { assert(idx < MR); region_privileges[idx] = start->get_privilege(); const Realm::RegionInstance inst = start->get_instance_info( region_privileges[idx], fid, actual_field_size, &is, Internal::NT_TemplateHelper::encode_tag<1,T>(), warning_string, silence_warnings, false/*generic accessor*/, check_field_size); if (inst != instance) region.report_incompatible_multi_accessor(idx, fid, instance, inst); region_bounds[idx] = AffineBounds::Tester<1,T>(is, source_bounds); bounds = bounds.union_bbox(source_bounds.inersection(is.bounds)); idx++; } if (!Realm::MultiAffineAccessor<FT,1,T>::is_compatible(instance, fid, bounds)) region.report_incompatible_accessor("MultiAffineAccessor", instance, fid); accessor = Realm::MultiAffineAccessor<FT,1,T>(instance, fid, bounds); total_regions = idx; } public: MultiRegionAccessor(const std::vector<PhysicalRegion> &regions, FieldID fid, size_t actual_field_size = sizeof(FT), #ifdef DEBUG_LEGION bool check_field_size = true, #else bool check_field_size = false, #endif bool silence_warnings = false, const char *warning_string = NULL, size_t offset = 0) : field(fid), total_regions(regions.size()) { if (regions.empty()) return; DomainT<1,T> is; const PhysicalRegion &region = regions.front(); region_privileges[0] = region.get_privilege(); const Realm::RegionInstance instance = region.get_instance_info(region_privileges[0], fid, actual_field_size, &is, Internal::NT_TemplateHelper::encode_tag<1,T>(), warning_string, silence_warnings, false/*generic accessor*/, check_field_size); region_bounds[0] = AffineBounds::Tester<1,T>(is); Rect<1,T> bounds = is.bounds; for (unsigned idx = 1; idx < regions.size(); idx++) { region_privileges[idx] = regions[idx].get_privilege(); const Realm::RegionInstance inst = regions[idx].get_instance_info( region_privileges[idx], fid, actual_field_size, &is, Internal::NT_TemplateHelper::encode_tag<1,T>(), warning_string, silence_warnings, false/*generic accessor*/, check_field_size); if (inst != instance) region.report_incompatible_multi_accessor(idx, fid, instance, inst); region_bounds[idx] = AffineBounds::Tester<1,T>(is); bounds = bounds.union_bbox(is.bounds); } if (!Realm::MultiAffineAccessor<FT,1,T>::is_compatible(instance, fid, bounds)) region.report_incompatible_accessor("MultiAffineAccessor", instance, fid); accessor = Realm::MultiAffineAccessor<FT,1,T>(instance, fid, bounds); } MultiRegionAccessor(const std::vector<PhysicalRegion> &regions, const Rect<1,T> source_bounds, FieldID fid, size_t actual_field_size = sizeof(FT), #ifdef DEBUG_LEGION bool check_field_size = true, #else bool check_field_size = false, #endif bool silence_warnings = false, const char *warning_string = NULL, size_t offset = 0) : field(fid), total_regions(regions.size()) { if (regions.empty()) return; DomainT<1,T> is; const PhysicalRegion &region = regions.front(); region_privileges[0] = region.get_privilege(); const Realm::RegionInstance instance = region.get_instance_info(region_privileges[0], fid, actual_field_size, &is, Internal::NT_TemplateHelper::encode_tag<1,T>(), warning_string, silence_warnings, false/*generic accessor*/, check_field_size); region_bounds[0] = AffineBounds::Tester<1,T>(is, source_bounds); Rect<1,T> bounds = source_bounds.intersection(is.bounds); for (unsigned idx = 1; idx < regions.size(); idx++) { region_privileges[idx] = regions[idx].get_privilege(); const Realm::RegionInstance inst = regions[idx].get_instance_info( region_privileges[idx], fid, actual_field_size, &is, Internal::NT_TemplateHelper::encode_tag<1,T>(), warning_string, silence_warnings, false/*generic accessor*/, check_field_size); if (inst != instance) region.report_incompatible_multi_accessor(idx, fid, instance, inst); region_bounds[idx] = AffineBounds::Tester<1,T>(is, source_bounds); bounds = bounds.union_bbox(source_bounds.inersection(is.bounds)); } if (!Realm::MultiAffineAccessor<FT,1,T>::is_compatible(instance, fid, bounds)) region.report_incompatible_accessor("MultiAffineAccessor", instance, fid); accessor = Realm::MultiAffineAccessor<FT,1,T>(instance, fid, bounds); } public: __CUDA_HD__ inline FT read(const Point<1,T>& p) const { bool found = false; for (unsigned idx = 0; idx < total_regions; idx++) { if (!region_bounds[idx].contains(p)) continue; if ((region_privileges[idx] & LEGION_READ_ONLY) == 0) { #ifdef __CUDA_ARCH__ // bounds checks are not precise for CUDA so keep going to // see if there is another region that has it with the privileges continue; #else PhysicalRegion::fail_privilege_check(DomainPoint(p), field, region_privileges[idx]); #endif } found = true; break; } #ifdef __CUDA_ARCH__ assert(found); #else if (!found) PhysicalRegion::fail_bounds_check(DomainPoint(p), field, region_privileges[0], true/*multi*/); #endif return accessor.read(p); } __CUDA_HD__ inline void write(const Point<1,T>& p, FT val) const { bool found = false; for (unsigned idx = 0; idx < total_regions; idx++) { if (!region_bounds[idx].contains(p)) continue; if ((region_privileges[idx] & LEGION_WRITE_PRIV) == 0) { #ifdef __CUDA_ARCH__ // bounds checks are not precise for CUDA so keep going to // see if there is another region that has it with the privileges continue; #else PhysicalRegion::fail_privilege_check(DomainPoint(p), field, region_privileges[idx]); #endif } found = true; break; } #ifdef __CUDA_ARCH__ assert(found); #else if (!found) PhysicalRegion::fail_bounds_check(DomainPoint(p), field, region_privileges[0], true/*multi*/); #endif return accessor.write(p, val); } __CUDA_HD__ inline ArraySyntax::AffineRefHelper<FT> operator[](const Point<1,T>& p) const { int index = -1; for (unsigned idx = 0; idx < total_regions; idx++) { if (!region_bounds[idx].contains(p)) continue; index = idx; break; } #ifdef __CUDA_ARCH__ assert(index >= 0); #else if (index < 0) PhysicalRegion::fail_bounds_check(DomainPoint(p), field, region_privileges[0], true/*multi*/); #endif return ArraySyntax::AffineRefHelper<FT>(accessor[p], field, DomainPoint(p), region_privileges[index]); } template<typename REDOP, bool EXCLUSIVE> __CUDA_HD__ inline void reduce(const Point<1,T>& p, typename REDOP::RHS val) const { bool found = false; for (unsigned idx = 0; idx < total_regions; idx++) { if (!region_bounds[idx].contains(p)) continue; if ((region_privileges[idx] & LEGION_REDUCE_PRIV) == 0) { #ifdef __CUDA_ARCH__ // bounds checks are not precise for CUDA so keep going to // see if there is another region that has it with the privileges continue; #else PhysicalRegion::fail_privilege_check(DomainPoint(p), field, region_privileges[idx]); #endif } found = true; break; } #ifdef __CUDA_ARCH__ assert(found); #else if (!found) PhysicalRegion::fail_bounds_check(DomainPoint(p), field, region_privileges[0], true/*multi*/); #endif REDOP::template apply<EXCLUSIVE>(accessor[p], val); } public: Realm::MultiAffineAccessor<FT,1,T> accessor; FieldID field; PrivilegeMode region_privileges[MR]; AffineBounds::Tester<1,T> region_bounds[MR]; unsigned total_regions; public: typedef FT value_type; typedef FT& reference; typedef const FT& const_reference; static const int dim = 1; }; // Multi-Accessor, multi affine, N, bounds checks only template<typename FT, int N, typename T, int MR> class MultiRegionAccessor<FT,N,T,Realm::MultiAffineAccessor<FT,N,T>, true/*check bounds*/,false/*check privileges*/,MR> { public: MultiRegionAccessor(void) { } public: template<typename InputIterator> MultiRegionAccessor(InputIterator start, InputIterator stop, FieldID fid, size_t actual_field_size = sizeof(FT), #ifdef DEBUG_LEGION bool check_field_size = true, #else bool check_field_size = false, #endif bool silence_warnings = false, const char *warning_string = NULL, size_t offset = 0) : field(fid) { if (start == stop) return; DomainT<N,T> is; const PhysicalRegion &region = *start; region_privileges[0] = region.get_privilege(); const Realm::RegionInstance instance = region.get_instance_info(region_privileges[0], fid, actual_field_size, &is, Internal::NT_TemplateHelper::encode_tag<N,T>(), warning_string, silence_warnings, false/*generic accessor*/, check_field_size); region_bounds[0] = AffineBounds::Tester<N,T>(is); Rect<N,T> bounds = is.bounds; unsigned idx = 0; while (++start != stop) { assert(idx < MR); region_privileges[idx] = start->get_privilege(); const Realm::RegionInstance inst = start->get_instance_info( region_privileges[idx], fid, actual_field_size, &is, Internal::NT_TemplateHelper::encode_tag<N,T>(), warning_string, silence_warnings, false/*generic accessor*/, check_field_size); if (inst != instance) region.report_incompatible_multi_accessor(idx, fid, instance, inst); region_bounds[idx] = AffineBounds::Tester<N,T>(is); bounds = bounds.union_bbox(is.bounds); idx++; } if (!Realm::MultiAffineAccessor<FT,N,T>::is_compatible(instance, fid, bounds)) region.report_incompatible_accessor("MultiAffineAccessor", instance, fid); accessor = Realm::MultiAffineAccessor<FT,N,T>(instance, fid, bounds, offset); total_regions = idx; } template<typename InputIterator> MultiRegionAccessor(InputIterator start, InputIterator stop, const Rect<N,T> source_bounds, FieldID fid, size_t actual_field_size = sizeof(FT), #ifdef DEBUG_LEGION bool check_field_size = true, #else bool check_field_size = false, #endif bool silence_warnings = false, const char *warning_string = NULL, size_t offset = 0) : field(fid) { if (start == stop) return; DomainT<N,T> is; const PhysicalRegion &region = *start; region_privileges[0] = region.get_privilege(); const Realm::RegionInstance instance = region.get_instance_info(region_privileges[0], fid, actual_field_size, &is, Internal::NT_TemplateHelper::encode_tag<N,T>(), warning_string, silence_warnings, false/*generic accessor*/, check_field_size); region_bounds[0] = AffineBounds::Tester<N,T>(is, source_bounds); Rect<N,T> bounds = source_bounds.intersection(is.bounds); unsigned idx = 1; while (++start != stop) { assert(idx < MR); region_privileges[idx] = start->get_privilege(); const Realm::RegionInstance inst = start->get_instance_info( region_privileges[idx], fid, actual_field_size, &is, Internal::NT_TemplateHelper::encode_tag<N,T>(), warning_string, silence_warnings, false/*generic accessor*/, check_field_size); if (inst != instance) region.report_incompatible_multi_accessor(idx, fid, instance, inst); region_bounds[idx] = AffineBounds::Tester<N,T>(is, source_bounds); bounds = bounds.union_bbox(source_bounds.inersection(is.bounds)); idx++; } if (!Realm::MultiAffineAccessor<FT,N,T>::is_compatible(instance, fid, bounds)) region.report_incompatible_accessor("MultiAffineAccessor", instance, fid); accessor = Realm::MultiAffineAccessor<FT,N,T>(instance, fid, bounds, offset); total_regions = idx; } public: MultiRegionAccessor(const std::vector<PhysicalRegion> &regions, FieldID fid, size_t actual_field_size = sizeof(FT), #ifdef DEBUG_LEGION bool check_field_size = true, #else bool check_field_size = false, #endif bool silence_warnings = false, const char *warning_string = NULL, size_t offset = 0) : field(fid), total_regions(regions.size()) { if (regions.empty()) return; DomainT<N,T> is; const PhysicalRegion &region = regions.front(); region_privileges[0] = region.get_privilege(); const Realm::RegionInstance instance = region.get_instance_info(region_privileges[0], fid, actual_field_size, &is, Internal::NT_TemplateHelper::encode_tag<N,T>(), warning_string, silence_warnings, false/*generic accessor*/, check_field_size); region_bounds[0] = AffineBounds::Tester<N,T>(is); Rect<N,T> bounds = is.bounds; for (unsigned idx = 1; idx < regions.size(); idx++) { region_privileges[idx] = regions[idx].get_privilege(); const Realm::RegionInstance inst = regions[idx].get_instance_info( region_privileges[idx], fid, actual_field_size, &is, Internal::NT_TemplateHelper::encode_tag<N,T>(), warning_string, silence_warnings, false/*generic accessor*/, check_field_size); if (inst != instance) region.report_incompatible_multi_accessor(idx, fid, instance, inst); region_bounds[idx] = AffineBounds::Tester<N,T>(is); bounds = bounds.union_bbox(is.bounds); } if (!Realm::MultiAffineAccessor<FT,N,T>::is_compatible(instance, fid, bounds)) region.report_incompatible_accessor("MultiAffineAccessor", instance, fid); accessor = Realm::MultiAffineAccessor<FT,N,T>(instance, fid, bounds, offset); } MultiRegionAccessor(const std::vector<PhysicalRegion> &regions, const Rect<N,T> source_bounds, FieldID fid, size_t actual_field_size = sizeof(FT), #ifdef DEBUG_LEGION bool check_field_size = true, #else bool check_field_size = false, #endif bool silence_warnings = false, const char *warning_string = NULL, size_t offset = 0) : field(fid), total_regions(regions.size()) { if (regions.empty()) return; DomainT<N,T> is; const PhysicalRegion &region = regions.front(); region_privileges[0] = region.get_privilege(); const Realm::RegionInstance instance = region.get_instance_info(region_privileges[0], fid, actual_field_size, &is, Internal::NT_TemplateHelper::encode_tag<N,T>(), warning_string, silence_warnings, false/*generic accessor*/, check_field_size); region_bounds[0] = AffineBounds::Tester<N,T>(is, source_bounds); Rect<N,T> bounds = source_bounds.intersection(is.bounds); for (unsigned idx = 1; idx < regions.size(); idx++) { region_privileges[idx] = regions[idx].get_privilege(); const Realm::RegionInstance inst = regions[idx].get_instance_info( region_privileges[idx], fid, actual_field_size, &is, Internal::NT_TemplateHelper::encode_tag<N,T>(), warning_string, silence_warnings, false/*generic accessor*/, check_field_size); if (inst != instance) region.report_incompatible_multi_accessor(idx, fid, instance, inst); region_bounds[idx] = AffineBounds::Tester<N,T>(is, source_bounds); bounds = bounds.union_bbox(source_bounds.inersection(is.bounds)); } if (!Realm::MultiAffineAccessor<FT,N,T>::is_compatible(instance, fid, bounds)) region.report_incompatible_accessor("MultiAffineAccessor", instance, fid); accessor = Realm::MultiAffineAccessor<FT,N,T>(instance, fid, bounds, offset); } public: __CUDA_HD__ inline FT read(const Point<N,T>& p) const { bool found = false; for (unsigned idx = 0; idx < total_regions; idx++) { if (!region_bounds[idx].contains(p)) continue; found = true; break; } #ifdef __CUDA_ARCH__ assert(found); #else if (!found) PhysicalRegion::fail_bounds_check(DomainPoint(p), field, region_privileges[0], true/*multi*/); #endif return accessor.read(p); } __CUDA_HD__ inline void write(const Point<N,T>& p, FT val) const { bool found = false; for (unsigned idx = 0; idx < total_regions; idx++) { if (!region_bounds[idx].contains(p)) continue; found = true; break; } #ifdef __CUDA_ARCH__ assert(found); #else if (!found) PhysicalRegion::fail_bounds_check(DomainPoint(p), field, region_privileges[0], true/*multi*/); #endif return accessor.write(p, val); } __CUDA_HD__ inline FT& operator[](const Point<N,T>& p) const { int index = -1; for (unsigned idx = 0; idx < total_regions; idx++) { if (!region_bounds[idx].contains(p)) continue; index = idx; break; } #ifdef __CUDA_ARCH__ assert(index >= 0); #else if (index < 0) PhysicalRegion::fail_bounds_check(DomainPoint(p), field, region_privileges[0], true/*multi*/); #endif return accessor[p]; } __CUDA_HD__ inline ArraySyntax::AffineSyntaxHelper<MultiRegionAccessor<FT,N,T, Realm::MultiAffineAccessor<FT,N,T>,true,false,MR>, FT,N,T,2,LEGION_READ_WRITE> operator[](T index) const { return ArraySyntax::AffineSyntaxHelper<MultiRegionAccessor<FT,N,T, Realm::MultiAffineAccessor<FT,N,T>,true,false,MR>, FT,N,T,2,LEGION_READ_WRITE>(*this, Point<1,T>(index)); } template<typename REDOP, bool EXCLUSIVE> __CUDA_HD__ inline void reduce(const Point<N,T>& p, typename REDOP::RHS val) const { bool found = false; for (unsigned idx = 0; idx < total_regions; idx++) { if (!region_bounds[idx].contains(p)) continue; found = true; break; } #ifdef __CUDA_ARCH__ assert(found); #else if (!found) PhysicalRegion::fail_bounds_check(DomainPoint(p), field, region_privileges[0], true/*multi*/); #endif REDOP::template apply<EXCLUSIVE>(accessor[p], val); } public: Realm::MultiAffineAccessor<FT,N,T> accessor; FieldID field; PrivilegeMode region_privileges[MR]; AffineBounds::Tester<N,T> region_bounds[MR]; unsigned total_regions; public: typedef FT value_type; typedef FT& reference; typedef const FT& const_reference; static const int dim = N; }; // Multi-Accessor, multi affine, 1, bounds checks only template<typename FT, typename T, int MR> class MultiRegionAccessor<FT,1,T,Realm::MultiAffineAccessor<FT,1,T>, true/*check bounds*/,false/*check privileges*/,MR> { public: MultiRegionAccessor(void) { } public: template<typename InputIterator> MultiRegionAccessor(InputIterator start, InputIterator stop, FieldID fid, size_t actual_field_size = sizeof(FT), #ifdef DEBUG_LEGION bool check_field_size = true, #else bool check_field_size = false, #endif bool silence_warnings = false, const char *warning_string = NULL, size_t offset = 0) : field(fid) { if (start == stop) return; DomainT<1,T> is; const PhysicalRegion &region = *start; region_privileges[0] = region.get_privilege(); const Realm::RegionInstance instance = region.get_instance_info(region_privileges[0], fid, actual_field_size, &is, Internal::NT_TemplateHelper::encode_tag<1,T>(), warning_string, silence_warnings, false/*generic accessor*/, check_field_size); region_bounds[0] = AffineBounds::Tester<1,T>(is); Rect<1,T> bounds = is.bounds; unsigned idx = 0; while (++start != stop) { assert(idx < MR); region_privileges[idx] = start->get_privilege(); const Realm::RegionInstance inst = start->get_instance_info( region_privileges[idx], fid, actual_field_size, &is, Internal::NT_TemplateHelper::encode_tag<1,T>(), warning_string, silence_warnings, false/*generic accessor*/, check_field_size); if (inst != instance) region.report_incompatible_multi_accessor(idx, fid, instance, inst); region_bounds[idx] = AffineBounds::Tester<1,T>(is); bounds = bounds.union_bbox(is.bounds); idx++; } if (!Realm::MultiAffineAccessor<FT,1,T>::is_compatible(instance, fid, bounds)) region.report_incompatible_accessor("MultiAffineAccessor", instance, fid); accessor = Realm::MultiAffineAccessor<FT,1,T>(instance, fid, bounds); total_regions = idx; } template<typename InputIterator> MultiRegionAccessor(InputIterator start, InputIterator stop, const Rect<1,T> source_bounds, FieldID fid, size_t actual_field_size = sizeof(FT), #ifdef DEBUG_LEGION bool check_field_size = true, #else bool check_field_size = false, #endif bool silence_warnings = false, const char *warning_string = NULL, size_t offset = 0) : field(fid) { if (start == stop) return; DomainT<1,T> is; const PhysicalRegion &region = *start; region_privileges[0] = region.get_privilege(); const Realm::RegionInstance instance = region.get_instance_info(region_privileges[0], fid, actual_field_size, &is, Internal::NT_TemplateHelper::encode_tag<1,T>(), warning_string, silence_warnings, false/*generic accessor*/, check_field_size); region_bounds[0] = AffineBounds::Tester<1,T>(is, source_bounds); Rect<1,T> bounds = source_bounds.intersection(is.bounds); unsigned idx = 1; while (++start != stop) { assert(idx < MR); region_privileges[idx] = start->get_privilege(); const Realm::RegionInstance inst = start->get_instance_info( region_privileges[idx], fid, actual_field_size, &is, Internal::NT_TemplateHelper::encode_tag<1,T>(), warning_string, silence_warnings, false/*generic accessor*/, check_field_size); if (inst != instance) region.report_incompatible_multi_accessor(idx, fid, instance, inst); region_bounds[idx] = AffineBounds::Tester<1,T>(is, source_bounds); bounds = bounds.union_bbox(source_bounds.inersection(is.bounds)); idx++; } if (!Realm::MultiAffineAccessor<FT,1,T>::is_compatible(instance, fid, bounds)) region.report_incompatible_accessor("MultiAffineAccessor", instance, fid); accessor = Realm::MultiAffineAccessor<FT,1,T>(instance, fid, bounds); total_regions = idx; } public: MultiRegionAccessor(const std::vector<PhysicalRegion> &regions, FieldID fid, size_t actual_field_size = sizeof(FT), #ifdef DEBUG_LEGION bool check_field_size = true, #else bool check_field_size = false, #endif bool silence_warnings = false, const char *warning_string = NULL, size_t offset = 0) : field(fid), total_regions(regions.size()) { if (regions.empty()) return; DomainT<1,T> is; const PhysicalRegion &region = regions.front(); region_privileges[0] = region.get_privilege(); const Realm::RegionInstance instance = region.get_instance_info(region_privileges[0], fid, actual_field_size, &is, Internal::NT_TemplateHelper::encode_tag<1,T>(), warning_string, silence_warnings, false/*generic accessor*/, check_field_size); region_bounds[0] = AffineBounds::Tester<1,T>(is); Rect<1,T> bounds = is.bounds; for (unsigned idx = 1; idx < regions.size(); idx++) { region_privileges[idx] = regions[idx].get_privilege(); const Realm::RegionInstance inst = regions[idx].get_instance_info( region_privileges[idx], fid, actual_field_size, &is, Internal::NT_TemplateHelper::encode_tag<1,T>(), warning_string, silence_warnings, false/*generic accessor*/, check_field_size); if (inst != instance) region.report_incompatible_multi_accessor(idx, fid, instance, inst); region_bounds[idx] = AffineBounds::Tester<1,T>(is); bounds = bounds.union_bbox(is.bounds); } if (!Realm::MultiAffineAccessor<FT,1,T>::is_compatible(instance, fid, bounds)) region.report_incompatible_accessor("MultiAffineAccessor", instance, fid); accessor = Realm::MultiAffineAccessor<FT,1,T>(instance, fid, bounds); } MultiRegionAccessor(const std::vector<PhysicalRegion> &regions, const Rect<1,T> source_bounds, FieldID fid, size_t actual_field_size = sizeof(FT), #ifdef DEBUG_LEGION bool check_field_size = true, #else bool check_field_size = false, #endif bool silence_warnings = false, const char *warning_string = NULL, size_t offset = 0) : field(fid), total_regions(regions.size()) { if (regions.empty()) return; DomainT<1,T> is; const PhysicalRegion &region = regions.front(); region_privileges[0] = region.get_privilege(); const Realm::RegionInstance instance = region.get_instance_info(region_privileges[0], fid, actual_field_size, &is, Internal::NT_TemplateHelper::encode_tag<1,T>(), warning_string, silence_warnings, false/*generic accessor*/, check_field_size); region_bounds[0] = AffineBounds::Tester<1,T>(is, source_bounds); Rect<1,T> bounds = source_bounds.intersection(is.bounds); for (unsigned idx = 1; idx < regions.size(); idx++) { region_privileges[idx] = regions[idx].get_privilege(); const Realm::RegionInstance inst = regions[idx].get_instance_info( region_privileges[idx], fid, actual_field_size, &is, Internal::NT_TemplateHelper::encode_tag<1,T>(), warning_string, silence_warnings, false/*generic accessor*/, check_field_size); if (inst != instance) region.report_incompatible_multi_accessor(idx, fid, instance, inst); region_bounds[idx] = AffineBounds::Tester<1,T>(is, source_bounds); bounds = bounds.union_bbox(source_bounds.inersection(is.bounds)); } if (!Realm::MultiAffineAccessor<FT,1,T>::is_compatible(instance, fid, bounds)) region.report_incompatible_accessor("MultiAffineAccessor", instance, fid); accessor = Realm::MultiAffineAccessor<FT,1,T>(instance, fid, bounds); } public: __CUDA_HD__ inline FT read(const Point<1,T>& p) const { bool found = false; for (unsigned idx = 0; idx < total_regions; idx++) { if (!region_bounds[idx].contains(p)) continue; found = true; break; } #ifdef __CUDA_ARCH__ assert(found); #else if (!found) PhysicalRegion::fail_bounds_check(DomainPoint(p), field, region_privileges[0], true/*multi*/); #endif return accessor.read(p); } __CUDA_HD__ inline void write(const Point<1,T>& p, FT val) const { bool found = false; for (unsigned idx = 0; idx < total_regions; idx++) { if (!region_bounds[idx].contains(p)) continue; found = true; break; } #ifdef __CUDA_ARCH__ assert(found); #else if (!found) PhysicalRegion::fail_bounds_check(DomainPoint(p), field, region_privileges[0], true/*multi*/); #endif return accessor.write(p, val); } __CUDA_HD__ inline FT& operator[](const Point<1,T>& p) const { int index = -1; for (unsigned idx = 0; idx < total_regions; idx++) { if (!region_bounds[idx].contains(p)) continue; index = idx; break; } #ifdef __CUDA_ARCH__ assert(index >= 0); #else if (index < 0) PhysicalRegion::fail_bounds_check(DomainPoint(p), field, region_privileges[0], true/*multi*/); #endif return accessor[p]; } template<typename REDOP, bool EXCLUSIVE> __CUDA_HD__ inline void reduce(const Point<1,T>& p, typename REDOP::RHS val) const { bool found = false; for (unsigned idx = 0; idx < total_regions; idx++) { if (!region_bounds[idx].contains(p)) continue; found = true; break; } #ifdef __CUDA_ARCH__ assert(found); #else if (!found) PhysicalRegion::fail_bounds_check(DomainPoint(p), field, region_privileges[0], true/*multi*/); #endif REDOP::template apply<EXCLUSIVE>(accessor[p], val); } public: Realm::MultiAffineAccessor<FT,1,T> accessor; FieldID field; PrivilegeMode region_privileges[MR]; AffineBounds::Tester<1,T> region_bounds[MR]; unsigned total_regions; public: typedef FT value_type; typedef FT& reference; typedef const FT& const_reference; static const int dim = 1; }; // Multi-Accessor, multi affine, N, no bounds, no privileges template<typename FT, int N, typename T, int MR> class MultiRegionAccessor<FT,N,T,Realm::MultiAffineAccessor<FT,N,T>, false/*check bounds*/,false/*check privileges*/,MR> { public: MultiRegionAccessor(void) { } public: template<typename InputIterator> MultiRegionAccessor(InputIterator start, InputIterator stop, FieldID fid, size_t actual_field_size = sizeof(FT), #ifdef DEBUG_LEGION bool check_field_size = true, #else bool check_field_size = false, #endif bool silence_warnings = false, const char *warning_string = NULL, size_t offset = 0) { if (start == stop) return; DomainT<N,T> is; const PhysicalRegion &region = *start; const Realm::RegionInstance instance = region.get_instance_info(region.get_privilege(), fid, actual_field_size, &is, Internal::NT_TemplateHelper::encode_tag<N,T>(), warning_string, silence_warnings, false/*generic accessor*/, check_field_size); Rect<N,T> bounds = is.bounds; unsigned idx = 1; while (++start != stop) { assert(idx < MR); const Realm::RegionInstance inst = start->get_instance_info( start->get_privilege(), fid, actual_field_size, &is, Internal::NT_TemplateHelper::encode_tag<N,T>(), warning_string, silence_warnings, false/*generic accessor*/, check_field_size); if (inst != instance) region.report_incompatible_multi_accessor(idx, fid, instance, inst); bounds = bounds.union_bbox(is.bounds); idx++; } if (!Realm::MultiAffineAccessor<FT,N,T>::is_compatible(instance, fid, bounds)) region.report_incompatible_accessor("MultiAffineAccessor", instance, fid); accessor = Realm::MultiAffineAccessor<FT,N,T>(instance, fid, bounds, offset); } template<typename InputIterator> MultiRegionAccessor(InputIterator start, InputIterator stop, const Rect<N,T> source_bounds, FieldID fid, size_t actual_field_size = sizeof(FT), #ifdef DEBUG_LEGION bool check_field_size = true, #else bool check_field_size = false, #endif bool silence_warnings = false, const char *warning_string = NULL, size_t offset = 0) { if (start == stop) return; DomainT<N,T> is; const PhysicalRegion &region = *start; const Realm::RegionInstance instance = region.get_instance_info(region.get_privilege(), fid, actual_field_size, &is, Internal::NT_TemplateHelper::encode_tag<N,T>(), warning_string, silence_warnings, false/*generic accessor*/, check_field_size); Rect<N,T> bounds = source_bounds.intersection(is.bounds); unsigned idx = 1; while (++start != stop) { assert(idx < MR); const Realm::RegionInstance inst = start->get_instance_info( start->get_privilege(), fid, actual_field_size, &is, Internal::NT_TemplateHelper::encode_tag<N,T>(), warning_string, silence_warnings, false/*generic accessor*/, check_field_size); if (inst != instance) region.report_incompatible_multi_accessor(idx, fid, instance, inst); bounds = bounds.union_bbox(source_bounds.inersection(is.bounds)); idx++; } if (!Realm::MultiAffineAccessor<FT,N,T>::is_compatible(instance, fid, bounds)) region.report_incompatible_accessor("MultiAffineAccessor", instance, fid); accessor = Realm::MultiAffineAccessor<FT,N,T>(instance, fid, bounds, offset); } public: MultiRegionAccessor(const std::vector<PhysicalRegion> &regions, FieldID fid, size_t actual_field_size = sizeof(FT), #ifdef DEBUG_LEGION bool check_field_size = true, #else bool check_field_size = false, #endif bool silence_warnings = false, const char *warning_string = NULL, size_t offset = 0) { if (regions.empty()) return; DomainT<N,T> is; const PhysicalRegion &region = regions.front(); const Realm::RegionInstance instance = region.get_instance_info(region.get_privilege(), fid, actual_field_size, &is, Internal::NT_TemplateHelper::encode_tag<N,T>(), warning_string, silence_warnings, false/*generic accessor*/, check_field_size); Rect<N,T> bounds = is.bounds; for (unsigned idx = 1; idx < regions.size(); idx++) { const Realm::RegionInstance inst = regions[idx].get_instance_info( regions[idx].get_privilege(), fid, actual_field_size, &is, Internal::NT_TemplateHelper::encode_tag<N,T>(), warning_string, silence_warnings, false/*generic accessor*/, check_field_size); if (inst != instance) region.report_incompatible_multi_accessor(idx, fid, instance, inst); bounds = bounds.union_bbox(is.bounds); } if (!Realm::MultiAffineAccessor<FT,N,T>::is_compatible(instance, fid, bounds)) region.report_incompatible_accessor("MultiAffineAccessor", instance, fid); accessor = Realm::MultiAffineAccessor<FT,N,T>(instance, fid, bounds, offset); } MultiRegionAccessor(const std::vector<PhysicalRegion> &regions, const Rect<N,T> source_bounds, FieldID fid, size_t actual_field_size = sizeof(FT), #ifdef DEBUG_LEGION bool check_field_size = true, #else bool check_field_size = false, #endif bool silence_warnings = false, const char *warning_string = NULL, size_t offset = 0) { if (regions.empty()) return; DomainT<N,T> is; const PhysicalRegion &region = regions.front(); const Realm::RegionInstance instance = region.get_instance_info(region.get_privilege(), fid, actual_field_size, &is, Internal::NT_TemplateHelper::encode_tag<N,T>(), warning_string, silence_warnings, false/*generic accessor*/, check_field_size); Rect<N,T> bounds = source_bounds.intersection(is.bounds); for (unsigned idx = 1; idx < regions.size(); idx++) { const Realm::RegionInstance inst = regions[idx].get_instance_info( regions[idx].get_privilege(), fid, actual_field_size, &is, Internal::NT_TemplateHelper::encode_tag<N,T>(), warning_string, silence_warnings, false/*generic accessor*/, check_field_size); if (inst != instance) region.report_incompatible_multi_accessor(idx, fid, instance, inst); bounds = bounds.union_bbox(source_bounds.inersection(is.bounds)); } if (!Realm::MultiAffineAccessor<FT,N,T>::is_compatible(instance, fid, bounds)) region.report_incompatible_accessor("MultiAffineAccessor", instance, fid); accessor = Realm::MultiAffineAccessor<FT,N,T>(instance, fid, bounds, offset); } public: __CUDA_HD__ inline FT read(const Point<N,T>& p) const { return accessor.read(p); } __CUDA_HD__ inline void write(const Point<N,T>& p, FT val) const { return accessor.write(p, val); } __CUDA_HD__ inline FT& operator[](const Point<N,T>& p) const { return accessor[p]; } __CUDA_HD__ inline ArraySyntax::AffineSyntaxHelper<MultiRegionAccessor<FT,N,T, Realm::MultiAffineAccessor<FT,N,T>,false,false,MR>,FT,N,T,2, LEGION_READ_WRITE> operator[](T index) const { return ArraySyntax::AffineSyntaxHelper<MultiRegionAccessor<FT,N,T, Realm::MultiAffineAccessor<FT,N,T>,false,false,MR>, FT,N,T,2,LEGION_READ_WRITE>(*this, Point<1,T>(index)); } template<typename REDOP, bool EXCLUSIVE> __CUDA_HD__ inline void reduce(const Point<N,T>& p, typename REDOP::RHS val) const { REDOP::template apply<EXCLUSIVE>(accessor[p], val); } public: Realm::MultiAffineAccessor<FT,N,T> accessor; public: typedef FT value_type; typedef FT& reference; typedef const FT& const_reference; static const int dim = N; }; // Multi-Accessor, multi affine, 1, no bounds, no privileges template<typename FT, typename T, int MR> class MultiRegionAccessor<FT,1,T,Realm::MultiAffineAccessor<FT,1,T>, false/*check bounds*/,false/*check privileges*/,MR> { public: MultiRegionAccessor(void) { } public: template<typename InputIterator> MultiRegionAccessor(InputIterator start, InputIterator stop, FieldID fid, size_t actual_field_size = sizeof(FT), #ifdef DEBUG_LEGION bool check_field_size = true, #else bool check_field_size = false, #endif bool silence_warnings = false, const char *warning_string = NULL, size_t offset = 0) { if (start == stop) return; DomainT<1,T> is; const PhysicalRegion &region = *start; const Realm::RegionInstance instance = region.get_instance_info(region.get_privilege(), fid, actual_field_size, &is, Internal::NT_TemplateHelper::encode_tag<1,T>(), warning_string, silence_warnings, false/*generic accessor*/, check_field_size); Rect<1,T> bounds = is.bounds; unsigned idx = 1; while (++start != stop) { assert(idx < MR); const Realm::RegionInstance inst = start->get_instance_info( start->get_privilege(), fid, actual_field_size, &is, Internal::NT_TemplateHelper::encode_tag<1,T>(), warning_string, silence_warnings, false/*generic accessor*/, check_field_size); if (inst != instance) region.report_incompatible_multi_accessor(idx, fid, instance, inst); bounds = bounds.union_bbox(is.bounds); idx++; } if (!Realm::MultiAffineAccessor<FT,1,T>::is_compatible(instance, fid, bounds)) region.report_incompatible_accessor("MultiAffineAccessor", instance, fid); accessor = Realm::MultiAffineAccessor<FT,1,T>(instance, fid, bounds); } template<typename InputIterator> MultiRegionAccessor(InputIterator start, InputIterator stop, const Rect<1,T> source_bounds, FieldID fid, size_t actual_field_size = sizeof(FT), #ifdef DEBUG_LEGION bool check_field_size = true, #else bool check_field_size = false, #endif bool silence_warnings = false, const char *warning_string = NULL, size_t offset = 0) { if (start == stop) return; DomainT<1,T> is; const PhysicalRegion &region = *start; const Realm::RegionInstance instance = region.get_instance_info(region.get_privilege(), fid, actual_field_size, &is, Internal::NT_TemplateHelper::encode_tag<1,T>(), warning_string, silence_warnings, false/*generic accessor*/, check_field_size); Rect<1,T> bounds = source_bounds.intersection(is.bounds); unsigned idx = 1; while (++start != stop) { assert(idx < MR); const Realm::RegionInstance inst = start->get_instance_info( start->get_privilege(), fid, actual_field_size, &is, Internal::NT_TemplateHelper::encode_tag<1,T>(), warning_string, silence_warnings, false/*generic accessor*/, check_field_size); if (inst != instance) region.report_incompatible_multi_accessor(idx, fid, instance, inst); bounds = bounds.union_bbox(source_bounds.inersection(is.bounds)); idx++; } if (!Realm::MultiAffineAccessor<FT,1,T>::is_compatible(instance, fid, bounds)) region.report_incompatible_accessor("MultiAffineAccessor", instance, fid); accessor = Realm::MultiAffineAccessor<FT,1,T>(instance, fid, bounds); } public: MultiRegionAccessor(const std::vector<PhysicalRegion> &regions, FieldID fid, size_t actual_field_size = sizeof(FT), #ifdef DEBUG_LEGION bool check_field_size = true, #else bool check_field_size = false, #endif bool silence_warnings = false, const char *warning_string = NULL, size_t offset = 0) { if (regions.empty()) return; DomainT<1,T> is; const PhysicalRegion &region = regions.front(); const Realm::RegionInstance instance = region.get_instance_info(region.get_privilege(), fid, actual_field_size, &is, Internal::NT_TemplateHelper::encode_tag<1,T>(), warning_string, silence_warnings, false/*generic accessor*/, check_field_size); Rect<1,T> bounds = is.bounds; for (unsigned idx = 1; idx < regions.size(); idx++) { const Realm::RegionInstance inst = regions[idx].get_instance_info( regions[idx].get_privilege(), fid, actual_field_size, &is, Internal::NT_TemplateHelper::encode_tag<1,T>(), warning_string, silence_warnings, false/*generic accessor*/, check_field_size); if (inst != instance) region.report_incompatible_multi_accessor(idx, fid, instance, inst); bounds = bounds.union_bbox(is.bounds); } if (!Realm::MultiAffineAccessor<FT,1,T>::is_compatible(instance, fid, bounds)) region.report_incompatible_accessor("MultiAffineAccessor", instance, fid); accessor = Realm::MultiAffineAccessor<FT,1,T>(instance, fid, bounds); } MultiRegionAccessor(const std::vector<PhysicalRegion> &regions, const Rect<1,T> source_bounds, FieldID fid, size_t actual_field_size = sizeof(FT), #ifdef DEBUG_LEGION bool check_field_size = true, #else bool check_field_size = false, #endif bool silence_warnings = false, const char *warning_string = NULL, size_t offset = 0) { if (regions.empty()) return; DomainT<1,T> is; const PhysicalRegion &region = regions.front(); const Realm::RegionInstance instance = region.get_instance_info(region.get_privilege(), fid, actual_field_size, &is, Internal::NT_TemplateHelper::encode_tag<1,T>(), warning_string, silence_warnings, false/*generic accessor*/, check_field_size); Rect<1,T> bounds = source_bounds.intersection(is.bounds); for (unsigned idx = 1; idx < regions.size(); idx++) { const Realm::RegionInstance inst = regions[idx].get_instance_info( regions[idx].get_privilege(), fid, actual_field_size, &is, Internal::NT_TemplateHelper::encode_tag<1,T>(), warning_string, silence_warnings, false/*generic accessor*/, check_field_size); if (inst != instance) region.report_incompatible_multi_accessor(idx, fid, instance, inst); bounds = bounds.union_bbox(source_bounds.inersection(is.bounds)); } if (!Realm::MultiAffineAccessor<FT,1,T>::is_compatible(instance, fid, bounds)) region.report_incompatible_accessor("MultiAffineAccessor", instance, fid); accessor = Realm::MultiAffineAccessor<FT,1,T>(instance, fid, bounds); } public: __CUDA_HD__ inline FT read(const Point<1,T>& p) const { return accessor.read(p); } __CUDA_HD__ inline void write(const Point<1,T>& p, FT val) const { return accessor.write(p, val); } __CUDA_HD__ inline FT& operator[](const Point<1,T>& p) const { return accessor[p]; } template<typename REDOP, bool EXCLUSIVE> __CUDA_HD__ inline void reduce(const Point<1,T>& p, typename REDOP::RHS val) const { REDOP::template apply<EXCLUSIVE>(accessor[p], val); } public: Realm::MultiAffineAccessor<FT,1,T> accessor; public: typedef FT value_type; typedef FT& reference; typedef const FT& const_reference; static const int dim = 1; }; // A hidden class for users that really know what they are doing /** * \class UnsafeFieldAccessor * This is a class for getting access to region data without * privilege checks or bounds checks. Users should only use * this accessor if they are confident that they actually do * have their privileges and bounds correct */ template<typename FT, int N, typename T = coord_t, typename A = Realm::GenericAccessor<FT,N,T> > class UnsafeFieldAccessor { public: UnsafeFieldAccessor(void) { } UnsafeFieldAccessor(const PhysicalRegion &region, FieldID fid, bool silence_warnings = false, const char *warning_string = NULL, size_t offset = 0) { DomainT<N,T> is; const Realm::RegionInstance instance = region.get_instance_info(LEGION_NO_ACCESS, fid, sizeof(FT), &is, Internal::NT_TemplateHelper::encode_tag<N,T>(), warning_string, silence_warnings, true/*generic accessor*/, false/*check field size*/); if (!A::is_compatible(instance, fid, is.bounds)) region.report_incompatible_accessor("GenericAccessor", instance, fid); accessor = A(instance, fid, is.bounds, offset); } public: inline FT read(const Point<N,T> &p) const { return accessor.read(p); } inline void write(const Point<N,T> &p, FT val) const { accessor.write(p, val); } inline ArraySyntax::AccessorRefHelper<FT,LEGION_READ_WRITE> operator[](const Point<N,T> &p) const { return ArraySyntax::AccessorRefHelper<FT,LEGION_READ_WRITE>( accessor[p]); } inline ArraySyntax::GenericSyntaxHelper<UnsafeFieldAccessor<FT,N,T,A>, FT,N,T,2,LEGION_READ_WRITE> operator[](T index) const { return ArraySyntax::GenericSyntaxHelper<UnsafeFieldAccessor<FT,N,T,A>, FT,N,T,2,LEGION_READ_WRITE>(*this, Point<1,T>(index)); } public: mutable A accessor; public: typedef FT value_type; typedef FT& reference; typedef const FT& const_reference; static const int dim = N; }; template<typename FT, typename T> class UnsafeFieldAccessor<FT,1,T,Realm::GenericAccessor<FT,1,T> > { public: UnsafeFieldAccessor(void) { } UnsafeFieldAccessor(const PhysicalRegion &region, FieldID fid, bool silence_warnings = false, const char *warning_string = NULL, size_t offset = 0) { DomainT<1,T> is; const Realm::RegionInstance instance = region.get_instance_info(LEGION_NO_ACCESS, fid, sizeof(FT), &is, Internal::NT_TemplateHelper::encode_tag<1,T>(), warning_string, silence_warnings, true/*generic accessor*/, false/*check field size*/); if (!Realm::GenericAccessor<FT,1,T>::is_compatible(instance, fid, is.bounds)) region.report_incompatible_accessor("GenericAccessor", instance, fid); accessor = Realm::GenericAccessor<FT,1,T>(instance, fid, is.bounds, offset); } public: inline FT read(const Point<1,T> &p) const { return accessor.read(p); } inline void write(const Point<1,T> &p, FT val) const { accessor.write(p, val); } inline ArraySyntax::AccessorRefHelper<FT,LEGION_READ_WRITE> operator[](const Point<1,T> &p) const { return ArraySyntax::AccessorRefHelper<FT,LEGION_READ_WRITE>( accessor[p]); } public: mutable Realm::GenericAccessor<FT,1,T> accessor; public: typedef FT value_type; typedef FT& reference; typedef const FT& const_reference; static const int dim = 1; }; template<typename FT, int N, typename T> class UnsafeFieldAccessor<FT, N, T, Realm::AffineAccessor<FT,N,T> > { public: UnsafeFieldAccessor(void) { } UnsafeFieldAccessor(const PhysicalRegion &region, FieldID fid, bool silence_warnings = false, const char *warning_string = NULL, size_t offset = 0) { DomainT<N,T> is; const Realm::RegionInstance instance = region.get_instance_info(LEGION_NO_ACCESS, fid, sizeof(FT), &is, Internal::NT_TemplateHelper::encode_tag<N,T>(), warning_string, silence_warnings, false/*generic accessor*/, false/*check field size*/); if (!Realm::AffineAccessor<FT,N,T>::is_compatible(instance, fid, is.bounds)) region.report_incompatible_accessor("AffineAccessor", instance, fid); accessor = Realm::AffineAccessor<FT,N,T>(instance, fid, is.bounds, offset); } // With explicit bounds UnsafeFieldAccessor(const PhysicalRegion &region, FieldID fid, const Rect<N,T> source_bounds, bool silence_warnings = false, const char *warning_string = NULL, size_t offset = 0) { DomainT<N,T> is; const Realm::RegionInstance instance = region.get_instance_info(LEGION_NO_ACCESS, fid, sizeof(FT), &is, Internal::NT_TemplateHelper::encode_tag<N,T>(), warning_string, silence_warnings, false/*generic accessor*/, false/*check field size*/); if (!Realm::AffineAccessor<FT,N,T>::is_compatible(instance, fid, source_bounds)) region.report_incompatible_accessor("AffineAccessor", instance, fid); accessor = Realm::AffineAccessor<FT,N,T>(instance, fid, source_bounds, offset); } // With explicit transform template<int M> UnsafeFieldAccessor(const PhysicalRegion &region, FieldID fid, const AffineTransform<M,N,T> transform, bool silence_warnings = false, const char *warning_string = NULL, size_t offset = 0) { DomainT<M,T> is; const Realm::RegionInstance instance = region.get_instance_info(LEGION_NO_ACCESS, fid, sizeof(FT), &is, Internal::NT_TemplateHelper::encode_tag<M,T>(), warning_string, silence_warnings, false/*generic accessor*/, false/*check field size*/); if (!Realm::AffineAccessor<FT,N,T>::is_compatible(instance, transform.transform, transform.offset, fid)) region.report_incompatible_accessor("AffineAccessor", instance, fid); accessor = Realm::AffineAccessor<FT,N,T>(instance, transform.transform, transform.offset, fid, offset); } // With explicit transform and bounds template<int M> UnsafeFieldAccessor(const PhysicalRegion &region, FieldID fid, const AffineTransform<M,N,T> transform, const Rect<N,T> source_bounds, bool silence_warnings = false, const char *warning_string = NULL, size_t offset = 0) { DomainT<M,T> is; const Realm::RegionInstance instance = region.get_instance_info(LEGION_NO_ACCESS, fid, sizeof(FT), &is, Internal::NT_TemplateHelper::encode_tag<M,T>(), warning_string, silence_warnings, false/*generic accessor*/, false/*check field size*/); if (!Realm::AffineAccessor<FT,N,T>::is_compatible(instance, transform.transform, transform.offset, fid, source_bounds)) region.report_incompatible_accessor("AffineAccessor", instance, fid); accessor = Realm::AffineAccessor<FT,N,T>(instance, transform.transform, transform.offset, fid, source_bounds, offset); } public: __CUDA_HD__ inline FT read(const Point<N,T> &p) const { return accessor.read(p); } __CUDA_HD__ inline void write(const Point<N,T> &p, FT val) const { accessor.write(p, val); } __CUDA_HD__ inline FT* ptr(const Point<N,T> &p) const { return accessor.ptr(p); } __CUDA_HD__ inline FT* ptr(const Rect<N,T>& r, size_t field_size = sizeof(FT)) const { #ifdef __CUDA_ARCH__ assert(Internal::is_dense_layout(r, accessor.strides, field_size)); #else if (!Internal::is_dense_layout(r, accessor.strides, field_size)) { fprintf(stderr, "ERROR: Illegal request for pointer of non-dense rectangle\n"); #ifdef DEBUG_LEGION assert(false); #else exit(ERROR_NON_DENSE_RECTANGLE); #endif } #endif return accessor.ptr(r.lo); } __CUDA_HD__ inline FT* ptr(const Rect<N,T>& r, size_t strides[N], size_t field_size = sizeof(FT)) const { for (int i = 0; i < N; i++) strides[i] = accessor.strides[i] / field_size; return accessor.ptr(r.lo); } __CUDA_HD__ inline FT& operator[](const Point<N,T> &p) const { return accessor[p]; } __CUDA_HD__ inline FT& operator[](T index) const { return ArraySyntax::AffineSyntaxHelper<UnsafeFieldAccessor<FT,N,T, Realm::AffineAccessor<FT,N,T> >,FT,N,T,2,LEGION_READ_WRITE>( *this, Point<1,T>(index)); } public: Realm::AffineAccessor<FT,N,T> accessor; public: typedef FT value_type; typedef FT& reference; typedef const FT& const_reference; static const int dim = N; }; // Specialization for UnsafeFieldAccessor for dimension 1 // to avoid ambiguity for array access template<typename FT, typename T> class UnsafeFieldAccessor<FT,1,T,Realm::AffineAccessor<FT,1,T> > { public: UnsafeFieldAccessor(void) { } UnsafeFieldAccessor(const PhysicalRegion &region, FieldID fid, bool silence_warnings = false, const char *warning_string = NULL, size_t offset = 0) { DomainT<1,T> is; const Realm::RegionInstance instance = region.get_instance_info(LEGION_NO_ACCESS, fid, sizeof(FT), &is, Internal::NT_TemplateHelper::encode_tag<1,T>(), warning_string, silence_warnings, false/*generic accessor*/, false/*check field size*/); if (!Realm::AffineAccessor<FT,1,T>::is_compatible(instance, fid, is.bounds)) region.report_incompatible_accessor("AffineAccessor", instance, fid); accessor = Realm::AffineAccessor<FT,1,T>(instance, fid, is.bounds, offset); } // With explicit bounds UnsafeFieldAccessor(const PhysicalRegion &region, FieldID fid, const Rect<1,T> source_bounds, bool silence_warnings = false, const char *warning_string = NULL, size_t offset = 0) { DomainT<1,T> is; const Realm::RegionInstance instance = region.get_instance_info(LEGION_NO_ACCESS, fid, sizeof(FT), &is, Internal::NT_TemplateHelper::encode_tag<1,T>(), warning_string, silence_warnings, false/*generic accessor*/, false/*check field size*/); if (!Realm::AffineAccessor<FT,1,T>::is_compatible(instance, fid, source_bounds)) region.report_incompatible_accessor("AffineAccessor", instance, fid); accessor = Realm::AffineAccessor<FT,1,T>(instance, fid, source_bounds, offset); } // With explicit transform template<int M> UnsafeFieldAccessor(const PhysicalRegion &region, FieldID fid, const AffineTransform<M,1,T> transform, bool silence_warnings = false, const char *warning_string = NULL, size_t offset = 0) { DomainT<M,T> is; const Realm::RegionInstance instance = region.get_instance_info(LEGION_NO_ACCESS, fid, sizeof(FT), &is, Internal::NT_TemplateHelper::encode_tag<M,T>(), warning_string, silence_warnings, false/*generic accessor*/, false/*check field size*/); if (!Realm::AffineAccessor<FT,1,T>::is_compatible(instance, transform.transform, transform.offset, fid)) region.report_incompatible_accessor("AffineAccessor", instance, fid); accessor = Realm::AffineAccessor<FT,1,T>(instance, transform.transform, transform.offset, fid, offset); } // With explicit transform and bounds template<int M> UnsafeFieldAccessor(const PhysicalRegion &region, FieldID fid, const AffineTransform<M,1,T> transform, const Rect<1,T> source_bounds, bool silence_warnings = false, const char *warning_string = NULL, size_t offset = 0) { DomainT<M,T> is; const Realm::RegionInstance instance = region.get_instance_info(LEGION_NO_ACCESS, fid, sizeof(FT), &is, Internal::NT_TemplateHelper::encode_tag<M,T>(), warning_string, silence_warnings, false/*generic accessor*/, false/*check field size*/); if (!Realm::AffineAccessor<FT,1,T>::is_compatible(instance, transform.transform, transform.offset, fid, source_bounds)) region.report_incompatible_accessor("AffineAccessor", instance, fid); accessor = Realm::AffineAccessor<FT,1,T>(instance, transform.transform, transform.offset, fid, source_bounds, offset); } public: __CUDA_HD__ inline FT read(const Point<1,T> &p) const { return accessor.read(p); } __CUDA_HD__ inline void write(const Point<1,T> &p, FT val) const { accessor.write(p, val); } __CUDA_HD__ inline FT* ptr(const Point<1,T> &p) const { return accessor.ptr(p); } __CUDA_HD__ inline FT* ptr(const Rect<1,T> &r, size_t field_size = sizeof(FT)) const { #ifdef __CUDA_ARCH__ assert(Internal::is_dense_layout(r, accessor.strides, field_size)); #else if (!Internal::is_dense_layout(r, accessor.strides, field_size)) { fprintf(stderr, "ERROR: Illegal request for pointer of non-dense rectangle\n"); #ifdef DEBUG_LEGION assert(false); #else exit(ERROR_NON_DENSE_RECTANGLE); #endif } #endif return accessor.ptr(r.lo); } __CUDA_HD__ inline FT* ptr(const Rect<1,T> &r, size_t strides[1], size_t field_size = sizeof(FT)) const { strides[0] = accessor.strides[0] / field_size; return accessor.ptr(r.lo); } __CUDA_HD__ inline FT& operator[](const Point<1,T> &p) const { return accessor[p]; } public: Realm::AffineAccessor<FT,1,T> accessor; public: typedef FT value_type; typedef FT& reference; typedef const FT& const_reference; static const int dim = 1; }; template<typename FT, int N, typename T> class UnsafeFieldAccessor<FT, N, T, Realm::MultiAffineAccessor<FT,N,T> > { public: UnsafeFieldAccessor(void) { } UnsafeFieldAccessor(const PhysicalRegion &region, FieldID fid, bool silence_warnings = false, const char *warning_string = NULL, size_t offset = 0) { DomainT<N,T> is; const Realm::RegionInstance instance = region.get_instance_info(LEGION_NO_ACCESS, fid, sizeof(FT), &is, Internal::NT_TemplateHelper::encode_tag<N,T>(), warning_string, silence_warnings, false/*generic accessor*/, false/*check field size*/); if (!Realm::MultiAffineAccessor<FT,N,T>::is_compatible(instance, fid, is.bounds)) region.report_incompatible_accessor("MultiAffineAccessor", instance, fid); accessor = Realm::MultiAffineAccessor<FT,N,T>(instance, fid, is.bounds, offset); } // With explicit bounds UnsafeFieldAccessor(const PhysicalRegion &region, FieldID fid, const Rect<N,T> source_bounds, bool silence_warnings = false, const char *warning_string = NULL, size_t offset = 0) { DomainT<N,T> is; const Realm::RegionInstance instance = region.get_instance_info(LEGION_NO_ACCESS, fid, sizeof(FT), &is, Internal::NT_TemplateHelper::encode_tag<N,T>(), warning_string, silence_warnings, false/*generic accessor*/, false/*check field size*/); if (!Realm::MultiAffineAccessor<FT,N,T>::is_compatible(instance, fid, source_bounds)) region.report_incompatible_accessor("MultiAffineAccessor", instance, fid); accessor = Realm::MultiAffineAccessor<FT,N,T>(instance, fid, source_bounds, offset); } public: __CUDA_HD__ inline FT read(const Point<N,T> &p) const { return accessor.read(p); } __CUDA_HD__ inline void write(const Point<N,T> &p, FT val) const { accessor.write(p, val); } __CUDA_HD__ inline FT* ptr(const Point<N,T> &p) const { return accessor.ptr(p); } __CUDA_HD__ inline FT* ptr(const Rect<N,T>& r, size_t field_size = sizeof(FT)) const { size_t strides[N]; FT *result = accessor.ptr(r, strides); #ifdef __CUDA_ARCH__ assert(result != NULL); assert(Internal::is_dense_layout(r, strides, field_size)); #else if (result == NULL) { fprintf(stderr, "ERROR: Illegal request for pointer of rectangle " "not contained within the bounds of a piece\n"); #ifdef DEBUG_LEGION assert(false); #else exit(ERROR_NON_PIECE_RECTANGLE); #endif } if (!Internal::is_dense_layout(r, strides, field_size)) { fprintf(stderr, "ERROR: Illegal request for pointer of non-dense rectangle\n"); #ifdef DEBUG_LEGION assert(false); #else exit(ERROR_NON_DENSE_RECTANGLE); #endif } #endif return result; } __CUDA_HD__ inline FT* ptr(const Rect<N,T>& r, size_t strides[N], size_t field_size = sizeof(FT)) const { FT *result = accessor.ptr(r, strides); #ifdef __CUDA_ARCH__ assert(result != NULL); #else if (result == NULL) { fprintf(stderr, "ERROR: Illegal request for pointer of rectangle " "not contained within the bounds of a piece\n"); #ifdef DEBUG_LEGION assert(false); #else exit(ERROR_NON_PIECE_RECTANGLE); #endif } #endif for (int i = 0; i < N; i++) strides[i] /= field_size; return result; } __CUDA_HD__ inline FT& operator[](const Point<N,T> &p) const { return accessor[p]; } __CUDA_HD__ inline FT& operator[](T index) const { return ArraySyntax::AffineSyntaxHelper<UnsafeFieldAccessor<FT,N,T, Realm::MultiAffineAccessor<FT,N,T> >, FT,N,T,2,LEGION_READ_WRITE>(*this, Point<1,T>(index)); } public: Realm::MultiAffineAccessor<FT,N,T> accessor; public: typedef FT value_type; typedef FT& reference; typedef const FT& const_reference; static const int dim = N; }; // Specialization for UnsafeFieldAccessor for dimension 1 // to avoid ambiguity for array access template<typename FT, typename T> class UnsafeFieldAccessor<FT,1,T,Realm::MultiAffineAccessor<FT,1,T> > { public: UnsafeFieldAccessor(void) { } UnsafeFieldAccessor(const PhysicalRegion &region, FieldID fid, bool silence_warnings = false, const char *warning_string = NULL, size_t offset = 0) { DomainT<1,T> is; const Realm::RegionInstance instance = region.get_instance_info(LEGION_NO_ACCESS, fid, sizeof(FT), &is, Internal::NT_TemplateHelper::encode_tag<1,T>(), warning_string, silence_warnings, false/*generic accessor*/, false/*check field size*/); if (!Realm::MultiAffineAccessor<FT,1,T>::is_compatible(instance, fid, is.bounds)) region.report_incompatible_accessor("MultiAffineAccessor", instance, fid); accessor = Realm::MultiAffineAccessor<FT,1,T>(instance, fid, is.bounds, offset); } // With explicit bounds UnsafeFieldAccessor(const PhysicalRegion &region, FieldID fid, const Rect<1,T> source_bounds, bool silence_warnings = false, const char *warning_string = NULL, size_t offset = 0) { DomainT<1,T> is; const Realm::RegionInstance instance = region.get_instance_info(LEGION_NO_ACCESS, fid, sizeof(FT), &is, Internal::NT_TemplateHelper::encode_tag<1,T>(), warning_string, silence_warnings, false/*generic accessor*/, false/*check field size*/); if (!Realm::MultiAffineAccessor<FT,1,T>::is_compatible(instance, fid, source_bounds)) region.report_incompatible_accessor("MultiAffineAccessor", instance, fid); accessor = Realm::MultiAffineAccessor<FT,1,T>(instance, fid, source_bounds, offset); } public: __CUDA_HD__ inline FT read(const Point<1,T> &p) const { return accessor.read(p); } __CUDA_HD__ inline void write(const Point<1,T> &p, FT val) const { accessor.write(p, val); } __CUDA_HD__ inline FT* ptr(const Point<1,T> &p) const { return accessor.ptr(p); } __CUDA_HD__ inline FT& operator[](const Point<1,T> &p) const { return accessor[p]; } public: Realm::MultiAffineAccessor<FT,1,T> accessor; public: typedef FT value_type; typedef FT& reference; typedef const FT& const_reference; static const int dim = 1; }; /** * \class UnsafeSpanIterator * This is a hidden class analogous to the UnsafeFieldAccessor that * allows for traversals over spans of elements in compact instances */ template<typename FT, int DIM, typename T = coord_t> class UnsafeSpanIterator { public: UnsafeSpanIterator(void) { } UnsafeSpanIterator(const PhysicalRegion &region, FieldID fid, bool privileges_only = true, bool silence_warnings = false, const char *warning_string = NULL, size_t offset = 0) : piece_iterator(PieceIteratorT<DIM,T>(region, fid, privileges_only)), partial_piece(false) { DomainT<DIM,T> is; const Realm::RegionInstance instance = region.get_instance_info(LEGION_NO_ACCESS, fid, sizeof(FT), &is, Internal::NT_TemplateHelper::encode_tag<DIM,T>(), warning_string, silence_warnings, false/*generic accessor*/, false/*check size*/); if (!Realm::MultiAffineAccessor<FT,DIM,T>::is_compatible(instance, fid, is.bounds)) region.report_incompatible_accessor("UnsafeSpanIterator", instance, fid); accessor = Realm::MultiAffineAccessor<FT,DIM,T>(instance, fid, is.bounds,offset); // initialize the first span step(); } public: inline bool valid(void) const { return !current.empty(); } inline bool step(void) { // Handle the remains of a partial piece if that is what we're doing if (partial_piece) { bool carry = false; for (int idx = 0; idx < DIM; idx++) { const int dim = dim_order[idx]; if (carry || (dim == partial_step_dim)) { if (partial_step_point[dim] < piece_iterator->hi[dim]) { partial_step_point[dim] += 1; carry = false; break; } // carry case so reset and roll-over partial_step_point[dim] = piece_iterator->lo[dim]; carry = true; } // Skip any dimensions before the partial step dim } // Make the next span current = Span<FT,LEGION_READ_WRITE>( accessor.ptr(partial_step_point), current.size(), current.step()); // See if we are done with this partial piece if (carry) partial_piece = false; return true; } // clear this for the next iteration current = Span<FT,LEGION_READ_WRITE>(); // Otherwise try to group as many rectangles together as we can while (piece_iterator.valid()) { size_t strides[DIM]; FT *ptr = accessor.ptr(*piece_iterator, strides); #ifdef DEBUG_LEGION // If we ever hit this it is a runtime error because the // runtime should already be guaranteeing these rectangles // are inside of pieces for the instance assert(ptr != NULL); #endif // Find the minimum stride and see if this piece is dense size_t min_stride = SIZE_MAX; for (int dim = 0; dim < DIM; dim++) if (strides[dim] < min_stride) min_stride = strides[dim]; if (Internal::is_dense_layout(*piece_iterator, strides, min_stride)) { const size_t volume = piece_iterator->volume(); if (!current.empty()) { uintptr_t base = current.get_base(); // See if we can append to the current span if ((current.step() == min_stride) && ((base + (current.size() * min_stride)) == uintptr_t(ptr))) current = Span<FT,LEGION_READ_WRITE>(current.data(), current.size() + volume, min_stride); else // Save this rectangle for the next iteration break; } else // Start a new span current = Span<FT,LEGION_READ_WRITE>(ptr, volume, min_stride); } else { // Not a uniform stride, so go to the partial piece case if (current.empty()) { partial_piece = true; // Compute the dimension order from smallest to largest size_t stride_floor = 0; for (int idx = 0; idx < DIM; idx++) { int index = -1; size_t local_min = SIZE_MAX; for (int dim = 0; dim < DIM; dim++) { if (strides[dim] <= stride_floor) continue; if (strides[dim] < local_min) { local_min = strides[dim]; index = dim; } } #ifdef DEBUG_LEGION assert(index >= 0); #endif dim_order[idx] = index; stride_floor = local_min; } // See which dimensions we can handle at once and which ones // we are going to need to walk over size_t extent = 1; size_t exp_offset = min_stride; partial_step_dim = -1; for (int idx = 0; idx < DIM; idx++) { const int dim = dim_order[idx]; if (strides[dim] == exp_offset) { size_t pitch = ((piece_iterator->hi[dim] - piece_iterator->lo[dim]) + 1); exp_offset *= pitch; extent *= pitch; } // First dimension that is not contiguous partial_step_dim = dim; break; } #ifdef DEBUG_LEGION assert(partial_step_dim >= 0); #endif partial_step_point = piece_iterator->lo; current = Span<FT,LEGION_READ_WRITE>( accessor.ptr(partial_step_point), extent, min_stride); } // No matter what we are breaking out here break; } // Step the piece iterator for the next iteration piece_iterator.step(); } return valid(); } public: inline operator bool(void) const { return valid(); } inline bool operator()(void) const { return valid(); } inline Span<FT,LEGION_READ_WRITE> operator*(void) const { return current; } inline const Span<FT,LEGION_READ_WRITE>* operator->(void) const { return &current; } inline UnsafeSpanIterator<FT,DIM,T>& operator++(void) { step(); return *this; } inline UnsafeSpanIterator<FT,DIM,T> operator++(int) { UnsafeSpanIterator<FT,DIM,T> result = *this; step(); return result; } private: PieceIteratorT<DIM,T> piece_iterator; Realm::MultiAffineAccessor<FT,DIM,T> accessor; Span<FT,LEGION_READ_WRITE> current; Point<DIM,T> partial_step_point; int dim_order[DIM]; int partial_step_dim; bool partial_piece; }; //-------------------------------------------------------------------------- template<typename T> inline DeferredValue<T>::DeferredValue(T initial_value, size_t alignment) //-------------------------------------------------------------------------- { // Construct a Region of size 1 in the zero copy memory for now Machine machine = Realm::Machine::get_machine(); Machine::MemoryQuery finder(machine); finder.has_affinity_to(Processor::get_executing_processor()); finder.only_kind(Memory::Z_COPY_MEM); if (finder.count() == 0) { fprintf(stderr,"Deferred Values currently need a local allocation " "of zero-copy memory to work correctly. Please provide " "a non-zero amount with the -ll:zsize flag"); assert(false); } const Memory memory = finder.first(); const Realm::Point<1,coord_t> zero(0); Realm::IndexSpace<1,coord_t> bounds = Realm::Rect<1,coord_t>(zero, zero); const std::vector<size_t> field_sizes(1,sizeof(T)); Realm::InstanceLayoutConstraints constraints(field_sizes, 0/*blocking*/); int dim_order[1]; dim_order[0] = 0; Realm::InstanceLayoutGeneric *layout = Realm::InstanceLayoutGeneric::choose_instance_layout(bounds, constraints, dim_order); layout->alignment_reqd = alignment; Runtime *runtime = Runtime::get_runtime(); instance = runtime->create_task_local_instance(memory, layout); #ifdef DEBUG_LEGION #ifndef NDEBUG const bool is_compatible = Realm::AffineAccessor<T,1,coord_t>::is_compatible(instance, 0); #endif assert(is_compatible); #endif // We can make the accessor accessor = Realm::AffineAccessor<T,1,coord_t>(instance, 0/*field id*/); // Initialize the value accessor[zero] = initial_value; } //-------------------------------------------------------------------------- template<typename T> __CUDA_HD__ inline T DeferredValue<T>::read(void) const //-------------------------------------------------------------------------- { return accessor.read(Point<1,coord_t>(0)); } //-------------------------------------------------------------------------- template<typename T> __CUDA_HD__ inline void DeferredValue<T>::write(T value) const //-------------------------------------------------------------------------- { accessor.write(Point<1,coord_t>(0), value); } //-------------------------------------------------------------------------- template<typename T> __CUDA_HD__ inline T* DeferredValue<T>::ptr(void) const //-------------------------------------------------------------------------- { return accessor.ptr(Point<1,coord_t>(0)); } //-------------------------------------------------------------------------- template<typename T> __CUDA_HD__ inline T& DeferredValue<T>::ref(void) const //-------------------------------------------------------------------------- { return accessor[Point<1,coord_t>(0)]; } //-------------------------------------------------------------------------- template<typename T> __CUDA_HD__ inline DeferredValue<T>::operator T(void) const //-------------------------------------------------------------------------- { return accessor[Point<1,coord_t>(0)]; } //-------------------------------------------------------------------------- template<typename T> __CUDA_HD__ inline DeferredValue<T>& DeferredValue<T>::operator=(T value) //-------------------------------------------------------------------------- { accessor[Point<1,coord_t>(0)] = value; return *this; } //-------------------------------------------------------------------------- template<typename T> inline void DeferredValue<T>::finalize(Runtime *runtime, Context ctx) const //-------------------------------------------------------------------------- { Runtime::legion_task_postamble(runtime, ctx, accessor.ptr(Point<1,coord_t>(0)), sizeof(T), false/*owner*/, instance); } //-------------------------------------------------------------------------- template<typename REDOP, bool EXCLUSIVE> inline DeferredReduction<REDOP,EXCLUSIVE>::DeferredReduction(size_t align) : DeferredValue<typename REDOP::LHS>(REDOP::identity, align) //-------------------------------------------------------------------------- { } //-------------------------------------------------------------------------- template<typename REDOP, bool EXCLUSIVE> __CUDA_HD__ inline void DeferredReduction<REDOP,EXCLUSIVE>::reduce( typename REDOP::RHS value) const //-------------------------------------------------------------------------- { REDOP::template fold<EXCLUSIVE>( this->accessor[Point<1,coord_t>(0)], value); } //-------------------------------------------------------------------------- template<typename REDOP, bool EXCLUSIVE> __CUDA_HD__ inline void DeferredReduction<REDOP,EXCLUSIVE>::operator<<=( typename REDOP::RHS value) const //-------------------------------------------------------------------------- { REDOP::template fold<EXCLUSIVE>( this->accessor[Point<1,coord_t>(0)], value); } #ifdef LEGION_BOUNDS_CHECKS // DeferredBuffer without bounds checks template<typename FT, int N, typename T> class DeferredBuffer<FT,N,T,false> { public: inline DeferredBuffer(void); // Memory kinds inline DeferredBuffer(Memory::Kind kind, const Domain &bounds, const FT *initial_value = NULL, size_t alignment = 16, bool fortran_order_dims = false); inline DeferredBuffer(Memory::Kind kind, IndexSpace bounds, const FT *initial_value = NULL, size_t alignment = 16, bool fortran_order_dims = false); inline DeferredBuffer(const Rect<N,T> &bounds, Memory::Kind kind, const FT *initial_value = NULL, size_t alignment = 16, bool fortran_order_dims = false); inline DeferredBuffer(IndexSpaceT<N,T> bounds, Memory::Kind kind, const FT *initial_value = NULL, size_t alignment = 16, bool fortran_order_dims = false); // Explicit memory inline DeferredBuffer(Memory memory, const Domain &bounds, const FT *initial_value = NULL, size_t alignment = 16, bool fortran_order_dims = false); inline DeferredBuffer(Memory memory, IndexSpace bounds, const FT *initial_value = NULL, size_t alignment = 16, bool fortran_order_dims = false); inline DeferredBuffer(const Rect<N,T> &bounds, Memory memory, const FT *initial_value = NULL, size_t alignment = 16, bool fortran_order_dims = false); inline DeferredBuffer(IndexSpaceT<N,T> bounds, Memory memory, const FT *initial_value = NULL, size_t alignment = 16, bool fortran_order_dims = false); public: __CUDA_HD__ inline FT read(const Point<N,T> &p) const; __CUDA_HD__ inline void write(const Point<N,T> &p, FT value) const; __CUDA_HD__ inline FT* ptr(const Point<N,T> &p) const; __CUDA_HD__ inline FT* ptr(const Rect<N,T> &r) const; // must be dense __CUDA_HD__ inline FT* ptr(const Rect<N,T> &r, size_t strides[N]) const; __CUDA_HD__ inline FT& operator[](const Point<N,T> &p) const; protected: Realm::RegionInstance instance; Realm::AffineAccessor<FT,N,T> accessor; }; #else // DeferredBuffer with bounds checks template<typename FT, int N, typename T> class DeferredBuffer<FT,N,T,true> { public: inline DeferredBuffer(void); // Memory kind inline DeferredBuffer(Memory::Kind kind, const Domain &bounds, const FT *initial_value = NULL, size_t alignment = 16, bool fortran_order_dims = false); inline DeferredBuffer(Memory::Kind kind, IndexSpace bounds, const FT *initial_value = NULL, size_t alignment = 16, bool fortran_order_dims = false); inline DeferredBuffer(const Rect<N,T> &bounds, Memory::Kind kind, const FT *initial_value = NULL, size_t alignment = 16, bool fortran_order_dims = false); inline DeferredBuffer(IndexSpaceT<N,T> bounds, Memory::Kind kind, const FT *initial_value = NULL, size_t alignment = 16, bool fortran_order_dims = false); // Explicit memory inline DeferredBuffer(Memory memory, const Domain &bounds, const FT *initial_value = NULL, size_t alignment = 16, bool fortran_order_dims = false); inline DeferredBuffer(Memory memory, IndexSpace bounds, const FT *initial_value = NULL, size_t alignment = 16, bool fortran_order_dims = false); inline DeferredBuffer(const Rect<N,T> &bounds, Memory memory, const FT *initial_value = NULL, size_t alignment = 16, bool fortran_order_dims = false); inline DeferredBuffer(IndexSpaceT<N,T> bounds, Memory memory, const FT *initial_value = NULL, size_t alignment = 16, bool fortran_order_dims = false); public: __CUDA_HD__ inline FT read(const Point<N,T> &p) const; __CUDA_HD__ inline void write(const Point<N,T> &p, FT value) const; __CUDA_HD__ inline FT* ptr(const Point<N,T> &p) const; __CUDA_HD__ inline FT* ptr(const Rect<N,T> &r) const; // must be dense __CUDA_HD__ inline FT* ptr(const Rect<N,T> &r, size_t strides[N]) const; __CUDA_HD__ inline FT& operator[](const Point<N,T> &p) const; protected: Realm::RegionInstance instance; Realm::AffineAccessor<FT,N,T> accessor; DomainT<N,T> bounds; }; #endif //-------------------------------------------------------------------------- template<typename FT, int N, typename T #ifndef LEGION_BOUNDS_CHECKS , bool CB #endif > inline DeferredBuffer<FT,N,T, #ifdef LEGION_BOUNDS_CHECKS false #else CB #endif >::DeferredBuffer(void) : instance(Realm::RegionInstance::NO_INST) //-------------------------------------------------------------------------- { } //-------------------------------------------------------------------------- template<typename FT, int N, typename T #ifndef LEGION_BOUNDS_CHECKS , bool CB #endif > inline DeferredBuffer<FT,N,T, #ifdef LEGION_BOUNDS_CHECKS false #else CB #endif >::DeferredBuffer(Memory::Kind kind, const Domain &space, const FT *initial_value/* = NULL*/, size_t alignment/* = 16*/, bool fortran_order_dims/* = false*/) //-------------------------------------------------------------------------- { // Construct an instance of the right size in the corresponding memory Machine machine = Realm::Machine::get_machine(); Machine::MemoryQuery finder(machine); finder.best_affinity_to(Processor::get_executing_processor()); finder.only_kind(kind); if (finder.count() == 0) { finder = Machine::MemoryQuery(machine); finder.has_affinity_to(Processor::get_executing_processor()); finder.only_kind(kind); } if (finder.count() == 0) { fprintf(stderr,"DeferredBuffer unable to find a memory of kind %d", kind); assert(false); } const Memory memory = finder.first(); const DomainT<N,T> bounds = space; const std::vector<size_t> field_sizes(1,sizeof(FT)); Realm::InstanceLayoutConstraints constraints(field_sizes, 0/*blocking*/); int dim_order[N]; if (fortran_order_dims) { for (int i = 0; i < N; i++) dim_order[i] = i; } else { for (int i = 0; i < N; i++) dim_order[i] = N - (i+1); } Realm::InstanceLayoutGeneric *layout = Realm::InstanceLayoutGeneric::choose_instance_layout(bounds, constraints, dim_order); layout->alignment_reqd = alignment; Runtime *runtime = Runtime::get_runtime(); instance = runtime->create_task_local_instance(memory, layout); if (initial_value != NULL) { Realm::ProfilingRequestSet no_requests; std::vector<Realm::CopySrcDstField> dsts(1); dsts[0].set_field(instance, 0/*field id*/, sizeof(FT)); const Internal::LgEvent wait_on( bounds.fill(dsts, no_requests, initial_value, sizeof(FT))); if (wait_on.exists()) wait_on.wait(); } #ifdef DEBUG_LEGION #ifndef NDEBUG const bool is_compatible = Realm::AffineAccessor<FT,N,T>::is_compatible(instance, 0/*fid*/); #endif assert(is_compatible); #endif // We can make the accessor accessor = Realm::AffineAccessor<FT,N,T>(instance, 0/*field id*/); } //-------------------------------------------------------------------------- template<typename FT, int N, typename T #ifndef LEGION_BOUNDS_CHECKS , bool CB #endif > inline DeferredBuffer<FT,N,T, #ifdef LEGION_BOUNDS_CHECKS false #else CB #endif >::DeferredBuffer(Memory::Kind kind, const IndexSpace space, const FT *initial_value/* = NULL*/, size_t alignment/* = 16*/, bool fortran_order_dims/* = false*/) //-------------------------------------------------------------------------- { // Construct an instance of the right size in the corresponding memory Machine machine = Realm::Machine::get_machine(); Machine::MemoryQuery finder(machine); finder.best_affinity_to(Processor::get_executing_processor()); finder.only_kind(kind); if (finder.count() == 0) { finder = Machine::MemoryQuery(machine); finder.has_affinity_to(Processor::get_executing_processor()); finder.only_kind(kind); } if (finder.count() == 0) { fprintf(stderr,"DeferredBuffer unable to find a memory of kind %d", kind); assert(false); } const Memory memory = finder.first(); Runtime *runtime = Runtime::get_runtime(); const DomainT<N,T> bounds = runtime->get_index_space_domain<N,T>(IndexSpaceT<N,T>(space)); const std::vector<size_t> field_sizes(1,sizeof(FT)); Realm::InstanceLayoutConstraints constraints(field_sizes, 0/*blocking*/); int dim_order[N]; if (fortran_order_dims) { for (int i = 0; i < N; i++) dim_order[i] = i; } else { for (int i = 0; i < N; i++) dim_order[i] = N - (i+1); } Realm::InstanceLayoutGeneric *layout = Realm::InstanceLayoutGeneric::choose_instance_layout(bounds, constraints, dim_order); layout->alignment_reqd = alignment; instance = runtime->create_task_local_instance(memory, layout); if (initial_value != NULL) { Realm::ProfilingRequestSet no_requests; std::vector<Realm::CopySrcDstField> dsts(1); dsts[0].set_field(instance, 0/*field id*/, sizeof(FT)); const Internal::LgEvent wait_on( bounds.fill(dsts, no_requests, initial_value, sizeof(FT))); if (wait_on.exists()) wait_on.wait(); } #ifdef DEBUG_LEGION #ifndef NDEBUG const bool is_compatible = Realm::AffineAccessor<FT,N,T>::is_compatible(instance, 0/*fid*/); #endif assert(is_compatible); #endif // We can make the accessor accessor = Realm::AffineAccessor<FT,N,T>(instance, 0/*field id*/); } //-------------------------------------------------------------------------- template<typename FT, int N, typename T #ifndef LEGION_BOUNDS_CHECKS , bool CB #endif > inline DeferredBuffer<FT,N,T, #ifdef LEGION_BOUNDS_CHECKS false #else CB #endif >::DeferredBuffer(const Rect<N,T> &rect, Memory::Kind kind, const FT *initial_value /*= NULL*/, size_t alignment/* = 16*/, bool fortran_order_dims /*= false*/) //-------------------------------------------------------------------------- { // Construct an instance of the right size in the corresponding memory Machine machine = Realm::Machine::get_machine(); Machine::MemoryQuery finder(machine); finder.best_affinity_to(Processor::get_executing_processor()); finder.only_kind(kind); if (finder.count() == 0) { finder = Machine::MemoryQuery(machine); finder.has_affinity_to(Processor::get_executing_processor()); finder.only_kind(kind); } if (finder.count() == 0) { fprintf(stderr,"DeferredBuffer unable to find a memory of kind %d", kind); assert(false); } const Memory memory = finder.first(); const DomainT<N,T> bounds(rect); const std::vector<size_t> field_sizes(1,sizeof(FT)); Realm::InstanceLayoutConstraints constraints(field_sizes, 0/*blocking*/); int dim_order[N]; if (fortran_order_dims) { for (int i = 0; i < N; i++) dim_order[i] = i; } else { for (int i = 0; i < N; i++) dim_order[i] = N - (i+1); } Realm::InstanceLayoutGeneric *layout = Realm::InstanceLayoutGeneric::choose_instance_layout(bounds, constraints, dim_order); layout->alignment_reqd = alignment; Runtime *runtime = Runtime::get_runtime(); instance = runtime->create_task_local_instance(memory, layout); if (initial_value != NULL) { Realm::ProfilingRequestSet no_requests; std::vector<Realm::CopySrcDstField> dsts(1); dsts[0].set_field(instance, 0/*field id*/, sizeof(FT)); const Internal::LgEvent wait_on( bounds.fill(dsts, no_requests, initial_value, sizeof(FT))); if (wait_on.exists()) wait_on.wait(); } #ifdef DEBUG_LEGION #ifndef NDEBUG const bool is_compatible = Realm::AffineAccessor<FT,N,T>::is_compatible(instance, 0/*fid*/); #endif assert(is_compatible); #endif // We can make the accessor accessor = Realm::AffineAccessor<FT,N,T>(instance, 0/*field id*/); } //-------------------------------------------------------------------------- template<typename FT, int N, typename T #ifndef LEGION_BOUNDS_CHECKS , bool CB #endif > inline DeferredBuffer<FT,N,T, #ifdef LEGION_BOUNDS_CHECKS false #else CB #endif >::DeferredBuffer(const IndexSpaceT<N,T> space, Memory::Kind kind, const FT *initial_value/* = NULL*/, size_t alignment/* = 16*/, bool fortran_order_dims/* = false*/) //-------------------------------------------------------------------------- { // Construct an instance of the right size in the corresponding memory Machine machine = Realm::Machine::get_machine(); Machine::MemoryQuery finder(machine); finder.best_affinity_to(Processor::get_executing_processor()); finder.only_kind(kind); if (finder.count() == 0) { finder = Machine::MemoryQuery(machine); finder.has_affinity_to(Processor::get_executing_processor()); finder.only_kind(kind); } if (finder.count() == 0) { fprintf(stderr,"DeferredBuffer unable to find a memory of kind %d", kind); assert(false); } const Realm::Memory memory = finder.first(); Runtime *runtime = Runtime::get_runtime(); const DomainT<N,T> bounds = runtime->get_index_space_domain<N,T>(space); const std::vector<size_t> field_sizes(1,sizeof(FT)); Realm::InstanceLayoutConstraints constraints(field_sizes, 0/*blocking*/); int dim_order[N]; if (fortran_order_dims) { for (int i = 0; i < N; i++) dim_order[i] = i; } else { for (int i = 0; i < N; i++) dim_order[i] = N - (i+1); } Realm::InstanceLayoutGeneric *layout = Realm::InstanceLayoutGeneric::choose_instance_layout(bounds, constraints, dim_order); layout->alignment_reqd = alignment; instance = runtime->create_task_local_instance(memory, layout); if (initial_value != NULL) { Realm::ProfilingRequestSet no_requests; std::vector<Realm::CopySrcDstField> dsts(1); dsts[0].set_field(instance, 0/*field id*/, sizeof(FT)); const Internal::LgEvent wait_on( bounds.fill(dsts, no_requests, initial_value, sizeof(FT))); if (wait_on.exists()) wait_on.wait(); } #ifdef DEBUG_LEGION #ifndef NDEBUG const bool is_compatible = Realm::AffineAccessor<FT,N,T>::is_compatible(instance, 0/*fid*/); #endif assert(is_compatible); #endif // We can make the accessor accessor = Realm::AffineAccessor<FT,N,T>(instance, 0/*field id*/); } //-------------------------------------------------------------------------- template<typename FT, int N, typename T #ifndef LEGION_BOUNDS_CHECKS , bool CB #endif > inline DeferredBuffer<FT,N,T, #ifdef LEGION_BOUNDS_CHECKS false #else CB #endif >::DeferredBuffer(Memory memory, const Domain &space, const FT *initial_value/* = NULL*/, size_t alignment/* = 16*/, bool fortran_order_dims/* = false*/) //-------------------------------------------------------------------------- { const DomainT<N,T> bounds = space; const std::vector<size_t> field_sizes(1,sizeof(FT)); Realm::InstanceLayoutConstraints constraints(field_sizes, 0/*blocking*/); int dim_order[N]; if (fortran_order_dims) { for (int i = 0; i < N; i++) dim_order[i] = i; } else { for (int i = 0; i < N; i++) dim_order[i] = N - (i+1); } Realm::InstanceLayoutGeneric *layout = Realm::InstanceLayoutGeneric::choose_instance_layout(bounds, constraints, dim_order); layout->alignment_reqd = alignment; Runtime *runtime = Runtime::get_runtime(); instance = runtime->create_task_local_instance(memory, layout); if (initial_value != NULL) { Realm::ProfilingRequestSet no_requests; std::vector<Realm::CopySrcDstField> dsts(1); dsts[0].set_field(instance, 0/*field id*/, sizeof(FT)); const Internal::LgEvent wait_on( bounds.fill(dsts, no_requests, initial_value, sizeof(FT))); if (wait_on.exists()) wait_on.wait(); } #ifdef DEBUG_LEGION #ifndef NDEBUG const bool is_compatible = Realm::AffineAccessor<FT,N,T>::is_compatible(instance, 0/*fid*/); #endif assert(is_compatible); #endif // We can make the accessor accessor = Realm::AffineAccessor<FT,N,T>(instance, 0/*field id*/); } //-------------------------------------------------------------------------- template<typename FT, int N, typename T #ifndef LEGION_BOUNDS_CHECKS , bool CB #endif > inline DeferredBuffer<FT,N,T, #ifdef LEGION_BOUNDS_CHECKS false #else CB #endif >::DeferredBuffer(Memory memory, const IndexSpace space, const FT *initial_value/* = NULL*/, size_t alignment/* = 16*/, bool fortran_order_dims/* = false*/) //-------------------------------------------------------------------------- { Runtime *runtime = Runtime::get_runtime(); const DomainT<N,T> bounds = runtime->get_index_space_domain<N,T>(IndexSpaceT<N,T>(space)); const std::vector<size_t> field_sizes(1,sizeof(FT)); Realm::InstanceLayoutConstraints constraints(field_sizes, 0/*blocking*/); int dim_order[N]; if (fortran_order_dims) { for (int i = 0; i < N; i++) dim_order[i] = i; } else { for (int i = 0; i < N; i++) dim_order[i] = N - (i+1); } Realm::InstanceLayoutGeneric *layout = Realm::InstanceLayoutGeneric::choose_instance_layout(bounds, constraints, dim_order); layout->alignment_reqd = alignment; instance = runtime->create_task_local_instance(memory, layout); if (initial_value != NULL) { Realm::ProfilingRequestSet no_requests; std::vector<Realm::CopySrcDstField> dsts(1); dsts[0].set_field(instance, 0/*field id*/, sizeof(FT)); const Internal::LgEvent wait_on( bounds.fill(dsts, no_requests, initial_value, sizeof(FT))); if (wait_on.exists()) wait_on.wait(); } #ifdef DEBUG_LEGION #ifndef NDEBUG const bool is_compatible = Realm::AffineAccessor<FT,N,T>::is_compatible(instance, 0/*fid*/); #endif assert(is_compatible); #endif // We can make the accessor accessor = Realm::AffineAccessor<FT,N,T>(instance, 0/*field id*/); } //-------------------------------------------------------------------------- template<typename FT, int N, typename T #ifndef LEGION_BOUNDS_CHECKS , bool CB #endif > inline DeferredBuffer<FT,N,T, #ifdef LEGION_BOUNDS_CHECKS false #else CB #endif >::DeferredBuffer(const Rect<N,T> &rect, Memory memory, const FT *initial_value /*= NULL*/, size_t alignment/* = 16*/, bool fortran_order_dims /*= false*/) //-------------------------------------------------------------------------- { const DomainT<N,T> bounds(rect); const std::vector<size_t> field_sizes(1,sizeof(FT)); Realm::InstanceLayoutConstraints constraints(field_sizes, 0/*blocking*/); int dim_order[N]; if (fortran_order_dims) { for (int i = 0; i < N; i++) dim_order[i] = i; } else { for (int i = 0; i < N; i++) dim_order[i] = N - (i+1); } Realm::InstanceLayoutGeneric *layout = Realm::InstanceLayoutGeneric::choose_instance_layout(bounds, constraints, dim_order); layout->alignment_reqd = alignment; Runtime *runtime = Runtime::get_runtime(); instance = runtime->create_task_local_instance(memory, layout); if (initial_value != NULL) { Realm::ProfilingRequestSet no_requests; std::vector<Realm::CopySrcDstField> dsts(1); dsts[0].set_field(instance, 0/*field id*/, sizeof(FT)); const Internal::LgEvent wait_on( bounds.fill(dsts, no_requests, initial_value, sizeof(FT))); if (wait_on.exists()) wait_on.wait(); } #ifdef DEBUG_LEGION #ifndef NDEBUG const bool is_compatible = Realm::AffineAccessor<FT,N,T>::is_compatible(instance, 0/*fid*/); #endif assert(is_compatible); #endif // We can make the accessor accessor = Realm::AffineAccessor<FT,N,T>(instance, 0/*field id*/); } //-------------------------------------------------------------------------- template<typename FT, int N, typename T #ifndef LEGION_BOUNDS_CHECKS , bool CB #endif > inline DeferredBuffer<FT,N,T, #ifdef LEGION_BOUNDS_CHECKS false #else CB #endif >::DeferredBuffer(const IndexSpaceT<N,T> space, Memory memory, const FT *initial_value/* = NULL*/, size_t alignment/* = 16*/, bool fortran_order_dims/* = false*/) //-------------------------------------------------------------------------- { Runtime *runtime = Runtime::get_runtime(); const DomainT<N,T> bounds = runtime->get_index_space_domain<N,T>(space); const std::vector<size_t> field_sizes(1,sizeof(FT)); Realm::InstanceLayoutConstraints constraints(field_sizes, 0/*blocking*/); int dim_order[N]; if (fortran_order_dims) { for (int i = 0; i < N; i++) dim_order[i] = i; } else { for (int i = 0; i < N; i++) dim_order[i] = N - (i+1); } Realm::InstanceLayoutGeneric *layout = Realm::InstanceLayoutGeneric::choose_instance_layout(bounds, constraints, dim_order); layout->alignment_reqd = alignment; instance = runtime->create_task_local_instance(memory, layout); if (initial_value != NULL) { Realm::ProfilingRequestSet no_requests; std::vector<Realm::CopySrcDstField> dsts(1); dsts[0].set_field(instance, 0/*field id*/, sizeof(FT)); const Internal::LgEvent wait_on( bounds.fill(dsts, no_requests, initial_value, sizeof(FT))); if (wait_on.exists()) wait_on.wait(); } #ifdef DEBUG_LEGION #ifndef NDEBUG const bool is_compatible = Realm::AffineAccessor<FT,N,T>::is_compatible(instance, 0/*fid*/); #endif assert(is_compatible); #endif // We can make the accessor accessor = Realm::AffineAccessor<FT,N,T>(instance, 0/*field id*/); } //-------------------------------------------------------------------------- template<typename FT, int N, typename T #ifndef LEGION_BOUNDS_CHECKS , bool CB #endif > __CUDA_HD__ inline FT DeferredBuffer<FT,N,T, #ifdef LEGION_BOUNDS_CHECKS false #else CB #endif >::read(const Point<N,T> &p) const //-------------------------------------------------------------------------- { return accessor.read(p); } //-------------------------------------------------------------------------- template<typename FT, int N, typename T #ifndef LEGION_BOUNDS_CHECKS , bool CB #endif > __CUDA_HD__ inline void DeferredBuffer<FT,N,T, #ifdef LEGION_BOUNDS_CHECKS false #else CB #endif >::write(const Point<N,T> &p, FT value) const //-------------------------------------------------------------------------- { accessor.write(p, value); } //-------------------------------------------------------------------------- template<typename FT, int N, typename T #ifndef LEGION_BOUNDS_CHECKS , bool CB #endif > __CUDA_HD__ inline FT* DeferredBuffer<FT,N,T, #ifdef LEGION_BOUNDS_CHECKS false #else CB #endif >::ptr(const Point<N,T> &p) const //-------------------------------------------------------------------------- { return accessor.ptr(p); } //-------------------------------------------------------------------------- template<typename FT, int N, typename T #ifndef LEGION_BOUNDS_CHECKS , bool CB #endif > __CUDA_HD__ inline FT* DeferredBuffer<FT,N,T, #ifdef LEGION_BOUNDS_CHECKS false #else CB #endif >::ptr(const Rect<N,T> &r) const //-------------------------------------------------------------------------- { #ifdef __CUDA_ARCH__ assert(Internal::is_dense_layout(r, accessor.strides, sizeof(FT))); #else if (!Internal::is_dense_layout(r, accessor.strides, sizeof(FT))) { fprintf(stderr, "ERROR: Illegal request for pointer of non-dense rectangle\n"); #ifdef DEBUG_LEGION assert(false); #else exit(ERROR_NON_DENSE_RECTANGLE); #endif } #endif return accessor.ptr(r.lo); } //-------------------------------------------------------------------------- template<typename FT, int N, typename T #ifndef LEGION_BOUNDS_CHECKS , bool CB #endif > __CUDA_HD__ inline FT* DeferredBuffer<FT,N,T, #ifdef LEGION_BOUNDS_CHECKS false #else CB #endif >::ptr(const Rect<N,T> &r, size_t strides[N]) const //-------------------------------------------------------------------------- { for (int i = 0; i < N; i++) strides[i] = accessor.strides[i] / sizeof(FT); return accessor.ptr(r.lo); } //-------------------------------------------------------------------------- template<typename FT, int N, typename T #ifndef LEGION_BOUNDS_CHECKS , bool CB #endif > __CUDA_HD__ inline FT& DeferredBuffer<FT,N,T, #ifdef LEGION_BOUNDS_CHECKS false #else CB #endif >::operator[](const Point<N,T> &p) const //-------------------------------------------------------------------------- { return accessor[p]; } //-------------------------------------------------------------------------- template<typename FT, int N, typename T #ifdef LEGION_BOUNDS_CHECKS , bool CB #endif > inline DeferredBuffer<FT,N,T, #ifdef LEGION_BOUNDS_CHECKS CB #else true #endif >::DeferredBuffer(void) : instance(Realm::RegionInstance::NO_INST) //-------------------------------------------------------------------------- { } //-------------------------------------------------------------------------- template<typename FT, int N, typename T #ifdef LEGION_BOUNDS_CHECKS , bool CB #endif > inline DeferredBuffer<FT,N,T, #ifdef LEGION_BOUNDS_CHECKS CB #else true #endif >::DeferredBuffer(Memory::Kind kind, const Domain &space, const FT *initial_value/* = NULL*/, size_t alignment/* = 16*/, const bool fortran_order_dims/* = false*/) //-------------------------------------------------------------------------- { // Construct an instance of the right size in the corresponding memory Machine machine = Realm::Machine::get_machine(); Machine::MemoryQuery finder(machine); finder.best_affinity_to(Processor::get_executing_processor()); finder.only_kind(kind); if (finder.count() == 0) { finder = Machine::MemoryQuery(machine); finder.has_affinity_to(Processor::get_executing_processor()); finder.only_kind(kind); } if (finder.count() == 0) { fprintf(stderr,"DeferredBuffer unable to find a memory of kind %d", kind); assert(false); } const Memory memory = finder.first(); bounds = space; const std::vector<size_t> field_sizes(1,sizeof(FT)); Realm::InstanceLayoutConstraints constraints(field_sizes, 0/*blocking*/); int dim_order[N]; if (fortran_order_dims) { for (int i = 0; i < N; i++) dim_order[i] = i; } else { for (int i = 0; i < N; i++) dim_order[i] = N - (i+1); } Realm::InstanceLayoutGeneric *layout = Realm::InstanceLayoutGeneric::choose_instance_layout(bounds, constraints, dim_order); layout->alignment_reqd = alignment; Runtime *runtime = Runtime::get_runtime(); instance = runtime->create_task_local_instance(memory, layout); if (initial_value != NULL) { Realm::ProfilingRequestSet no_requests; std::vector<Realm::CopySrcDstField> dsts(1); dsts[0].set_field(instance, 0/*field id*/, sizeof(FT)); const Internal::LgEvent wait_on( bounds.fill(dsts, no_requests, initial_value, sizeof(FT))); if (wait_on.exists()) wait_on.wait(); } #ifdef DEBUG_LEGION #ifndef NDEBUG const bool is_compatible = Realm::AffineAccessor<FT,N,T>::is_compatible(instance, 0/*fid*/); #endif assert(is_compatible); #endif // We can make the accessor accessor = Realm::AffineAccessor<FT,N,T>(instance, 0/*field id*/); } //-------------------------------------------------------------------------- template<typename FT, int N, typename T #ifdef LEGION_BOUNDS_CHECKS , bool CB #endif > inline DeferredBuffer<FT,N,T, #ifdef LEGION_BOUNDS_CHECKS CB #else true #endif >::DeferredBuffer(Memory::Kind kind, const IndexSpace space, const FT *initial_value/* = NULL*/, size_t alignment/* = 16*/, const bool fortran_order_dims/* = false*/) //-------------------------------------------------------------------------- { // Construct an instance of the right size in the corresponding memory Machine machine = Realm::Machine::get_machine(); Machine::MemoryQuery finder(machine); finder.best_affinity_to(Processor::get_executing_processor()); finder.only_kind(kind); if (finder.count() == 0) { finder = Machine::MemoryQuery(machine); finder.has_affinity_to(Processor::get_executing_processor()); finder.only_kind(kind); } if (finder.count() == 0) { fprintf(stderr,"DeferredBuffer unable to find a memory of kind %d", kind); assert(false); } const Memory memory = finder.first(); Runtime *runtime = Runtime::get_runtime(); bounds = runtime->get_index_space_domain<N,T>(IndexSpaceT<N,T>(space)); const std::vector<size_t> field_sizes(1,sizeof(FT)); Realm::InstanceLayoutConstraints constraints(field_sizes, 0/*blocking*/); int dim_order[N]; if (fortran_order_dims) { for (int i = 0; i < N; i++) dim_order[i] = i; } else { for (int i = 0; i < N; i++) dim_order[i] = N - (i+1); } Realm::InstanceLayoutGeneric *layout = Realm::InstanceLayoutGeneric::choose_instance_layout(bounds, constraints, dim_order); layout->alignment_reqd = alignment; instance = runtime->create_task_local_instance(memory, layout); if (initial_value != NULL) { Realm::ProfilingRequestSet no_requests; std::vector<Realm::CopySrcDstField> dsts(1); dsts[0].set_field(instance, 0/*field id*/, sizeof(FT)); const Internal::LgEvent wait_on( bounds.fill(dsts, no_requests, initial_value, sizeof(FT))); if (wait_on.exists()) wait_on.wait(); } #ifdef DEBUG_LEGION #ifndef NDEBUG const bool is_compatible = Realm::AffineAccessor<FT,N,T>::is_compatible(instance, 0/*fid*/); #endif assert(is_compatible); #endif // We can make the accessor accessor = Realm::AffineAccessor<FT,N,T>(instance, 0/*field id*/); } //-------------------------------------------------------------------------- template<typename FT, int N, typename T #ifdef LEGION_BOUNDS_CHECKS , bool CB #endif > inline DeferredBuffer<FT,N,T, #ifdef LEGION_BOUNDS_CHECKS CB #else true #endif >::DeferredBuffer(const Rect<N,T> &rect, Memory::Kind kind, const FT *initial_value /*= NULL*/, size_t alignment/* = 16*/, const bool fortran_order_dims/* = false*/) //-------------------------------------------------------------------------- { // Construct an instance of the right size in the corresponding memory Machine machine = Realm::Machine::get_machine(); Machine::MemoryQuery finder(machine); finder.best_affinity_to(Processor::get_executing_processor()); finder.only_kind(kind); if (finder.count() == 0) { finder = Machine::MemoryQuery(machine); finder.has_affinity_to(Processor::get_executing_processor()); finder.only_kind(kind); } if (finder.count() == 0) { fprintf(stderr,"DeferredBuffer unable to find a memory of kind %d", kind); assert(false); } const Memory memory = finder.first(); bounds = DomainT<N,T>(rect); const std::vector<size_t> field_sizes(1,sizeof(FT)); Realm::InstanceLayoutConstraints constraints(field_sizes, 0/*blocking*/); int dim_order[N]; if (fortran_order_dims) { for (int i = 0; i < N; i++) dim_order[i] = i; } else { for (int i = 0; i < N; i++) dim_order[i] = N - (i+1); } Realm::InstanceLayoutGeneric *layout = Realm::InstanceLayoutGeneric::choose_instance_layout(bounds, constraints, dim_order); layout->alignment_reqd = alignment; Runtime *runtime = Runtime::get_runtime(); instance = runtime->create_task_local_instance(memory, layout); if (initial_value != NULL) { Realm::ProfilingRequestSet no_requests; std::vector<Realm::CopySrcDstField> dsts(1); dsts[0].set_field(instance, 0/*field id*/, sizeof(FT)); const Internal::LgEvent wait_on( bounds.fill(dsts, no_requests, initial_value, sizeof(FT))); if (wait_on.exists()) wait_on.wait(); } #ifdef DEBUG_LEGION #ifndef NDEBUG const bool is_compatible = Realm::AffineAccessor<FT,N,T>::is_compatible(instance, 0/*fid*/); #endif assert(is_compatible); #endif // We can make the accessor accessor = Realm::AffineAccessor<FT,N,T>(instance, 0/*field id*/); } //-------------------------------------------------------------------------- template<typename FT, int N, typename T #ifdef LEGION_BOUNDS_CHECKS , bool CB #endif > inline DeferredBuffer<FT,N,T, #ifdef LEGION_BOUNDS_CHECKS CB #else true #endif >::DeferredBuffer(const IndexSpaceT<N,T> space, Memory::Kind kind, const FT *initial_value/* = NULL*/, size_t alignment/* = 16*/, const bool fortran_order_dims/* = false*/) //-------------------------------------------------------------------------- { // Construct an instance of the right size in the corresponding memory Machine machine = Realm::Machine::get_machine(); Machine::MemoryQuery finder(machine); finder.best_affinity_to(Processor::get_executing_processor()); finder.only_kind(kind); if (finder.count() == 0) { finder = Machine::MemoryQuery(machine); finder.has_affinity_to(Processor::get_executing_processor()); finder.only_kind(kind); } if (finder.count() == 0) { fprintf(stderr,"DeferredBuffer unable to find a memory of kind %d", kind); assert(false); } const Memory memory = finder.first(); Runtime *runtime = Runtime::get_runtime(); bounds = runtime->get_index_space_domain<N,T>(space); const std::vector<size_t> field_sizes(1,sizeof(FT)); Realm::InstanceLayoutConstraints constraints(field_sizes, 0/*blocking*/); int dim_order[N]; if (fortran_order_dims) { for (int i = 0; i < N; i++) dim_order[i] = i; } else { for (int i = 0; i < N; i++) dim_order[i] = N - (i+1); } Realm::InstanceLayoutGeneric *layout = Realm::InstanceLayoutGeneric::choose_instance_layout(bounds, constraints, dim_order); layout->alignment_reqd = alignment; instance = runtime->create_task_local_instance(memory, layout); if (initial_value != NULL) { Realm::ProfilingRequestSet no_requests; std::vector<Realm::CopySrcDstField> dsts(1); dsts[0].set_field(instance, 0/*field id*/, sizeof(FT)); const Internal::LgEvent wait_on( bounds.fill(dsts, no_requests, initial_value, sizeof(FT))); if (wait_on.exists()) wait_on.wait(); } #ifdef DEBUG_LEGION #ifndef NDEBUG const bool is_compatible = Realm::AffineAccessor<FT,N,T>::is_compatible(instance, 0/*fid*/); #endif assert(is_compatible); #endif // We can make the accessor accessor = Realm::AffineAccessor<FT,N,T>(instance, 0/*field id*/); } //-------------------------------------------------------------------------- template<typename FT, int N, typename T #ifdef LEGION_BOUNDS_CHECKS , bool CB #endif > inline DeferredBuffer<FT,N,T, #ifdef LEGION_BOUNDS_CHECKS CB #else true #endif >::DeferredBuffer(Memory memory, const Domain &space, const FT *initial_value/* = NULL*/, size_t alignment/* = 16*/, const bool fortran_order_dims/* = false*/) //-------------------------------------------------------------------------- { bounds = space; const std::vector<size_t> field_sizes(1,sizeof(FT)); Realm::InstanceLayoutConstraints constraints(field_sizes, 0/*blocking*/); int dim_order[N]; if (fortran_order_dims) { for (int i = 0; i < N; i++) dim_order[i] = i; } else { for (int i = 0; i < N; i++) dim_order[i] = N - (i+1); } Realm::InstanceLayoutGeneric *layout = Realm::InstanceLayoutGeneric::choose_instance_layout(bounds, constraints, dim_order); layout->alignment_reqd = alignment; Runtime *runtime = Runtime::get_runtime(); instance = runtime->create_task_local_instance(memory, layout); if (initial_value != NULL) { Realm::ProfilingRequestSet no_requests; std::vector<Realm::CopySrcDstField> dsts(1); dsts[0].set_field(instance, 0/*field id*/, sizeof(FT)); const Internal::LgEvent wait_on( bounds.fill(dsts, no_requests, initial_value, sizeof(FT))); if (wait_on.exists()) wait_on.wait(); } #ifdef DEBUG_LEGION #ifndef NDEBUG const bool is_compatible = Realm::AffineAccessor<FT,N,T>::is_compatible(instance, 0/*fid*/); #endif assert(is_compatible); #endif // We can make the accessor accessor = Realm::AffineAccessor<FT,N,T>(instance, 0/*field id*/); } //-------------------------------------------------------------------------- template<typename FT, int N, typename T #ifdef LEGION_BOUNDS_CHECKS , bool CB #endif > inline DeferredBuffer<FT,N,T, #ifdef LEGION_BOUNDS_CHECKS CB #else true #endif >::DeferredBuffer(Memory memory, const IndexSpace space, const FT *initial_value/* = NULL*/, size_t alignment/* = 16*/, const bool fortran_order_dims/* = false*/) //-------------------------------------------------------------------------- { Runtime *runtime = Runtime::get_runtime(); bounds = runtime->get_index_space_domain<N,T>(IndexSpaceT<N,T>(space)); const std::vector<size_t> field_sizes(1,sizeof(FT)); Realm::InstanceLayoutConstraints constraints(field_sizes, 0/*blocking*/); int dim_order[N]; if (fortran_order_dims) { for (int i = 0; i < N; i++) dim_order[i] = i; } else { for (int i = 0; i < N; i++) dim_order[i] = N - (i+1); } Realm::InstanceLayoutGeneric *layout = Realm::InstanceLayoutGeneric::choose_instance_layout(bounds, constraints, dim_order); layout->alignment_reqd = alignment; instance = runtime->create_task_local_instance(memory, layout); if (initial_value != NULL) { Realm::ProfilingRequestSet no_requests; std::vector<Realm::CopySrcDstField> dsts(1); dsts[0].set_field(instance, 0/*field id*/, sizeof(FT)); const Internal::LgEvent wait_on( bounds.fill(dsts, no_requests, initial_value, sizeof(FT))); if (wait_on.exists()) wait_on.wait(); } #ifdef DEBUG_LEGION #ifndef NDEBUG const bool is_compatible = Realm::AffineAccessor<FT,N,T>::is_compatible(instance, 0/*fid*/); #endif assert(is_compatible); #endif // We can make the accessor accessor = Realm::AffineAccessor<FT,N,T>(instance, 0/*field id*/); } //-------------------------------------------------------------------------- template<typename FT, int N, typename T #ifdef LEGION_BOUNDS_CHECKS , bool CB #endif > inline DeferredBuffer<FT,N,T, #ifdef LEGION_BOUNDS_CHECKS CB #else true #endif >::DeferredBuffer(const Rect<N,T> &rect, Memory memory, const FT *initial_value /*= NULL*/, size_t alignment/* = 16*/, const bool fortran_order_dims/* = false*/) //-------------------------------------------------------------------------- { bounds = DomainT<N,T>(rect); const std::vector<size_t> field_sizes(1,sizeof(FT)); Realm::InstanceLayoutConstraints constraints(field_sizes, 0/*blocking*/); int dim_order[N]; if (fortran_order_dims) { for (int i = 0; i < N; i++) dim_order[i] = i; } else { for (int i = 0; i < N; i++) dim_order[i] = N - (i+1); } Realm::InstanceLayoutGeneric *layout = Realm::InstanceLayoutGeneric::choose_instance_layout(bounds, constraints, dim_order); layout->alignment_reqd = alignment; Runtime *runtime = Runtime::get_runtime(); instance = runtime->create_task_local_instance(memory, layout); if (initial_value != NULL) { Realm::ProfilingRequestSet no_requests; std::vector<Realm::CopySrcDstField> dsts(1); dsts[0].set_field(instance, 0/*field id*/, sizeof(FT)); const Internal::LgEvent wait_on( bounds.fill(dsts, no_requests, initial_value, sizeof(FT))); if (wait_on.exists()) wait_on.wait(); } #ifdef DEBUG_LEGION #ifndef NDEBUG const bool is_compatible = Realm::AffineAccessor<FT,N,T>::is_compatible(instance, 0/*fid*/); #endif assert(is_compatible); #endif // We can make the accessor accessor = Realm::AffineAccessor<FT,N,T>(instance, 0/*field id*/); } //-------------------------------------------------------------------------- template<typename FT, int N, typename T #ifdef LEGION_BOUNDS_CHECKS , bool CB #endif > inline DeferredBuffer<FT,N,T, #ifdef LEGION_BOUNDS_CHECKS CB #else true #endif >::DeferredBuffer(const IndexSpaceT<N,T> space, Memory memory, const FT *initial_value/* = NULL*/, size_t alignment/* = 16*/, const bool fortran_order_dims/* = false*/) //-------------------------------------------------------------------------- { Runtime *runtime = Runtime::get_runtime(); bounds = runtime->get_index_space_domain<N,T>(space); const std::vector<size_t> field_sizes(1,sizeof(FT)); Realm::InstanceLayoutConstraints constraints(field_sizes, 0/*blocking*/); int dim_order[N]; if (fortran_order_dims) { for (int i = 0; i < N; i++) dim_order[i] = i; } else { for (int i = 0; i < N; i++) dim_order[i] = N - (i+1); } Realm::InstanceLayoutGeneric *layout = Realm::InstanceLayoutGeneric::choose_instance_layout(bounds, constraints, dim_order); layout->alignment_reqd = alignment; instance = runtime->create_task_local_instance(memory, layout); if (initial_value != NULL) { Realm::ProfilingRequestSet no_requests; std::vector<Realm::CopySrcDstField> dsts(1); dsts[0].set_field(instance, 0/*field id*/, sizeof(FT)); const Internal::LgEvent wait_on( bounds.fill(dsts, no_requests, initial_value, sizeof(FT))); if (wait_on.exists()) wait_on.wait(); } #ifdef DEBUG_LEGION #ifndef NDEBUG const bool is_compatible = Realm::AffineAccessor<FT,N,T>::is_compatible(instance, 0/*fid*/); #endif assert(is_compatible); #endif // We can make the accessor accessor = Realm::AffineAccessor<FT,N,T>(instance, 0/*field id*/); } //-------------------------------------------------------------------------- template<typename FT, int N, typename T #ifdef LEGION_BOUNDS_CHECKS , bool CB #endif > __CUDA_HD__ inline FT DeferredBuffer<FT,N,T, #ifdef LEGION_BOUNDS_CHECKS CB #else true #endif >::read(const Point<N,T> &p) const //-------------------------------------------------------------------------- { assert(instance.exists()); #ifdef __CUDA_ARCH__ assert(bounds.bounds.contains(p)); #else assert(bounds.contains(p)); #endif return accessor.read(p); } //-------------------------------------------------------------------------- template<typename FT, int N, typename T #ifdef LEGION_BOUNDS_CHECKS , bool CB #endif > __CUDA_HD__ inline void DeferredBuffer<FT,N,T, #ifdef LEGION_BOUNDS_CHECKS CB #else true #endif >::write(const Point<N,T> &p, FT value) const //-------------------------------------------------------------------------- { assert(instance.exists()); #ifdef __CUDA_ARCH__ assert(bounds.bounds.contains(p)); #else assert(bounds.contains(p)); #endif accessor.write(p, value); } //-------------------------------------------------------------------------- template<typename FT, int N, typename T #ifdef LEGION_BOUNDS_CHECKS , bool CB #endif > __CUDA_HD__ inline FT* DeferredBuffer<FT,N,T, #ifdef LEGION_BOUNDS_CHECKS CB #else true #endif >::ptr(const Point<N,T> &p) const //-------------------------------------------------------------------------- { assert(instance.exists()); #ifdef __CUDA_ARCH__ assert(bounds.bounds.contains(p)); #else assert(bounds.contains(p)); #endif return accessor.ptr(p); } //-------------------------------------------------------------------------- template<typename FT, int N, typename T #ifdef LEGION_BOUNDS_CHECKS , bool CB #endif > __CUDA_HD__ inline FT* DeferredBuffer<FT,N,T, #ifdef LEGION_BOUNDS_CHECKS CB #else true #endif >::ptr(const Rect<N,T> &r) const //-------------------------------------------------------------------------- { assert(instance.exists()); #ifdef __CUDA_ARCH__ assert(bounds.bounds.contains(r)); assert(Internal::is_dense_layout(r, accessor.strides, sizeof(FT))); #else assert(bounds.contains_all(r)); if (!Internal::is_dense_layout(r, accessor.strides, sizeof(FT))) { fprintf(stderr, "ERROR: Illegal request for pointer of non-dense rectangle\n"); #ifdef DEBUG_LEGION assert(false); #else exit(ERROR_NON_DENSE_RECTANGLE); #endif } #endif return accessor.ptr(r.lo); } //-------------------------------------------------------------------------- template<typename FT, int N, typename T #ifdef LEGION_BOUNDS_CHECKS , bool CB #endif > __CUDA_HD__ inline FT* DeferredBuffer<FT,N,T, #ifdef LEGION_BOUNDS_CHECKS CB #else true #endif >::ptr(const Rect<N,T> &r, size_t strides[N]) const //-------------------------------------------------------------------------- { assert(instance.exists()); #ifdef __CUDA_ARCH__ assert(bounds.bounds.contains(r)); #else assert(bounds.contains_all(r)); #endif for (int i = 0; i < N; i++) strides[i] = accessor.strides[i] / sizeof(FT); return accessor.ptr(r.lo); } //-------------------------------------------------------------------------- template<typename FT, int N, typename T #ifdef LEGION_BOUNDS_CHECKS , bool CB #endif > __CUDA_HD__ inline FT& DeferredBuffer<FT,N,T, #ifdef LEGION_BOUNDS_CHECKS CB #else true #endif >::operator[](const Point<N,T> &p) const //-------------------------------------------------------------------------- { assert(instance.exists()); #ifdef __CUDA_ARCH__ assert(bounds.bounds.contains(p)); #else assert(bounds.contains(p)); #endif return accessor[p]; } //-------------------------------------------------------------------------- inline bool IndexSpace::operator==(const IndexSpace &rhs) const //-------------------------------------------------------------------------- { if (id != rhs.id) return false; if (tid != rhs.tid) return false; #ifdef DEBUG_LEGION assert(type_tag == rhs.type_tag); #endif return true; } //-------------------------------------------------------------------------- inline bool IndexSpace::operator!=(const IndexSpace &rhs) const //-------------------------------------------------------------------------- { if ((id == rhs.id) && (tid == rhs.tid)) return false; return true; } //-------------------------------------------------------------------------- inline bool IndexSpace::operator<(const IndexSpace &rhs) const //-------------------------------------------------------------------------- { if (id < rhs.id) return true; if (id > rhs.id) return false; return (tid < rhs.tid); } //-------------------------------------------------------------------------- inline bool IndexSpace::operator>(const IndexSpace &rhs) const //-------------------------------------------------------------------------- { if (id > rhs.id) return true; if (id < rhs.id) return false; return (tid > rhs.tid); } //-------------------------------------------------------------------------- inline int IndexSpace::get_dim(void) const //-------------------------------------------------------------------------- { if (type_tag == 0) return 0; return Internal::NT_TemplateHelper::get_dim(type_tag); } //-------------------------------------------------------------------------- template<int DIM, typename T> IndexSpaceT<DIM,T>::IndexSpaceT(IndexSpaceID id, IndexTreeID tid) : IndexSpace(id, tid, Internal::NT_TemplateHelper::template encode_tag<DIM,T>()) //-------------------------------------------------------------------------- { } //-------------------------------------------------------------------------- template<int DIM, typename T> IndexSpaceT<DIM,T>::IndexSpaceT(void) : IndexSpace(0,0,Internal::NT_TemplateHelper::template encode_tag<DIM,T>()) //-------------------------------------------------------------------------- { } //-------------------------------------------------------------------------- template<int DIM, typename T> IndexSpaceT<DIM,T>::IndexSpaceT(const IndexSpace &rhs) : IndexSpace(rhs.get_id(), rhs.get_tree_id(), rhs.get_type_tag()) //-------------------------------------------------------------------------- { Internal::NT_TemplateHelper::template check_type<DIM,T>(type_tag); } //-------------------------------------------------------------------------- template<int DIM, typename T> inline IndexSpaceT<DIM,T>& IndexSpaceT<DIM,T>::operator=( const IndexSpace &rhs) //-------------------------------------------------------------------------- { id = rhs.get_id(); tid = rhs.get_tree_id(); type_tag = rhs.get_type_tag(); Internal::NT_TemplateHelper::template check_type<DIM,T>(type_tag); return *this; } //-------------------------------------------------------------------------- inline bool IndexPartition::operator==(const IndexPartition &rhs) const //-------------------------------------------------------------------------- { if (id != rhs.id) return false; if (tid != rhs.tid) return false; #ifdef DEBUG_LEGION assert(type_tag == rhs.type_tag); #endif return true; } //-------------------------------------------------------------------------- inline bool IndexPartition::operator!=(const IndexPartition &rhs) const //-------------------------------------------------------------------------- { if ((id == rhs.id) && (tid == rhs.tid)) return false; return true; } //-------------------------------------------------------------------------- inline bool IndexPartition::operator<(const IndexPartition &rhs) const //-------------------------------------------------------------------------- { if (id < rhs.id) return true; if (id > rhs.id) return false; return (tid < rhs.tid); } //-------------------------------------------------------------------------- inline bool IndexPartition::operator>(const IndexPartition &rhs) const //-------------------------------------------------------------------------- { if (id > rhs.id) return true; if (id < rhs.id) return false; return (tid > rhs.tid); } //-------------------------------------------------------------------------- inline int IndexPartition::get_dim(void) const //-------------------------------------------------------------------------- { if (type_tag == 0) return 0; return Internal::NT_TemplateHelper::get_dim(type_tag); } //-------------------------------------------------------------------------- template<int DIM, typename T> IndexPartitionT<DIM,T>::IndexPartitionT(IndexPartitionID id,IndexTreeID tid) : IndexPartition(id, tid, Internal::NT_TemplateHelper::template encode_tag<DIM,T>()) //-------------------------------------------------------------------------- { } //-------------------------------------------------------------------------- template<int DIM, typename T> IndexPartitionT<DIM,T>::IndexPartitionT(void) : IndexPartition(0,0, Internal::NT_TemplateHelper::template encode_tag<DIM,T>()) //-------------------------------------------------------------------------- { } //-------------------------------------------------------------------------- template<int DIM, typename T> IndexPartitionT<DIM,T>::IndexPartitionT(const IndexPartition &rhs) : IndexPartition(rhs.get_id(), rhs.get_tree_id(), rhs.get_type_tag()) //-------------------------------------------------------------------------- { Internal::NT_TemplateHelper::template check_type<DIM,T>(type_tag); } //-------------------------------------------------------------------------- template<int DIM, typename T> IndexPartitionT<DIM,T>& IndexPartitionT<DIM,T>::operator=( const IndexPartition &rhs) //-------------------------------------------------------------------------- { id = rhs.get_id(); tid = rhs.get_tree_id(); type_tag = rhs.get_type_tag(); Internal::NT_TemplateHelper::template check_type<DIM,T>(type_tag); return *this; } //-------------------------------------------------------------------------- inline bool FieldSpace::operator==(const FieldSpace &rhs) const //-------------------------------------------------------------------------- { return (id == rhs.id); } //-------------------------------------------------------------------------- inline bool FieldSpace::operator!=(const FieldSpace &rhs) const //-------------------------------------------------------------------------- { return (id != rhs.id); } //-------------------------------------------------------------------------- inline bool FieldSpace::operator<(const FieldSpace &rhs) const //-------------------------------------------------------------------------- { return (id < rhs.id); } //-------------------------------------------------------------------------- inline bool FieldSpace::operator>(const FieldSpace &rhs) const //-------------------------------------------------------------------------- { return (id > rhs.id); } //-------------------------------------------------------------------------- inline bool LogicalRegion::operator==(const LogicalRegion &rhs) const //-------------------------------------------------------------------------- { return ((tree_id == rhs.tree_id) && (index_space == rhs.index_space) && (field_space == rhs.field_space)); } //-------------------------------------------------------------------------- inline bool LogicalRegion::operator!=(const LogicalRegion &rhs) const //-------------------------------------------------------------------------- { return (!((*this) == rhs)); } //-------------------------------------------------------------------------- inline bool LogicalRegion::operator<(const LogicalRegion &rhs) const //-------------------------------------------------------------------------- { if (tree_id < rhs.tree_id) return true; else if (tree_id > rhs.tree_id) return false; else { if (index_space < rhs.index_space) return true; else if (index_space != rhs.index_space) // therefore greater than return false; else return field_space < rhs.field_space; } } //-------------------------------------------------------------------------- template<int DIM, typename T> LogicalRegionT<DIM,T>::LogicalRegionT(RegionTreeID tid, IndexSpace is, FieldSpace fs) : LogicalRegion(tid, is, fs) //-------------------------------------------------------------------------- { Internal::NT_TemplateHelper::template check_type<DIM,T>( is.get_type_tag()); } //-------------------------------------------------------------------------- template<int DIM, typename T> LogicalRegionT<DIM,T>::LogicalRegionT(void) : LogicalRegion() //-------------------------------------------------------------------------- { } //-------------------------------------------------------------------------- template<int DIM, typename T> LogicalRegionT<DIM,T>::LogicalRegionT(const LogicalRegion &rhs) : LogicalRegion(rhs.get_tree_id(), rhs.get_index_space(), rhs.get_field_space()) //-------------------------------------------------------------------------- { Internal::NT_TemplateHelper::template check_type<DIM,T>( rhs.get_type_tag()); } //-------------------------------------------------------------------------- template<int DIM, typename T> LogicalRegionT<DIM,T>& LogicalRegionT<DIM,T>::operator=( const LogicalRegion &rhs) //-------------------------------------------------------------------------- { tree_id = rhs.get_tree_id(); index_space = rhs.get_index_space(); field_space = rhs.get_field_space(); Internal::NT_TemplateHelper::template check_type<DIM,T>( rhs.get_type_tag()); return *this; } //-------------------------------------------------------------------------- inline bool LogicalPartition::operator==(const LogicalPartition &rhs) const //-------------------------------------------------------------------------- { return ((tree_id == rhs.tree_id) && (index_partition == rhs.index_partition) && (field_space == rhs.field_space)); } //-------------------------------------------------------------------------- inline bool LogicalPartition::operator!=(const LogicalPartition &rhs) const //-------------------------------------------------------------------------- { return (!((*this) == rhs)); } //-------------------------------------------------------------------------- inline bool LogicalPartition::operator<(const LogicalPartition &rhs) const //-------------------------------------------------------------------------- { if (tree_id < rhs.tree_id) return true; else if (tree_id > rhs.tree_id) return false; else { if (index_partition < rhs.index_partition) return true; else if (index_partition > rhs.index_partition) return false; else return (field_space < rhs.field_space); } } //-------------------------------------------------------------------------- template<int DIM, typename T> LogicalPartitionT<DIM,T>::LogicalPartitionT(RegionTreeID tid, IndexPartition pid, FieldSpace fs) : LogicalPartition(tid, pid, fs) //-------------------------------------------------------------------------- { Internal::NT_TemplateHelper::template check_type<DIM,T>( pid.get_type_tag()); } //-------------------------------------------------------------------------- template<int DIM, typename T> LogicalPartitionT<DIM,T>::LogicalPartitionT(void) : LogicalPartition() //-------------------------------------------------------------------------- { } //-------------------------------------------------------------------------- template<int DIM, typename T> LogicalPartitionT<DIM,T>::LogicalPartitionT(const LogicalPartition &rhs) : LogicalPartition(rhs.get_tree_id(), rhs.get_index_partition(), rhs.get_field_space()) //-------------------------------------------------------------------------- { Internal::NT_TemplateHelper::template check_type<DIM,T>( rhs.get_type_tag()); } //-------------------------------------------------------------------------- template<int DIM, typename T> LogicalPartitionT<DIM,T>& LogicalPartitionT<DIM,T>::operator=( const LogicalPartition &rhs) //-------------------------------------------------------------------------- { tree_id = rhs.get_tree_id(); index_partition = rhs.get_index_partition(); field_space = rhs.get_field_space(); Internal::NT_TemplateHelper::template check_type<DIM,T>( rhs.get_type_tag()); return *this; } //-------------------------------------------------------------------------- inline bool FieldAllocator::operator==(const FieldAllocator &rhs) const //-------------------------------------------------------------------------- { return (impl == rhs.impl); } //-------------------------------------------------------------------------- inline bool FieldAllocator::operator<(const FieldAllocator &rhs) const //-------------------------------------------------------------------------- { return (impl < rhs.impl); } //-------------------------------------------------------------------------- template<typename PT, unsigned DIM> inline void ArgumentMap::set_point_arg(const PT point[DIM], const TaskArgument &arg, bool replace/*= false*/) //-------------------------------------------------------------------------- { LEGION_STATIC_ASSERT(DIM <= DomainPoint::MAX_POINT_DIM, "ArgumentMap DIM is larger than LEGION_MAX_DIM"); DomainPoint dp; dp.dim = DIM; for (unsigned idx = 0; idx < DIM; idx++) dp.point_data[idx] = point[idx]; set_point(dp, arg, replace); } //-------------------------------------------------------------------------- template<typename PT, unsigned DIM> inline bool ArgumentMap::remove_point(const PT point[DIM]) //-------------------------------------------------------------------------- { LEGION_STATIC_ASSERT(DIM <= DomainPoint::MAX_POINT_DIM, "ArgumentMap DIM is larger than LEGION_MAX_DIM"); DomainPoint dp; dp.dim = DIM; for (unsigned idx = 0; idx < DIM; idx++) dp.point_data[idx] = point[idx]; return remove_point(dp); } //-------------------------------------------------------------------------- inline bool Predicate::operator==(const Predicate &p) const //-------------------------------------------------------------------------- { if (impl == NULL) { if (p.impl == NULL) return (const_value == p.const_value); else return false; } else return (impl == p.impl); } //-------------------------------------------------------------------------- inline bool Predicate::operator<(const Predicate &p) const //-------------------------------------------------------------------------- { if (impl == NULL) { if (p.impl == NULL) return (const_value < p.const_value); else return true; } else return (impl < p.impl); } //-------------------------------------------------------------------------- inline bool Predicate::operator!=(const Predicate &p) const //-------------------------------------------------------------------------- { return !(*this == p); } //-------------------------------------------------------------------------- inline RegionFlags operator~(RegionFlags f) //-------------------------------------------------------------------------- { return static_cast<RegionFlags>(~unsigned(f)); } //-------------------------------------------------------------------------- inline RegionFlags operator|(RegionFlags left, RegionFlags right) //-------------------------------------------------------------------------- { return static_cast<RegionFlags>(unsigned(left) | unsigned(right)); } //-------------------------------------------------------------------------- inline RegionFlags operator&(RegionFlags left, RegionFlags right) //-------------------------------------------------------------------------- { return static_cast<RegionFlags>(unsigned(left) & unsigned(right)); } //-------------------------------------------------------------------------- inline RegionFlags operator^(RegionFlags left, RegionFlags right) //-------------------------------------------------------------------------- { return static_cast<RegionFlags>(unsigned(left) ^ unsigned(right)); } //-------------------------------------------------------------------------- inline RegionFlags operator|=(RegionFlags &left, RegionFlags right) //-------------------------------------------------------------------------- { unsigned l = static_cast<unsigned>(left); unsigned r = static_cast<unsigned>(right); l |= r; return left = static_cast<RegionFlags>(l); } //-------------------------------------------------------------------------- inline RegionFlags operator&=(RegionFlags &left, RegionFlags right) //-------------------------------------------------------------------------- { unsigned l = static_cast<unsigned>(left); unsigned r = static_cast<unsigned>(right); l &= r; return left = static_cast<RegionFlags>(l); } //-------------------------------------------------------------------------- inline RegionFlags operator^=(RegionFlags &left, RegionFlags right) //-------------------------------------------------------------------------- { unsigned l = static_cast<unsigned>(left); unsigned r = static_cast<unsigned>(right); l ^= r; return left = static_cast<RegionFlags>(l); } //-------------------------------------------------------------------------- inline RegionRequirement& RegionRequirement::add_field(FieldID fid, bool instance/*= true*/) //-------------------------------------------------------------------------- { privilege_fields.insert(fid); if (instance) instance_fields.push_back(fid); return *this; } //-------------------------------------------------------------------------- inline RegionRequirement& RegionRequirement::add_fields( const std::vector<FieldID>& fids, bool instance/*= true*/) //-------------------------------------------------------------------------- { privilege_fields.insert(fids.begin(), fids.end()); if (instance) instance_fields.insert(instance_fields.end(), fids.begin(), fids.end()); return *this; } //-------------------------------------------------------------------------- inline RegionRequirement& RegionRequirement::add_flags( RegionFlags new_flags) //-------------------------------------------------------------------------- { flags |= new_flags; return *this; } //-------------------------------------------------------------------------- inline void StaticDependence::add_field(FieldID fid) //-------------------------------------------------------------------------- { dependent_fields.insert(fid); } //-------------------------------------------------------------------------- inline IndexSpaceRequirement& TaskLauncher::add_index_requirement( const IndexSpaceRequirement &req) //-------------------------------------------------------------------------- { index_requirements.push_back(req); return index_requirements.back(); } //-------------------------------------------------------------------------- inline RegionRequirement& TaskLauncher::add_region_requirement( const RegionRequirement &req) //-------------------------------------------------------------------------- { region_requirements.push_back(req); return region_requirements.back(); } //-------------------------------------------------------------------------- inline void TaskLauncher::add_field(unsigned idx, FieldID fid, bool inst) //-------------------------------------------------------------------------- { #ifdef DEBUG_LEGION assert(idx < region_requirements.size()); #endif region_requirements[idx].add_field(fid, inst); } //-------------------------------------------------------------------------- inline void TaskLauncher::add_future(Future f) //-------------------------------------------------------------------------- { futures.push_back(f); } //-------------------------------------------------------------------------- inline void TaskLauncher::add_grant(Grant g) //-------------------------------------------------------------------------- { grants.push_back(g); } //-------------------------------------------------------------------------- inline void TaskLauncher::add_wait_barrier(PhaseBarrier bar) //-------------------------------------------------------------------------- { assert(bar.exists()); wait_barriers.push_back(bar); } //-------------------------------------------------------------------------- inline void TaskLauncher::add_arrival_barrier(PhaseBarrier bar) //-------------------------------------------------------------------------- { assert(bar.exists()); arrive_barriers.push_back(bar); } //-------------------------------------------------------------------------- inline void TaskLauncher::add_wait_handshake(LegionHandshake handshake) //-------------------------------------------------------------------------- { wait_barriers.push_back(handshake.get_legion_wait_phase_barrier()); } //-------------------------------------------------------------------------- inline void TaskLauncher::add_arrival_handshake(LegionHandshake handshake) //-------------------------------------------------------------------------- { arrive_barriers.push_back(handshake.get_legion_arrive_phase_barrier()); } //-------------------------------------------------------------------------- inline void TaskLauncher::set_predicate_false_future(Future f) //-------------------------------------------------------------------------- { predicate_false_future = f; } //-------------------------------------------------------------------------- inline void TaskLauncher::set_predicate_false_result(TaskArgument arg) //-------------------------------------------------------------------------- { predicate_false_result = arg; } //-------------------------------------------------------------------------- inline void TaskLauncher::set_independent_requirements(bool independent) //-------------------------------------------------------------------------- { independent_requirements = independent; } //-------------------------------------------------------------------------- inline IndexSpaceRequirement& IndexTaskLauncher::add_index_requirement( const IndexSpaceRequirement &req) //-------------------------------------------------------------------------- { index_requirements.push_back(req); return index_requirements.back(); } //-------------------------------------------------------------------------- inline RegionRequirement& IndexTaskLauncher::add_region_requirement( const RegionRequirement &req) //-------------------------------------------------------------------------- { region_requirements.push_back(req); return region_requirements.back(); } //-------------------------------------------------------------------------- inline void IndexTaskLauncher::add_field(unsigned idx,FieldID fid,bool inst) //-------------------------------------------------------------------------- { #ifdef DEBUG_LEGION assert(idx < region_requirements.size()); #endif region_requirements[idx].add_field(fid, inst); } //-------------------------------------------------------------------------- inline void IndexTaskLauncher::add_future(Future f) //-------------------------------------------------------------------------- { futures.push_back(f); } //-------------------------------------------------------------------------- inline void IndexTaskLauncher::add_grant(Grant g) //-------------------------------------------------------------------------- { grants.push_back(g); } //-------------------------------------------------------------------------- inline void IndexTaskLauncher::add_wait_barrier(PhaseBarrier bar) //-------------------------------------------------------------------------- { assert(bar.exists()); wait_barriers.push_back(bar); } //-------------------------------------------------------------------------- inline void IndexTaskLauncher::add_arrival_barrier(PhaseBarrier bar) //-------------------------------------------------------------------------- { assert(bar.exists()); arrive_barriers.push_back(bar); } //-------------------------------------------------------------------------- inline void IndexTaskLauncher::add_wait_handshake(LegionHandshake handshake) //-------------------------------------------------------------------------- { wait_barriers.push_back(handshake.get_legion_wait_phase_barrier()); } //-------------------------------------------------------------------------- inline void IndexTaskLauncher::add_arrival_handshake( LegionHandshake handshake) //-------------------------------------------------------------------------- { arrive_barriers.push_back(handshake.get_legion_arrive_phase_barrier()); } //-------------------------------------------------------------------------- inline void IndexTaskLauncher::set_predicate_false_future(Future f) //-------------------------------------------------------------------------- { predicate_false_future = f; } //-------------------------------------------------------------------------- inline void IndexTaskLauncher::set_predicate_false_result(TaskArgument arg) //-------------------------------------------------------------------------- { predicate_false_result = arg; } //-------------------------------------------------------------------------- inline void IndexTaskLauncher::set_independent_requirements( bool independent) //-------------------------------------------------------------------------- { independent_requirements = independent; } //-------------------------------------------------------------------------- inline void InlineLauncher::add_field(FieldID fid, bool inst) //-------------------------------------------------------------------------- { requirement.add_field(fid, inst); } //-------------------------------------------------------------------------- inline void InlineLauncher::add_grant(Grant g) //-------------------------------------------------------------------------- { grants.push_back(g); } //-------------------------------------------------------------------------- inline void InlineLauncher::add_wait_barrier(PhaseBarrier bar) //-------------------------------------------------------------------------- { assert(bar.exists()); wait_barriers.push_back(bar); } //-------------------------------------------------------------------------- inline void InlineLauncher::add_arrival_barrier(PhaseBarrier bar) //-------------------------------------------------------------------------- { assert(bar.exists()); arrive_barriers.push_back(bar); } //-------------------------------------------------------------------------- inline void InlineLauncher::add_wait_handshake(LegionHandshake handshake) //-------------------------------------------------------------------------- { wait_barriers.push_back(handshake.get_legion_wait_phase_barrier()); } //-------------------------------------------------------------------------- inline void InlineLauncher::add_arrival_handshake(LegionHandshake handshake) //-------------------------------------------------------------------------- { arrive_barriers.push_back(handshake.get_legion_arrive_phase_barrier()); } //-------------------------------------------------------------------------- inline unsigned CopyLauncher::add_copy_requirements( const RegionRequirement &src, const RegionRequirement &dst) //-------------------------------------------------------------------------- { unsigned result = src_requirements.size(); #ifdef DEBUG_LEGION assert(result == dst_requirements.size()); #endif src_requirements.push_back(src); dst_requirements.push_back(dst); return result; } //-------------------------------------------------------------------------- inline void CopyLauncher::add_src_field(unsigned idx,FieldID fid,bool inst) //-------------------------------------------------------------------------- { #ifdef DEBUG_LEGION assert(idx < src_requirements.size()); #endif src_requirements[idx].add_field(fid, inst); } //-------------------------------------------------------------------------- inline void CopyLauncher::add_dst_field(unsigned idx,FieldID fid,bool inst) //-------------------------------------------------------------------------- { #ifdef DEBUG_LEGION assert(idx < dst_requirements.size()); #endif dst_requirements[idx].add_field(fid, inst); } //-------------------------------------------------------------------------- inline void CopyLauncher::add_src_indirect_field(FieldID src_idx_field, const RegionRequirement &req, bool range, bool inst) //-------------------------------------------------------------------------- { src_indirect_requirements.push_back(req); src_indirect_requirements.back().add_field(src_idx_field, inst); src_indirect_is_range.push_back(range); } //-------------------------------------------------------------------------- inline void CopyLauncher::add_dst_indirect_field(FieldID dst_idx_field, const RegionRequirement &req, bool range, bool inst) //-------------------------------------------------------------------------- { dst_indirect_requirements.push_back(req); dst_indirect_requirements.back().add_field(dst_idx_field, inst); dst_indirect_is_range.push_back(range); } //-------------------------------------------------------------------------- inline RegionRequirement& CopyLauncher::add_src_indirect_field( const RegionRequirement &req, bool range) //-------------------------------------------------------------------------- { src_indirect_requirements.push_back(req); src_indirect_is_range.push_back(range); return src_indirect_requirements.back(); } //-------------------------------------------------------------------------- inline RegionRequirement& CopyLauncher::add_dst_indirect_field( const RegionRequirement &req, bool range) //-------------------------------------------------------------------------- { dst_indirect_requirements.push_back(req); dst_indirect_is_range.push_back(range); return dst_indirect_requirements.back(); } //-------------------------------------------------------------------------- inline void CopyLauncher::add_grant(Grant g) //-------------------------------------------------------------------------- { grants.push_back(g); } //-------------------------------------------------------------------------- inline void CopyLauncher::add_wait_barrier(PhaseBarrier bar) //-------------------------------------------------------------------------- { assert(bar.exists()); wait_barriers.push_back(bar); } //-------------------------------------------------------------------------- inline void CopyLauncher::add_arrival_barrier(PhaseBarrier bar) //-------------------------------------------------------------------------- { assert(bar.exists()); arrive_barriers.push_back(bar); } //-------------------------------------------------------------------------- inline void CopyLauncher::add_wait_handshake(LegionHandshake handshake) //-------------------------------------------------------------------------- { wait_barriers.push_back(handshake.get_legion_wait_phase_barrier()); } //-------------------------------------------------------------------------- inline void CopyLauncher::add_arrival_handshake(LegionHandshake handshake) //-------------------------------------------------------------------------- { arrive_barriers.push_back(handshake.get_legion_arrive_phase_barrier()); } //-------------------------------------------------------------------------- inline unsigned IndexCopyLauncher::add_copy_requirements( const RegionRequirement &src, const RegionRequirement &dst) //-------------------------------------------------------------------------- { unsigned result = src_requirements.size(); #ifdef DEBUG_LEGION assert(result == dst_requirements.size()); #endif src_requirements.push_back(src); dst_requirements.push_back(dst); return result; } //-------------------------------------------------------------------------- inline void IndexCopyLauncher::add_src_field(unsigned idx, FieldID fid, bool inst) //-------------------------------------------------------------------------- { #ifdef DEBUG_LEGION assert(idx < src_requirements.size()); #endif src_requirements[idx].add_field(fid, inst); } //-------------------------------------------------------------------------- inline void IndexCopyLauncher::add_dst_field(unsigned idx, FieldID fid, bool inst) //-------------------------------------------------------------------------- { #ifdef DEBUG_LEGION assert(idx < dst_requirements.size()); #endif dst_requirements[idx].add_field(fid, inst); } //-------------------------------------------------------------------------- inline void IndexCopyLauncher::add_src_indirect_field(FieldID src_idx_field, const RegionRequirement &r, bool range, bool inst) //-------------------------------------------------------------------------- { src_indirect_requirements.push_back(r); src_indirect_requirements.back().add_field(src_idx_field, inst); src_indirect_is_range.push_back(range); } //-------------------------------------------------------------------------- inline void IndexCopyLauncher::add_dst_indirect_field(FieldID dst_idx_field, const RegionRequirement &r, bool range, bool inst) //-------------------------------------------------------------------------- { dst_indirect_requirements.push_back(r); dst_indirect_requirements.back().add_field(dst_idx_field, inst); dst_indirect_is_range.push_back(range); } //-------------------------------------------------------------------------- inline RegionRequirement& IndexCopyLauncher::add_src_indirect_field( const RegionRequirement &req, bool range) //-------------------------------------------------------------------------- { src_indirect_requirements.push_back(req); src_indirect_is_range.push_back(range); return src_indirect_requirements.back(); } //-------------------------------------------------------------------------- inline RegionRequirement& IndexCopyLauncher::add_dst_indirect_field( const RegionRequirement &req, bool range) //-------------------------------------------------------------------------- { dst_indirect_requirements.push_back(req); dst_indirect_is_range.push_back(range); return dst_indirect_requirements.back(); } //-------------------------------------------------------------------------- inline void IndexCopyLauncher::add_grant(Grant g) //-------------------------------------------------------------------------- { grants.push_back(g); } //-------------------------------------------------------------------------- inline void IndexCopyLauncher::add_wait_barrier(PhaseBarrier bar) //-------------------------------------------------------------------------- { assert(bar.exists()); wait_barriers.push_back(bar); } //-------------------------------------------------------------------------- inline void IndexCopyLauncher::add_arrival_barrier(PhaseBarrier bar) //-------------------------------------------------------------------------- { assert(bar.exists()); arrive_barriers.push_back(bar); } //-------------------------------------------------------------------------- inline void IndexCopyLauncher::add_wait_handshake(LegionHandshake handshake) //-------------------------------------------------------------------------- { wait_barriers.push_back(handshake.get_legion_wait_phase_barrier()); } //-------------------------------------------------------------------------- inline void IndexCopyLauncher::add_arrival_handshake( LegionHandshake handshake) //-------------------------------------------------------------------------- { arrive_barriers.push_back(handshake.get_legion_arrive_phase_barrier()); } //-------------------------------------------------------------------------- inline void AcquireLauncher::add_field(FieldID f) //-------------------------------------------------------------------------- { fields.insert(f); } //-------------------------------------------------------------------------- inline void AcquireLauncher::add_grant(Grant g) //-------------------------------------------------------------------------- { grants.push_back(g); } //-------------------------------------------------------------------------- inline void AcquireLauncher::add_wait_barrier(PhaseBarrier bar) //-------------------------------------------------------------------------- { assert(bar.exists()); wait_barriers.push_back(bar); } //-------------------------------------------------------------------------- inline void AcquireLauncher::add_arrival_barrier(PhaseBarrier bar) //-------------------------------------------------------------------------- { assert(bar.exists()); arrive_barriers.push_back(bar); } //-------------------------------------------------------------------------- inline void AcquireLauncher::add_wait_handshake(LegionHandshake handshake) //-------------------------------------------------------------------------- { wait_barriers.push_back(handshake.get_legion_wait_phase_barrier()); } //-------------------------------------------------------------------------- inline void AcquireLauncher::add_arrival_handshake( LegionHandshake handshake) //-------------------------------------------------------------------------- { arrive_barriers.push_back(handshake.get_legion_arrive_phase_barrier()); } //-------------------------------------------------------------------------- inline void ReleaseLauncher::add_field(FieldID f) //-------------------------------------------------------------------------- { fields.insert(f); } //-------------------------------------------------------------------------- inline void ReleaseLauncher::add_grant(Grant g) //-------------------------------------------------------------------------- { grants.push_back(g); } //-------------------------------------------------------------------------- inline void ReleaseLauncher::add_wait_barrier(PhaseBarrier bar) //-------------------------------------------------------------------------- { assert(bar.exists()); wait_barriers.push_back(bar); } //-------------------------------------------------------------------------- inline void ReleaseLauncher::add_arrival_barrier(PhaseBarrier bar) //-------------------------------------------------------------------------- { assert(bar.exists()); arrive_barriers.push_back(bar); } //-------------------------------------------------------------------------- inline void ReleaseLauncher::add_wait_handshake(LegionHandshake handshake) //-------------------------------------------------------------------------- { wait_barriers.push_back(handshake.get_legion_wait_phase_barrier()); } //-------------------------------------------------------------------------- inline void ReleaseLauncher::add_arrival_handshake( LegionHandshake handshake) //-------------------------------------------------------------------------- { arrive_barriers.push_back(handshake.get_legion_arrive_phase_barrier()); } //-------------------------------------------------------------------------- inline void FillLauncher::set_argument(TaskArgument arg) //-------------------------------------------------------------------------- { argument = arg; } //-------------------------------------------------------------------------- inline void FillLauncher::set_future(Future f) //-------------------------------------------------------------------------- { future = f; } //-------------------------------------------------------------------------- inline void FillLauncher::add_field(FieldID fid) //-------------------------------------------------------------------------- { fields.insert(fid); } //-------------------------------------------------------------------------- inline void FillLauncher::add_grant(Grant g) //-------------------------------------------------------------------------- { grants.push_back(g); } //-------------------------------------------------------------------------- inline void FillLauncher::add_wait_barrier(PhaseBarrier pb) //-------------------------------------------------------------------------- { assert(pb.exists()); wait_barriers.push_back(pb); } //-------------------------------------------------------------------------- inline void FillLauncher::add_arrival_barrier(PhaseBarrier pb) //-------------------------------------------------------------------------- { assert(pb.exists()); arrive_barriers.push_back(pb); } //-------------------------------------------------------------------------- inline void FillLauncher::add_wait_handshake(LegionHandshake handshake) //-------------------------------------------------------------------------- { wait_barriers.push_back(handshake.get_legion_wait_phase_barrier()); } //-------------------------------------------------------------------------- inline void FillLauncher::add_arrival_handshake(LegionHandshake handshake) //-------------------------------------------------------------------------- { arrive_barriers.push_back(handshake.get_legion_arrive_phase_barrier()); } //-------------------------------------------------------------------------- inline void IndexFillLauncher::set_argument(TaskArgument arg) //-------------------------------------------------------------------------- { argument = arg; } //-------------------------------------------------------------------------- inline void IndexFillLauncher::set_future(Future f) //-------------------------------------------------------------------------- { future = f; } //-------------------------------------------------------------------------- inline void IndexFillLauncher::add_field(FieldID fid) //-------------------------------------------------------------------------- { fields.insert(fid); } //-------------------------------------------------------------------------- inline void IndexFillLauncher::add_grant(Grant g) //-------------------------------------------------------------------------- { grants.push_back(g); } //-------------------------------------------------------------------------- inline void IndexFillLauncher::add_wait_barrier(PhaseBarrier pb) //-------------------------------------------------------------------------- { assert(pb.exists()); wait_barriers.push_back(pb); } //-------------------------------------------------------------------------- inline void IndexFillLauncher::add_arrival_barrier(PhaseBarrier pb) //-------------------------------------------------------------------------- { assert(pb.exists()); arrive_barriers.push_back(pb); } //-------------------------------------------------------------------------- inline void IndexFillLauncher::add_wait_handshake(LegionHandshake handshake) //-------------------------------------------------------------------------- { wait_barriers.push_back(handshake.get_legion_wait_phase_barrier()); } //-------------------------------------------------------------------------- inline void IndexFillLauncher::add_arrival_handshake( LegionHandshake handshake) //-------------------------------------------------------------------------- { arrive_barriers.push_back(handshake.get_legion_arrive_phase_barrier()); } //-------------------------------------------------------------------------- inline void AttachLauncher::attach_file(const char *name, const std::vector<FieldID> &fields, LegionFileMode m) //-------------------------------------------------------------------------- { #ifdef DEBUG_LEGION assert(resource == LEGION_EXTERNAL_POSIX_FILE); #endif file_name = name; mode = m; file_fields = fields; } //-------------------------------------------------------------------------- inline void AttachLauncher::attach_hdf5(const char *name, const std::map<FieldID,const char*> &field_map, LegionFileMode m) //-------------------------------------------------------------------------- { #ifdef DEBUG_LEGION assert(resource == LEGION_EXTERNAL_HDF5_FILE); #endif file_name = name; mode = m; field_files = field_map; } //-------------------------------------------------------------------------- inline void AttachLauncher::attach_array_aos(void *base, bool column_major, const std::vector<FieldID> &fields, Memory mem, const std::map<FieldID,size_t> *alignments /*= NULL*/) //-------------------------------------------------------------------------- { #ifdef DEBUG_LEGION assert(handle.exists()); assert(resource == LEGION_EXTERNAL_INSTANCE); #endif constraints.add_constraint(PointerConstraint(mem, uintptr_t(base))); constraints.add_constraint(MemoryConstraint(mem.kind())); constraints.add_constraint( FieldConstraint(fields, true/*contiugous*/, true/*inorder*/)); const int dims = handle.get_index_space().get_dim(); std::vector<DimensionKind> dim_order(dims+1); // Field dimension first for AOS dim_order[0] = LEGION_DIM_F; if (column_major) { for (int idx = 0; idx < dims; idx++) dim_order[idx+1] = (DimensionKind)(LEGION_DIM_X + idx); } else { for (int idx = 0; idx < dims; idx++) dim_order[idx+1] = (DimensionKind)(LEGION_DIM_X + (dims-1) - idx); } constraints.add_constraint( OrderingConstraint(dim_order, false/*contiguous*/)); if (alignments != NULL) for (std::map<FieldID,size_t>::const_iterator it = alignments->begin(); it != alignments->end(); it++) constraints.add_constraint( AlignmentConstraint(it->first, LEGION_GE_EK, it->second)); privilege_fields.insert(fields.begin(), fields.end()); } //-------------------------------------------------------------------------- inline void AttachLauncher::attach_array_soa(void *base, bool column_major, const std::vector<FieldID> &fields, Memory mem, const std::map<FieldID,size_t> *alignments /*= NULL*/) //-------------------------------------------------------------------------- { #ifdef DEBUG_LEGION assert(handle.exists()); assert(resource == LEGION_EXTERNAL_INSTANCE); #endif constraints.add_constraint(PointerConstraint(mem, uintptr_t(base))); constraints.add_constraint(MemoryConstraint(mem.kind())); constraints.add_constraint( FieldConstraint(fields, true/*contiguous*/, true/*inorder*/)); const int dims = handle.get_index_space().get_dim(); std::vector<DimensionKind> dim_order(dims+1); if (column_major) { for (int idx = 0; idx < dims; idx++) dim_order[idx] = (DimensionKind)(LEGION_DIM_X + idx); } else { for (int idx = 0; idx < dims; idx++) dim_order[idx] = (DimensionKind)(LEGION_DIM_X + (dims-1) - idx); } // Field dimension last for SOA dim_order[dims] = LEGION_DIM_F; constraints.add_constraint( OrderingConstraint(dim_order, false/*contiguous*/)); if (alignments != NULL) for (std::map<FieldID,size_t>::const_iterator it = alignments->begin(); it != alignments->end(); it++) constraints.add_constraint( AlignmentConstraint(it->first, LEGION_GE_EK, it->second)); privilege_fields.insert(fields.begin(), fields.end()); } //-------------------------------------------------------------------------- inline void IndexAttachLauncher::attach_file(LogicalRegion handle, const char *file_name, const std::vector<FieldID> &fields, LegionFileMode m) //-------------------------------------------------------------------------- { #ifdef DEBUG_LEGION assert(resource == LEGION_EXTERNAL_POSIX_FILE); #endif if (handles.empty()) mode = m; #ifdef DEBUG_LEGION #ifndef NDEBUG else assert(mode == m); #endif #endif handles.push_back(handle); file_names.push_back(file_name); if (!file_fields.empty()) { #ifdef DEBUG_LEGION assert(fields.size() == file_fields.size()); #ifndef NDEBUG for (unsigned idx = 0; idx < fields.size(); idx++) assert(file_fields[idx] == fields[idx]); #endif #endif } else file_fields = fields; } //-------------------------------------------------------------------------- inline void IndexAttachLauncher::attach_hdf5(LogicalRegion handle, const char *file_name, const std::map<FieldID,const char*> &field_map, LegionFileMode m) //-------------------------------------------------------------------------- { #ifdef DEBUG_LEGION assert(resource == LEGION_EXTERNAL_HDF5_FILE); #endif if (handles.empty()) mode = m; #ifdef DEBUG_LEGION #ifndef NDEBUG else assert(mode == m); #endif #endif handles.push_back(handle); file_names.push_back(file_name); #ifdef DEBUG_LEGION #ifndef NDEBUG const bool first = field_files.empty(); #endif #endif for (std::map<FieldID,const char*>::const_iterator it = field_map.begin(); it != field_map.end(); it++) { #ifdef DEBUG_LEGION assert(first || (field_files.find(it->first) != field_files.end())); #endif field_files[it->first].push_back(it->second); } } //-------------------------------------------------------------------------- inline void IndexAttachLauncher::attach_array_aos(LogicalRegion handle, void *base, bool column_major, const std::vector<FieldID> &fields, Memory mem, const std::map<FieldID,size_t> *alignments) //-------------------------------------------------------------------------- { #ifdef DEBUG_LEGION assert(handle.exists()); assert(resource == LEGION_EXTERNAL_INSTANCE); #endif if (handles.empty()) { constraints.add_constraint( FieldConstraint(fields, true/*contiugous*/, true/*inorder*/)); const int dims = handle.get_index_space().get_dim(); std::vector<DimensionKind> dim_order(dims+1); // Field dimension first for AOS dim_order[0] = LEGION_DIM_F; if (column_major) { for (int idx = 0; idx < dims; idx++) dim_order[idx+1] = (DimensionKind)(LEGION_DIM_X + idx); } else { for (int idx = 0; idx < dims; idx++) dim_order[idx+1] = (DimensionKind)(LEGION_DIM_X + (dims-1) - idx); } constraints.add_constraint( OrderingConstraint(dim_order, false/*contiguous*/)); if (alignments != NULL) for (std::map<FieldID,size_t>::const_iterator it = alignments->begin(); it != alignments->end(); it++) constraints.add_constraint( AlignmentConstraint(it->first, LEGION_GE_EK, it->second)); privilege_fields.insert(fields.begin(), fields.end()); } #ifdef DEBUG_LEGION else { // Check that the fields are the same assert(fields.size() == privilege_fields.size()); for (std::vector<FieldID>::const_iterator it = fields.begin(); it != fields.end(); it++) assert(privilege_fields.find(*it) != privilege_fields.end()); // Check that the layouts are the same const OrderingConstraint &order = constraints.ordering_constraint; assert(order.ordering.front() == LEGION_DIM_F); const int dims = handle.get_index_space().get_dim(); assert(dims == handles.back().get_index_space().get_dim()); if (column_major) { for (int idx = 0; idx < dims; idx++) assert(order.ordering[idx+1] == ((DimensionKind)LEGION_DIM_X+idx)); } else { for (int idx = 0; idx < dims; idx++) assert(order.ordering[idx+1] == ((DimensionKind)(LEGION_DIM_X + (dims-1) - idx))); } // Check that the alignments are the same if (alignments != NULL) { assert(alignments->size() == constraints.alignment_constraints.size()); unsigned index = 0; for (std::map<FieldID,size_t>::const_iterator it = alignments->begin(); it != alignments->end(); it++, index++) { const AlignmentConstraint &alignment = constraints.alignment_constraints[index]; assert(alignment.fid == it->first); assert(alignment.alignment == it->second); } } } #endif handles.push_back(handle); pointers.emplace_back(PointerConstraint(mem, uintptr_t(base))); } //-------------------------------------------------------------------------- inline void IndexAttachLauncher::attach_array_soa(LogicalRegion handle, void *base, bool column_major, const std::vector<FieldID> &fields, Memory mem, const std::map<FieldID,size_t> *alignments) //-------------------------------------------------------------------------- { #ifdef DEBUG_LEGION assert(handle.exists()); assert(resource == LEGION_EXTERNAL_INSTANCE); #endif if (handles.empty()) { constraints.add_constraint( FieldConstraint(fields, true/*contiguous*/, true/*inorder*/)); const int dims = handle.get_index_space().get_dim(); std::vector<DimensionKind> dim_order(dims+1); if (column_major) { for (int idx = 0; idx < dims; idx++) dim_order[idx] = (DimensionKind)(LEGION_DIM_X + idx); } else { for (int idx = 0; idx < dims; idx++) dim_order[idx] = (DimensionKind)(LEGION_DIM_X + (dims-1) - idx); } // Field dimension last for SOA dim_order[dims] = LEGION_DIM_F; constraints.add_constraint( OrderingConstraint(dim_order, false/*contiguous*/)); if (alignments != NULL) for (std::map<FieldID,size_t>::const_iterator it = alignments->begin(); it != alignments->end(); it++) constraints.add_constraint( AlignmentConstraint(it->first, LEGION_GE_EK, it->second)); privilege_fields.insert(fields.begin(), fields.end()); } #ifdef DEBUG_LEGION else { // Check that the fields are the same assert(fields.size() == privilege_fields.size()); for (std::vector<FieldID>::const_iterator it = fields.begin(); it != fields.end(); it++) assert(privilege_fields.find(*it) != privilege_fields.end()); // Check that the layouts are the same const OrderingConstraint &order = constraints.ordering_constraint; const int dims = handle.get_index_space().get_dim(); assert(dims == handles.back().get_index_space().get_dim()); if (column_major) { for (int idx = 0; idx < dims; idx++) assert(order.ordering[idx] == ((DimensionKind)LEGION_DIM_X+idx)); } else { for (int idx = 0; idx < dims; idx++) assert(order.ordering[idx] == ((DimensionKind)(LEGION_DIM_X + (dims-1) - idx))); } assert(order.ordering.back() == LEGION_DIM_F); // Check that the alignments are the same if (alignments != NULL) { assert(alignments->size() == constraints.alignment_constraints.size()); unsigned index = 0; for (std::map<FieldID,size_t>::const_iterator it = alignments->begin(); it != alignments->end(); it++, index++) { const AlignmentConstraint &alignment = constraints.alignment_constraints[index]; assert(alignment.fid == it->first); assert(alignment.alignment == it->second); } } } #endif handles.push_back(handle); pointers.emplace_back(PointerConstraint(mem, uintptr_t(base))); } //-------------------------------------------------------------------------- inline void PredicateLauncher::add_predicate(const Predicate &pred) //-------------------------------------------------------------------------- { predicates.push_back(pred); } //-------------------------------------------------------------------------- inline void TimingLauncher::add_precondition(const Future &f) //-------------------------------------------------------------------------- { preconditions.insert(f); } //-------------------------------------------------------------------------- inline void MustEpochLauncher::add_single_task(const DomainPoint &point, const TaskLauncher &launcher) //-------------------------------------------------------------------------- { single_tasks.push_back(launcher); single_tasks.back().point = point; } //-------------------------------------------------------------------------- inline void MustEpochLauncher::add_index_task( const IndexTaskLauncher &launcher) //-------------------------------------------------------------------------- { index_tasks.push_back(launcher); } //-------------------------------------------------------------------------- inline LayoutConstraintRegistrar& LayoutConstraintRegistrar:: add_constraint(const SpecializedConstraint &constraint) //-------------------------------------------------------------------------- { layout_constraints.add_constraint(constraint); return *this; } //-------------------------------------------------------------------------- inline LayoutConstraintRegistrar& LayoutConstraintRegistrar:: add_constraint(const MemoryConstraint &constraint) //-------------------------------------------------------------------------- { layout_constraints.add_constraint(constraint); return *this; } //-------------------------------------------------------------------------- inline LayoutConstraintRegistrar& LayoutConstraintRegistrar:: add_constraint(const OrderingConstraint &constraint) //-------------------------------------------------------------------------- { layout_constraints.add_constraint(constraint); return *this; } //-------------------------------------------------------------------------- inline LayoutConstraintRegistrar& LayoutConstraintRegistrar:: add_constraint(const SplittingConstraint &constraint) //-------------------------------------------------------------------------- { layout_constraints.add_constraint(constraint); return *this; } //-------------------------------------------------------------------------- inline LayoutConstraintRegistrar& LayoutConstraintRegistrar:: add_constraint(const FieldConstraint &constraint) //-------------------------------------------------------------------------- { layout_constraints.add_constraint(constraint); return *this; } //-------------------------------------------------------------------------- inline LayoutConstraintRegistrar& LayoutConstraintRegistrar:: add_constraint(const DimensionConstraint &constraint) //-------------------------------------------------------------------------- { layout_constraints.add_constraint(constraint); return *this; } //-------------------------------------------------------------------------- inline LayoutConstraintRegistrar& LayoutConstraintRegistrar:: add_constraint(const AlignmentConstraint &constraint) //-------------------------------------------------------------------------- { layout_constraints.add_constraint(constraint); return *this; } //-------------------------------------------------------------------------- inline LayoutConstraintRegistrar& LayoutConstraintRegistrar:: add_constraint(const OffsetConstraint &constraint) //-------------------------------------------------------------------------- { layout_constraints.add_constraint(constraint); return *this; } //-------------------------------------------------------------------------- inline LayoutConstraintRegistrar& LayoutConstraintRegistrar:: add_constraint(const PointerConstraint &constraint) //-------------------------------------------------------------------------- { layout_constraints.add_constraint(constraint); return *this; } //-------------------------------------------------------------------------- inline TaskVariantRegistrar& TaskVariantRegistrar:: add_constraint(const ISAConstraint &constraint) //-------------------------------------------------------------------------- { execution_constraints.add_constraint(constraint); return *this; } //-------------------------------------------------------------------------- inline TaskVariantRegistrar& TaskVariantRegistrar:: add_constraint(const ProcessorConstraint &constraint) //-------------------------------------------------------------------------- { execution_constraints.add_constraint(constraint); return *this; } //-------------------------------------------------------------------------- inline TaskVariantRegistrar& TaskVariantRegistrar:: add_constraint(const ResourceConstraint &constraint) //-------------------------------------------------------------------------- { execution_constraints.add_constraint(constraint); return *this; } //-------------------------------------------------------------------------- inline TaskVariantRegistrar& TaskVariantRegistrar:: add_constraint(const LaunchConstraint &constraint) //-------------------------------------------------------------------------- { execution_constraints.add_constraint(constraint); return *this; } //-------------------------------------------------------------------------- inline TaskVariantRegistrar& TaskVariantRegistrar:: add_constraint(const ColocationConstraint &constraint) //-------------------------------------------------------------------------- { execution_constraints.add_constraint(constraint); return *this; } //-------------------------------------------------------------------------- inline TaskVariantRegistrar& TaskVariantRegistrar:: add_layout_constraint_set(unsigned index, LayoutConstraintID desc) //-------------------------------------------------------------------------- { layout_constraints.add_layout_constraint(index, desc); return *this; } //-------------------------------------------------------------------------- inline void TaskVariantRegistrar::set_leaf(bool is_leaf /*= true*/) //-------------------------------------------------------------------------- { leaf_variant = is_leaf; } //-------------------------------------------------------------------------- inline void TaskVariantRegistrar::set_inner(bool is_inner /*= true*/) //-------------------------------------------------------------------------- { inner_variant = is_inner; } //-------------------------------------------------------------------------- inline void TaskVariantRegistrar::set_idempotent(bool is_idemp/*= true*/) //-------------------------------------------------------------------------- { idempotent_variant = is_idemp; } //-------------------------------------------------------------------------- inline void TaskVariantRegistrar::set_replicable(bool is_repl/*= true*/) //-------------------------------------------------------------------------- { replicable_variant = is_repl; } //-------------------------------------------------------------------------- inline void TaskVariantRegistrar::add_generator_task(TaskID tid) //-------------------------------------------------------------------------- { generator_tasks.insert(tid); } //-------------------------------------------------------------------------- template<typename T> inline T Future::get_result(bool silence_warnings, const char *warning_string) const //-------------------------------------------------------------------------- { // Unpack the value using LegionSerialization in case // the type has an alternative method of unpacking return LegionSerialization::unpack<T>(*this, silence_warnings, warning_string); } //-------------------------------------------------------------------------- template<typename T> inline const T& Future::get_reference(bool silence_warnings, const char *warning_string) const //-------------------------------------------------------------------------- { return *((const T*)get_untyped_result(silence_warnings, warning_string, true/*check size*/, sizeof(T))); } //-------------------------------------------------------------------------- inline const void* Future::get_untyped_pointer(bool silence_warnings, const char *warning_string) const //-------------------------------------------------------------------------- { return get_untyped_result(silence_warnings, warning_string, false); } //-------------------------------------------------------------------------- template<typename T> inline T Future::get(void) //-------------------------------------------------------------------------- { return get_result<T>(); } //-------------------------------------------------------------------------- inline bool Future::valid(void) const //-------------------------------------------------------------------------- { return (impl != NULL); } //-------------------------------------------------------------------------- inline void Future::wait(void) const //-------------------------------------------------------------------------- { get_void_result(); } //-------------------------------------------------------------------------- template<typename T> /*static*/ inline Future Future::from_value(Runtime *rt, const T &value) //-------------------------------------------------------------------------- { return LegionSerialization::from_value(rt, &value); } //-------------------------------------------------------------------------- /*static*/ inline Future Future::from_untyped_pointer(Runtime *rt, const void *buffer, size_t bytes) //-------------------------------------------------------------------------- { return LegionSerialization::from_value_helper(rt, buffer, bytes, false /*!owned*/); } //-------------------------------------------------------------------------- template<typename T> inline T FutureMap::get_result(const DomainPoint &dp, bool silence_warnings, const char *warning_string) const //-------------------------------------------------------------------------- { Future f = get_future(dp); return f.get_result<T>(silence_warnings, warning_string); } //-------------------------------------------------------------------------- template<typename RT, typename PT, unsigned DIM> inline RT FutureMap::get_result(const PT point[DIM]) const //-------------------------------------------------------------------------- { LEGION_STATIC_ASSERT(DIM <= DomainPoint::MAX_POINT_DIM, "FutureMap DIM is larger than LEGION_MAX_DIM"); DomainPoint dp; dp.dim = DIM; for (unsigned idx = 0; idx < DIM; idx++) dp.point_data[idx] = point[idx]; Future f = get_future(dp); return f.get_result<RT>(); } //-------------------------------------------------------------------------- template<typename PT, unsigned DIM> inline Future FutureMap::get_future(const PT point[DIM]) const //-------------------------------------------------------------------------- { LEGION_STATIC_ASSERT(DIM <= DomainPoint::MAX_POINT_DIM, "FutureMap DIM is larger than LEGION_MAX_DIM"); DomainPoint dp; dp.dim = DIM; for (unsigned idx = 0; idx < DIM; idx++) dp.point_data[idx] = point[idx]; return get_future(dp); } //-------------------------------------------------------------------------- template<typename PT, unsigned DIM> inline void FutureMap::get_void_result(const PT point[DIM]) const //-------------------------------------------------------------------------- { LEGION_STATIC_ASSERT(DIM <= DomainPoint::MAX_POINT_DIM, "FutureMap DIM is larger than LEGION_MAX_DIM"); DomainPoint dp; dp.dim = DIM; for (unsigned idx = 0; idx < DIM; idx++) dp.point_data[idx] = point[idx]; Future f = get_future(dp); return f.get_void_result(); } //-------------------------------------------------------------------------- template<int DIM, typename T> DomainT<DIM,T> PhysicalRegion::get_bounds(void) const //-------------------------------------------------------------------------- { DomainT<DIM,T> result; get_bounds(&result, Internal::NT_TemplateHelper::encode_tag<DIM,T>()); return result; } //-------------------------------------------------------------------------- template<int DIM, typename T> PhysicalRegion::operator DomainT<DIM,T>(void) const //-------------------------------------------------------------------------- { DomainT<DIM,T> result; get_bounds(&result, Internal::NT_TemplateHelper::encode_tag<DIM,T>()); return result; } //-------------------------------------------------------------------------- template<int DIM, typename T> PhysicalRegion::operator Rect<DIM,T>(void) const //-------------------------------------------------------------------------- { DomainT<DIM,T> result; get_bounds(&result, Internal::NT_TemplateHelper::encode_tag<DIM,T>()); #ifdef DEBUG_LEGION assert(result.dense()); #endif return result.bounds; } //-------------------------------------------------------------------------- inline bool PieceIterator::valid(void) const //-------------------------------------------------------------------------- { return (impl != NULL) && (index >= 0); } //-------------------------------------------------------------------------- inline PieceIterator::operator bool(void) const //-------------------------------------------------------------------------- { return valid(); } //-------------------------------------------------------------------------- inline bool PieceIterator::operator()(void) const //-------------------------------------------------------------------------- { return valid(); } //-------------------------------------------------------------------------- inline const Domain& PieceIterator::operator*(void) const //-------------------------------------------------------------------------- { return current_piece; } //-------------------------------------------------------------------------- inline const Domain* PieceIterator::operator->(void) const //-------------------------------------------------------------------------- { return &current_piece; } //-------------------------------------------------------------------------- inline PieceIterator& PieceIterator::operator++(void) //-------------------------------------------------------------------------- { step(); return *this; } //-------------------------------------------------------------------------- inline PieceIterator PieceIterator::operator++(int) //-------------------------------------------------------------------------- { PieceIterator result = *this; step(); return result; } //-------------------------------------------------------------------------- inline bool PieceIterator::operator<(const PieceIterator &rhs) const //-------------------------------------------------------------------------- { if (impl < rhs.impl) return true; if (impl > rhs.impl) return false; if (index < rhs.index) return true; return false; } //-------------------------------------------------------------------------- inline bool PieceIterator::operator==(const PieceIterator &rhs) const //-------------------------------------------------------------------------- { if (impl != rhs.impl) return false; return index == rhs.index; } //-------------------------------------------------------------------------- inline bool PieceIterator::operator!=(const PieceIterator &rhs) const //-------------------------------------------------------------------------- { if (impl != rhs.impl) return true; return index != rhs.index; } //-------------------------------------------------------------------------- template<int DIM, typename T> inline PieceIteratorT<DIM,T>::PieceIteratorT(void) : PieceIterator() //-------------------------------------------------------------------------- { } //-------------------------------------------------------------------------- template<int DIM, typename T> inline PieceIteratorT<DIM,T>::PieceIteratorT(const PieceIteratorT &rhs) : PieceIterator(rhs), current_rect(rhs.current_rect) //-------------------------------------------------------------------------- { } //-------------------------------------------------------------------------- template<int DIM, typename T> inline PieceIteratorT<DIM,T>::PieceIteratorT(PieceIteratorT &&rhs) : PieceIterator(rhs), current_rect(rhs.current_rect) //-------------------------------------------------------------------------- { } //-------------------------------------------------------------------------- template<int DIM, typename T> inline PieceIteratorT<DIM,T>::PieceIteratorT(const PhysicalRegion &region, FieldID fid, bool privilege_only, bool silence_warn, const char *warn) : PieceIterator(region, fid, privilege_only, silence_warn, warn) //-------------------------------------------------------------------------- { if (valid()) current_rect = current_piece; } //-------------------------------------------------------------------------- template<int DIM, typename T> inline PieceIteratorT<DIM,T>& PieceIteratorT<DIM,T>::operator=( const PieceIteratorT &rhs) //-------------------------------------------------------------------------- { PieceIterator::operator=(rhs); current_rect = rhs.current_rect; return *this; } //-------------------------------------------------------------------------- template<int DIM, typename T> inline PieceIteratorT<DIM,T>& PieceIteratorT<DIM,T>::operator=( PieceIteratorT &&rhs) //-------------------------------------------------------------------------- { PieceIterator::operator=(rhs); current_rect = rhs.current_rect; return *this; } //-------------------------------------------------------------------------- template<int DIM, typename T> inline bool PieceIteratorT<DIM,T>::step(void) //-------------------------------------------------------------------------- { const bool result = PieceIterator::step(); current_rect = current_piece; return result; } //-------------------------------------------------------------------------- template<int DIM, typename T> inline const Rect<DIM,T>& PieceIteratorT<DIM,T>::operator*(void) const //-------------------------------------------------------------------------- { return current_rect; } //-------------------------------------------------------------------------- template<int DIM, typename T> inline const Rect<DIM,T>* PieceIteratorT<DIM,T>::operator->(void) const //-------------------------------------------------------------------------- { return &current_rect; } //-------------------------------------------------------------------------- template<int DIM, typename T> inline PieceIteratorT<DIM,T>& PieceIteratorT<DIM,T>::operator++(void) //-------------------------------------------------------------------------- { step(); return *this; } //-------------------------------------------------------------------------- template<int DIM, typename T> inline PieceIteratorT<DIM,T> PieceIteratorT<DIM,T>::operator++(int) //-------------------------------------------------------------------------- { PieceIteratorT<DIM,T> result = *this; step(); return result; } //-------------------------------------------------------------------------- template<PrivilegeMode PM, typename FT, int DIM, typename T> inline SpanIterator<PM,FT,DIM,T>::SpanIterator(const PhysicalRegion &region, FieldID fid, size_t actual_field_size, bool check_field_size, bool priv, bool silence_warnings, const char *warning_string) : piece_iterator(PieceIteratorT<DIM,T>(region, fid, priv)), partial_piece(false) //-------------------------------------------------------------------------- { DomainT<DIM,T> is; const Realm::RegionInstance instance = region.get_instance_info(PM, fid, actual_field_size, &is, Internal::NT_TemplateHelper::encode_tag<DIM,T>(), warning_string, silence_warnings, false/*generic accessor*/, check_field_size); if (!Realm::MultiAffineAccessor<FT,DIM,T>::is_compatible(instance, fid, is.bounds)) region.report_incompatible_accessor("SpanIterator", instance, fid); accessor = Realm::MultiAffineAccessor<FT,DIM,T>(instance, fid, is.bounds); // initialize the first span step(); } //-------------------------------------------------------------------------- template<PrivilegeMode PM, typename FT, int DIM, typename T> inline bool SpanIterator<PM,FT,DIM,T>::valid(void) const //-------------------------------------------------------------------------- { return !current.empty(); } //-------------------------------------------------------------------------- template<PrivilegeMode PM, typename FT, int DIM, typename T> inline bool SpanIterator<PM,FT,DIM,T>::step(void) //-------------------------------------------------------------------------- { // Handle the remains of a partial piece if that is what we're doing if (partial_piece) { bool carry = false; for (int idx = 0; idx < DIM; idx++) { const int dim = dim_order[idx]; if (carry || (dim == partial_step_dim)) { if (partial_step_point[dim] < piece_iterator->hi[dim]) { partial_step_point[dim] += 1; carry = false; break; } // carry case so reset and roll-over partial_step_point[dim] = piece_iterator->lo[dim]; carry = true; } // Skip any dimensions before the partial step dim } // Make the next span current = Span<FT,PM>(accessor.ptr(partial_step_point), current.size(), current.step()); // See if we are done with this partial piece if (carry) partial_piece = false; return true; } current = Span<FT,PM>(); // clear this for the next iteration // Otherwise try to group as many rectangles together as we can while (piece_iterator.valid()) { size_t strides[DIM]; FT *ptr = accessor.ptr(*piece_iterator, strides); #ifdef DEBUG_LEGION // If we ever hit this it is a runtime error because the // runtime should already be guaranteeing these rectangles // are inside of pieces for the instance assert(ptr != NULL); #endif // Find the minimum stride and see if this piece is dense size_t min_stride = SIZE_MAX; for (int dim = 0; dim < DIM; dim++) if (strides[dim] < min_stride) min_stride = strides[dim]; if (Internal::is_dense_layout(*piece_iterator, strides, min_stride)) { const size_t volume = piece_iterator->volume(); if (!current.empty()) { uintptr_t base = current.get_base(); // See if we can append to the current span if ((current.step() == min_stride) && ((base + (current.size() * min_stride)) == uintptr_t(ptr))) current = Span<FT,PM>(current.data(), current.size() + volume, min_stride); else // Save this rectangle for the next iteration break; } else // Start a new span current = Span<FT,PM>(ptr, volume, min_stride); } else { // Not a uniform stride, so go to the partial piece case if (current.empty()) { partial_piece = true; // Compute the dimension order from smallest to largest size_t stride_floor = 0; for (int idx = 0; idx < DIM; idx++) { int index = -1; size_t local_min = SIZE_MAX; for (int dim = 0; dim < DIM; dim++) { if (strides[dim] <= stride_floor) continue; if (strides[dim] < local_min) { local_min = strides[dim]; index = dim; } } #ifdef DEBUG_LEGION assert(index >= 0); #endif dim_order[idx] = index; stride_floor = local_min; } // See which dimensions we can handle at once and which ones // we are going to need to walk over size_t extent = 1; size_t exp_offset = min_stride; partial_step_dim = -1; for (int idx = 0; idx < DIM; idx++) { const int dim = dim_order[idx]; if (strides[dim] == exp_offset) { size_t pitch = ((piece_iterator->hi[dim] - piece_iterator->lo[dim]) + 1); exp_offset *= pitch; extent *= pitch; } // First dimension that is not contiguous partial_step_dim = dim; break; } #ifdef DEBUG_LEGION assert(partial_step_dim >= 0); #endif partial_step_point = piece_iterator->lo; current = Span<FT,PM>(accessor.ptr(partial_step_point), extent, min_stride); } // No matter what we are breaking out here break; } // Step the piece iterator for the next iteration piece_iterator.step(); } return valid(); } //-------------------------------------------------------------------------- template<PrivilegeMode PM, typename FT, int DIM, typename T> inline SpanIterator<PM,FT,DIM,T>::operator bool(void) const //-------------------------------------------------------------------------- { return valid(); } //-------------------------------------------------------------------------- template<PrivilegeMode PM, typename FT, int DIM, typename T> inline bool SpanIterator<PM,FT,DIM,T>::operator()(void) const //-------------------------------------------------------------------------- { return valid(); } //-------------------------------------------------------------------------- template<PrivilegeMode PM, typename FT, int DIM, typename T> inline const Span<FT,PM>& SpanIterator<PM,FT,DIM,T>::operator*(void) const //-------------------------------------------------------------------------- { return current; } //-------------------------------------------------------------------------- template<PrivilegeMode PM, typename FT, int DIM, typename T> inline const Span<FT,PM>* SpanIterator<PM,FT,DIM,T>::operator->(void) const //-------------------------------------------------------------------------- { return &current; } //-------------------------------------------------------------------------- template<PrivilegeMode PM, typename FT, int DIM, typename T> inline SpanIterator<PM,FT,DIM,T>& SpanIterator<PM,FT,DIM,T>::operator++( void) //-------------------------------------------------------------------------- { step(); return *this; } //-------------------------------------------------------------------------- template<PrivilegeMode PM, typename FT, int DIM, typename T> inline SpanIterator<PM,FT,DIM,T> SpanIterator<PM,FT,DIM,T>::operator++(int) //-------------------------------------------------------------------------- { SpanIterator<PM,FT,DIM,T> result = *this; step(); return result; } #ifdef __GNUC__ #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wdeprecated-declarations" #endif #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wdeprecated-declarations" #endif //-------------------------------------------------------------------------- inline bool IndexIterator::has_next(void) const //-------------------------------------------------------------------------- { return is_iterator.valid; } //-------------------------------------------------------------------------- inline ptr_t IndexIterator::next(void) //-------------------------------------------------------------------------- { if (!rect_iterator.valid) rect_iterator = Realm::PointInRectIterator<1,coord_t>(is_iterator.rect); const ptr_t result = rect_iterator.p[0]; rect_iterator.step(); if (!rect_iterator.valid) is_iterator.step(); return result; } //-------------------------------------------------------------------------- inline ptr_t IndexIterator::next_span(size_t& act_count, size_t req_count) //-------------------------------------------------------------------------- { if (rect_iterator.valid) { // If we have a rect iterator we just go to the end of the rectangle const ptr_t result = rect_iterator.p[0]; const ptr_t last = is_iterator.rect.hi[0]; act_count = (last.value - result.value) + 1; if (act_count <= req_count) { rect_iterator.valid = false; is_iterator.step(); } else { rect_iterator.p[0] = result.value + req_count; act_count = req_count; } return result; } else { // Consume the whole rectangle const ptr_t result = is_iterator.rect.lo[0]; const ptr_t last = is_iterator.rect.hi[0]; act_count = (last.value - result.value) + 1; if (act_count > req_count) { rect_iterator = Realm::PointInRectIterator<1,coord_t>(is_iterator.rect); rect_iterator.p[0] = result.value + req_count; act_count = req_count; } else { rect_iterator.valid = false; is_iterator.step(); } return result; } } #ifdef __GNUC__ #pragma GCC diagnostic pop #endif #ifdef __clang__ #pragma clang diagnostic pop #endif //-------------------------------------------------------------------------- template<int DIM, typename T> IndexSpaceT<DIM,T> Runtime::create_index_space(Context ctx, const Rect<DIM,T> &bounds) //-------------------------------------------------------------------------- { const Domain domain(bounds); return IndexSpaceT<DIM,T>(create_index_space(ctx, domain, Internal::NT_TemplateHelper::template encode_tag<DIM,T>())); } //-------------------------------------------------------------------------- template<int DIM, typename T> IndexSpaceT<DIM,T> Runtime::create_index_space(Context ctx, const DomainT<DIM,T> &bounds) //-------------------------------------------------------------------------- { const Domain domain(bounds); return IndexSpaceT<DIM,T>(create_index_space(ctx, domain, Internal::NT_TemplateHelper::template encode_tag<DIM,T>())); } //-------------------------------------------------------------------------- template<int DIM, typename T> IndexSpaceT<DIM,T> Runtime::create_index_space(Context ctx, const Future &future) //-------------------------------------------------------------------------- { return IndexSpaceT<DIM,T>(create_index_space(ctx, DIM, future, Internal::NT_TemplateHelper::template encode_tag<DIM,T>())); } //-------------------------------------------------------------------------- template<int DIM, typename T> IndexSpaceT<DIM,T> Runtime::create_index_space(Context ctx, const std::vector<Point<DIM,T> > &points) //-------------------------------------------------------------------------- { // C++ type system is dumb std::vector<Realm::Point<DIM,T> > realm_points(points.size()); for (unsigned idx = 0; idx < points.size(); idx++) realm_points[idx] = points[idx]; const DomainT<DIM,T> realm_is((Realm::IndexSpace<DIM,T>(realm_points))); const Domain domain(realm_is); return IndexSpaceT<DIM,T>(create_index_space(ctx, domain, Internal::NT_TemplateHelper::template encode_tag<DIM,T>())); } //-------------------------------------------------------------------------- template<int DIM, typename T> IndexSpaceT<DIM,T> Runtime::create_index_space(Context ctx, const std::vector<Rect<DIM,T> > &rects) //-------------------------------------------------------------------------- { // C++ type system is dumb std::vector<Realm::Rect<DIM,T> > realm_rects(rects.size()); for (unsigned idx = 0; idx < rects.size(); idx++) realm_rects[idx] = rects[idx]; const DomainT<DIM,T> realm_is((Realm::IndexSpace<DIM,T>(realm_rects))); const Domain domain(realm_is); return IndexSpaceT<DIM,T>(create_index_space(ctx, domain, Internal::NT_TemplateHelper::template encode_tag<DIM,T>())); } //-------------------------------------------------------------------------- template<int DIM, typename T> IndexSpaceT<DIM,T> Runtime::union_index_spaces(Context ctx, const std::vector<IndexSpaceT<DIM,T> > &spaces) //-------------------------------------------------------------------------- { std::vector<IndexSpace> handles(spaces.size()); for (unsigned idx = 0; idx < spaces.size(); idx++) handles[idx] = spaces[idx]; return IndexSpaceT<DIM,T>(union_index_spaces(ctx, handles)); } //-------------------------------------------------------------------------- template<int DIM, typename T> IndexSpaceT<DIM,T> Runtime::intersect_index_spaces(Context ctx, const std::vector<IndexSpaceT<DIM,T> > &spaces) //-------------------------------------------------------------------------- { std::vector<IndexSpace> handles(spaces.size()); for (unsigned idx = 0; idx < spaces.size(); idx++) handles[idx] = spaces[idx]; return IndexSpaceT<DIM,T>(intersect_index_spaces(ctx, handles)); } //-------------------------------------------------------------------------- template<int DIM, typename T> IndexSpaceT<DIM,T> Runtime::subtract_index_spaces(Context ctx, IndexSpaceT<DIM,T> left, IndexSpaceT<DIM,T> right) //-------------------------------------------------------------------------- { return IndexSpaceT<DIM,T>(subtract_index_spaces(ctx, IndexSpace(left), IndexSpace(right))); } //-------------------------------------------------------------------------- template<typename T> IndexPartition Runtime::create_index_partition(Context ctx, IndexSpace parent, const T& mapping, Color part_color /*= AUTO_GENERATE*/) //-------------------------------------------------------------------------- { LegionRuntime::Arrays::Rect<T::IDIM> parent_rect = get_index_space_domain(ctx, parent).get_rect<T::IDIM>(); LegionRuntime::Arrays::Rect<T::ODIM> color_space = mapping.image_convex(parent_rect); DomainPointColoring c; for (typename T::PointInOutputRectIterator pir(color_space); pir; pir++) { LegionRuntime::Arrays::Rect<T::IDIM> preimage = mapping.preimage(pir.p); #ifdef DEBUG_LEGION assert(mapping.preimage_is_dense(pir.p)); #endif c[DomainPoint::from_point<T::IDIM>(pir.p)] = Domain::from_rect<T::IDIM>(preimage.intersection(parent_rect)); } return create_index_partition(ctx, parent, Domain::from_rect<T::ODIM>(color_space), c, LEGION_DISJOINT_KIND, part_color); } //-------------------------------------------------------------------------- template<int DIM, typename T, int COLOR_DIM, typename COLOR_T> IndexPartitionT<DIM,T> Runtime::create_equal_partition(Context ctx, IndexSpaceT<DIM,T> parent, IndexSpaceT<COLOR_DIM,COLOR_T> color_space, size_t granularity, Color color) //-------------------------------------------------------------------------- { return IndexPartitionT<DIM,T>(create_equal_partition(ctx, IndexSpace(parent), IndexSpace(color_space), granularity, color)); } //-------------------------------------------------------------------------- template<int DIM, typename T, int COLOR_DIM, typename COLOR_T> IndexPartitionT<DIM,T> Runtime::create_partition_by_weights(Context ctx, IndexSpaceT<DIM,T> parent, const std::map<Point<COLOR_DIM,COLOR_T>,int> &weights, IndexSpaceT<COLOR_DIM,COLOR_T> color_space, size_t granularity, Color color) //-------------------------------------------------------------------------- { std::map<DomainPoint,int> untyped_weights; for (typename std::map<Point<COLOR_DIM,COLOR_T>,int>::const_iterator it = weights.begin(); it != weights.end(); it++) untyped_weights[DomainPoint(it->first)] = it->second; return IndexPartitionT<DIM,T>(create_partition_by_weights(ctx, IndexSpace(parent), untyped_weights, IndexSpace(color_space), granularity, color)); } //-------------------------------------------------------------------------- template<int DIM, typename T, int COLOR_DIM, typename COLOR_T> IndexPartitionT<DIM,T> Runtime::create_partition_by_weights(Context ctx, IndexSpaceT<DIM,T> parent, const std::map<Point<COLOR_DIM,COLOR_T>,size_t> &weights, IndexSpaceT<COLOR_DIM,COLOR_T> color_space, size_t granularity, Color color) //-------------------------------------------------------------------------- { std::map<DomainPoint,size_t> untyped_weights; for (typename std::map<Point<COLOR_DIM,COLOR_T>,size_t>::const_iterator it = weights.begin(); it != weights.end(); it++) untyped_weights[DomainPoint(it->first)] = it->second; return IndexPartitionT<DIM,T>(create_partition_by_weights(ctx, IndexSpace(parent), untyped_weights, IndexSpace(color_space), granularity, color)); } //-------------------------------------------------------------------------- template<int DIM, typename T, int COLOR_DIM, typename COLOR_T> IndexPartitionT<DIM,T> Runtime::create_partition_by_weights(Context ctx, IndexSpaceT<DIM,T> parent, const FutureMap &weights, IndexSpaceT<COLOR_DIM,COLOR_T> color_space, size_t granularity, Color color) //-------------------------------------------------------------------------- { return IndexPartitionT<DIM,T>(create_partition_by_weights(ctx, IndexSpace(parent), weights, IndexSpace(color_space), granularity, color)); } //-------------------------------------------------------------------------- template<int DIM, typename T, int COLOR_DIM, typename COLOR_T> IndexPartitionT<DIM,T> Runtime::create_partition_by_union(Context ctx, IndexSpaceT<DIM,T> parent, IndexPartitionT<DIM,T> handle1, IndexPartitionT<DIM,T> handle2, IndexSpaceT<COLOR_DIM,COLOR_T> color_space, PartitionKind part_kind, Color color) //-------------------------------------------------------------------------- { return IndexPartitionT<DIM,T>(create_partition_by_union(ctx, IndexSpace(parent), IndexPartition(handle1), IndexPartition(handle2), IndexSpace(color_space), part_kind, color)); } //-------------------------------------------------------------------------- template<int DIM, typename T, int COLOR_DIM, typename COLOR_T> IndexPartitionT<DIM,T> Runtime::create_partition_by_intersection( Context ctx, IndexSpaceT<DIM,T> parent, IndexPartitionT<DIM,T> handle1, IndexPartitionT<DIM,T> handle2, IndexSpaceT<COLOR_DIM,COLOR_T> color_space, PartitionKind part_kind, Color color) //-------------------------------------------------------------------------- { return IndexPartitionT<DIM,T>(create_partition_by_intersection(ctx, IndexSpace(parent), IndexPartition(handle1), IndexPartition(handle2), IndexSpace(color_space), part_kind, color)); } //-------------------------------------------------------------------------- template<int DIM, typename T> IndexPartitionT<DIM,T> Runtime::create_partition_by_intersection( Context ctx, IndexSpaceT<DIM,T> parent, IndexPartitionT<DIM,T> partition, PartitionKind part_kind, Color color, bool safe) //-------------------------------------------------------------------------- { return IndexPartitionT<DIM,T>(create_partition_by_intersection(ctx, IndexSpace(parent), IndexPartition(partition), part_kind, color, safe)); } //-------------------------------------------------------------------------- template<int DIM, typename T, int COLOR_DIM, typename COLOR_T> IndexPartitionT<DIM,T> Runtime::create_partition_by_difference(Context ctx, IndexSpaceT<DIM,T> parent, IndexPartitionT<DIM,T> handle1, IndexPartitionT<DIM,T> handle2, IndexSpaceT<COLOR_DIM,COLOR_T> color_space, PartitionKind part_kind, Color color) //-------------------------------------------------------------------------- { return IndexPartitionT<DIM,T>(create_partition_by_difference(ctx, IndexSpace(parent), IndexPartition(handle1), IndexPartition(handle2), IndexSpace(color_space), part_kind, color)); } //-------------------------------------------------------------------------- template<int DIM, typename T, int COLOR_DIM, typename COLOR_T> Color Runtime::create_cross_product_partitions(Context ctx, IndexPartitionT<DIM,T> handle1, IndexPartitionT<DIM,T> handle2, typename std::map< IndexSpaceT<DIM,T>, IndexPartitionT<DIM,T> > &handles, PartitionKind part_kind, Color color) //-------------------------------------------------------------------------- { std::map<IndexSpace,IndexPartition> untyped_handles; for (typename std::map<IndexSpaceT<DIM,T>, IndexPartitionT<DIM,T> >::const_iterator it = handles.begin(); it != handles.end(); it++) untyped_handles[it->first] = IndexPartition::NO_PART; Color result = create_cross_product_partitions(ctx, handle1, handle2, untyped_handles, part_kind, color); for (typename std::map<IndexSpaceT<DIM,T>, IndexPartitionT<DIM,T> >::iterator it = handles.begin(); it != handles.end(); it++) { std::map<IndexSpace,IndexPartition>::const_iterator finder = untyped_handles.find(it->first); #ifdef DEBUG_LEGION assert(finder != untyped_handles.end()); #endif it->second = IndexPartitionT<DIM,T>(finder->second); } return result; } //-------------------------------------------------------------------------- template<int DIM1, typename T1, int DIM2, typename T2> void Runtime::create_association(Context ctx, LogicalRegionT<DIM1,T1> domain, LogicalRegionT<DIM1,T1> domain_parent, FieldID domain_fid, IndexSpaceT<DIM2,T2> range, MapperID id, MappingTagID tag) //-------------------------------------------------------------------------- { create_association(ctx, LogicalRegion(domain), LogicalRegion(domain_parent), domain_fid, IndexSpace(range), id, tag); } //-------------------------------------------------------------------------- template<int DIM1, typename T1, int DIM2, typename T2> void Runtime::create_bidirectional_association(Context ctx, LogicalRegionT<DIM1,T1> domain, LogicalRegionT<DIM1,T1> domain_parent, FieldID domain_fid, LogicalRegionT<DIM2,T2> range, LogicalRegionT<DIM2,T2> range_parent, FieldID range_fid, MapperID id, MappingTagID tag) //-------------------------------------------------------------------------- { create_bidirectional_association(ctx, LogicalRegion(domain), LogicalRegion(domain_parent), domain_fid, LogicalRegion(range), LogicalRegion(range_parent), range_fid, id, tag); } //-------------------------------------------------------------------------- template<int DIM, int COLOR_DIM, typename T> IndexPartitionT<DIM,T> Runtime::create_partition_by_restriction(Context ctx, IndexSpaceT<DIM,T> parent, IndexSpaceT<COLOR_DIM,T> color_space, Transform<DIM,COLOR_DIM,T> transform, Rect<DIM,T> extent, PartitionKind part_kind, Color color) //-------------------------------------------------------------------------- { return IndexPartitionT<DIM,T>(create_restricted_partition(ctx, parent, color_space, &transform, sizeof(transform), &extent, sizeof(extent), part_kind, color)); } //-------------------------------------------------------------------------- template<int DIM, typename T> IndexPartitionT<DIM,T> Runtime::create_partition_by_blockify(Context ctx, IndexSpaceT<DIM,T> parent, Point<DIM,T> blocking_factor, Color color) //-------------------------------------------------------------------------- { Point<DIM,T> origin; for (int i = 0; i < DIM; i++) origin[i] = 0; return create_partition_by_blockify<DIM,T>(ctx, parent, blocking_factor, origin, color); } //-------------------------------------------------------------------------- template<int DIM, typename T> IndexPartitionT<DIM,T> Runtime::create_partition_by_blockify(Context ctx, IndexSpaceT<DIM,T> parent, Point<DIM,T> blocking_factor, Point<DIM,T> origin, Color color) //-------------------------------------------------------------------------- { // Get the domain of the color space to partition const DomainT<DIM,T> parent_is = get_index_space_domain(parent); const Rect<DIM,T> &bounds = parent_is.bounds; if (bounds.empty()) return IndexPartitionT<DIM,T>(); // Compute the intended color space bounds Point<DIM,T> colors; for (int i = 0; i < DIM; i++) colors[i] = (((bounds.hi[i] - bounds.lo[i]) + // -1 and +1 cancel out blocking_factor[i]) / blocking_factor[i]) - 1; Point<DIM,T> zeroes; for (int i = 0; i < DIM; i++) zeroes[i] = 0; // Make the color space IndexSpaceT<DIM,T> color_space = create_index_space(ctx, Rect<DIM,T>(zeroes, colors)); // Now make the transform matrix Transform<DIM,DIM,T> transform; for (int i = 0; i < DIM; i++) for (int j = 0; j < DIM; j++) if (i == j) transform[i][j] = blocking_factor[i]; else transform[i][j] = 0; // And the extent Point<DIM,T> ones; for (int i = 0; i < DIM; i++) ones[i] = 1; const Rect<DIM,T> extent(origin, origin + blocking_factor - ones); // Then do the create partition by restriction call return create_partition_by_restriction(ctx, parent, color_space, transform, extent, LEGION_DISJOINT_KIND, color); } //-------------------------------------------------------------------------- template<int DIM, typename T, int COLOR_DIM, typename COLOR_T> IndexPartitionT<DIM,T> Runtime::create_partition_by_domain( Context ctx, IndexSpaceT<DIM,T> parent, const std::map<Point<COLOR_DIM,COLOR_T>, DomainT<DIM,T> > &domains, IndexSpaceT<COLOR_DIM,COLOR_T> color_space, bool perform_intersections, PartitionKind part_kind, Color color) //-------------------------------------------------------------------------- { std::map<DomainPoint,Domain> converted_domains; for (typename std::map<Point<COLOR_DIM,COLOR_T>,DomainT<DIM,T> >:: const_iterator it = domains.begin(); it != domains.end(); it++) converted_domains[DomainPoint(it->first)] = Domain(it->second); return IndexPartitionT<DIM,T>(create_partition_by_domain(ctx, IndexSpace(parent), converted_domains, IndexSpace(color_space), perform_intersections, part_kind, color)); } //-------------------------------------------------------------------------- template<int DIM, typename T, int COLOR_DIM, typename COLOR_T> IndexPartitionT<DIM,T> Runtime::create_partition_by_domain( Context ctx, IndexSpaceT<DIM,T> parent, const FutureMap &domain_future_map, IndexSpaceT<COLOR_DIM,COLOR_T> color_space, bool perform_intersections, PartitionKind part_kind, Color color) //-------------------------------------------------------------------------- { return IndexPartitionT<DIM,T>(create_partition_by_domain(ctx, IndexSpace(parent), domain_future_map, IndexSpace(color_space), perform_intersections, part_kind, color)); } //-------------------------------------------------------------------------- template<int DIM, typename T, int COLOR_DIM, typename COLOR_T> IndexPartitionT<DIM,T> Runtime::create_partition_by_field(Context ctx, LogicalRegionT<DIM,T> handle, LogicalRegionT<DIM,T> parent, FieldID fid, IndexSpaceT<COLOR_DIM,COLOR_T> color_space, Color color, MapperID id, MappingTagID tag, PartitionKind part_kind) //-------------------------------------------------------------------------- { return IndexPartitionT<DIM,T>(create_partition_by_field(ctx, LogicalRegion(handle), LogicalRegion(parent), fid, IndexSpace(color_space), color, id, tag, part_kind)); } //-------------------------------------------------------------------------- template<int DIM1, typename T1, int DIM2, typename T2, int COLOR_DIM, typename COLOR_T> IndexPartitionT<DIM2,T2> Runtime::create_partition_by_image(Context ctx, IndexSpaceT<DIM2,T2> handle, LogicalPartitionT<DIM1,T1> projection, LogicalRegionT<DIM1,T1> parent, FieldID fid, // type: Point<DIM2,COORD_T2> IndexSpaceT<COLOR_DIM,COLOR_T> color_space, PartitionKind part_kind, Color color, MapperID id, MappingTagID tag) //-------------------------------------------------------------------------- { return IndexPartitionT<DIM2,T2>(create_partition_by_image(ctx, IndexSpace(handle), LogicalPartition(projection), LogicalRegion(parent), fid, IndexSpace(color_space), part_kind, color, id, tag)); } //-------------------------------------------------------------------------- template<int DIM1, typename T1, int DIM2, typename T2, int COLOR_DIM, typename COLOR_T> IndexPartitionT<DIM2,T2> Runtime::create_partition_by_image_range( Context ctx, IndexSpaceT<DIM2,T2> handle, LogicalPartitionT<DIM1,T1> projection, LogicalRegionT<DIM1,T1> parent, FieldID fid, // type: Point<DIM2,COORD_T2> IndexSpaceT<COLOR_DIM,COLOR_T> color_space, PartitionKind part_kind, Color color, MapperID id, MappingTagID tag) //-------------------------------------------------------------------------- { return IndexPartitionT<DIM2,T2>(create_partition_by_image_range(ctx, IndexSpace(handle), LogicalPartition(projection), LogicalRegion(parent), fid, IndexSpace(color_space), part_kind, color, id, tag)); } //-------------------------------------------------------------------------- template<int DIM1, typename T1, int DIM2, typename T2, int COLOR_DIM, typename COLOR_T> IndexPartitionT<DIM1,T1> Runtime::create_partition_by_preimage(Context ctx, IndexPartitionT<DIM2,T2> projection, LogicalRegionT<DIM1,T1> handle, LogicalRegionT<DIM1,T1> parent, FieldID fid, // type: Point<DIM2,COORD_T2> IndexSpaceT<COLOR_DIM,COLOR_T> color_space, PartitionKind part_kind, Color color, MapperID id, MappingTagID tag) //-------------------------------------------------------------------------- { return IndexPartitionT<DIM1,T1>(create_partition_by_preimage(ctx, IndexPartition(projection), LogicalRegion(handle), LogicalRegion(parent), fid, IndexSpace(color_space), part_kind, color, id, tag)); } //-------------------------------------------------------------------------- template<int DIM1, typename T1, int DIM2, typename T2, int COLOR_DIM, typename COLOR_T> IndexPartitionT<DIM1,T1> Runtime::create_partition_by_preimage_range( Context ctx, IndexPartitionT<DIM2,T2> projection, LogicalRegionT<DIM1,T1> handle, LogicalRegionT<DIM1,T1> parent, FieldID fid, // type: Rect<DIM2,COORD_T2> IndexSpaceT<COLOR_DIM,COLOR_T> color_space, PartitionKind part_kind, Color color, MapperID id, MappingTagID tag) //-------------------------------------------------------------------------- { return IndexPartitionT<DIM1,T1>(create_partition_by_preimage_range(ctx, IndexPartition(projection), LogicalRegion(handle), LogicalRegion(parent), fid, IndexSpace(color_space), part_kind, color, id, tag)); } //-------------------------------------------------------------------------- template<int DIM, typename T, int COLOR_DIM, typename COLOR_T> IndexPartitionT<DIM,T> Runtime::create_pending_partition(Context ctx, IndexSpaceT<DIM,T> parent, IndexSpaceT<COLOR_DIM,COLOR_T> color_space, PartitionKind part_kind, Color color) //-------------------------------------------------------------------------- { return IndexPartitionT<DIM,T>(create_pending_partition(ctx, IndexSpace(parent), IndexSpace(color_space), part_kind, color)); } //-------------------------------------------------------------------------- template<int DIM, typename T, int COLOR_DIM, typename COLOR_T> IndexSpaceT<DIM,T> Runtime::create_index_space_union(Context ctx, IndexPartitionT<DIM,T> parent, Point<COLOR_DIM,COLOR_T> color, const typename std::vector< IndexSpaceT<DIM,T> > &handles) //-------------------------------------------------------------------------- { std::vector<IndexSpace> untyped_handles(handles.size()); for (unsigned idx = 0; idx < handles.size(); idx++) untyped_handles[idx] = handles[idx]; return IndexSpaceT<DIM,T>(create_index_space_union_internal(ctx, IndexPartition(parent), &color, Internal::NT_TemplateHelper::encode_tag<COLOR_DIM,COLOR_T>(), untyped_handles)); } //-------------------------------------------------------------------------- template<int DIM, typename T, int COLOR_DIM, typename COLOR_T> IndexSpaceT<DIM,T> Runtime::create_index_space_union(Context ctx, IndexPartitionT<DIM,T> parent, Point<COLOR_DIM,COLOR_T> color, IndexPartitionT<DIM,T> handle) //-------------------------------------------------------------------------- { return IndexSpaceT<DIM,T>(create_index_space_union_internal(ctx, IndexPartition(parent), &color, Internal::NT_TemplateHelper::encode_tag<COLOR_DIM,COLOR_T>(), IndexPartition(handle))); } //-------------------------------------------------------------------------- template<int DIM, typename T, int COLOR_DIM, typename COLOR_T> IndexSpaceT<DIM,T> Runtime::create_index_space_intersection(Context ctx, IndexPartitionT<DIM,T> parent, Point<COLOR_DIM,COLOR_T> color, const typename std::vector< IndexSpaceT<DIM,T> > &handles) //-------------------------------------------------------------------------- { std::vector<IndexSpace> untyped_handles(handles.size()); for (unsigned idx = 0; idx < handles.size(); idx++) untyped_handles[idx] = handles[idx]; return IndexSpaceT<DIM,T>(create_index_space_intersection_internal(ctx, IndexPartition(parent), &color, Internal::NT_TemplateHelper::encode_tag<COLOR_DIM,COLOR_T>(), untyped_handles)); } //-------------------------------------------------------------------------- template<int DIM, typename T, int COLOR_DIM, typename COLOR_T> IndexSpaceT<DIM,T> Runtime::create_index_space_intersection(Context ctx, IndexPartitionT<DIM,T> parent, Point<COLOR_DIM,COLOR_T> color, IndexPartitionT<DIM,T> handle) //-------------------------------------------------------------------------- { return IndexSpaceT<DIM,T>(create_index_space_intersection_internal(ctx, IndexPartition(parent), &color, Internal::NT_TemplateHelper::encode_tag<COLOR_DIM,COLOR_T>(), IndexPartition(handle))); } //-------------------------------------------------------------------------- template<int DIM, typename T, int COLOR_DIM, typename COLOR_T> IndexSpaceT<DIM,T> Runtime::create_index_space_difference(Context ctx, IndexPartitionT<DIM,T> parent, Point<COLOR_DIM,COLOR_T> color, IndexSpaceT<DIM,T> initial, const typename std::vector< IndexSpaceT<DIM,T> > &handles) //-------------------------------------------------------------------------- { std::vector<IndexSpace> untyped_handles(handles.size()); for (unsigned idx = 0; idx < handles.size(); idx++) untyped_handles[idx] = handles[idx]; return IndexSpaceT<DIM,T>(create_index_space_difference_internal(ctx, IndexPartition(parent), &color, Internal::NT_TemplateHelper::encode_tag<COLOR_DIM,COLOR_T>(), IndexSpace(initial), untyped_handles)); } //-------------------------------------------------------------------------- template<int DIM, typename T> IndexPartitionT<DIM,T> Runtime::get_index_partition( IndexSpaceT<DIM,T> parent, Color color) //-------------------------------------------------------------------------- { return IndexPartitionT<DIM,T>( get_index_partition(IndexSpace(parent), color)); } //-------------------------------------------------------------------------- template<int DIM, typename T> bool Runtime::has_index_partition(IndexSpaceT<DIM,T> parent, Color color) //-------------------------------------------------------------------------- { return has_index_partition(IndexSpace(parent), color); } //-------------------------------------------------------------------------- template<int DIM, typename T, int COLOR_DIM, typename COLOR_T> IndexSpaceT<DIM,T> Runtime::get_index_subspace(IndexPartitionT<DIM,T> p, Point<COLOR_DIM,COLOR_T> color) //-------------------------------------------------------------------------- { return IndexSpaceT<DIM,T>(get_index_subspace_internal(IndexPartition(p), &color, Internal::NT_TemplateHelper::encode_tag<COLOR_DIM,COLOR_T>())); } //-------------------------------------------------------------------------- template<int DIM, typename T, int COLOR_DIM, typename COLOR_T> bool Runtime::has_index_subspace(IndexPartitionT<DIM,T> p, Point<COLOR_DIM,COLOR_T> color) //-------------------------------------------------------------------------- { return has_index_subspace_internal(IndexPartition(p), &color, Internal::NT_TemplateHelper::encode_tag<COLOR_DIM,COLOR_T>()); } //-------------------------------------------------------------------------- template<int DIM, typename T> DomainT<DIM,T> Runtime::get_index_space_domain(IndexSpaceT<DIM,T> handle) //-------------------------------------------------------------------------- { DomainT<DIM,T> realm_is; get_index_space_domain_internal(handle, &realm_is, Internal::NT_TemplateHelper::encode_tag<DIM,T>()); return realm_is; } //-------------------------------------------------------------------------- template<int DIM, typename T, int COLOR_DIM, typename COLOR_T> DomainT<COLOR_DIM,COLOR_T> Runtime::get_index_partition_color_space(IndexPartitionT<DIM,T> p) //-------------------------------------------------------------------------- { DomainT<COLOR_DIM, COLOR_T> realm_is; get_index_partition_color_space_internal(p, &realm_is, Internal::NT_TemplateHelper::encode_tag<COLOR_DIM,COLOR_T>()); return realm_is; } //-------------------------------------------------------------------------- template<int DIM, typename T, int COLOR_DIM, typename COLOR_T> IndexSpaceT<COLOR_DIM,COLOR_T> Runtime::get_index_partition_color_space_name(IndexPartitionT<DIM,T> p) //-------------------------------------------------------------------------- { return IndexSpaceT<COLOR_DIM,COLOR_T>( get_index_partition_color_space_name(p)); } //-------------------------------------------------------------------------- template<unsigned DIM> IndexSpace Runtime::get_index_subspace(Context ctx, IndexPartition p, LegionRuntime::Arrays::Point<DIM> color_point) //-------------------------------------------------------------------------- { DomainPoint dom_point = DomainPoint::from_point<DIM>(color_point); return get_index_subspace(ctx, p, dom_point); } //-------------------------------------------------------------------------- template<int DIM, typename T, int COLOR_DIM, typename COLOR_T> Point<COLOR_DIM,COLOR_T> Runtime::get_index_space_color( IndexSpaceT<DIM,T> handle) //-------------------------------------------------------------------------- { Point<COLOR_DIM,COLOR_T> point; return get_index_space_color_internal(IndexSpace(handle), &point, Internal::NT_TemplateHelper::encode_tag<COLOR_DIM,COLOR_T>()); } //-------------------------------------------------------------------------- template<int DIM, typename T> IndexSpaceT<DIM,T> Runtime::get_parent_index_space( IndexPartitionT<DIM,T> handle) //-------------------------------------------------------------------------- { return IndexSpaceT<DIM,T>(get_parent_index_space(IndexPartition(handle))); } //-------------------------------------------------------------------------- template<int DIM, typename T> IndexPartitionT<DIM,T> Runtime::get_parent_index_partition( IndexSpaceT<DIM,T> handle) //-------------------------------------------------------------------------- { return IndexPartitionT<DIM,T>(get_parent_index_partition( IndexSpace(handle))); } //-------------------------------------------------------------------------- template<int DIM, typename T> bool Runtime::safe_cast(Context ctx, Point<DIM,T> point, LogicalRegionT<DIM,T> region) //-------------------------------------------------------------------------- { return safe_cast_internal(ctx, LogicalRegion(region), &point, Internal::NT_TemplateHelper::encode_tag<DIM,T>()); } //-------------------------------------------------------------------------- template<int DIM, typename T> LogicalRegionT<DIM,T> Runtime::create_logical_region(Context ctx, IndexSpaceT<DIM,T> index, FieldSpace fields, bool task_local) //-------------------------------------------------------------------------- { return LogicalRegionT<DIM,T>(create_logical_region(ctx, IndexSpace(index), fields, task_local)); } //-------------------------------------------------------------------------- template<int DIM, typename T> LogicalPartitionT<DIM,T> Runtime::get_logical_partition( LogicalRegionT<DIM,T> parent, IndexPartitionT<DIM,T> handle) //-------------------------------------------------------------------------- { return LogicalPartitionT<DIM,T>(get_logical_partition( LogicalRegion(parent), IndexPartition(handle))); } //-------------------------------------------------------------------------- template<int DIM, typename T> LogicalPartitionT<DIM,T> Runtime::get_logical_partition_by_color( LogicalRegionT<DIM,T> parent, Color color) //-------------------------------------------------------------------------- { return LogicalPartitionT<DIM,T>(get_logical_partition_by_color( LogicalRegion(parent), color)); } //-------------------------------------------------------------------------- template<int DIM, typename T> LogicalPartitionT<DIM,T> Runtime::get_logical_partition_by_tree( IndexPartitionT<DIM,T> handle, FieldSpace space, RegionTreeID tid) //-------------------------------------------------------------------------- { return LogicalPartitionT<DIM,T>(get_logical_partition_by_tree( IndexPartition(handle), space, tid)); } //-------------------------------------------------------------------------- template<int DIM, typename T> LogicalRegionT<DIM,T> Runtime::get_logical_subregion( LogicalPartitionT<DIM,T> parent, IndexSpaceT<DIM,T> handle) //-------------------------------------------------------------------------- { return LogicalRegionT<DIM,T>(get_logical_subregion( LogicalPartition(parent), IndexSpace(handle))); } //-------------------------------------------------------------------------- template<int DIM, typename T, int COLOR_DIM, typename COLOR_T> LogicalRegionT<DIM,T> Runtime::get_logical_subregion_by_color( LogicalPartitionT<DIM,T> parent, Point<COLOR_DIM,COLOR_T> color) //-------------------------------------------------------------------------- { return LogicalRegionT<DIM,T>(get_logical_subregion_by_color_internal( LogicalPartition(parent), &color, Internal::NT_TemplateHelper::encode_tag<COLOR_DIM,COLOR_T>())); } //-------------------------------------------------------------------------- template<int DIM, typename T, int COLOR_DIM, typename COLOR_T> bool Runtime::has_logical_subregion_by_color( LogicalPartitionT<DIM,T> parent, Point<COLOR_DIM,COLOR_T> color) //-------------------------------------------------------------------------- { return has_logical_subregion_by_color_internal( LogicalPartition(parent), &color, Internal::NT_TemplateHelper::encode_tag<COLOR_DIM,COLOR_T>()); } //-------------------------------------------------------------------------- template<int DIM, typename T> LogicalRegionT<DIM,T> Runtime::get_logical_subregion_by_tree( IndexSpaceT<DIM,T> handle, FieldSpace space, RegionTreeID tid) //-------------------------------------------------------------------------- { return LogicalRegionT<DIM,T>(get_logical_subregion_by_tree( IndexSpace(handle), space, tid)); } //-------------------------------------------------------------------------- template<int DIM, typename T, int COLOR_DIM, typename COLOR_T> Point<COLOR_DIM,COLOR_T> Runtime::get_logical_region_color_point( LogicalRegionT<DIM,T> handle) //-------------------------------------------------------------------------- { return get_logical_region_color_point(LogicalRegion(handle)); } //-------------------------------------------------------------------------- template<int DIM, typename T> LogicalRegionT<DIM,T> Runtime::get_parent_logical_region( LogicalPartitionT<DIM,T> handle) //-------------------------------------------------------------------------- { return LogicalRegionT<DIM,T>(get_parent_logical_region( LogicalPartition(handle))); } //-------------------------------------------------------------------------- template<int DIM, typename T> LogicalPartitionT<DIM,T> Runtime::get_parent_logical_partition( LogicalRegionT<DIM,T> handle) //-------------------------------------------------------------------------- { return LogicalPartitionT<DIM,T>(get_parent_logical_partition( LogicalRegion(handle))); } //-------------------------------------------------------------------------- template<typename T> void Runtime::fill_field(Context ctx, LogicalRegion handle, LogicalRegion parent, FieldID fid, const T &value, Predicate pred) //-------------------------------------------------------------------------- { fill_field(ctx, handle, parent, fid, &value, sizeof(T), pred); } //-------------------------------------------------------------------------- template<typename T> void Runtime::fill_fields(Context ctx, LogicalRegion handle, LogicalRegion parent, const std::set<FieldID> &fields, const T &value, Predicate pred) //-------------------------------------------------------------------------- { fill_fields(ctx, handle, parent, fields, &value, sizeof(T), pred); } //-------------------------------------------------------------------------- template<typename T> T* Runtime::get_local_task_variable(Context ctx, LocalVariableID id) //-------------------------------------------------------------------------- { return static_cast<T*>(get_local_task_variable_untyped(ctx, id)); } //-------------------------------------------------------------------------- template<typename T> void Runtime::set_local_task_variable(Context ctx, LocalVariableID id, const T* value, void (*destructor)(void*)) //-------------------------------------------------------------------------- { set_local_task_variable_untyped(ctx, id, value, destructor); } //-------------------------------------------------------------------------- template<typename REDOP> /*static*/ void Runtime::register_reduction_op(ReductionOpID redop_id, bool permit_duplicates) //-------------------------------------------------------------------------- { // We also have to check to see if there are explicit serialization // and deserialization methods on the RHS type for doing fold reductions LegionSerialization::register_reduction<REDOP>(redop_id, permit_duplicates); } #ifdef LEGION_GPU_REDUCTIONS #ifdef __CUDACC__ #define LEGION_THREADS_PER_BLOCK 256 #define LEGION_MIN_BLOCKS_PER_SM 4 namespace Internal { template<int N> struct DimOrder { int index[N]; }; template<typename REDOP, int N, typename T, bool EXCLUSIVE> __global__ void __launch_bounds__(LEGION_THREADS_PER_BLOCK,LEGION_MIN_BLOCKS_PER_SM) fold_kernel(const Realm::AffineAccessor<typename REDOP::RHS,N,T> dst, const Realm::AffineAccessor<typename REDOP::RHS,N,T> src, const Realm::AffineAccessor<Rect<N,T>,1,coord_t> piece_rects, const Realm::AffineAccessor<size_t,1,coord_t> scan_volumes, const DimOrder<N> order, const size_t max_offset, const size_t max_rects) { size_t offset = blockIdx.x * blockDim.x + threadIdx.x; if (offset >= max_offset) return; // Perform a binary search for the rectangle that we are in coord_t first = 0; coord_t last = max_rects - 1; coord_t mid = 0; while (first <= last) { mid = (first + last) / 2; if (scan_volumes[mid+1] <= offset) first = mid + 1; else if (offset < scan_volumes[mid]) last = mid - 1; else break; } const Rect<N,T> rect = piece_rects[mid]; Point<N,T> point = rect.lo; size_t pitch = 1; for (int i = 0; i < N; i++) { const int index = order.index[i]; point[index] += (offset / pitch); offset = offset % pitch; pitch *= ((rect.hi[index] - rect.lo[index]) + 1); } REDOP::template fold<EXCLUSIVE>(dst[point], src[point]); } template<typename REDOP, int N, typename T, bool EXCLUSIVE> __global__ void __launch_bounds__(LEGION_THREADS_PER_BLOCK,LEGION_MIN_BLOCKS_PER_SM) apply_kernel(const Realm::AffineAccessor<typename REDOP::LHS,N,T> dst, const Realm::AffineAccessor<typename REDOP::RHS,N,T> src, const Realm::AffineAccessor<Rect<N,T>,1,coord_t> piece_rects, const Realm::AffineAccessor<size_t,1,coord_t> scan_volumes, const DimOrder<N> order, const size_t max_offset, const size_t max_rects) { size_t offset = blockIdx.x * blockDim.x + threadIdx.x; if (offset >= max_offset) return; // Perform a binary search for the rectangle that we are in int first = 0; int last = max_rects - 1; int mid = 0; while (first <= last) { mid = (first + last) / 2; if (scan_volumes[mid+1] <= offset) first = mid + 1; else if (offset < scan_volumes[mid]) last = mid - 1; else break; } const Rect<N,T> rect = piece_rects[mid]; Point<N,T> point = rect.lo; size_t pitch = 1; for (int i = 0; i < N; i++) { const int index = order.index[i]; point[index] += (offset / pitch); offset = offset % pitch; pitch *= ((rect.hi[index] - rect.lo[index]) + 1); } REDOP::template apply<EXCLUSIVE>(dst[point], src[point]); } template<typename REDOP> struct ReductionRunner { public: __host__ ReductionRunner(const void *b, size_t s) : buffer(((const char*)b)), index(0), size(s) { } __host__ ~ReductionRunner(void) { assert(index == size); } public: template<typename T> __host__ inline void deserialize(T &element) { assert((index + sizeof(T)) <= size); element = *((const T*)(buffer+index)); index += sizeof(T); } __host__ inline void deserialize_bool(bool &element) { // bools are stored with 4 bytes in the serializer assert((index + 4) <= size); element = *((const bool*)(buffer+index)); index += 4; } template<typename FT> inline Realm::AffineAccessor<FT,1,coord_t> create_temporary_buffer( Memory memory, const Rect<1,coord_t> &bounds) { Realm::IndexSpace<1,coord_t> space(bounds); const std::vector<size_t> field_sizes(1,sizeof(FT)); Realm::InstanceLayoutConstraints constraints(field_sizes, 0/*fid*/); const int dim_order[1] = { 0 }; Realm::InstanceLayoutGeneric *layout = Realm::InstanceLayoutGeneric::choose_instance_layout(space, constraints, dim_order); Realm::RegionInstance instance; Realm::ProfilingRequestSet no_requests; const LgEvent wait_on(Realm::RegionInstance::create_instance( instance, memory, layout, no_requests)); assert(instance.exists()); if (wait_on.exists() && !wait_on.has_triggered()) wait_on.wait(); // Can destroy this instance as soon as the task is done instance.destroy(Processor::get_current_finish_event()); return Realm::AffineAccessor<FT,1,coord_t>(instance, 0/*fid*/); } template<int N, typename T> __host__ inline void run(void) { Realm::IndexSpace<N,T> space; deserialize(space); Realm::Event ready = space.make_valid(); bool fold, exclusive;; deserialize_bool(fold); deserialize_bool(exclusive); size_t num_fields; deserialize(num_fields); std::vector<FieldID> src_fields(num_fields); std::vector<FieldID> dst_fields(num_fields);; std::vector<Realm::RegionInstance> src_insts(num_fields); std::vector<Realm::RegionInstance> dst_insts(num_fields); for (unsigned idx = 0; idx < num_fields; idx++) { deserialize(dst_insts[idx]); deserialize(src_insts[idx]); deserialize(dst_fields[idx]); deserialize(src_fields[idx]); } size_t num_pieces; deserialize(num_pieces); if (ready.exists() && !ready.has_triggered()) ready.wait(); // Iterate over all the pieces for (unsigned pidx = 0; pidx < num_pieces; pidx++) { Rect<N,T> piece_rect; deserialize(piece_rect); std::vector<Rect<N,T> > piece_rects; std::vector<size_t> scan_volumes; size_t sum_volume = 0; for (Realm::IndexSpaceIterator<N,T> itr(space);itr.valid;itr.step()) { const Rect<N,T> intersection = piece_rect.intersection(itr.rect); if (intersection.empty()) continue; piece_rects.push_back(intersection); scan_volumes.push_back(sum_volume); sum_volume += intersection.volume(); } if (piece_rects.empty()) continue; scan_volumes.push_back(sum_volume); assert(scan_volumes.size() == (piece_rects.size() + 1)); const Rect<1,coord_t> bounds(0, piece_rects.size()-1); const Rect<1,coord_t> scan_bounds(0, piece_rects.size()); Machine machine = Realm::Machine::get_machine(); Machine::MemoryQuery finder(machine); finder.best_affinity_to(Processor::get_executing_processor()); finder.only_kind(Memory::GPU_FB_MEM); assert(finder.count() > 0); const Memory memory = finder.first(); Realm::AffineAccessor<Rect<N,T>,1,coord_t> device_piece_rects = create_temporary_buffer<Rect<N,T> >(memory, bounds); Realm::AffineAccessor<size_t,1,coord_t> device_scan_volumes = create_temporary_buffer<size_t>(memory, scan_bounds); #ifdef LEGION_USE_CUDA cudaMemcpyAsync(device_piece_rects.ptr(bounds.lo), &piece_rects.front(), piece_rects.size() * sizeof(Rect<N,T>), cudaMemcpyHostToDevice); cudaMemcpyAsync(device_scan_volumes.ptr(scan_bounds.lo), &scan_volumes.front(), scan_volumes.size() * sizeof(size_t), cudaMemcpyHostToDevice); #endif #ifdef LEGION_USE_HIP #ifdef __HIP_PLATFORM_HCC__ hipMemcpyAsync(device_piece_rects.ptr(bounds.lo), &piece_rects.front(), piece_rects.size() * sizeof(Rect<N,T>), hipMemcpyHostToDevice, hipGetTaskStream()); hipMemcpyAsync(device_scan_volumes.ptr(scan_bounds.lo), &scan_volumes.front(), scan_volumes.size() * sizeof(size_t), hipMemcpyHostToDevice, hipGetTaskStream()); #else cudaMemcpyAsync(device_piece_rects.ptr(bounds.lo), &piece_rects.front(), piece_rects.size() * sizeof(Rect<N,T>), cudaMemcpyHostToDevice, hipGetTaskStream()); cudaMemcpyAsync(device_scan_volumes.ptr(scan_bounds.lo), &scan_volumes.front(), scan_volumes.size() * sizeof(size_t), cudaMemcpyHostToDevice, hipGetTaskStream()); #endif #endif const size_t blocks = (sum_volume + LEGION_THREADS_PER_BLOCK - 1) / LEGION_THREADS_PER_BLOCK; // Iterate over all the fields we should handle for (unsigned fidx = 0; fidx < num_fields; fidx++) { // Make accessors for the source and destination for this piece const Realm::AffineAccessor<typename REDOP::RHS,N,T> src_accessor(src_insts[fidx], src_fields[fidx], piece_rect); // Compute the order of dimensions to walk based on sorting the // strides for the source accessor, we'll optimistically assume // the two instances are laid out the same way, if we're wrong // it will still be correct, just slow std::map<size_t,int> strides; for (int i = 0; i < N; i++) { std::pair<std::map<size_t,int>::iterator,bool> result = strides.insert(std::pair<size_t,int>( src_accessor.strides[i],i)); // Strides should be unique across dimensions unless extent is 1 assert(result.second || (piece_rect.hi[i] == piece_rect.lo[i])); } // Put the dimensions in order from largest to smallest DimOrder<N> order; std::map<size_t,int>::const_reverse_iterator rit = strides.rbegin(); for (int i = 0; i < N; i++, rit++) order.index[i] = rit->second; // See if we are folding or applying if (fold) { const Realm::AffineAccessor<typename REDOP::RHS,N,T> dst_accessor(dst_insts[fidx], dst_fields[fidx], piece_rect); // Now launch the kernel if (exclusive) { #ifdef LEGION_USE_CUDA fold_kernel<REDOP,N,T,true> <<<blocks,LEGION_THREADS_PER_BLOCK>>>( dst_accessor, src_accessor, device_piece_rects, device_scan_volumes, order, sum_volume, piece_rects.size()); #endif #ifdef LEGION_USE_HIP #ifdef __HIP_PLATFORM_HCC__ hipLaunchKernelGGL( HIP_KERNEL_NAME(fold_kernel<REDOP,N,T,true>), dim3(blocks), dim3(LEGION_THREADS_PER_BLOCK), 0, hipGetTaskStream(), dst_accessor, src_accessor, device_piece_rects, device_scan_volumes, order, sum_volume, piece_rects.size()); #else fold_kernel<REDOP,N,T,true> <<<blocks,LEGION_THREADS_PER_BLOCK, 0, hipGetTaskStream()>>>( dst_accessor, src_accessor, device_piece_rects, device_scan_volumes, order, sum_volume, piece_rects.size()); #endif #endif } else { #ifdef LEGION_USE_CUDA fold_kernel<REDOP,N,T,false> <<<blocks,LEGION_THREADS_PER_BLOCK>>>( dst_accessor, src_accessor, device_piece_rects, device_scan_volumes, order, sum_volume, piece_rects.size()); #endif #ifdef LEGION_USE_HIP #ifdef __HIP_PLATFORM_HCC__ hipLaunchKernelGGL( HIP_KERNEL_NAME(fold_kernel<REDOP,N,T,false>), dim3(blocks), dim3(LEGION_THREADS_PER_BLOCK), 0, hipGetTaskStream(), dst_accessor, src_accessor, device_piece_rects, device_scan_volumes, order, sum_volume, piece_rects.size()); #else fold_kernel<REDOP,N,T,false> <<<blocks,LEGION_THREADS_PER_BLOCK, 0, hipGetTaskStream()>>>( dst_accessor, src_accessor, device_piece_rects, device_scan_volumes, order, sum_volume, piece_rects.size()); #endif #endif } } else { const Realm::AffineAccessor<typename REDOP::LHS,N,T> dst_accessor(dst_insts[fidx], dst_fields[fidx], piece_rect); // Now launch the kernel if (exclusive) { #ifdef LEGION_USE_CUDA apply_kernel<REDOP,N,T,true> <<<blocks,LEGION_THREADS_PER_BLOCK>>>( dst_accessor, src_accessor, device_piece_rects, device_scan_volumes, order, sum_volume, piece_rects.size()); #endif #ifdef LEGION_USE_HIP #ifdef __HIP_PLATFORM_HCC__ hipLaunchKernelGGL( HIP_KERNEL_NAME(apply_kernel<REDOP,N,T,true>), dim3(blocks), dim3(LEGION_THREADS_PER_BLOCK), 0, hipGetTaskStream(), dst_accessor, src_accessor, device_piece_rects, device_scan_volumes, order, sum_volume, piece_rects.size()); #else apply_kernel<REDOP,N,T,true> <<<blocks,LEGION_THREADS_PER_BLOCK, 0, hipGetTaskStream()>>>( dst_accessor, src_accessor, device_piece_rects, device_scan_volumes, order, sum_volume, piece_rects.size()); #endif #endif } else { #ifdef LEGION_USE_CUDA apply_kernel<REDOP,N,T,false> <<<blocks,LEGION_THREADS_PER_BLOCK>>>( dst_accessor, src_accessor, device_piece_rects, device_scan_volumes, order, sum_volume, piece_rects.size()); #endif #ifdef LEGION_USE_HIP #ifdef __HIP_PLATFORM_HCC__ hipLaunchKernelGGL( HIP_KERNEL_NAME(apply_kernel<REDOP,N,T,false>), dim3(blocks), dim3(LEGION_THREADS_PER_BLOCK), 0, hipGetTaskStream(), dst_accessor, src_accessor, device_piece_rects, device_scan_volumes, order, sum_volume, piece_rects.size()); #else apply_kernel<REDOP,N,T,false> <<<blocks,LEGION_THREADS_PER_BLOCK, 0, hipGetTaskStream()>>>( dst_accessor, src_accessor, device_piece_rects, device_scan_volumes, order, sum_volume, piece_rects.size()); #endif #endif } } } } #ifdef LEGION_USE_HIP #ifdef __HIP_PLATFORM_HCC__ hipStreamSynchronize(hipGetTaskStream()); #else cudaStreamSynchronize(hipGetTaskStream()); #endif #endif } template<typename N, typename T> __host__ static inline void demux(ReductionRunner<REDOP> *runner) { runner->run<N::N,T>(); } public: const char *buffer; size_t index; size_t size; }; // This is a Realm task function signature that we use for launching // off kernels that perform reductions between a reduction instance // and a normal instance on a GPU since Realm does not support this yet. template<typename REDOP> __host__ void gpu_reduction_helper(const void *args, size_t arglen, const void *user_data,size_t user_data_size, Processor proc) { implicit_context = NULL; ReductionRunner<REDOP> runner(args, arglen); TypeTag type_tag; runner.deserialize(type_tag); NT_TemplateHelper::demux<ReductionRunner<REDOP> >(type_tag, &runner); } }; // namespace Internal //-------------------------------------------------------------------------- template<typename REDOP> /*static*/ void Runtime::preregister_gpu_reduction_op(ReductionOpID redop) //-------------------------------------------------------------------------- { CodeDescriptor desc(Internal::gpu_reduction_helper<REDOP>); preregister_gpu_reduction_op(redop, desc); } #undef LEGION_THREADS_PER_BLOCK #undef LEGION_MIN_BLOCKS_PER_SM #endif // __CUDACC__ #endif // LEGION_GPU_REDUCTIONS //-------------------------------------------------------------------------- template<typename SERDEZ> /*static*/ void Runtime::register_custom_serdez_op(CustomSerdezID serdez_id, bool permit_duplicates) //-------------------------------------------------------------------------- { Runtime::register_custom_serdez_op(serdez_id, Realm::CustomSerdezUntyped::create_custom_serdez<SERDEZ>(), permit_duplicates); } namespace Internal { // Wrapper class for old projection functions template<RegionProjectionFnptr FNPTR> class RegionProjectionWrapper : public ProjectionFunctor { public: RegionProjectionWrapper(void) : ProjectionFunctor() { } virtual ~RegionProjectionWrapper(void) { } public: virtual LogicalRegion project(Context ctx, Task *task, unsigned index, LogicalRegion upper_bound, const DomainPoint &point) { return (*FNPTR)(upper_bound, point, runtime); } virtual LogicalRegion project(Context ctx, Task *task, unsigned index, LogicalPartition upper_bound, const DomainPoint &point) { assert(false); return LogicalRegion::NO_REGION; } virtual bool is_exclusive(void) const { return false; } }; }; //-------------------------------------------------------------------------- template<LogicalRegion (*PROJ_PTR)(LogicalRegion, const DomainPoint&, Runtime*)> /*static*/ ProjectionID Runtime::register_region_function( ProjectionID handle) //-------------------------------------------------------------------------- { Runtime::preregister_projection_functor(handle, new Internal::RegionProjectionWrapper<PROJ_PTR>()); return handle; } namespace Internal { // Wrapper class for old projection functions template<PartitionProjectionFnptr FNPTR> class PartitionProjectionWrapper : public ProjectionFunctor { public: PartitionProjectionWrapper(void) : ProjectionFunctor() { } virtual ~PartitionProjectionWrapper(void) { } public: virtual LogicalRegion project(Context ctx, Task *task, unsigned index, LogicalRegion upper_bound, const DomainPoint &point) { assert(false); return LogicalRegion::NO_REGION; } virtual LogicalRegion project(Context ctx, Task *task, unsigned index, LogicalPartition upper_bound, const DomainPoint &point) { return (*FNPTR)(upper_bound, point, runtime); } virtual bool is_exclusive(void) const { return false; } }; }; //-------------------------------------------------------------------------- template<LogicalRegion (*PROJ_PTR)(LogicalPartition, const DomainPoint&, Runtime*)> /*static*/ ProjectionID Runtime::register_partition_function( ProjectionID handle) //-------------------------------------------------------------------------- { Runtime::preregister_projection_functor(handle, new Internal::PartitionProjectionWrapper<PROJ_PTR>()); return handle; } //-------------------------------------------------------------------------- // Wrapper functions for high-level tasks //-------------------------------------------------------------------------- /** * \class LegionTaskWrapper * This is a helper class that has static template methods for * wrapping Legion application tasks. For all tasks we can make * wrappers both for normal execution and also for inline execution. */ class LegionTaskWrapper { public: // Non-void return type for new legion task types template<typename T, T (*TASK_PTR)(const Task*, const std::vector<PhysicalRegion>&, Context, Runtime*)> static void legion_task_wrapper(const void*, size_t, const void*, size_t, Processor); template<typename T, typename UDT, T (*TASK_PTR)(const Task*, const std::vector<PhysicalRegion>&, Context, Runtime*, const UDT&)> static void legion_udt_task_wrapper(const void*, size_t, const void*, size_t, Processor); public: // Void return type for new legion task types template< void (*TASK_PTR)(const Task*, const std::vector<PhysicalRegion>&, Context, Runtime*)> static void legion_task_wrapper(const void*, size_t, const void*, size_t, Processor); template<typename UDT, void (*TASK_PTR)(const Task*, const std::vector<PhysicalRegion>&, Context, Runtime*, const UDT&)> static void legion_udt_task_wrapper(const void*, size_t, const void*, size_t, Processor); public: // Do-it-yourself pre/post-ambles for code generators // These are deprecated and are just here for backwards compatibility static void legion_task_preamble(const void *data, size_t datalen, Processor p, const Task *& task, const std::vector<PhysicalRegion> *& ptr, Context& ctx, Runtime *& runtime); static void legion_task_postamble(Runtime *runtime, Context ctx, const void *retvalptr = NULL, size_t retvalsize = 0); }; //-------------------------------------------------------------------------- template<typename T, T (*TASK_PTR)(const Task*, const std::vector<PhysicalRegion>&, Context, Runtime*)> void LegionTaskWrapper::legion_task_wrapper(const void *args, size_t arglen, const void *userdata, size_t userlen, Processor p) //-------------------------------------------------------------------------- { // Assert that we are returning Futures or FutureMaps LEGION_STATIC_ASSERT((LegionTypeInequality<T,Future>::value), "Future types are not permitted as return types for Legion tasks"); LEGION_STATIC_ASSERT((LegionTypeInequality<T,FutureMap>::value), "FutureMap types are not permitted as return types for Legion tasks"); // Assert that the return type size is within the required size LEGION_STATIC_ASSERT(sizeof(T) <= LEGION_MAX_RETURN_SIZE, "Task return values must be less than or equal to " "LEGION_MAX_RETURN_SIZE bytes"); const Task *task; Context ctx; Runtime *rt; const std::vector<PhysicalRegion> *regions; Runtime::legion_task_preamble(args, arglen, p, task, regions, ctx, rt); // Invoke the task with the given context T return_value = (*TASK_PTR)(task, *regions, ctx, rt); // Send the return value back LegionSerialization::end_task<T>(rt, ctx, &return_value); } //-------------------------------------------------------------------------- template< void (*TASK_PTR)(const Task*, const std::vector<PhysicalRegion>&, Context, Runtime*)> void LegionTaskWrapper::legion_task_wrapper(const void *args, size_t arglen, const void *userdata, size_t userlen, Processor p) //-------------------------------------------------------------------------- { const Task *task; Context ctx; Runtime *rt; const std::vector<PhysicalRegion> *regions; Runtime::legion_task_preamble(args, arglen, p, task, regions, ctx, rt); (*TASK_PTR)(task, *regions, ctx, rt); Runtime::legion_task_postamble(rt, ctx); } //-------------------------------------------------------------------------- template<typename T, typename UDT, T (*TASK_PTR)(const Task*, const std::vector<PhysicalRegion>&, Context, Runtime*, const UDT&)> void LegionTaskWrapper::legion_udt_task_wrapper(const void *args, size_t arglen, const void *userdata, size_t userlen, Processor p) //-------------------------------------------------------------------------- { // Assert that we are returning Futures or FutureMaps LEGION_STATIC_ASSERT((LegionTypeInequality<T,Future>::value), "Future types are not permitted as return types for Legion tasks"); LEGION_STATIC_ASSERT((LegionTypeInequality<T,FutureMap>::value), "FutureMap types are not permitted as return types for Legion tasks"); // Assert that the return type size is within the required size LEGION_STATIC_ASSERT((sizeof(T) <= LEGION_MAX_RETURN_SIZE) || (std::is_class<T>::value && LegionSerialization::IsSerdezType<T>::value), "Task return values must be less than or equal to " "LEGION_MAX_RETURN_SIZE bytes"); const Task *task; Context ctx; Runtime *rt; const std::vector<PhysicalRegion> *regions; Runtime::legion_task_preamble(args, arglen, p, task, regions, ctx, rt); const UDT *user_data = NULL; static_assert(sizeof(user_data) == sizeof(userdata), "C++ is dumb"); memcpy(&user_data, &userdata, sizeof(user_data)); // Invoke the task with the given context T return_value = (*TASK_PTR)(task, *regions, ctx, rt, *user_data); // Send the return value back LegionSerialization::end_task<T>(rt, ctx, &return_value); } //-------------------------------------------------------------------------- template<typename UDT, void (*TASK_PTR)(const Task*, const std::vector<PhysicalRegion>&, Context, Runtime*, const UDT&)> void LegionTaskWrapper::legion_udt_task_wrapper(const void *args, size_t arglen, const void *userdata, size_t userlen, Processor p) //-------------------------------------------------------------------------- { const Task *task; Context ctx; Runtime *rt; const std::vector<PhysicalRegion> *regions; Runtime::legion_task_preamble(args, arglen, p, task, regions, ctx, rt); const UDT *user_data = NULL; static_assert(sizeof(user_data) == sizeof(userdata), "C++ is dumb"); memcpy(&user_data, &userdata, sizeof(user_data)); (*TASK_PTR)(task, *regions, ctx, rt, *user_data); // Send an empty return value back Runtime::legion_task_postamble(rt, ctx); } //-------------------------------------------------------------------------- inline void LegionTaskWrapper::legion_task_preamble( const void *data, size_t datalen, Processor p, const Task *& task, const std::vector<PhysicalRegion> *& regionsptr, Context& ctx, Runtime *& runtime) //-------------------------------------------------------------------------- { Runtime::legion_task_preamble(data, datalen, p, task, regionsptr, ctx, runtime); } //-------------------------------------------------------------------------- inline void LegionTaskWrapper::legion_task_postamble( Runtime *runtime, Context ctx, const void *retvalptr /*= NULL*/, size_t retvalsize /*= 0*/) //-------------------------------------------------------------------------- { Runtime::legion_task_postamble(runtime, ctx, retvalptr, retvalsize); } //-------------------------------------------------------------------------- template<typename T, T (*TASK_PTR)(const Task*, const std::vector<PhysicalRegion>&, Context, Runtime*)> VariantID Runtime::register_task_variant( const TaskVariantRegistrar &registrar, VariantID vid) //-------------------------------------------------------------------------- { CodeDescriptor desc(LegionTaskWrapper::legion_task_wrapper<T,TASK_PTR>); return register_task_variant(registrar, desc,NULL/*UDT*/, 0/*sizeof(UDT)*/, LegionSerialization::ReturnSize<T>::value, vid); } //-------------------------------------------------------------------------- template<typename T, typename UDT, T (*TASK_PTR)(const Task*, const std::vector<PhysicalRegion>&, Context, Runtime*, const UDT&)> VariantID Runtime::register_task_variant( const TaskVariantRegistrar &registrar, const UDT &user_data, VariantID vid) //-------------------------------------------------------------------------- { CodeDescriptor desc( LegionTaskWrapper::legion_udt_task_wrapper<T,UDT,TASK_PTR>); return register_task_variant(registrar, desc, &user_data, sizeof(UDT), LegionSerialization::ReturnSize<T>::value, vid); } //-------------------------------------------------------------------------- template< void (*TASK_PTR)(const Task*, const std::vector<PhysicalRegion>&, Context, Runtime*)> VariantID Runtime::register_task_variant( const TaskVariantRegistrar &registrar, VariantID vid) //-------------------------------------------------------------------------- { CodeDescriptor desc(LegionTaskWrapper::legion_task_wrapper<TASK_PTR>); return register_task_variant(registrar, desc, NULL/*UDT*/, 0/*sizeof(UDT)*/, 0/*return size*/, vid); } //-------------------------------------------------------------------------- template<typename UDT, void (*TASK_PTR)(const Task*, const std::vector<PhysicalRegion>&, Context, Runtime*, const UDT&)> VariantID Runtime::register_task_variant( const TaskVariantRegistrar &registrar, const UDT &user_data, VariantID vid) //-------------------------------------------------------------------------- { CodeDescriptor desc( LegionTaskWrapper::legion_udt_task_wrapper<UDT,TASK_PTR>); return register_task_variant(registrar, desc, &user_data, sizeof(UDT), 0/*return size*/, vid); } //-------------------------------------------------------------------------- template<typename T, T (*TASK_PTR)(const Task*, const std::vector<PhysicalRegion>&, Context, Runtime*)> /*static*/ VariantID Runtime::preregister_task_variant( const TaskVariantRegistrar &registrar, const char *task_name /*= NULL*/, VariantID vid /*=AUTO_GENERATE_ID*/) //-------------------------------------------------------------------------- { CodeDescriptor desc(LegionTaskWrapper::legion_task_wrapper<T,TASK_PTR>); return preregister_task_variant(registrar, desc, NULL/*UDT*/, 0/*sizeof(UDT)*/, task_name, vid, LegionSerialization::ReturnSize<T>::value); } //-------------------------------------------------------------------------- template<typename T, typename UDT, T (*TASK_PTR)(const Task*, const std::vector<PhysicalRegion>&, Context, Runtime*, const UDT&)> /*static*/ VariantID Runtime::preregister_task_variant( const TaskVariantRegistrar &registrar, const UDT &user_data, const char *task_name /*= NULL*/, VariantID vid /*=AUTO_GENERATE_ID*/) //-------------------------------------------------------------------------- { CodeDescriptor desc( LegionTaskWrapper::legion_udt_task_wrapper<T,UDT,TASK_PTR>); return preregister_task_variant(registrar, desc, &user_data, sizeof(UDT), task_name, vid, LegionSerialization::ReturnSize<T>::value); } //-------------------------------------------------------------------------- template< void (*TASK_PTR)(const Task*, const std::vector<PhysicalRegion>&, Context, Runtime*)> /*static*/ VariantID Runtime::preregister_task_variant( const TaskVariantRegistrar &registrar, const char *task_name /*= NULL*/, const VariantID vid /*=AUTO_GENERATE_ID*/) //-------------------------------------------------------------------------- { CodeDescriptor desc(LegionTaskWrapper::legion_task_wrapper<TASK_PTR>); return preregister_task_variant(registrar, desc, NULL/*UDT*/, 0/*sizeof(UDT)*/, task_name, vid, 0/*return size*/); } //-------------------------------------------------------------------------- template<typename UDT, void (*TASK_PTR)(const Task*, const std::vector<PhysicalRegion>&, Context, Runtime*, const UDT&)> /*static*/ VariantID Runtime::preregister_task_variant( const TaskVariantRegistrar &registrar, const UDT &user_data, const char *task_name /*= NULL*/, VariantID vid /*=AUTO_GENERATE_ID*/) //-------------------------------------------------------------------------- { CodeDescriptor desc( LegionTaskWrapper::legion_udt_task_wrapper<UDT,TASK_PTR>); return preregister_task_variant(registrar, desc, &user_data, sizeof(UDT), task_name, vid, 0/*return size*/); } //-------------------------------------------------------------------------- template<typename T, T (*TASK_PTR)(const Task*, const std::vector<PhysicalRegion>&, Context, Runtime*)> /*static*/ TaskID Runtime::register_legion_task(TaskID id, Processor::Kind proc_kind, bool single, bool index, VariantID vid, TaskConfigOptions options, const char *task_name) //-------------------------------------------------------------------------- { bool check_task_id = true; if (id == LEGION_AUTO_GENERATE_ID) { id = generate_static_task_id(); check_task_id = false; } TaskVariantRegistrar registrar(id, task_name); registrar.set_leaf(options.leaf); registrar.set_inner(options.inner); registrar.set_idempotent(options.idempotent); registrar.add_constraint(ProcessorConstraint(proc_kind)); CodeDescriptor desc(LegionTaskWrapper::legion_task_wrapper<T,TASK_PTR>); preregister_task_variant(registrar, desc, NULL/*UDT*/, 0/*sizeof(UDT)*/, task_name, vid, LegionSerialization::ReturnSize<T>::value, check_task_id); return id; } //-------------------------------------------------------------------------- template< void (*TASK_PTR)(const Task*, const std::vector<PhysicalRegion>&, Context, Runtime*)> /*static*/ TaskID Runtime::register_legion_task(TaskID id, Processor::Kind proc_kind, bool single, bool index, VariantID vid, TaskConfigOptions options, const char *task_name) //-------------------------------------------------------------------------- { bool check_task_id = true; if (id == LEGION_AUTO_GENERATE_ID) { id = generate_static_task_id(); check_task_id = false; } TaskVariantRegistrar registrar(id, task_name); registrar.set_leaf(options.leaf); registrar.set_inner(options.inner); registrar.set_idempotent(options.idempotent); registrar.add_constraint(ProcessorConstraint(proc_kind)); CodeDescriptor desc(LegionTaskWrapper::legion_task_wrapper<TASK_PTR>); preregister_task_variant(registrar, desc, NULL/*UDT*/, 0/*sizeof(UDT)*/, task_name, vid, 0/*return size*/, check_task_id); return id; } //-------------------------------------------------------------------------- template<typename T, typename UDT, T (*TASK_PTR)(const Task*, const std::vector<PhysicalRegion>&, Context, Runtime*, const UDT&)> /*static*/ TaskID Runtime::register_legion_task(TaskID id, Processor::Kind proc_kind, bool single, bool index, const UDT &user_data, VariantID vid, TaskConfigOptions options, const char *task_name) //-------------------------------------------------------------------------- { bool check_task_id = true; if (id == LEGION_AUTO_GENERATE_ID) { id = generate_static_task_id(); check_task_id = false; } TaskVariantRegistrar registrar(id, task_name); registrar.set_leaf(options.leaf); registrar.set_inner(options.inner); registrar.set_idempotent(options.idempotent); registrar.add_constraint(ProcessorConstraint(proc_kind)); CodeDescriptor desc( LegionTaskWrapper::legion_udt_task_wrapper<T,UDT,TASK_PTR>); preregister_task_variant(registrar, desc, &user_data, sizeof(UDT), task_name, vid, LegionSerialization::ReturnSize<T>::value, check_task_id); return id; } //-------------------------------------------------------------------------- template<typename UDT, void (*TASK_PTR)(const Task*, const std::vector<PhysicalRegion>&, Context, Runtime*, const UDT&)> /*static*/ TaskID Runtime::register_legion_task(TaskID id, Processor::Kind proc_kind, bool single, bool index, const UDT &user_data, VariantID vid, TaskConfigOptions options, const char *task_name) //-------------------------------------------------------------------------- { bool check_task_id = true; if (id == LEGION_AUTO_GENERATE_ID) { id = generate_static_task_id(); check_task_id = false; } TaskVariantRegistrar registrar(id, task_name); registrar.set_leaf(options.leaf); registrar.set_inner(options.inner); registrar.set_idempotent(options.idempotent); registrar.add_constraint(ProcessorConstraint(proc_kind)); CodeDescriptor desc( LegionTaskWrapper::legion_udt_task_wrapper<UDT,TASK_PTR>); preregister_task_variant(registrar, desc, &user_data, sizeof(UDT), task_name, vid, 0/*return size*/, check_task_id); return id; } //-------------------------------------------------------------------------- inline PrivilegeMode operator~(PrivilegeMode p) //-------------------------------------------------------------------------- { return static_cast<PrivilegeMode>(~unsigned(p)); } //-------------------------------------------------------------------------- inline PrivilegeMode operator|(PrivilegeMode left, PrivilegeMode right) //-------------------------------------------------------------------------- { return static_cast<PrivilegeMode>(unsigned(left) | unsigned(right)); } //-------------------------------------------------------------------------- inline PrivilegeMode operator&(PrivilegeMode left, PrivilegeMode right) //-------------------------------------------------------------------------- { return static_cast<PrivilegeMode>(unsigned(left) & unsigned(right)); } //-------------------------------------------------------------------------- inline PrivilegeMode operator^(PrivilegeMode left, PrivilegeMode right) //-------------------------------------------------------------------------- { return static_cast<PrivilegeMode>(unsigned(left) ^ unsigned(right)); } //-------------------------------------------------------------------------- inline PrivilegeMode operator|=(PrivilegeMode &left, PrivilegeMode right) //-------------------------------------------------------------------------- { unsigned l = static_cast<unsigned>(left); unsigned r = static_cast<unsigned>(right); l |= r; return left = static_cast<PrivilegeMode>(l); } //-------------------------------------------------------------------------- inline PrivilegeMode operator&=(PrivilegeMode &left, PrivilegeMode right) //-------------------------------------------------------------------------- { unsigned l = static_cast<unsigned>(left); unsigned r = static_cast<unsigned>(right); l &= r; return left = static_cast<PrivilegeMode>(l); } //-------------------------------------------------------------------------- inline PrivilegeMode operator^=(PrivilegeMode &left, PrivilegeMode right) //-------------------------------------------------------------------------- { unsigned l = static_cast<unsigned>(left); unsigned r = static_cast<unsigned>(right); l ^= r; return left = static_cast<PrivilegeMode>(l); } //-------------------------------------------------------------------------- inline AllocateMode operator~(AllocateMode a) //-------------------------------------------------------------------------- { return static_cast<AllocateMode>(~unsigned(a)); } //-------------------------------------------------------------------------- inline AllocateMode operator|(AllocateMode left, AllocateMode right) //-------------------------------------------------------------------------- { return static_cast<AllocateMode>(unsigned(left) | unsigned(right)); } //-------------------------------------------------------------------------- inline AllocateMode operator&(AllocateMode left, AllocateMode right) //-------------------------------------------------------------------------- { return static_cast<AllocateMode>(unsigned(left) & unsigned(right)); } //-------------------------------------------------------------------------- inline AllocateMode operator^(AllocateMode left, AllocateMode right) //-------------------------------------------------------------------------- { return static_cast<AllocateMode>(unsigned(left) ^ unsigned(right)); } //-------------------------------------------------------------------------- inline AllocateMode operator|=(AllocateMode &left, AllocateMode right) //-------------------------------------------------------------------------- { unsigned l = static_cast<unsigned>(left); unsigned r = static_cast<unsigned>(right); l |= r; return left = static_cast<AllocateMode>(l); } //-------------------------------------------------------------------------- inline AllocateMode operator&=(AllocateMode &left, AllocateMode right) //-------------------------------------------------------------------------- { unsigned l = static_cast<unsigned>(left); unsigned r = static_cast<unsigned>(right); l &= r; return left = static_cast<AllocateMode>(l); } //-------------------------------------------------------------------------- inline AllocateMode operator^=(AllocateMode &left, AllocateMode right) //-------------------------------------------------------------------------- { unsigned l = static_cast<unsigned>(left); unsigned r = static_cast<unsigned>(right); l ^= r; return left = static_cast<AllocateMode>(l); } //-------------------------------------------------------------------------- inline std::ostream& operator<<(std::ostream& os, const LogicalRegion& lr) //-------------------------------------------------------------------------- { os << "LogicalRegion(" << lr.tree_id << "," << lr.index_space << "," << lr.field_space << ")"; return os; } //-------------------------------------------------------------------------- inline std::ostream& operator<<(std::ostream& os,const LogicalPartition& lp) //-------------------------------------------------------------------------- { os << "LogicalPartition(" << lp.tree_id << "," << lp.index_partition << "," << lp.field_space << ")"; return os; } //-------------------------------------------------------------------------- inline std::ostream& operator<<(std::ostream& os, const IndexSpace& is) //-------------------------------------------------------------------------- { os << "IndexSpace(" << is.id << "," << is.tid << ")"; return os; } //-------------------------------------------------------------------------- inline std::ostream& operator<<(std::ostream& os, const IndexPartition& ip) //-------------------------------------------------------------------------- { os << "IndexPartition(" << ip.id << "," << ip.tid << ")"; return os; } //-------------------------------------------------------------------------- inline std::ostream& operator<<(std::ostream& os, const FieldSpace& fs) //-------------------------------------------------------------------------- { os << "FieldSpace(" << fs.id << ")"; return os; } //-------------------------------------------------------------------------- inline std::ostream& operator<<(std::ostream& os, const PhaseBarrier& pb) //-------------------------------------------------------------------------- { os << "PhaseBarrier(" << pb.phase_barrier << ")"; return os; } //-------------------------------------------------------------------------- template<typename T> inline size_t Unserializable<T>::legion_buffer_size(void) //-------------------------------------------------------------------------- { const std::type_info &info = typeid(T); fprintf(stderr,"ERROR: Illegal attempt to serialize Legion type %s. " "Objects of type %s are not allowed to be passed by value into or " "out of tasks.\n", info.name(), info.name()); assert(false); return 0; } //-------------------------------------------------------------------------- template<typename T> inline size_t Unserializable<T>::legion_serialize(void *buffer) //-------------------------------------------------------------------------- { const std::type_info &info = typeid(T); fprintf(stderr,"ERROR: Illegal attempt to serialize Legion type %s. " "Objects of type %s are not allowed to be passed by value into or " "out of tasks.\n", info.name(), info.name()); assert(false); return 0; } //-------------------------------------------------------------------------- template<typename T> inline size_t Unserializable<T>::legion_deserialize(const void *buffer) //-------------------------------------------------------------------------- { const std::type_info &info = typeid(T); fprintf(stderr,"ERROR: Illegal attempt to deserialize Legion type %s. " "Objects of type %s are not allowed to be passed by value into or " "out of tasks.\n", info.name(), info.name()); assert(false); return 0; } }; // namespace Legion // This is for backwards compatibility with the old namespace scheme namespace LegionRuntime { namespace HighLevel { using namespace LegionRuntime::Arrays; LEGION_DEPRECATED("Use the Legion namespace instance instead.") typedef Legion::IndexSpace IndexSpace; LEGION_DEPRECATED("Use the Legion namespace instance instead.") typedef Legion::IndexPartition IndexPartition; LEGION_DEPRECATED("Use the Legion namespace instance instead.") typedef Legion::FieldSpace FieldSpace; LEGION_DEPRECATED("Use the Legion namespace instance instead.") typedef Legion::LogicalRegion LogicalRegion; LEGION_DEPRECATED("Use the Legion namespace instance instead.") typedef Legion::LogicalPartition LogicalPartition; LEGION_DEPRECATED("Use the Legion namespace instance instead.") typedef Legion::FieldAllocator FieldAllocator; LEGION_DEPRECATED("Use the Legion namespace instance instead.") typedef Legion::TaskArgument TaskArgument; LEGION_DEPRECATED("Use the Legion namespace instance instead.") typedef Legion::ArgumentMap ArgumentMap; LEGION_DEPRECATED("Use the Legion namespace instance instead.") typedef Legion::Predicate Predicate; LEGION_DEPRECATED("Use the Legion namespace instance instead.") typedef Legion::Lock Lock; LEGION_DEPRECATED("Use the Legion namespace instance instead.") typedef Legion::LockRequest LockRequest; LEGION_DEPRECATED("Use the Legion namespace instance instead.") typedef Legion::Grant Grant; LEGION_DEPRECATED("Use the Legion namespace instance instead.") typedef Legion::PhaseBarrier PhaseBarrier; LEGION_DEPRECATED("Use the Legion namespace instance instead.") typedef Legion::DynamicCollective DynamicCollective; LEGION_DEPRECATED("Use the Legion namespace instance instead.") typedef Legion::RegionRequirement RegionRequirement; LEGION_DEPRECATED("Use the Legion namespace instance instead.") typedef Legion::IndexSpaceRequirement IndexSpaceRequirement; LEGION_DEPRECATED("Use the Legion namespace instance instead.") typedef Legion::FieldSpaceRequirement FieldSpaceRequirement; LEGION_DEPRECATED("Use the Legion namespace instance instead.") typedef Legion::Future Future; LEGION_DEPRECATED("Use the Legion namespace instance instead.") typedef Legion::FutureMap FutureMap; LEGION_DEPRECATED("Use the Legion namespace instance instead.") typedef Legion::TaskLauncher TaskLauncher; LEGION_DEPRECATED("Use the Legion namespace instance instead.") typedef Legion::IndexLauncher IndexLauncher; LEGION_DEPRECATED("Use the Legion namespace instance instead.") typedef Legion::InlineLauncher InlineLauncher; LEGION_DEPRECATED("Use the Legion namespace instance instead.") typedef Legion::CopyLauncher CopyLauncher; LEGION_DEPRECATED("Use the Legion namespace instance instead.") typedef Legion::PhysicalRegion PhysicalRegion; #ifdef __GNUC__ #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wdeprecated-declarations" #endif #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wdeprecated-declarations" #endif LEGION_DEPRECATED("Use the Legion namespace instance instead.") typedef Legion::IndexIterator IndexIterator; LEGION_DEPRECATED("Use the Legion namespace instance instead.") typedef Legion::IndexAllocator IndexAllocator; #ifdef __GNUC__ #pragma GCC diagnostic pop #endif #ifdef __clang__ #pragma clang diagnostic pop #endif LEGION_DEPRECATED("Use the Legion namespace instance instead.") typedef Legion::AcquireLauncher AcquireLauncher; LEGION_DEPRECATED("Use the Legion namespace instance instead.") typedef Legion::ReleaseLauncher ReleaseLauncher; LEGION_DEPRECATED("Use the Legion namespace instance instead.") typedef Legion::TaskVariantRegistrar TaskVariantRegistrar; LEGION_DEPRECATED("Use the Legion namespace instance instead.") typedef Legion::MustEpochLauncher MustEpochLauncher; LEGION_DEPRECATED("Use the Legion namespace instance instead.") typedef Legion::MPILegionHandshake MPILegionHandshake; LEGION_DEPRECATED("Use the Legion namespace instance instead.") typedef Legion::Mappable Mappable; LEGION_DEPRECATED("Use the Legion namespace instance instead.") typedef Legion::Task Task; LEGION_DEPRECATED("Use the Legion namespace instance instead.") typedef Legion::Copy Copy; LEGION_DEPRECATED("Use the Legion namespace instance instead.") typedef Legion::InlineMapping Inline; LEGION_DEPRECATED("Use the Legion namespace instance instead.") typedef Legion::Acquire Acquire; LEGION_DEPRECATED("Use the Legion namespace instance instead.") typedef Legion::Release Release; LEGION_DEPRECATED("Use the Legion namespace instance instead.") typedef Legion::Mapping::Mapper Mapper; LEGION_DEPRECATED("Use the Legion namespace instance instead.") typedef Legion::InputArgs InputArgs; LEGION_DEPRECATED("Use the Legion namespace instance instead.") typedef Legion::TaskConfigOptions TaskConfigOptions; LEGION_DEPRECATED("Use the Legion namespace instance instead.") typedef Legion::ProjectionFunctor ProjectionFunctor; LEGION_DEPRECATED("Use the Legion namespace instance instead.") typedef Legion::Runtime Runtime; LEGION_DEPRECATED("Use the Legion namespace instance instead.") typedef Legion::Runtime HighLevelRuntime; // for backwards compatibility LEGION_DEPRECATED("Use the Legion namespace instance instead.") typedef Legion::ColoringSerializer ColoringSerializer; LEGION_DEPRECATED("Use the Legion namespace instance instead.") typedef Legion::DomainColoringSerializer DomainColoringSerializer; LEGION_DEPRECATED("Use the Legion namespace instance instead.") typedef Legion::Serializer Serializer; LEGION_DEPRECATED("Use the Legion namespace instance instead.") typedef Legion::Deserializer Deserializer; LEGION_DEPRECATED("Use the Legion namespace instance instead.") typedef Legion::TaskResult TaskResult; LEGION_DEPRECATED("Use the Legion namespace instance instead.") typedef Legion::CObjectWrapper CObjectWrapper; LEGION_DEPRECATED("Use the Legion namespace instance instead.") typedef Legion::ISAConstraint ISAConstraint; LEGION_DEPRECATED("Use the Legion namespace instance instead.") typedef Legion::ProcessorConstraint ProcessorConstraint; LEGION_DEPRECATED("Use the Legion namespace instance instead.") typedef Legion::ResourceConstraint ResourceConstraint; LEGION_DEPRECATED("Use the Legion namespace instance instead.") typedef Legion::LaunchConstraint LaunchConstraint; LEGION_DEPRECATED("Use the Legion namespace instance instead.") typedef Legion::ColocationConstraint ColocationConstraint; LEGION_DEPRECATED("Use the Legion namespace instance instead.") typedef Legion::ExecutionConstraintSet ExecutionConstraintSet; LEGION_DEPRECATED("Use the Legion namespace instance instead.") typedef Legion::SpecializedConstraint SpecializedConstraint; LEGION_DEPRECATED("Use the Legion namespace instance instead.") typedef Legion::MemoryConstraint MemoryConstraint; LEGION_DEPRECATED("Use the Legion namespace instance instead.") typedef Legion::FieldConstraint FieldConstraint; LEGION_DEPRECATED("Use the Legion namespace instance instead.") typedef Legion::OrderingConstraint OrderingConstraint; LEGION_DEPRECATED("Use the Legion namespace instance instead.") typedef Legion::SplittingConstraint SplittingConstraint; LEGION_DEPRECATED("Use the Legion namespace instance instead.") typedef Legion::DimensionConstraint DimensionConstraint; LEGION_DEPRECATED("Use the Legion namespace instance instead.") typedef Legion::AlignmentConstraint AlignmentConstraint; LEGION_DEPRECATED("Use the Legion namespace instance instead.") typedef Legion::OffsetConstraint OffsetConstraint; LEGION_DEPRECATED("Use the Legion namespace instance instead.") typedef Legion::PointerConstraint PointerConstraint; LEGION_DEPRECATED("Use the Legion namespace instance instead.") typedef Legion::LayoutConstraintSet LayoutConstraintSet; LEGION_DEPRECATED("Use the Legion namespace instance instead.") typedef Legion::TaskLayoutConstraintSet TaskLayoutConstraintSet; LEGION_DEPRECATED("Use the Legion namespace instance instead.") typedef Realm::Runtime RealmRuntime; LEGION_DEPRECATED("Use the Legion namespace instance instead.") typedef Realm::Machine Machine; LEGION_DEPRECATED("Use the Legion namespace instance instead.") typedef Legion::Domain Domain; LEGION_DEPRECATED("Use the Legion namespace instance instead.") typedef Legion::DomainPoint DomainPoint; LEGION_DEPRECATED("Use the Legion namespace instance instead.") typedef Realm::RegionInstance PhysicalInstance; LEGION_DEPRECATED("Use the Legion namespace instance instead.") typedef Realm::Memory Memory; LEGION_DEPRECATED("Use the Legion namespace instance instead.") typedef Realm::Processor Processor; LEGION_DEPRECATED("Use the Legion namespace instance instead.") typedef Realm::CodeDescriptor CodeDescriptor; LEGION_DEPRECATED("Use the Legion namespace instance instead.") typedef Realm::Event Event; LEGION_DEPRECATED("Use the Legion namespace instance instead.") typedef Realm::Event MapperEvent; LEGION_DEPRECATED("Use the Legion namespace instance instead.") typedef Realm::UserEvent UserEvent; LEGION_DEPRECATED("Use the Legion namespace instance instead.") typedef Realm::Reservation Reservation; LEGION_DEPRECATED("Use the Legion namespace instance instead.") typedef Realm::Barrier Barrier; LEGION_DEPRECATED("Use the Legion namespace instance instead.") typedef ::legion_reduction_op_id_t ReductionOpID; LEGION_DEPRECATED("Use the Legion namespace instance instead.") typedef Realm::ReductionOpUntyped ReductionOp; LEGION_DEPRECATED("Use the Legion namespace instance instead.") typedef ::legion_custom_serdez_id_t CustomSerdezID; LEGION_DEPRECATED("Use the Legion namespace instance instead.") typedef Realm::CustomSerdezUntyped SerdezOp; LEGION_DEPRECATED("Use the Legion namespace instance instead.") typedef Realm::Machine::ProcessorMemoryAffinity ProcessorMemoryAffinity; LEGION_DEPRECATED("Use the Legion namespace instance instead.") typedef Realm::Machine::MemoryMemoryAffinity MemoryMemoryAffinity; LEGION_DEPRECATED("Use the Legion namespace instance instead.") typedef std::map<Legion::CustomSerdezID, const Realm::CustomSerdezUntyped *> SerdezOpTable; LEGION_DEPRECATED("Use the Legion namespace instance instead.") typedef std::map<Realm::ReductionOpID, const Realm::ReductionOpUntyped *> ReductionOpTable; LEGION_DEPRECATED("Use the Legion namespace instance instead.") typedef void (*SerdezInitFnptr)(const Legion::ReductionOp*, void *&, size_t&); LEGION_DEPRECATED("Use the Legion namespace instance instead.") typedef void (*SerdezFoldFnptr)(const Legion::ReductionOp*, void *&, size_t&, const void*, bool); LEGION_DEPRECATED("Use the Legion namespace instance instead.") typedef std::map<Realm::ReductionOpID, Legion::SerdezRedopFns> SerdezRedopTable; LEGION_DEPRECATED("Use the Legion namespace instance instead.") typedef ::legion_address_space_t AddressSpace; LEGION_DEPRECATED("Use the Legion namespace instance instead.") typedef ::legion_task_priority_t TaskPriority; LEGION_DEPRECATED("Use the Legion namespace instance instead.") typedef ::legion_color_t Color; LEGION_DEPRECATED("Use the Legion namespace instance instead.") typedef ::legion_field_id_t FieldID; LEGION_DEPRECATED("Use the Legion namespace instance instead.") typedef ::legion_trace_id_t TraceID; LEGION_DEPRECATED("Use the Legion namespace instance instead.") typedef ::legion_mapper_id_t MapperID; LEGION_DEPRECATED("Use the Legion namespace instance instead.") typedef ::legion_context_id_t ContextID; LEGION_DEPRECATED("Use the Legion namespace instance instead.") typedef ::legion_instance_id_t InstanceID; LEGION_DEPRECATED("Use the Legion namespace instance instead.") typedef ::legion_index_space_id_t IndexSpaceID; LEGION_DEPRECATED("Use the Legion namespace instance instead.") typedef ::legion_index_partition_id_t IndexPartitionID; LEGION_DEPRECATED("Use the Legion namespace instance instead.") typedef ::legion_index_tree_id_t IndexTreeID; LEGION_DEPRECATED("Use the Legion namespace instance instead.") typedef ::legion_field_space_id_t FieldSpaceID; LEGION_DEPRECATED("Use the Legion namespace instance instead.") typedef ::legion_generation_id_t GenerationID; LEGION_DEPRECATED("Use the Legion namespace instance instead.") typedef ::legion_type_handle TypeHandle; LEGION_DEPRECATED("Use the Legion namespace instance instead.") typedef ::legion_projection_id_t ProjectionID; LEGION_DEPRECATED("Use the Legion namespace instance instead.") typedef ::legion_region_tree_id_t RegionTreeID; LEGION_DEPRECATED("Use the Legion namespace instance instead.") typedef ::legion_distributed_id_t DistributedID; LEGION_DEPRECATED("Use the Legion namespace instance instead.") typedef ::legion_address_space_t AddressSpaceID; LEGION_DEPRECATED("Use the Legion namespace instance instead.") typedef ::legion_tunable_id_t TunableID; LEGION_DEPRECATED("Use the Legion namespace instance instead.") typedef ::legion_mapping_tag_id_t MappingTagID; LEGION_DEPRECATED("Use the Legion namespace instance instead.") typedef ::legion_semantic_tag_t SemanticTag; LEGION_DEPRECATED("Use the Legion namespace instance instead.") typedef ::legion_variant_id_t VariantID; LEGION_DEPRECATED("Use the Legion namespace instance instead.") typedef ::legion_unique_id_t UniqueID; LEGION_DEPRECATED("Use the Legion namespace instance instead.") typedef ::legion_version_id_t VersionID; LEGION_DEPRECATED("Use the Legion namespace instance instead.") typedef ::legion_task_id_t TaskID; LEGION_DEPRECATED("Use the Legion namespace instance instead.") typedef ::legion_layout_constraint_id_t LayoutConstraintID; LEGION_DEPRECATED("Use the Legion namespace instance instead.") typedef std::map<Legion::Color,Legion::ColoredPoints<ptr_t> > Coloring; LEGION_DEPRECATED("Use the Legion namespace instance instead.") typedef std::map<Legion::Color,Legion::Domain> DomainColoring; LEGION_DEPRECATED("Use the Legion namespace instance instead.") typedef std::map<Legion::Color, std::set<Legion::Domain> > MultiDomainColoring; LEGION_DEPRECATED("Use the Legion namespace instance instead.") typedef std::map<Legion::DomainPoint, Legion::ColoredPoints<ptr_t> > PointColoring; LEGION_DEPRECATED("Use the Legion namespace instance instead.") typedef std::map<Legion::DomainPoint,Legion::Domain> DomainPointColoring; LEGION_DEPRECATED("Use the Legion namespace instance instead.") typedef std::map<Legion::DomainPoint, std::set<Legion::Domain> > MultiDomainPointColoring; LEGION_DEPRECATED("Use the Legion namespace instance instead.") typedef void (*RegistrationCallbackFnptr)(Realm::Machine machine, Legion::Runtime *rt, const std::set<Legion::Processor> &local_procs); LEGION_DEPRECATED("Use the Legion namespace instance instead.") typedef Legion::LogicalRegion (*RegionProjectionFnptr)( Legion::LogicalRegion parent, const Legion::DomainPoint&, Legion::Runtime *rt); LEGION_DEPRECATED("Use the Legion namespace instance instead.") typedef Legion::LogicalRegion (*PartitionProjectionFnptr)( Legion::LogicalPartition parent, const Legion::DomainPoint&, Legion::Runtime *rt); LEGION_DEPRECATED("Use the Legion namespace instance instead.") typedef bool (*PredicateFnptr)(const void*, size_t, const std::vector<Legion::Future> futures); LEGION_DEPRECATED("Use the Legion namespace instance instead.") typedef std::map<Legion::ProjectionID,Legion::RegionProjectionFnptr> RegionProjectionTable; LEGION_DEPRECATED("Use the Legion namespace instance instead.") typedef std::map<Legion::ProjectionID,Legion::PartitionProjectionFnptr> PartitionProjectionTable; LEGION_DEPRECATED("Use the Legion namespace instance instead.") typedef void (*RealmFnptr)(const void*,size_t, const void*,size_t,Legion::Processor); LEGION_DEPRECATED("Use the Legion namespace instance instead.") typedef Legion::Internal::TaskContext* Context; }; // map old Logger::Category to new Realm::Logger namespace Logger { typedef Realm::Logger Category; }; };
41.561069
87
0.538329
[ "vector", "transform" ]
6051e70fbc7ea889aa0ecb7e506579a422ddd09c
19,717
cpp
C++
ssc/vartab.cpp
qualand/ssc
9e21ccff7f0a366d1bc8ab23d3ff32e528fcacdf
[ "BSD-3-Clause" ]
null
null
null
ssc/vartab.cpp
qualand/ssc
9e21ccff7f0a366d1bc8ab23d3ff32e528fcacdf
[ "BSD-3-Clause" ]
null
null
null
ssc/vartab.cpp
qualand/ssc
9e21ccff7f0a366d1bc8ab23d3ff32e528fcacdf
[ "BSD-3-Clause" ]
null
null
null
/** BSD-3-Clause Copyright 2019 Alliance for Sustainable Energy, LLC Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met : 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.IN NO EVENT SHALL THE COPYRIGHT HOLDER, CONTRIBUTORS, UNITED STATES GOVERNMENT OR UNITED STATES DEPARTMENT OF ENERGY, NOR ANY OF THEIR EMPLOYEES, BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "lib_util.h" #include "vartab.h" static const char *var_data_types[] = { "<invalid>", // SSC_INVALID "<string>", // SSC_STRING "<number>", // SSC_NUMBER "<array>", // SSC_ARRAY "<matrix>", // SSC_MATRIX "<table>", // SSC_TABLE NULL }; var_data::var_data(std::vector<int> arr) : type(SSC_ARRAY) { num.resize(arr.size()); for (size_t i = 0; i < arr.size(); i++) { num[i] = (ssc_number_t)arr[i]; } } const char *var_data::type_name() { if (type < 6) return var_data_types[ (int)type ]; else return NULL; } std::string var_data::type_name(int type) { if (type >= 0 && type < 5) return var_data_types[ (int)type ]; else return ""; } std::string var_data::to_string() { return var_data::to_string( *this ); } std::string var_data::to_string( const var_data &value ) { switch( value.type ) { case SSC_STRING: return value.str; case SSC_NUMBER: return util::to_string( value.num.value() ); case SSC_ARRAY: { std::string s; for (size_t i=0;i<value.num.length();i++) { s += util::to_string( (double) value.num[i] ); if ( i < value.num.length()-1 ) s += ','; } return s; } case SSC_MATRIX: { std::string s; for (size_t r=0;r<value.num.nrows();r++) { s += "["; for (size_t c=0; c<value.num.ncols();c++) { s += util::to_string( (double) value.num.at(r,c) ); if ( c < value.num.ncols()-1 ) s += ' '; } s += "]"; } return s; } } return "<invalid>"; } std::vector<double> var_data::arr_vector() { if (type != SSC_ARRAY) throw std::runtime_error("arr_vector error: var_data type not SSC_ARRAY."); std::vector<double> v; for (unsigned int i = 0; i < num.length(); i++){ v.push_back(num[i]); } return v; } std::vector<std::vector<double>> var_data::matrix_vector() { if (type != SSC_MATRIX) throw std::runtime_error("arr_matrix error: var_data type not SSC_MATRIX."); std::vector<std::vector<double>> v; for (unsigned int i = 0; i < num.nrows(); i++){ std::vector<double> row; for (unsigned int j = 0; j < num.ncols(); j++){ row.push_back(num.at(i, j)); } v.push_back(row); } return v; } bool var_data::parse( unsigned char type, const std::string &buf, var_data &value ) { switch(type) { case SSC_STRING: { value.type = SSC_STRING; value.str = buf; return true; } case SSC_NUMBER: { double x; if (util::to_double(buf, &x)) { value.type = SSC_NUMBER; value.num = (ssc_number_t)x; return true; } else return false; } case SSC_ARRAY: { std::vector<std::string> tokens = util::split(buf," ,\t[]\n"); value.type = SSC_ARRAY; value.num.resize_fill( tokens.size(), 0.0 ); for (size_t i=0; i<tokens.size(); i++) { double x; if (util::to_double( tokens[i], &x )) value.num[i] = (ssc_number_t) x; else return false; } return true; } case SSC_MATRIX: { std::vector<std::string> rows = util::split(buf,"[]\n"); if (rows.size() < 1) return false; std::vector<std::string> cur_row = util::split(rows[0], " ,\t"); if (cur_row.size() < 1) return false; value.type = SSC_MATRIX; value.num.resize_fill( rows.size(), cur_row.size(), 0.0 ); for( size_t c=0; c < cur_row.size(); c++) { double x; if (util::to_double(cur_row[c], &x)) value.num.at(0,c) = (ssc_number_t)x; } for (size_t r=1; r < rows.size(); r++) { cur_row = util::split(rows[r], " ,\t"); for (size_t c=0; c<cur_row.size() && c<value.num.ncols(); c++) { double x; if (util::to_double(cur_row[c], &x)) value.num.at(r,c) = (ssc_number_t)x; } } return true; } } return false; } var_table::var_table() : m_iterator(m_hash.begin()) { /* nothing to do here */ } var_table::var_table(const var_table &rhs) : var_table() { operator=(rhs); } var_table::~var_table() { clear(); } var_table &var_table::operator=( const var_table &rhs ) { clear(); for ( var_hash::const_iterator it = rhs.m_hash.begin(); it != rhs.m_hash.end(); ++it ) assign_match_case( (*it).first, *((*it).second) ); return *this; } void var_table::clear() { for (var_hash::iterator it = m_hash.begin(); it != m_hash.end(); ++it) { // debug heap corruption delete it->second; // delete the var_data object } if (!m_hash.empty()) m_hash.clear(); } var_data *var_table::assign( const std::string &name, const var_data &val ) { var_data *v = lookup(name); if (!v) { v = new var_data; m_hash[ util::lower_case(name) ] = v; } v->copy(val); return v; } var_data *var_table::assign_match_case( const std::string &name, const var_data &val ) { var_data *v = lookup(name); if (!v) { v = new var_data; m_hash[ name ] = v; } v->copy(val); return v; } void var_table::merge(const var_table &rhs, bool overwrite_existing){ for ( var_hash::const_iterator it = rhs.m_hash.begin(); it != rhs.m_hash.end(); ++it ){ if (is_assigned(it->first)){ if (overwrite_existing) assign_match_case( (*it).first, *((*it).second) ); } else assign_match_case( (*it).first, *((*it).second) ); } } bool var_table::is_assigned( const std::string &name ) { return (lookup(name) != 0); } void var_table::unassign( const std::string &name ) { var_hash::iterator it = m_hash.find( util::lower_case(name) ); if (it == m_hash.end()) { it = m_hash.find( name ); } if (it != m_hash.end()) { delete (*it).second; // delete the associated data m_hash.erase( it ); } } bool var_table::rename( const std::string &oldname, const std::string &newname ) { return rename_match_case(util::lower_case(oldname), util::lower_case(newname)); } bool var_table::rename_match_case( const std::string &oldname, const std::string &newname ) { var_hash::iterator it = m_hash.find( oldname ); if ( it != m_hash.end() ) { std::string lcnewname( newname ); var_data *data = it->second; // save ptr to data m_hash.erase( it ); // if a variable with 'newname' already exists, // delete its data, and reassign the name to the new data it = m_hash.find( lcnewname ); if ( it != m_hash.end() ) { delete it->second; it->second = data; } else // otherwise, just add a new itme m_hash[ lcnewname ] = data; return true; } else return false; } var_data *var_table::lookup( const std::string &name ) { var_hash::iterator it = m_hash.find(name); if (it == m_hash.end()) it = m_hash.find( util::lower_case(name)); if ( it != m_hash.end() ) return (*it).second; else return NULL; } var_data *var_table::lookup_match_case( const std::string &name ) { var_hash::iterator it = m_hash.find( name ); if ( it != m_hash.end() ) return (*it).second; else return NULL; } const char *var_table::first( ) { m_iterator = m_hash.begin(); if (m_iterator != m_hash.end()) return m_iterator->first.c_str(); else return NULL; } const char *var_table::key(int pos){ m_iterator = m_hash.begin(); if (m_iterator == m_hash.end()) return NULL; int n = 0; for (n = 0; n < pos; n++) ++m_iterator; if (m_iterator != m_hash.end()) return m_iterator->first.c_str(); return NULL; } const char *var_table::next() { if (m_iterator == m_hash.end()) return NULL; ++m_iterator; if (m_iterator != m_hash.end()) return m_iterator->first.c_str(); return NULL; } void vt_get_int(var_table* vt, const std::string& name, int* lvalue) { if (var_data* vd = vt->lookup(name)) *lvalue = (int)vd->num; else throw std::runtime_error(std::string(name) + std::string(" must be assigned.")); } void vt_get_uint(var_table* vt, const std::string& name, size_t* lvalue) { if (var_data* vd = vt->lookup(name)) *lvalue = (size_t)vd->num; else throw std::runtime_error(std::string(name) + std::string(" must be assigned.")); } void vt_get_bool(var_table* vt, const std::string& name, bool* lvalue) { if (var_data* vd = vt->lookup(name)) *lvalue = (bool)vd->num; else throw std::runtime_error(std::string(name) + std::string(" must be assigned.")); } void vt_get_number(var_table* vt, const std::string& name, double* lvalue) { if (var_data* vd = vt->lookup(name)) *lvalue = vd->num; else throw std::runtime_error(std::string(name) + std::string(" must be assigned.")); } void vt_get_array_vec(var_table* vt, const std::string& name, std::vector<double>& vec_double) { if (var_data* vd = vt->lookup(name)){ if (vd->type != SSC_ARRAY) throw std::runtime_error(std::string(name) + std::string(" must be array type.")); vec_double = vd->arr_vector(); } else throw std::runtime_error(std::string(name) + std::string(" must be assigned.")); } void vt_get_array_vec(var_table* vt, const std::string& name, std::vector<int>& vec_int) { if (var_data* vd = vt->lookup(name)){ if (vd->type != SSC_ARRAY) throw std::runtime_error(std::string(name) + std::string(" must be array type.")); vec_int.clear(); for (auto &i : vd->arr_vector()) { vec_int.push_back((int)i); } } else throw std::runtime_error(std::string(name) + std::string(" must be assigned.")); } void vt_get_matrix(var_table* vt, const std::string& name, util::matrix_t<double>& matrix) { if (var_data* vd = vt->lookup(name)){ if (vd->type == SSC_ARRAY) { std::vector<double> vec_double = vd->arr_vector(); matrix.resize(vec_double.size()); for (size_t i = 0; i < vec_double.size(); i++) matrix.at(i) = vec_double[i]; } else if (vd->type != SSC_MATRIX) throw std::runtime_error(std::string(name) + std::string(" must be matrix type.")); matrix = vd->num; } else throw std::runtime_error(std::string(name) + std::string(" must be assigned.")); } void vt_get_matrix_vec(var_table* vt, const std::string& name, std::vector<std::vector<double>>& mat) { if (var_data* vd = vt->lookup(name)) mat = vd->matrix_vector(); else throw std::runtime_error(std::string(name)+std::string(" must be assigned.")); } int var_table::as_integer( const std::string &name ) { var_data* x = lookup(name); if (!x) throw general_error(name + " not assigned"); if (x->type != SSC_NUMBER) throw cast_error("integer", *x, name); return static_cast<int>(x->num); } size_t var_table::as_unsigned_long(const std::string &name) { var_data*x = lookup(name); if (!x) throw general_error(name + " not assigned"); if (x->type != SSC_NUMBER) throw cast_error("unsigned long", *x, name); return static_cast<size_t>(x->num); } bool var_table::as_boolean( const std::string &name ) { var_data* x = lookup(name); if (!x) throw general_error(name + " not assigned"); if (x->type != SSC_NUMBER) throw cast_error("boolean", *x, name); return static_cast<bool> ( (int)(x->num!=0) ); } float var_table::as_float( const std::string &name ) { var_data* x = lookup(name); if (!x) throw general_error(name + " not assigned"); if (x->type != SSC_NUMBER) throw cast_error("float", *x, name); return static_cast<float>(x->num); } ssc_number_t var_table::as_number( const std::string &name ) { var_data* x = lookup(name); if (!x) throw general_error(name + " not assigned"); if (x->type != SSC_NUMBER) throw cast_error("ssc_number_t", *x, name); return x->num; } double var_table::as_double( const std::string &name ) { var_data* x = lookup(name); if (!x) throw general_error(name + " not assigned"); if (x->type != SSC_NUMBER) throw cast_error("double", *x, name); return static_cast<double>(x->num); } const char *var_table::as_string( const std::string &name ) { var_data* x = lookup(name); if (!x) throw general_error(name + " not assigned"); if (x->type != SSC_STRING) throw cast_error("string", *x, name); return x->str.c_str(); } ssc_number_t *var_table::as_array( const std::string &name, size_t *count ) { var_data* x = lookup(name); if (!x) throw general_error(name + " not assigned"); if (x->type != SSC_ARRAY) throw cast_error("array", *x, name); if (count) *count = x->num.length(); return x->num.data(); } std::vector<int> var_table::as_vector_integer(const std::string &name) { var_data* x = lookup(name); if (!x) throw general_error(name + " not assigned"); if (x->type != SSC_ARRAY) throw cast_error("array", *x, name); size_t len = x->num.length(); std::vector<int> v(len); ssc_number_t *p = x->num.data(); for (size_t k = 0; k<len; k++) v[k] = static_cast<int>(p[k]); return v; } std::vector<ssc_number_t> var_table::as_vector_ssc_number_t(const std::string &name) { var_data* x = lookup(name); if (!x) throw general_error(name + " not assigned"); if (x->type != SSC_ARRAY) throw cast_error("array", *x, name); size_t len = x->num.length(); std::vector<ssc_number_t> v(len); ssc_number_t *p = x->num.data(); for (size_t k = 0; k<len; k++) v[k] = static_cast<ssc_number_t>(p[k]); return v; } std::vector<double> var_table::as_vector_double(const std::string &name) { var_data* x = lookup(name); if (!x) throw general_error(name + " not assigned"); if (x->type != SSC_ARRAY) throw cast_error("array", *x, name); size_t len = x->num.length(); std::vector<double> v(len); ssc_number_t *p = x->num.data(); for (size_t k=0;k<len;k++) v[k] = static_cast<double>(p[k]); return v; } std::vector<float> var_table::as_vector_float(const std::string &name) { var_data* x = lookup(name); if (!x) throw general_error(name + " not assigned"); if (x->type != SSC_ARRAY) throw cast_error("array", *x, name); size_t len = x->num.length(); std::vector<float> v(len); ssc_number_t *p = x->num.data(); for (size_t k = 0; k<len; k++) v[k] = static_cast<float>(p[k]); return v; } std::vector<size_t> var_table::as_vector_unsigned_long(const std::string &name) { var_data* x = lookup(name); if (!x) throw general_error(name + " not assigned"); if (x->type != SSC_ARRAY) throw cast_error("array", *x, name); size_t len = x->num.length(); std::vector<size_t> v(len); ssc_number_t *p = x->num.data(); for (size_t k = 0; k<len; k++) v[k] = static_cast<size_t>(p[k]); return v; } std::vector<bool> var_table::as_vector_bool(const std::string &name) { var_data* x = lookup(name); if (!x) throw general_error(name + " not assigned"); if (x->type != SSC_ARRAY) throw cast_error("array", *x, name); size_t len = x->num.length(); std::vector<bool> v(len); ssc_number_t *p = x->num.data(); for (size_t k = 0; k<len; k++) v[k] = p[k] != 0; return v; } ssc_number_t *var_table::as_matrix( const std::string &name, size_t *rows, size_t *cols ) { var_data* x = lookup(name); if (!x) throw general_error(name + " not assigned"); if (x->type != SSC_MATRIX) throw cast_error("matrix", *x, name); if (rows) *rows = x->num.nrows(); if (cols) *cols = x->num.ncols(); return x->num.data(); } util::matrix_t<double> var_table::as_matrix(const std::string &name) { var_data* x = lookup(name); if (!x) throw general_error(name + " not assigned"); if (x->type != SSC_MATRIX) throw cast_error("matrix", *x, name); util::matrix_t<double> mat(x->num.nrows(), x->num.ncols(), 0.0); for (size_t r = 0; r<x->num.nrows(); r++) for (size_t c = 0; c<x->num.ncols(); c++) mat.at(r, c) = static_cast<double>(x->num(r, c)); return mat; } util::matrix_t<size_t> var_table::as_matrix_unsigned_long(const std::string &name) { var_data* x = lookup(name); if (!x) throw general_error(name + " not assigned"); if (x->type != SSC_MATRIX) throw cast_error("matrix", *x, name); util::matrix_t<size_t> mat(x->num.nrows(), x->num.ncols(), (size_t)0.0); for (size_t r = 0; r<x->num.nrows(); r++) for (size_t c = 0; c<x->num.ncols(); c++) mat.at(r, c) = static_cast<size_t>(x->num(r, c)); return mat; } util::matrix_t<double> var_table::as_matrix_transpose(const std::string &name) { var_data* x = lookup(name); if (!x) throw general_error(name + " not assigned"); if (x->type != SSC_MATRIX) throw cast_error("matrix", *x, name); util::matrix_t<double> mat(x->num.ncols(), x->num.nrows(), 0.0); for (size_t r = 0; r<x->num.nrows(); r++) for (size_t c = 0; c<x->num.ncols(); c++) mat.at(c, r) = static_cast<double>(x->num(r, c)); return mat; } bool var_table::get_matrix(const std::string &name, util::matrix_t<ssc_number_t> &mat) { var_data* x = lookup(name); if (!x) throw general_error(name + " not assigned"); if (x->type != SSC_MATRIX) throw cast_error("matrix", *x, name); size_t nrows, ncols; ssc_number_t *arr = as_matrix(name, &nrows, &ncols); if (nrows < 1 || ncols < 1) return false; mat.resize_fill(nrows, ncols, 1.0); for (size_t r = 0; r<nrows; r++) for (size_t c = 0; c<ncols; c++) mat.at(r, c) = arr[r*ncols + c]; return true; } ssc_number_t *var_table::allocate( const std::string &name, size_t length ) { var_data *v = assign(name, var_data()); v->type = SSC_ARRAY; v->num.resize_fill( length, 0.0 ); return v->num.data(); } ssc_number_t *var_table::allocate( const std::string &name, size_t nrows, size_t ncols ) { var_data *v = assign(name, var_data()); v->type = SSC_MATRIX; v->num.resize_fill(nrows, ncols, 0.0); return v->num.data(); } util::matrix_t<ssc_number_t>& var_table::allocate_matrix( const std::string &name, size_t nrows, size_t ncols ) { var_data *v = assign(name, var_data()); v->type = SSC_MATRIX; v->num.resize_fill(nrows, ncols, 0.0); return v->num; }
29.253709
117
0.620835
[ "object", "vector" ]
6053c2159bd2e5b9711033712c1f59e7b6181f82
6,958
cpp
C++
source/drivers/LSM303Accelerometer.cpp
AkhilaLabs/bsp-AkhilaFlex-0
302a4f4aa4b9d3b0a5bea2c3a7f97707ebf3cfd2
[ "MIT" ]
null
null
null
source/drivers/LSM303Accelerometer.cpp
AkhilaLabs/bsp-AkhilaFlex-0
302a4f4aa4b9d3b0a5bea2c3a7f97707ebf3cfd2
[ "MIT" ]
null
null
null
source/drivers/LSM303Accelerometer.cpp
AkhilaLabs/bsp-AkhilaFlex-0
302a4f4aa4b9d3b0a5bea2c3a7f97707ebf3cfd2
[ "MIT" ]
null
null
null
/* The MIT License (MIT) Copyright (c) 2017 Lancaster University. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /** * Class definition for an LSM303 3 axis accelerometer. * * Represents an implementation of the LSM303 3 axis accelerometer * Also includes basic data caching and on demand activation. */ #include "AKHILAFLEXConfig.h" #include "LSM303Accelerometer.h" #include "ErrorNo.h" #include "AKHILAFLEXEvent.h" #include "AKHILAFLEXCompat.h" #include "AKHILAFLEXFiber.h" // // Configuration table for available g force ranges. // Maps g -> CTRL_REG4 full scale selection bits [4..5] // static const KeyValueTableEntry accelerometerRangeData[] = { {2, 0x00}, {4, 0x10}, {8, 0x20}, {16, 0x30} }; CREATE_KEY_VALUE_TABLE(accelerometerRange, accelerometerRangeData); // // Configuration table for available data update frequency. // maps microsecond period -> CTRL_REG1 data rate selection bits [4..7] // static const KeyValueTableEntry accelerometerPeriodData[] = { {617, 0x80}, {744, 0x90}, {2500, 0x70}, {5000, 0x60}, {10000, 0x50}, {20000, 0x40}, {40000, 0x30}, {100000, 0x20}, {1000000, 0x10} }; CREATE_KEY_VALUE_TABLE(accelerometerPeriod, accelerometerPeriodData); /** * Constructor. * Create a software abstraction of an accelerometer. * * @param coordinateSpace The orientation of the sensor. Defaults to: SIMPLE_CARTESIAN * @param id The unique EventModel id of this component. Defaults to: AKHILAFLEX_ID_ACCELEROMETER * */ LSM303Accelerometer::LSM303Accelerometer(AKHILAFLEXI2C& _i2c, AKHILAFLEXPin _int1, CoordinateSpace &coordinateSpace, uint16_t address, uint16_t id) : AKHILAFLEXAccelerometer(coordinateSpace, id), i2c(_i2c), int1(_int1) { // Store our identifiers. this->status = 0; this->address = address; // Configure and enable the accelerometer. configure(); } /** * Configures the accelerometer for G range and sample rate defined * in this object. The nearest values are chosen to those defined * that are supported by the hardware. The instance variables are then * updated to reflect reality. * * @return AKHILAFLEX_OK on success, AKHILAFLEX_I2C_ERROR if the accelerometer could not be configured. * * @note This method should be overidden by the hardware driver to implement the requested * changes in hardware. */ int LSM303Accelerometer::configure() { int result; // First find the nearest sample rate to that specified. samplePeriod = accelerometerPeriod.getKey(samplePeriod * 1000) / 1000; sampleRange = accelerometerRange.getKey(sampleRange); // Now configure the accelerometer accordingly. // Place the device into normal (10 bit) mode, with all axes enabled at the nearest supported data rate to that requested. result = i2c.writeRegister(address, LSM303_CTRL_REG1_A, accelerometerPeriod.get(samplePeriod * 1000) | 0x07); if (result != 0) return AKHILAFLEX_I2C_ERROR; // Enable the DRDY1 interrupt on INT1 pin. result = i2c.writeRegister(address, LSM303_CTRL_REG3_A, 0x10); if (result != 0) return AKHILAFLEX_I2C_ERROR; // Select the g range to that requested, using little endian data format and disable self-test and high rate functions. result = i2c.writeRegister(address, LSM303_CTRL_REG4_A, 0x80 | accelerometerRange.get(sampleRange)); if (result != 0) return AKHILAFLEX_I2C_ERROR; return AKHILAFLEX_OK; } /** * Poll to see if new data is available from the hardware. If so, update it. * n.b. it is not necessary to explicitly call this funciton to update data * (it normally happens in the background when the scheduler is idle), but a check is performed * if the user explicitly requests up to date data. * * @return AKHILAFLEX_OK on success, AKHILAFLEX_I2C_ERROR if the update fails. * * @note This method should be overidden by the hardware driver to implement the requested * changes in hardware. */ int LSM303Accelerometer::requestUpdate() { // Ensure we're scheduled to update the data periodically if(!(status & AKHILAFLEX_ACCEL_ADDED_TO_IDLE)) { fiber_add_idle_component(this); status |= AKHILAFLEX_ACCEL_ADDED_TO_IDLE; } // Poll interrupt line from device (ACTIVE HI) if(int1.getDigitalValue()) { uint8_t data[6]; int result; int16_t *x; int16_t *y; int16_t *z; // Read the combined accelerometer and magnetometer data. result = i2c.readRegister(address, LSM303_OUT_X_L_A | 0x80, data, 6); if (result !=0) return AKHILAFLEX_I2C_ERROR; // Read in each reading as a 16 bit little endian value, and scale to 10 bits. x = ((int16_t *) &data[0]); y = ((int16_t *) &data[2]); z = ((int16_t *) &data[4]); *x = *x / 32; *y = *y / 32; *z = *z / 32; // Scale into millig (approx) and align to ENU coordinate system sampleENU.x = -((int)(*y)) * sampleRange; sampleENU.y = -((int)(*x)) * sampleRange; sampleENU.z = ((int)(*z)) * sampleRange; // indicate that new data is available. update(); } return AKHILAFLEX_OK; } /** * A periodic callback invoked by the fiber scheduler idle thread. * * Internally calls updateSample(). */ void LSM303Accelerometer::idleTick() { requestUpdate(); } /** * Attempts to read the 8 bit WHO_AM_I value from the accelerometer * * @return true if the WHO_AM_I value is succesfully read. false otherwise. */ int LSM303Accelerometer::isDetected(AKHILAFLEXI2C &i2c, uint16_t address) { return i2c.readRegister(address, LSM303_WHO_AM_I_A) == LSM303_A_WHOAMI_VAL; } /** * Destructor. */ LSM303Accelerometer::~LSM303Accelerometer() { }
33.133333
219
0.690716
[ "object" ]
605a0d485a46d0fd4eda12e647bbc343d1bce3cb
2,597
cpp
C++
src/database/overlay/ftgl/src/FTGLPixmapFont.cpp
OpenXIP/xip-libraries
9f0fef66038b20ff0c81c089d7dd0038e3126e40
[ "Apache-2.0" ]
2
2020-05-21T07:06:07.000Z
2021-06-28T02:14:34.000Z
src/database/overlay/ftgl/src/FTGLPixmapFont.cpp
OpenXIP/xip-libraries
9f0fef66038b20ff0c81c089d7dd0038e3126e40
[ "Apache-2.0" ]
null
null
null
src/database/overlay/ftgl/src/FTGLPixmapFont.cpp
OpenXIP/xip-libraries
9f0fef66038b20ff0c81c089d7dd0038e3126e40
[ "Apache-2.0" ]
6
2016-03-21T19:53:18.000Z
2021-06-08T18:06:03.000Z
/* Copyright (c) 2011, Siemens Corporate Research a Division of Siemens Corporation All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */#include "FTGLPixmapFont.h" #include "FTPixmapGlyph.h" FTGLPixmapFont::FTGLPixmapFont( const char* fontFilePath) : FTFont( fontFilePath) {} FTGLPixmapFont::FTGLPixmapFont( const unsigned char *pBufferBytes, size_t bufferSizeInBytes) : FTFont( pBufferBytes, bufferSizeInBytes) {} FTGLPixmapFont::~FTGLPixmapFont() {} FTGlyph* FTGLPixmapFont::MakeGlyph( unsigned int g) { FT_GlyphSlot ftGlyph = face.Glyph( g, FT_LOAD_NO_HINTING); if( ftGlyph) { FTPixmapGlyph* tempGlyph = new FTPixmapGlyph( ftGlyph); return tempGlyph; } err = face.Error(); return NULL; } void FTGLPixmapFont::Render( const char* string) { glPushAttrib( GL_ENABLE_BIT | GL_PIXEL_MODE_BIT | GL_COLOR_BUFFER_BIT); glPushClientAttrib( GL_CLIENT_PIXEL_STORE_BIT); glEnable(GL_BLEND); glBlendFunc( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glDisable( GL_TEXTURE_2D); GLfloat ftglColour[4]; glGetFloatv( GL_CURRENT_RASTER_COLOR, ftglColour); glPixelTransferf(GL_RED_SCALE, ftglColour[0]); glPixelTransferf(GL_GREEN_SCALE, ftglColour[1]); glPixelTransferf(GL_BLUE_SCALE, ftglColour[2]); glPixelTransferf(GL_ALPHA_SCALE, ftglColour[3]); FTFont::Render( string); glPopClientAttrib(); glPopAttrib(); } void FTGLPixmapFont::Render( const wchar_t* string) { glPushAttrib( GL_ENABLE_BIT | GL_PIXEL_MODE_BIT | GL_COLOR_BUFFER_BIT); glPushClientAttrib( GL_CLIENT_PIXEL_STORE_BIT); glEnable(GL_BLEND); glBlendFunc( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glDisable( GL_TEXTURE_2D); GLfloat ftglColour[4]; glGetFloatv( GL_CURRENT_RASTER_COLOR, ftglColour); glPixelTransferf(GL_RED_SCALE, ftglColour[0]); glPixelTransferf(GL_GREEN_SCALE, ftglColour[1]); glPixelTransferf(GL_BLUE_SCALE, ftglColour[2]); glPixelTransferf(GL_ALPHA_SCALE, ftglColour[3]); FTFont::Render( string); glPopClientAttrib(); glPopAttrib(); }
26.232323
92
0.741625
[ "render" ]
60660764f2c6e915f5997d121fe2ced8800b090c
2,446
cpp
C++
ex4/surf/main.cpp
jmichael16/ECEN5763_EMVIA
50b4916cc5e3b08f586b71a158cad20d235fe942
[ "MIT" ]
1
2021-06-08T19:03:03.000Z
2021-06-08T19:03:03.000Z
ex4/surf/main.cpp
jmichael16/ECEN5763_EMVIA
50b4916cc5e3b08f586b71a158cad20d235fe942
[ "MIT" ]
null
null
null
ex4/surf/main.cpp
jmichael16/ECEN5763_EMVIA
50b4916cc5e3b08f586b71a158cad20d235fe942
[ "MIT" ]
null
null
null
#include <iostream> #include "opencv2/core.hpp" #ifdef HAVE_OPENCV_XFEATURES2D #include "opencv2/highgui.hpp" #include "opencv2/features2d.hpp" #include "opencv2/xfeatures2d.hpp" using namespace cv; using namespace cv::xfeatures2d; using std::cout; using std::endl; // Note: changed to positional args const char* keys = "{help h usage ? || Print help message. }" "{@input1 || Path to input image 1. }" "{@input2 || Path to input image 2. }"; int main( int argc, char* argv[] ) { CommandLineParser parser( argc, argv, keys ); Mat img1 = imread( parser.get<String>(0), IMREAD_GRAYSCALE ); Mat img2 = imread( parser.get<String>(1), IMREAD_GRAYSCALE ); if ( img1.empty() || img2.empty() ) { cout << "Could not open or find the image!\n" << endl; parser.printMessage(); return -1; } //-- Step 1: Detect the keypoints using SURF Detector, compute the descriptors int minHessian = 400; Ptr<SURF> detector = SURF::create( minHessian ); std::vector<KeyPoint> keypoints1, keypoints2; Mat descriptors1, descriptors2; detector->detectAndCompute( img1, noArray(), keypoints1, descriptors1 ); detector->detectAndCompute( img2, noArray(), keypoints2, descriptors2 ); //-- Step 2: Matching descriptor vectors with a FLANN based matcher // Since SURF is a floating-point descriptor NORM_L2 is used Ptr<DescriptorMatcher> matcher = DescriptorMatcher::create(DescriptorMatcher::FLANNBASED); std::vector< std::vector<DMatch> > knn_matches; matcher->knnMatch( descriptors1, descriptors2, knn_matches, 2 ); //-- Filter matches using the Lowe's ratio test const float ratio_thresh = 0.7f; std::vector<DMatch> good_matches; for (size_t i = 0; i < knn_matches.size(); i++) { if (knn_matches[i][0].distance < ratio_thresh * knn_matches[i][1].distance) { good_matches.push_back(knn_matches[i][0]); } } //-- Draw matches Mat img_matches; drawMatches( img1, keypoints1, img2, keypoints2, good_matches, img_matches, Scalar::all(-1), Scalar::all(-1), std::vector<char>(), DrawMatchesFlags::NOT_DRAW_SINGLE_POINTS ); //-- Show detected matches imshow("Good Matches", img_matches ); while( waitKey() != 'q') {} return 0; } #else int main() { std::cout << "This tutorial code needs the xfeatures2d contrib module to be run." << std::endl; return 0; } #endif
37.630769
99
0.663941
[ "vector" ]
60664f1c2bb8d8cb98798a99393c82c85c27b31b
11,282
cc
C++
tensorflow/core/kernels/data/experimental/auto_shard_dataset_op_test.cc
uve/tensorflow
e08079463bf43e5963acc41da1f57e95603f8080
[ "Apache-2.0" ]
null
null
null
tensorflow/core/kernels/data/experimental/auto_shard_dataset_op_test.cc
uve/tensorflow
e08079463bf43e5963acc41da1f57e95603f8080
[ "Apache-2.0" ]
null
null
null
tensorflow/core/kernels/data/experimental/auto_shard_dataset_op_test.cc
uve/tensorflow
e08079463bf43e5963acc41da1f57e95603f8080
[ "Apache-2.0" ]
null
null
null
/* Copyright 2019 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include "tensorflow/core/kernels/data/experimental/auto_shard_dataset_op.h" #include "tensorflow/core/kernels/data/dataset_test_base.h" #include "tensorflow/core/kernels/data/shard_dataset_op.h" namespace tensorflow { namespace data { namespace experimental { namespace { constexpr char kNodeName[] = "auto_shard_dataset"; constexpr char kIteratorPrefix[] = "Iterator"; class AutoShardDatasetOpTest : public DatasetOpsTestBase { protected: // Creates a new `AutoShardDataset` op kernel. Status CreateAutoShardDatasetOpKernel( const DataTypeVector& output_types, const std::vector<PartialTensorShape>& output_shapes, std::unique_ptr<OpKernel>* op_kernel) { NodeDef node_def = test::function::NDef( kNodeName, name_utils::OpName(AutoShardDatasetOp::kDatasetType), {AutoShardDatasetOp::kInputDataset, AutoShardDatasetOp::kNumWorkers, AutoShardDatasetOp::kIndex}, {{AutoShardDatasetOp::kOutputTypes, output_types}, {AutoShardDatasetOp::kOutputShapes, output_shapes}}); TF_RETURN_IF_ERROR(CreateOpKernel(node_def, op_kernel)); return Status::OK(); } // Create a new `AutoShardDataset` op kernel context Status CreateAutoShardDatasetContext( OpKernel* const op_kernel, gtl::InlinedVector<TensorValue, 4>* const inputs, std::unique_ptr<OpKernelContext>* context) { TF_RETURN_IF_ERROR(CheckOpKernelInput(*op_kernel, *inputs)); TF_RETURN_IF_ERROR(CreateOpKernelContext(op_kernel, inputs, context)); return Status::OK(); } }; struct TestCase { TestCase(int64 start, int64 stop, int64 step, int64 num_workers, int64 index, std::vector<Tensor> expected_outputs, DataTypeVector expected_output_dtypes, std::vector<PartialTensorShape> expected_output_shapes, int64 expected_cardinality, std::vector<int> breakpoints) : start(CreateTensor<int64>(TensorShape({}), {start})), stop(CreateTensor<int64>(TensorShape({}), {stop})), step(CreateTensor<int64>(TensorShape({}), {step})), num_workers(CreateTensor<int64>(TensorShape({}), {num_workers})), index(CreateTensor<int64>(TensorShape({}), {index})), expected_outputs(std::move(expected_outputs)), expected_output_dtypes(std::move(expected_output_dtypes)), expected_output_shapes(std::move(expected_output_shapes)), expected_cardinality(expected_cardinality), breakpoints(std::move(breakpoints)) {} Tensor start; Tensor stop; Tensor step; Tensor num_workers; Tensor index; std::vector<Tensor> expected_outputs; DataTypeVector expected_output_dtypes; std::vector<PartialTensorShape> expected_output_shapes; int64 expected_cardinality; std::vector<int> breakpoints; }; // Test Case 1: simple case. TestCase SimpleCase() { return {/*start=*/0, /*stop=*/10, /*step=*/1, /*num_workers=*/5, /*index=*/2, /*expected_outputs=*/ {CreateTensor<int64>(TensorShape({}), {2}), CreateTensor<int64>(TensorShape({}), {7})}, /*expected_output_dtypes=*/{DT_INT64}, /*expected_output_shapes=*/{PartialTensorShape({})}, /*expected_cardinality=*/2, /*breakpoints=*/{0, 1, 5}}; } // Test Case 2: the index is larger than the available elements. TestCase IndexLargerThanAvailableElementsCase() { return {/*start=*/0, /*stop=*/1, /*step=*/1, /*num_workers=*/5, /*index=*/2, /*expected_outputs=*/{}, /*expected_output_dtypes=*/{DT_INT64}, /*expected_output_shapes=*/{PartialTensorShape({})}, /*expected_cardinality=*/2, /*breakpoints=*/{0, 1}}; } // Test Case 3: the number of outputs could not be evenly divided by // num_workers. TestCase ElementsUnequallyDividedCase() { return {/*start=*/0, /*stop=*/10, /*step=*/1, /*num_workers=*/4, /*index=*/3, /*expected_outputs=*/ {CreateTensor<int64>(TensorShape({}), {3}), CreateTensor<int64>(TensorShape({}), {7})}, /*expected_output_dtypes=*/{DT_INT64}, /*expected_output_shapes=*/{PartialTensorShape({})}, /*expected_cardinality=*/2, /*breakpoints=*/{0, 1, 5}}; } // TODO(feihugis): add more test cases that have ReaderDatasets (e.g. a // CSVDataset or a TFRecordDataset) in the pipeline. TestCase IndexGreaterNumWorkersCase() { return {/*start=*/0, /*stop=*/10, /*step=*/1, /*num_workers=*/5, /*index=*/7, /*expected_outputs=*/{}, /*expected_output_dtypes=*/{DT_INT64}, /*expected_output_shapes=*/{PartialTensorShape({})}, /*expected_cardinality=*/0, /*breakpoints=*/{}}; } TestCase NegativeIndexTestCase() { return {/*start=*/0, /*stop=*/10, /*step=*/1, /*num_workers=*/5, /*index=*/-3, /*expected_outputs=*/{}, /*expected_output_dtypes=*/{DT_INT64}, /*expected_output_shapes=*/{PartialTensorShape({})}, /*expected_cardinality=*/0, /*breakpoints=*/{}}; } TestCase NegativeNumWorkersTestCase() { return {/*start=*/0, /*stop=*/10, /*step=*/1, /*num_workers=*/-3, /*index=*/1, /*expected_outputs=*/{}, /*expected_output_dtypes=*/{DT_INT64}, /*expected_output_shapes=*/{PartialTensorShape({})}, /*expected_cardinality=*/0, /*breakpoints=*/{}}; } TestCase ZeroNumWorkersTestCase() { return {/*start=*/0, /*stop=*/10, /*step=*/1, /*num_workers=*/0, /*index=*/1, /*expected_outputs=*/{}, /*expected_output_dtypes=*/{DT_INT64}, /*expected_output_shapes=*/{PartialTensorShape({})}, /*expected_cardinality=*/0, /*breakpoints=*/{}}; } class ParameterizedAutoShardDatasetOpTest : public AutoShardDatasetOpTest, public ::testing::WithParamInterface<TestCase> {}; TEST_P(ParameterizedAutoShardDatasetOpTest, GetNext) { int thread_num = 2, cpu_num = 2; TestCase test_case = GetParam(); TF_ASSERT_OK(InitThreadPool(thread_num)); TF_ASSERT_OK(InitFunctionLibraryRuntime({}, cpu_num)); std::unique_ptr<OpKernel> auto_shard_dataset_kernel; TF_ASSERT_OK(CreateAutoShardDatasetOpKernel(test_case.expected_output_dtypes, test_case.expected_output_shapes, &auto_shard_dataset_kernel)); Tensor range_dataset_tensor(DT_VARIANT, TensorShape({})); TF_ASSERT_OK(MakeRangeDataset(test_case.start, test_case.stop, test_case.step, {DT_INT64}, {TensorShape({})}, &range_dataset_tensor)); gtl::InlinedVector<TensorValue, 4> inputs( {TensorValue(&range_dataset_tensor), TensorValue(&test_case.num_workers), TensorValue(&test_case.index)}); std::unique_ptr<OpKernelContext> auto_shard_dataset_context; TF_ASSERT_OK(CreateAutoShardDatasetContext( auto_shard_dataset_kernel.get(), &inputs, &auto_shard_dataset_context)); DatasetBase* auto_shard_dataset; TF_ASSERT_OK(CreateDataset(auto_shard_dataset_kernel.get(), auto_shard_dataset_context.get(), &auto_shard_dataset)); core::ScopedUnref scoped_unref_auto_shard_dataset(auto_shard_dataset); std::unique_ptr<IteratorContext> iterator_ctx; TF_ASSERT_OK( CreateIteratorContext(auto_shard_dataset_context.get(), &iterator_ctx)); std::unique_ptr<IteratorBase> iterator; TF_ASSERT_OK(auto_shard_dataset->MakeIterator(iterator_ctx.get(), kIteratorPrefix, &iterator)); bool end_of_sequence = false; auto expected_outputs_it = test_case.expected_outputs.begin(); std::vector<Tensor> out_tensors; while (!end_of_sequence) { TF_EXPECT_OK( iterator->GetNext(iterator_ctx.get(), &out_tensors, &end_of_sequence)); if (!end_of_sequence) { EXPECT_LT(expected_outputs_it, test_case.expected_outputs.end()); TF_EXPECT_OK(ExpectEqual(out_tensors.back(), *expected_outputs_it)); expected_outputs_it++; } } EXPECT_EQ(expected_outputs_it, test_case.expected_outputs.end()); } INSTANTIATE_TEST_SUITE_P(AutoShardDatasetOpTest, ParameterizedAutoShardDatasetOpTest, ::testing::ValuesIn(std::vector<TestCase>( {SimpleCase(), IndexLargerThanAvailableElementsCase(), ElementsUnequallyDividedCase()}))); TEST_F(AutoShardDatasetOpTest, InvalidArguments) { int thread_num = 2, cpu_num = 2; TF_ASSERT_OK(InitThreadPool(thread_num)); TF_ASSERT_OK(InitFunctionLibraryRuntime({}, cpu_num)); std::vector<TestCase> test_cases = { IndexGreaterNumWorkersCase(), NegativeIndexTestCase(), NegativeNumWorkersTestCase(), ZeroNumWorkersTestCase()}; for (auto& test_case : test_cases) { std::unique_ptr<OpKernel> auto_shard_dataset_kernel; TF_ASSERT_OK(CreateAutoShardDatasetOpKernel( test_case.expected_output_dtypes, test_case.expected_output_shapes, &auto_shard_dataset_kernel)); Tensor range_dataset_tensor(DT_VARIANT, TensorShape({})); TF_ASSERT_OK(MakeRangeDataset(test_case.start, test_case.stop, test_case.step, {DT_INT64}, {TensorShape({})}, &range_dataset_tensor)); gtl::InlinedVector<TensorValue, 4> inputs( {TensorValue(&range_dataset_tensor), TensorValue(&test_case.num_workers), TensorValue(&test_case.index)}); std::unique_ptr<OpKernelContext> auto_shard_dataset_context; TF_ASSERT_OK(CreateAutoShardDatasetContext( auto_shard_dataset_kernel.get(), &inputs, &auto_shard_dataset_context)); DatasetBase* auto_shard_dataset; EXPECT_EQ( CreateDataset(auto_shard_dataset_kernel.get(), auto_shard_dataset_context.get(), &auto_shard_dataset) .code(), tensorflow::error::INVALID_ARGUMENT); } } } // namespace } // namespace experimental } // namespace data } // namespace tensorflow
39.865724
81
0.637653
[ "vector" ]
60665c2403c11359783c5fe7ab911823e0e27e08
18,577
cc
C++
wrappers/8.1.1/vtkAbstractInterpolatedVelocityFieldWrap.cc
axkibe/node-vtk
900ad7b5500f672519da5aa24c99aa5a96466ef3
[ "BSD-3-Clause" ]
6
2016-02-03T12:48:36.000Z
2020-09-16T15:07:51.000Z
wrappers/8.1.1/vtkAbstractInterpolatedVelocityFieldWrap.cc
axkibe/node-vtk
900ad7b5500f672519da5aa24c99aa5a96466ef3
[ "BSD-3-Clause" ]
4
2016-02-13T01:30:43.000Z
2020-03-30T16:59:32.000Z
wrappers/8.1.1/vtkAbstractInterpolatedVelocityFieldWrap.cc
axkibe/node-vtk
900ad7b5500f672519da5aa24c99aa5a96466ef3
[ "BSD-3-Clause" ]
null
null
null
/* this file has been autogenerated by vtkNodeJsWrap */ /* editing this might proof futile */ #define VTK_WRAPPING_CXX #define VTK_STREAMS_FWD_ONLY #include <nan.h> #include "vtkFunctionSetWrap.h" #include "vtkAbstractInterpolatedVelocityFieldWrap.h" #include "vtkObjectBaseWrap.h" #include "vtkDataSetWrap.h" #include "../../plus/plus.h" using namespace v8; extern Nan::Persistent<v8::Object> vtkNodeJsNoWrap; Nan::Persistent<v8::FunctionTemplate> VtkAbstractInterpolatedVelocityFieldWrap::ptpl; VtkAbstractInterpolatedVelocityFieldWrap::VtkAbstractInterpolatedVelocityFieldWrap() { } VtkAbstractInterpolatedVelocityFieldWrap::VtkAbstractInterpolatedVelocityFieldWrap(vtkSmartPointer<vtkAbstractInterpolatedVelocityField> _native) { native = _native; } VtkAbstractInterpolatedVelocityFieldWrap::~VtkAbstractInterpolatedVelocityFieldWrap() { } void VtkAbstractInterpolatedVelocityFieldWrap::Init(v8::Local<v8::Object> exports) { Nan::SetAccessor(exports, Nan::New("vtkAbstractInterpolatedVelocityField").ToLocalChecked(), ConstructorGetter); Nan::SetAccessor(exports, Nan::New("AbstractInterpolatedVelocityField").ToLocalChecked(), ConstructorGetter); } void VtkAbstractInterpolatedVelocityFieldWrap::ConstructorGetter( v8::Local<v8::String> property, const Nan::PropertyCallbackInfo<v8::Value>& info) { InitPtpl(); info.GetReturnValue().Set(Nan::New(ptpl)->GetFunction()); } void VtkAbstractInterpolatedVelocityFieldWrap::InitPtpl() { if (!ptpl.IsEmpty()) return; v8::Local<v8::FunctionTemplate> tpl = Nan::New<v8::FunctionTemplate>(New); VtkFunctionSetWrap::InitPtpl( ); tpl->Inherit(Nan::New<FunctionTemplate>(VtkFunctionSetWrap::ptpl)); tpl->SetClassName(Nan::New("VtkAbstractInterpolatedVelocityFieldWrap").ToLocalChecked()); tpl->InstanceTemplate()->SetInternalFieldCount(1); Nan::SetPrototypeMethod(tpl, "ClearLastCellId", ClearLastCellId); Nan::SetPrototypeMethod(tpl, "clearLastCellId", ClearLastCellId); Nan::SetPrototypeMethod(tpl, "CopyParameters", CopyParameters); Nan::SetPrototypeMethod(tpl, "copyParameters", CopyParameters); Nan::SetPrototypeMethod(tpl, "GetCacheHit", GetCacheHit); Nan::SetPrototypeMethod(tpl, "getCacheHit", GetCacheHit); Nan::SetPrototypeMethod(tpl, "GetCacheMiss", GetCacheMiss); Nan::SetPrototypeMethod(tpl, "getCacheMiss", GetCacheMiss); Nan::SetPrototypeMethod(tpl, "GetCaching", GetCaching); Nan::SetPrototypeMethod(tpl, "getCaching", GetCaching); Nan::SetPrototypeMethod(tpl, "GetForceSurfaceTangentVector", GetForceSurfaceTangentVector); Nan::SetPrototypeMethod(tpl, "getForceSurfaceTangentVector", GetForceSurfaceTangentVector); Nan::SetPrototypeMethod(tpl, "GetLastDataSet", GetLastDataSet); Nan::SetPrototypeMethod(tpl, "getLastDataSet", GetLastDataSet); Nan::SetPrototypeMethod(tpl, "GetLastLocalCoordinates", GetLastLocalCoordinates); Nan::SetPrototypeMethod(tpl, "getLastLocalCoordinates", GetLastLocalCoordinates); Nan::SetPrototypeMethod(tpl, "GetNormalizeVector", GetNormalizeVector); Nan::SetPrototypeMethod(tpl, "getNormalizeVector", GetNormalizeVector); Nan::SetPrototypeMethod(tpl, "GetSurfaceDataset", GetSurfaceDataset); Nan::SetPrototypeMethod(tpl, "getSurfaceDataset", GetSurfaceDataset); Nan::SetPrototypeMethod(tpl, "GetVectorsSelection", GetVectorsSelection); Nan::SetPrototypeMethod(tpl, "getVectorsSelection", GetVectorsSelection); Nan::SetPrototypeMethod(tpl, "GetVectorsType", GetVectorsType); Nan::SetPrototypeMethod(tpl, "getVectorsType", GetVectorsType); Nan::SetPrototypeMethod(tpl, "NewInstance", NewInstance); Nan::SetPrototypeMethod(tpl, "newInstance", NewInstance); Nan::SetPrototypeMethod(tpl, "SafeDownCast", SafeDownCast); Nan::SetPrototypeMethod(tpl, "safeDownCast", SafeDownCast); Nan::SetPrototypeMethod(tpl, "SelectVectors", SelectVectors); Nan::SetPrototypeMethod(tpl, "selectVectors", SelectVectors); Nan::SetPrototypeMethod(tpl, "SetCaching", SetCaching); Nan::SetPrototypeMethod(tpl, "setCaching", SetCaching); Nan::SetPrototypeMethod(tpl, "SetForceSurfaceTangentVector", SetForceSurfaceTangentVector); Nan::SetPrototypeMethod(tpl, "setForceSurfaceTangentVector", SetForceSurfaceTangentVector); Nan::SetPrototypeMethod(tpl, "SetNormalizeVector", SetNormalizeVector); Nan::SetPrototypeMethod(tpl, "setNormalizeVector", SetNormalizeVector); Nan::SetPrototypeMethod(tpl, "SetSurfaceDataset", SetSurfaceDataset); Nan::SetPrototypeMethod(tpl, "setSurfaceDataset", SetSurfaceDataset); #ifdef VTK_NODE_PLUS_VTKABSTRACTINTERPOLATEDVELOCITYFIELDWRAP_INITPTPL VTK_NODE_PLUS_VTKABSTRACTINTERPOLATEDVELOCITYFIELDWRAP_INITPTPL #endif ptpl.Reset( tpl ); } void VtkAbstractInterpolatedVelocityFieldWrap::New(const Nan::FunctionCallbackInfo<v8::Value>& info) { if(!info.IsConstructCall()) { Nan::ThrowError("Constructor not called in a construct call."); return; } if(info.Length() == 0) { Nan::ThrowError("Cannot create instance of abstract class."); return; } else { if(info[0]->ToObject() != vtkNodeJsNoWrap ) { Nan::ThrowError("Parameter Error"); return; } } info.GetReturnValue().Set(info.This()); } void VtkAbstractInterpolatedVelocityFieldWrap::ClearLastCellId(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkAbstractInterpolatedVelocityFieldWrap *wrapper = ObjectWrap::Unwrap<VtkAbstractInterpolatedVelocityFieldWrap>(info.Holder()); vtkAbstractInterpolatedVelocityField *native = (vtkAbstractInterpolatedVelocityField *)wrapper->native.GetPointer(); if(info.Length() != 0) { Nan::ThrowError("Too many parameters."); return; } native->ClearLastCellId(); } void VtkAbstractInterpolatedVelocityFieldWrap::CopyParameters(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkAbstractInterpolatedVelocityFieldWrap *wrapper = ObjectWrap::Unwrap<VtkAbstractInterpolatedVelocityFieldWrap>(info.Holder()); vtkAbstractInterpolatedVelocityField *native = (vtkAbstractInterpolatedVelocityField *)wrapper->native.GetPointer(); if(info.Length() > 0 && info[0]->IsObject() && (Nan::New(VtkAbstractInterpolatedVelocityFieldWrap::ptpl))->HasInstance(info[0])) { VtkAbstractInterpolatedVelocityFieldWrap *a0 = ObjectWrap::Unwrap<VtkAbstractInterpolatedVelocityFieldWrap>(info[0]->ToObject()); if(info.Length() != 1) { Nan::ThrowError("Too many parameters."); return; } native->CopyParameters( (vtkAbstractInterpolatedVelocityField *) a0->native.GetPointer() ); return; } Nan::ThrowError("Parameter mismatch"); } void VtkAbstractInterpolatedVelocityFieldWrap::GetCacheHit(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkAbstractInterpolatedVelocityFieldWrap *wrapper = ObjectWrap::Unwrap<VtkAbstractInterpolatedVelocityFieldWrap>(info.Holder()); vtkAbstractInterpolatedVelocityField *native = (vtkAbstractInterpolatedVelocityField *)wrapper->native.GetPointer(); int r; if(info.Length() != 0) { Nan::ThrowError("Too many parameters."); return; } r = native->GetCacheHit(); info.GetReturnValue().Set(Nan::New(r)); } void VtkAbstractInterpolatedVelocityFieldWrap::GetCacheMiss(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkAbstractInterpolatedVelocityFieldWrap *wrapper = ObjectWrap::Unwrap<VtkAbstractInterpolatedVelocityFieldWrap>(info.Holder()); vtkAbstractInterpolatedVelocityField *native = (vtkAbstractInterpolatedVelocityField *)wrapper->native.GetPointer(); int r; if(info.Length() != 0) { Nan::ThrowError("Too many parameters."); return; } r = native->GetCacheMiss(); info.GetReturnValue().Set(Nan::New(r)); } void VtkAbstractInterpolatedVelocityFieldWrap::GetCaching(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkAbstractInterpolatedVelocityFieldWrap *wrapper = ObjectWrap::Unwrap<VtkAbstractInterpolatedVelocityFieldWrap>(info.Holder()); vtkAbstractInterpolatedVelocityField *native = (vtkAbstractInterpolatedVelocityField *)wrapper->native.GetPointer(); bool r; if(info.Length() != 0) { Nan::ThrowError("Too many parameters."); return; } r = native->GetCaching(); info.GetReturnValue().Set(Nan::New(r)); } void VtkAbstractInterpolatedVelocityFieldWrap::GetForceSurfaceTangentVector(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkAbstractInterpolatedVelocityFieldWrap *wrapper = ObjectWrap::Unwrap<VtkAbstractInterpolatedVelocityFieldWrap>(info.Holder()); vtkAbstractInterpolatedVelocityField *native = (vtkAbstractInterpolatedVelocityField *)wrapper->native.GetPointer(); bool r; if(info.Length() != 0) { Nan::ThrowError("Too many parameters."); return; } r = native->GetForceSurfaceTangentVector(); info.GetReturnValue().Set(Nan::New(r)); } void VtkAbstractInterpolatedVelocityFieldWrap::GetLastDataSet(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkAbstractInterpolatedVelocityFieldWrap *wrapper = ObjectWrap::Unwrap<VtkAbstractInterpolatedVelocityFieldWrap>(info.Holder()); vtkAbstractInterpolatedVelocityField *native = (vtkAbstractInterpolatedVelocityField *)wrapper->native.GetPointer(); vtkDataSet * r; if(info.Length() != 0) { Nan::ThrowError("Too many parameters."); return; } r = native->GetLastDataSet(); VtkDataSetWrap::InitPtpl(); v8::Local<v8::Value> argv[1] = { Nan::New(vtkNodeJsNoWrap) }; v8::Local<v8::Function> cons = Nan::New<v8::FunctionTemplate>(VtkDataSetWrap::ptpl)->GetFunction(); v8::Local<v8::Object> wo = cons->NewInstance(1, argv); VtkDataSetWrap *w = new VtkDataSetWrap(); w->native = r; w->Wrap(wo); info.GetReturnValue().Set(wo); } void VtkAbstractInterpolatedVelocityFieldWrap::GetLastLocalCoordinates(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkAbstractInterpolatedVelocityFieldWrap *wrapper = ObjectWrap::Unwrap<VtkAbstractInterpolatedVelocityFieldWrap>(info.Holder()); vtkAbstractInterpolatedVelocityField *native = (vtkAbstractInterpolatedVelocityField *)wrapper->native.GetPointer(); size_t i; if(info.Length() > 0 && info[0]->IsFloat64Array()) { v8::Local<v8::Float64Array>a0(v8::Local<v8::Float64Array>::Cast(info[0]->ToObject())); if( a0->Length() < 3 ) { Nan::ThrowError("Array too short."); return; } int r; if(info.Length() != 1) { Nan::ThrowError("Too many parameters."); return; } r = native->GetLastLocalCoordinates( (double *)(a0->Buffer()->GetContents().Data()) ); info.GetReturnValue().Set(Nan::New(r)); return; } else if(info.Length() > 0 && info[0]->IsArray()) { v8::Local<v8::Array>a0(v8::Local<v8::Array>::Cast(info[0]->ToObject())); double b0[3]; if( a0->Length() < 3 ) { Nan::ThrowError("Array too short."); return; } for( i = 0; i < 3; i++ ) { if( !a0->Get(i)->IsNumber() ) { Nan::ThrowError("Array contents invalid."); return; } b0[i] = a0->Get(i)->NumberValue(); } int r; if(info.Length() != 1) { Nan::ThrowError("Too many parameters."); return; } r = native->GetLastLocalCoordinates( b0 ); info.GetReturnValue().Set(Nan::New(r)); return; } Nan::ThrowError("Parameter mismatch"); } void VtkAbstractInterpolatedVelocityFieldWrap::GetNormalizeVector(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkAbstractInterpolatedVelocityFieldWrap *wrapper = ObjectWrap::Unwrap<VtkAbstractInterpolatedVelocityFieldWrap>(info.Holder()); vtkAbstractInterpolatedVelocityField *native = (vtkAbstractInterpolatedVelocityField *)wrapper->native.GetPointer(); bool r; if(info.Length() != 0) { Nan::ThrowError("Too many parameters."); return; } r = native->GetNormalizeVector(); info.GetReturnValue().Set(Nan::New(r)); } void VtkAbstractInterpolatedVelocityFieldWrap::GetSurfaceDataset(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkAbstractInterpolatedVelocityFieldWrap *wrapper = ObjectWrap::Unwrap<VtkAbstractInterpolatedVelocityFieldWrap>(info.Holder()); vtkAbstractInterpolatedVelocityField *native = (vtkAbstractInterpolatedVelocityField *)wrapper->native.GetPointer(); bool r; if(info.Length() != 0) { Nan::ThrowError("Too many parameters."); return; } r = native->GetSurfaceDataset(); info.GetReturnValue().Set(Nan::New(r)); } void VtkAbstractInterpolatedVelocityFieldWrap::GetVectorsSelection(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkAbstractInterpolatedVelocityFieldWrap *wrapper = ObjectWrap::Unwrap<VtkAbstractInterpolatedVelocityFieldWrap>(info.Holder()); vtkAbstractInterpolatedVelocityField *native = (vtkAbstractInterpolatedVelocityField *)wrapper->native.GetPointer(); char const * r; if(info.Length() != 0) { Nan::ThrowError("Too many parameters."); return; } r = native->GetVectorsSelection(); info.GetReturnValue().Set(Nan::New(r).ToLocalChecked()); } void VtkAbstractInterpolatedVelocityFieldWrap::GetVectorsType(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkAbstractInterpolatedVelocityFieldWrap *wrapper = ObjectWrap::Unwrap<VtkAbstractInterpolatedVelocityFieldWrap>(info.Holder()); vtkAbstractInterpolatedVelocityField *native = (vtkAbstractInterpolatedVelocityField *)wrapper->native.GetPointer(); int r; if(info.Length() != 0) { Nan::ThrowError("Too many parameters."); return; } r = native->GetVectorsType(); info.GetReturnValue().Set(Nan::New(r)); } void VtkAbstractInterpolatedVelocityFieldWrap::NewInstance(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkAbstractInterpolatedVelocityFieldWrap *wrapper = ObjectWrap::Unwrap<VtkAbstractInterpolatedVelocityFieldWrap>(info.Holder()); vtkAbstractInterpolatedVelocityField *native = (vtkAbstractInterpolatedVelocityField *)wrapper->native.GetPointer(); vtkAbstractInterpolatedVelocityField * r; if(info.Length() != 0) { Nan::ThrowError("Too many parameters."); return; } r = native->NewInstance(); VtkAbstractInterpolatedVelocityFieldWrap::InitPtpl(); v8::Local<v8::Value> argv[1] = { Nan::New(vtkNodeJsNoWrap) }; v8::Local<v8::Function> cons = Nan::New<v8::FunctionTemplate>(VtkAbstractInterpolatedVelocityFieldWrap::ptpl)->GetFunction(); v8::Local<v8::Object> wo = cons->NewInstance(1, argv); VtkAbstractInterpolatedVelocityFieldWrap *w = new VtkAbstractInterpolatedVelocityFieldWrap(); w->native = r; w->Wrap(wo); info.GetReturnValue().Set(wo); } void VtkAbstractInterpolatedVelocityFieldWrap::SafeDownCast(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkAbstractInterpolatedVelocityFieldWrap *wrapper = ObjectWrap::Unwrap<VtkAbstractInterpolatedVelocityFieldWrap>(info.Holder()); vtkAbstractInterpolatedVelocityField *native = (vtkAbstractInterpolatedVelocityField *)wrapper->native.GetPointer(); if(info.Length() > 0 && info[0]->IsObject() && (Nan::New(VtkObjectBaseWrap::ptpl))->HasInstance(info[0])) { VtkObjectBaseWrap *a0 = ObjectWrap::Unwrap<VtkObjectBaseWrap>(info[0]->ToObject()); vtkAbstractInterpolatedVelocityField * r; if(info.Length() != 1) { Nan::ThrowError("Too many parameters."); return; } r = native->SafeDownCast( (vtkObjectBase *) a0->native.GetPointer() ); VtkAbstractInterpolatedVelocityFieldWrap::InitPtpl(); v8::Local<v8::Value> argv[1] = { Nan::New(vtkNodeJsNoWrap) }; v8::Local<v8::Function> cons = Nan::New<v8::FunctionTemplate>(VtkAbstractInterpolatedVelocityFieldWrap::ptpl)->GetFunction(); v8::Local<v8::Object> wo = cons->NewInstance(1, argv); VtkAbstractInterpolatedVelocityFieldWrap *w = new VtkAbstractInterpolatedVelocityFieldWrap(); w->native = r; w->Wrap(wo); info.GetReturnValue().Set(wo); return; } Nan::ThrowError("Parameter mismatch"); } void VtkAbstractInterpolatedVelocityFieldWrap::SelectVectors(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkAbstractInterpolatedVelocityFieldWrap *wrapper = ObjectWrap::Unwrap<VtkAbstractInterpolatedVelocityFieldWrap>(info.Holder()); vtkAbstractInterpolatedVelocityField *native = (vtkAbstractInterpolatedVelocityField *)wrapper->native.GetPointer(); if(info.Length() > 0 && info[0]->IsInt32()) { if(info.Length() > 1 && info[1]->IsString()) { Nan::Utf8String a1(info[1]); if(info.Length() != 2) { Nan::ThrowError("Too many parameters."); return; } native->SelectVectors( info[0]->Int32Value(), *a1 ); return; } } Nan::ThrowError("Parameter mismatch"); } void VtkAbstractInterpolatedVelocityFieldWrap::SetCaching(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkAbstractInterpolatedVelocityFieldWrap *wrapper = ObjectWrap::Unwrap<VtkAbstractInterpolatedVelocityFieldWrap>(info.Holder()); vtkAbstractInterpolatedVelocityField *native = (vtkAbstractInterpolatedVelocityField *)wrapper->native.GetPointer(); if(info.Length() > 0 && info[0]->IsBoolean()) { if(info.Length() != 1) { Nan::ThrowError("Too many parameters."); return; } native->SetCaching( info[0]->BooleanValue() ); return; } Nan::ThrowError("Parameter mismatch"); } void VtkAbstractInterpolatedVelocityFieldWrap::SetForceSurfaceTangentVector(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkAbstractInterpolatedVelocityFieldWrap *wrapper = ObjectWrap::Unwrap<VtkAbstractInterpolatedVelocityFieldWrap>(info.Holder()); vtkAbstractInterpolatedVelocityField *native = (vtkAbstractInterpolatedVelocityField *)wrapper->native.GetPointer(); if(info.Length() > 0 && info[0]->IsBoolean()) { if(info.Length() != 1) { Nan::ThrowError("Too many parameters."); return; } native->SetForceSurfaceTangentVector( info[0]->BooleanValue() ); return; } Nan::ThrowError("Parameter mismatch"); } void VtkAbstractInterpolatedVelocityFieldWrap::SetNormalizeVector(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkAbstractInterpolatedVelocityFieldWrap *wrapper = ObjectWrap::Unwrap<VtkAbstractInterpolatedVelocityFieldWrap>(info.Holder()); vtkAbstractInterpolatedVelocityField *native = (vtkAbstractInterpolatedVelocityField *)wrapper->native.GetPointer(); if(info.Length() > 0 && info[0]->IsBoolean()) { if(info.Length() != 1) { Nan::ThrowError("Too many parameters."); return; } native->SetNormalizeVector( info[0]->BooleanValue() ); return; } Nan::ThrowError("Parameter mismatch"); } void VtkAbstractInterpolatedVelocityFieldWrap::SetSurfaceDataset(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkAbstractInterpolatedVelocityFieldWrap *wrapper = ObjectWrap::Unwrap<VtkAbstractInterpolatedVelocityFieldWrap>(info.Holder()); vtkAbstractInterpolatedVelocityField *native = (vtkAbstractInterpolatedVelocityField *)wrapper->native.GetPointer(); if(info.Length() > 0 && info[0]->IsBoolean()) { if(info.Length() != 1) { Nan::ThrowError("Too many parameters."); return; } native->SetSurfaceDataset( info[0]->BooleanValue() ); return; } Nan::ThrowError("Parameter mismatch"); }
35.725
145
0.763256
[ "object" ]
6067491eccb09c6e0594b70286137172175e8737
7,189
hpp
C++
include/pypp/posix/path.hpp
mdklatt/pypp
4b17bdf8d57b777d6f22c0f359ce5e93bd81c5bc
[ "MIT" ]
null
null
null
include/pypp/posix/path.hpp
mdklatt/pypp
4b17bdf8d57b777d6f22c0f359ce5e93bd81c5bc
[ "MIT" ]
null
null
null
include/pypp/posix/path.hpp
mdklatt/pypp
4b17bdf8d57b777d6f22c0f359ce5e93bd81c5bc
[ "MIT" ]
null
null
null
/** * Common file path manipulations for POSIX platforms. * * This combines functionality from the Python os.path and pathlib modules. * * @file */ #ifndef PYPP_POSIX_PATH_HPP #define PYPP_POSIX_PATH_HPP #include <fstream> #include <string> #include <utility> #include <vector> #include "pypp/path.hpp" namespace pypp { namespace path { /// /// class PosixPath { public: /// Represent the path as a std::string. /// /// @return string representation explicit operator std::string() const; /// Determine if the path is absolute. /// /// @return true if this is an absolute path bool is_absolute() const; /// Get the final path component. /// /// @return name std::string name() const; /// Split the path into its component parts. /// /// @return path parts const std::vector<std::string>& parts() const; /// Get the path root (`` or `/`). /// /// @return root std::string root() const; /// Get the path name without its suffix. /// /// @return stem std::string stem() const; /// Get the final file extension for the path name. /// /// @return suffix std::string suffix() const; /// Get all file extensions for the path name. /// /// @return std::vector<std::string> suffixes() const; /// Get the current working directory. /// /// @return path of the current working directory static PosixPath cwd(); /// Create a path object. /// /// @param path path as a string explicit PosixPath(const std::string& path="."); /// Copy constructor. /// /// @param path explicit PosixPath(PurePosixPath path); /// Join this path with another path. /// /// @param path other path to join with /// @return new joined path PosixPath joinpath(const PosixPath& path) const; /// @overload PosixPath joinpath(const std::string& path) const; /// Join this path with another path, /// /// @param path path to join with /// @return new joined path PosixPath operator/(const std::string& path) const; /// @return overload PosixPath operator/(const PosixPath& other) const; /// Join this path in place with another path. /// /// @param other path to join with /// @return modified path PosixPath& operator/=(const std::string& other); /// @overload PosixPath& operator/=(const PosixPath& other); /// Equality operator. /// /// @param other path to compare /// @return true if path is equal to other bool operator==(const PosixPath& other) const; /// Inequality operator. /// /// @param other path to compare /// @return true if path is not equal to other bool operator!=(const PosixPath& other) const; /// Less-than operator. /// /// This a lexical comparison and does not imply anything about directory /// hierarchies. This is mainly intended to allow the use of PosixPath /// objects in contexts that require a sort order. /// /// @param other path to compare /// @return true if path is less than other bool operator<(const PosixPath& other) const; /// Compute the direct parent path. /// /// @return parent path PosixPath parent() const; /// Compute all ancestor paths, starting with the direct parent. /// /// @return ancestor paths std::vector<PosixPath> parents() const; /// Compute a relative path. /// /// @param other parent path /// @return relative path PosixPath relative_to(const PosixPath& other) const; /// Replace the path name. /// /// @return new path PosixPath with_name(const std::string& name) const; /// Replace the path suffix. /// /// @return new path PosixPath with_suffix(const std::string& suffix) const; /// Convert to a PurePath object. /// PurePosixPath pure() const; /// Test for the existence of the path. /// /// @return true if this is an existing file or directory. bool exists() const; /// Test if the path is a valid directory. /// /// @return true for a directory bool is_dir() const; /// Test if the path is a valid file. /// /// @return true for a file bool is_file() const; /// Test if the path is a valid symbolic link. /// /// @return true for a symbolic link bool is_symlink() const; /// Open a file stream for this path. /// /// Unlike the Python version, an exception will not be thrown if the file /// cannot be opened. /// /// @param mode file mode (follows Python conventions) /// @return open file stream std::fstream open(const std::string& mode="rt") const; /// Create a directory at this path. /// /// @param mode permissions for new leaf directory /// @param parents create missing parents as needed /// @param exist_ok no error if directory already exists void mkdir(mode_t mode=0777, bool parents=false, bool exist_ok=false) const; /// Create a symbolic link at this path. /// /// @param target: path to link to void symlink_to(const PosixPath& target) const; /// @overload void symlink_to(const std::string& target) const; /// Remove the file with this path. /// /// Trying to unlink a nonexistent file is an error. Use `rmdir()` to /// remove a directory. /// void unlink() const; /// Remove the directory with this path. /// /// Trying to remove a nonexistent or non-empty directory is an error. Use /// `unlink` to remove a file. /// void rmdir() const; /// Read binary data from a file with this path. /// /// @return binary data std::string read_bytes() const; /// Read text data from a file with this path. /// /// Unlike the Python version, this does not support the `encoding` or /// `errors` parameters. /// /// @return file contents std::string read_text() const; /// Write binary data to a file with this path. /// /// If the file already exists it will be overwritten. /// /// @param data: file contents void write_bytes(const std::string& data) const; /// Write text data to a file with this path. /// /// If the file already exists it will be overwritten. Unlike the Python /// version, this does not support the `enocoding` or `errors` parameters. /// /// @param data: file contents void write_text(const std::string& data) const; /// List all items in the directory with this path. /// /// Unlike Python, this returns a complete sequence, not a generator. /// /// @return std::vector<PosixPath> iterdir() const; private: PurePosixPath base_; /// Read file contents. /// /// @param mode file mode /// @return file contents std::string read_file(const std::string& mode) const; /// Write file contents. /// /// @param mode file mode /// @param data file contents void write_file(const std::string& data, const std::string& mode) const; }; }} // namespace pypp::path #endif // PYPP_POSIX_PATH_HPP
26.333333
80
0.619975
[ "object", "vector" ]
6067bbb6605cc0e2796f63e4bd0527c4231b4d7f
3,659
cpp
C++
benchmark/src/fifo_queue_auto_scaling_benchmark.cpp
charles-typ/jiffy
21803d74af8fff3c4d001e7533ba264dc531e792
[ "Apache-2.0" ]
10
2021-03-04T07:23:24.000Z
2022-03-26T07:36:00.000Z
benchmark/src/fifo_queue_auto_scaling_benchmark.cpp
charles-typ/jiffy
21803d74af8fff3c4d001e7533ba264dc531e792
[ "Apache-2.0" ]
1
2021-03-12T15:20:03.000Z
2021-03-12T15:20:03.000Z
benchmark/src/fifo_queue_auto_scaling_benchmark.cpp
charles-typ/jiffy
21803d74af8fff3c4d001e7533ba264dc531e792
[ "Apache-2.0" ]
7
2021-03-12T05:46:15.000Z
2022-02-14T07:08:01.000Z
#include <vector> #include <thread> #include <boost/program_options.hpp> #include <jiffy/client/jiffy_client.h> #include <jiffy/utils/logger.h> #include <jiffy/utils/signal_handling.h> #include <jiffy/utils/time_utils.h> #include <fstream> #include <atomic> #include <chrono> using namespace ::jiffy::client; using namespace ::jiffy::directory; using namespace ::jiffy::storage; using namespace ::jiffy::utils; using namespace ::apache::thrift; namespace ts = std::chrono; int main() { std::string address = "127.0.0.1"; int service_port = 9090; int lease_port = 9091; int num_blocks = 1; int chain_length = 1; size_t num_ops = 419430; size_t data_size = 102400; std::string op_type = "fifo_queue_auto_scaling"; std::string path = "/tmp"; std::string backing_path = "local://tmp"; // Output all the configuration parameters: LOG(log_level::info) << "host: " << address; LOG(log_level::info) << "service-port: " << service_port; LOG(log_level::info) << "lease-port: " << lease_port; LOG(log_level::info) << "num-blocks: " << num_blocks; LOG(log_level::info) << "chain-length: " << chain_length; LOG(log_level::info) << "num-ops: " << num_ops; LOG(log_level::info) << "data-size: " << data_size; LOG(log_level::info) << "test: " << op_type; LOG(log_level::info) << "path: " << path; LOG(log_level::info) << "backing-path: " << backing_path; jiffy_client client(address, service_port, lease_port); std::shared_ptr<fifo_queue_client> fq_client = client.open_or_create_fifo_queue(path, backing_path, num_blocks, chain_length); std::string data_(data_size, 'x'); std::chrono::milliseconds periodicity_ms_(1000); std::atomic_bool stop_{false}; std::size_t j = 0; auto worker_ = std::thread([&] { std::ofstream out("dataset.trace"); while (!stop_.load()) { auto start = std::chrono::steady_clock::now(); try { auto cur_epoch = ts::duration_cast<ts::milliseconds>(ts::system_clock::now().time_since_epoch()).count(); out << cur_epoch; out << "\t" << j * 100 * 1024; out << std::endl; } catch (std::exception &e) { LOG(log_level::error) << "Exception: " << e.what(); } auto end = std::chrono::steady_clock::now(); auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(end - start); auto time_to_wait = std::chrono::duration_cast<std::chrono::milliseconds>(periodicity_ms_ - elapsed); if (time_to_wait > std::chrono::milliseconds::zero()) { std::this_thread::sleep_for(time_to_wait); } } out.close(); }); std::ofstream out("latency.trace"); uint64_t enqueue_tot_time = 0, enqueue_t0 = 0, enqueue_t1 = 0; for (j = 0; j < num_ops; ++j) { enqueue_t0 = time_utils::now_us(); fq_client->enqueue(data_); enqueue_t1 = time_utils::now_us(); enqueue_tot_time = enqueue_t1 - enqueue_t0; auto cur_epoch = ts::duration_cast<ts::milliseconds>(ts::system_clock::now().time_since_epoch()).count(); out << cur_epoch << " " << enqueue_tot_time << " enqueue"; out << std::endl; } uint64_t dequeue_tot_time = 0, dequeue_t0 = 0, dequeue_t1 = 0; for (j = num_ops; j > 0; --j) { dequeue_t0 = time_utils::now_us(); fq_client->front(); fq_client->dequeue(); dequeue_t1 = time_utils::now_us(); dequeue_tot_time = (dequeue_t1 - dequeue_t0); auto cur_epoch = ts::duration_cast<ts::milliseconds>(ts::system_clock::now().time_since_epoch()).count(); out << cur_epoch << " " << dequeue_tot_time << " dequeue" << std::endl; } stop_.store(true); if (worker_.joinable()) worker_.join(); client.remove(path); return 0; }
37.336735
113
0.65537
[ "vector" ]
60680dd710e05f2322b719ed2289c0cc1e3e42c8
8,923
cpp
C++
Tests/UnitTests/V2LibraryTests/LearnerTests.cpp
KeDengMS/CNTK
fce86cd9581e7ba746d1ec75bbd67dd35d35d11c
[ "RSA-MD" ]
1
2021-05-09T01:37:49.000Z
2021-05-09T01:37:49.000Z
Tests/UnitTests/V2LibraryTests/LearnerTests.cpp
KeDengMS/CNTK
fce86cd9581e7ba746d1ec75bbd67dd35d35d11c
[ "RSA-MD" ]
null
null
null
Tests/UnitTests/V2LibraryTests/LearnerTests.cpp
KeDengMS/CNTK
fce86cd9581e7ba746d1ec75bbd67dd35d35d11c
[ "RSA-MD" ]
null
null
null
// // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE.md file in the project root for full license information. // #include "CNTKLibrary.h" #include "Common.h" #include <string> #include <random> #include <initializer_list> using namespace CNTK; using namespace std; static const size_t maxMinibatchSize = 1000; static const size_t maxNumAxes = 5; static const size_t maxDimSize = 10; template <typename ElementType> void TestUpdate(LearnerPtr& learner, NDShape& shape, size_t numMinibatches, const DeviceDescriptor& device) { auto seed = (unsigned long) rng(); unordered_map<Parameter, NDArrayViewPtr> gradientValues; for (auto i = 0; i < numMinibatches; i++) { for (auto& parameter : learner->Parameters()) { gradientValues[parameter] = NDArrayView::RandomUniform<ElementType>(shape, -1.0, 1.0, seed + i, device); } learner->Update(gradientValues, 1); } } template <typename ElementType> vector<Parameter> CreateParameters(const NDShape& shape, size_t numParameters, const DeviceDescriptor& device) { vector<Parameter> parameters; for (int i = 0; i < numParameters; i++) { parameters.push_back( Parameter(NDArrayView::RandomUniform<ElementType>(shape, -1.0, 1.0, i, device), L"parameter_" + to_wstring(i))); } return parameters; } template <typename ElementType> void TestSGDLearner(size_t numParameters, size_t numMinibatches, const DeviceDescriptor& device) { NDShape shape = CreateShape(rng() % maxNumAxes + 1, maxDimSize); auto parameters = CreateParameters<ElementType>(shape, numParameters, device); auto learner = SGDLearner(parameters, 0.4); TestUpdate<ElementType>(learner, shape, numMinibatches, device); } template <typename ElementType> void TestMomentumSGDLearner(size_t numParameters, size_t numMinibatches, const DeviceDescriptor& device) { NDShape shape = CreateShape(rng() % maxNumAxes + 1, maxDimSize); auto parameters = CreateParameters<ElementType>(shape, numParameters, device); MomentumValuesPerSample momentumValues = { { { 1, 1.0 }, { 3, 0.1 }, { 10, 0.01 } }, 2 }; auto learner = MomentumSGDLearner(parameters, { { 0.3, 0.2, 0.1 } }, momentumValues); TestUpdate<ElementType>(learner, shape, numMinibatches, device); } template <typename ElementType> void TestNesterovLearner(size_t numParameters, size_t numMinibatches, const DeviceDescriptor& device) { NDShape shape = CreateShape(rng() % maxNumAxes + 1, maxDimSize); auto parameters = CreateParameters<ElementType>(shape, numParameters, device); MomentumValuesAsTimeConstants momentumValues = { { { 1, 1 }, { 3, 5 }, { 10, 25 } }, 100 }; auto learner = NesterovLearner(parameters, { { { 1, 0.5 }, { 10, 0.25 }, { 20, 0.125 } }, 3 }, momentumValues); TestUpdate<ElementType>(learner, shape, numMinibatches, device); } template <typename ElementType> void TestAdaGradLearner(size_t numParameters, size_t numMinibatches, const DeviceDescriptor& device) { NDShape shape = CreateShape(rng() % maxNumAxes + 1, maxDimSize); auto parameters = CreateParameters<ElementType>(shape, numParameters, device); auto learner = AdaGradLearner(parameters, { vector<double>{0.5, 0.4, 0.3, 0.2, 0.1}, 2 }, true); TestUpdate<ElementType>(learner, shape, numMinibatches, device); } template <typename ElementType> void TestFSAdaGradLearner(size_t numParameters, size_t numMinibatches, const DeviceDescriptor& device) { NDShape shape = CreateShape(rng() % maxNumAxes + 1, maxDimSize); auto parameters = CreateParameters<ElementType>(shape, numParameters, device); auto learner = FSAdaGradLearner(parameters, { { 0.5 } }, MomentumValuesAsTimeConstants({ 10, 100, 1000 })); TestUpdate<ElementType>(learner, shape, numMinibatches, device); } template <typename ElementType> void TestRMSPropLearner(size_t numParameters, size_t numMinibatches, const DeviceDescriptor& device) { NDShape shape = CreateShape(rng() % maxNumAxes + 1, maxDimSize); auto parameters = CreateParameters<ElementType>(shape, numParameters, device); auto learner = RMSPropLearner(parameters, { { { 3, 0.7 }, { 1, 0.2 } } }, 0.01, 0.02, 0.03, 0.1, 0.001); TestUpdate<ElementType>(learner, shape, numMinibatches, device); } void TestTrainingParametersSchedule() { LearningRatesPerSample schedule1 = 0.5; assert(schedule1[0] == 0.5); assert(schedule1[1] == 0.5); assert(schedule1[100] == 0.5); LearningRatesPerSample schedule2 = { 0.5 }; assert(schedule2[0] == 0.5); assert(schedule2[10] == 0.5); assert(schedule2[100] == 0.5); LearningRatesPerSample schedule3 = { { 0.5, 0.3, 0.3 } }; assert(schedule3[0] == 0.5); assert(schedule3[1] == 0.3); assert(schedule3[100] == 0.3); LearningRatesPerSample schedule4 = { vector<double>{ 0.5 }, 10 }; // without vector<> gcc complains that conversion here is ambiguousS assert(schedule4[0] == 0.5); assert(schedule4[10] == 0.5); assert(schedule4[100] == 0.5); LearningRatesPerSample schedule5 = { { 0.5, 0.3, 0.2 }, 10 }; assert(schedule5[0] == 0.5); assert(schedule5[9] == 0.5); assert(schedule5[10] == 0.3); assert(schedule5[19] == 0.3); assert(schedule5[20] == 0.2); assert(schedule5[100] == 0.2); LearningRatesPerSample schedule6 = { { make_pair(1, 0.5) } }; // without make_pair this is interpreted as a vector of doubles assert(schedule6[0] == 0.5); assert(schedule6[10] == 0.5); assert(schedule6[100] == 0.5); LearningRatesPerSample schedule7 = { { { 1, 0.5 }, { 1, 0.3 }, { 1, 0.2 } } }; assert(schedule7[0] == 0.5); assert(schedule7[1] == 0.3); assert(schedule7[2] == 0.2); assert(schedule7[100] == 0.2); LearningRatesPerSample schedule8 = { { { 1, 0.5 }, { 1, 0.3 }, { 1, 0.2 } }, 10 }; assert(schedule8[0] == 0.5); assert(schedule8[9] == 0.5); assert(schedule8[10] == 0.3); assert(schedule8[19] == 0.3); assert(schedule8[20] == 0.2); assert(schedule8[100] == 0.2); LearningRatesPerSample schedule9 = { { { 3, 0.5 }, { 2, 0.3 }, { 1, 0.2 } } }; assert(schedule9[0] == 0.5); assert(schedule9[2] == 0.5); assert(schedule9[3] == 0.3); assert(schedule9[4] == 0.3); assert(schedule9[5] == 0.2); assert(schedule9[100] == 0.2); LearningRatesPerSample schedule10 = { { { 3, 0.5 }, { 2, 0.3 }, { 1, 0.2 } }, 10 }; assert(schedule10[0] == 0.5); assert(schedule10[29] == 0.5); assert(schedule10[30] == 0.3); assert(schedule10[49] == 0.3); assert(schedule10[50] == 0.2); assert(schedule10[100] == 0.2); MomentumValuesAsTimeConstants schedule11 = { { 0.0, 1.0, 2.0 }, 10 }; assert(schedule11[0] == 0.0); assert(schedule11[9] == 0.0); assert(schedule11[10] == exp(-1.0 / 1.0)); assert(schedule11[19] == exp(-1.0 / 1.0)); assert(schedule11[20] == exp(-1.0 / 2.0)); assert(schedule11[30] == exp(-1.0 / 2.0)); MomentumValuesPerSample schedule12 = schedule11; assert(schedule12[0] == 0.0); assert(schedule12[9] == 0.0); assert(schedule12[10] == exp(-1.0 / 1.0)); assert(schedule12[19] == exp(-1.0 / 1.0)); assert(schedule12[20] == exp(-1.0 / 2.0)); assert(schedule12[30] == exp(-1.0 / 2.0)); MomentumValuesAsTimeConstants schedule13 = 1; assert(schedule13[0] == exp(-1.0 / 1.0)); assert(schedule13[1] == exp(-1.0 / 1.0)); assert(schedule13[100] == exp(-1.0 / 1.0)); MomentumValuesAsTimeConstants schedule14 = { { 1.0, 2.0, 3.0 } }; assert(schedule14[0] == exp(-1.0 / 1.0)); assert(schedule14[1] == exp(-1.0 / 2.0)); assert(schedule14[2] == exp(-1.0 / 3.0)); assert(schedule14[100] == exp(-1.0 / 3.0)); MomentumValuesAsTimeConstants schedule15 = { { { 100, 7.0 }, { 10, 5.0 }, { 1, 3.0 } }, 100 }; assert(schedule15[0] == exp(-1.0 / 7.0)); assert(schedule15[9999] == exp(-1.0 / 7.0)); assert(schedule15[10000] == exp(-1.0 / 5.0)); assert(schedule15[10999] == exp(-1.0 / 5.0)); assert(schedule15[11000] == exp(-1.0 / 3.0)); assert(schedule15[99999] == exp(-1.0 / 3.0)); } void LearnerTests() { fprintf(stderr, "\nLearnerTests..\n"); TestTrainingParametersSchedule(); TestSGDLearner<double>(5, 3, DeviceDescriptor::CPUDevice()); if (IsGPUAvailable()) { TestMomentumSGDLearner<float>(3, 11, DeviceDescriptor::GPUDevice(0)); TestNesterovLearner<float>(1, 20, DeviceDescriptor::GPUDevice(0)); } else { TestMomentumSGDLearner<float>(3, 11, DeviceDescriptor::CPUDevice()); TestNesterovLearner<float>(1, 20, DeviceDescriptor::CPUDevice()); } TestAdaGradLearner<double>(2, 10, DeviceDescriptor::CPUDevice()); TestFSAdaGradLearner<double>(10, 2, DeviceDescriptor::CPUDevice()); TestRMSPropLearner<float>(3, 3, DeviceDescriptor::CPUDevice()); }
38.795652
138
0.651126
[ "shape", "vector" ]
6068b347b17dd0f221b03752537bae3672de5d5d
6,835
cpp
C++
Source/Core/Visualization/Exporter/StructuredVolumeExporter.cpp
X1aoyueyue/KVS
ad47d62bef4fdd9ddd3412a26ee6557b63f0543b
[ "BSD-3-Clause" ]
42
2015-07-24T23:05:07.000Z
2022-03-16T01:31:04.000Z
Source/Core/Visualization/Exporter/StructuredVolumeExporter.cpp
X1aoyueyue/KVS
ad47d62bef4fdd9ddd3412a26ee6557b63f0543b
[ "BSD-3-Clause" ]
4
2015-03-17T05:42:49.000Z
2020-08-09T15:21:45.000Z
Source/Core/Visualization/Exporter/StructuredVolumeExporter.cpp
X1aoyueyue/KVS
ad47d62bef4fdd9ddd3412a26ee6557b63f0543b
[ "BSD-3-Clause" ]
29
2015-01-03T05:56:32.000Z
2021-10-05T15:28:33.000Z
/*****************************************************************************/ /** * @file StructuredVolumeExporter.cpp * @author Naohisa Sakamoto */ /*****************************************************************************/ #include "StructuredVolumeExporter.h" #include <kvs/ObjectBase> #include <kvs/VolumeObjectBase> #include <kvs/StructuredVolumeObject> namespace kvs { /*===========================================================================*/ /** * @brief Constructs a KVSMLStructuredVolumeObject data from given object. * @param object [in] pointer to the structured volume object */ /*===========================================================================*/ StructuredVolumeExporter<kvs::KVSMLStructuredVolumeObject>::StructuredVolumeExporter( const kvs::StructuredVolumeObject* object ) { this->exec( object ); } /*===========================================================================*/ /** * @brief Exports object to a KVSMLStructuredVolumeObject data. * @param object [in] pointer to the structured volume object */ /*===========================================================================*/ kvs::KVSMLStructuredVolumeObject* StructuredVolumeExporter<kvs::KVSMLStructuredVolumeObject>::exec( const kvs::ObjectBase* object ) { BaseClass::setSuccess( true ); if ( !object ) { BaseClass::setSuccess( false ); kvsMessageError("Input object is NULL."); return NULL; } // Cast to the structured volume object. const kvs::StructuredVolumeObject* volume = kvs::StructuredVolumeObject::DownCast( object ); if ( !volume ) { BaseClass::setSuccess( false ); kvsMessageError("Input object is not structured volume object."); return NULL; } if ( volume->label() != "" ) { this->setLabel( volume->label() ); } if ( volume->unit() != "" ) { this->setUnit( volume->unit() ); } // Check the grid type of the given structured volume object. switch ( volume->gridType() ) { case kvs::StructuredVolumeObject::UnknownGridType: { kvsMessageError("Unknown grid type."); break; } case kvs::StructuredVolumeObject::Uniform: { this->setGridType("uniform"); break; } /* case kvs::StructuredVolumeObject::Rectilinear: this->setGridType("rectilinear"); break; case kvs::StructuredVolumeObject::Curvilinear: this->setGridType("curvilinear"); break; */ default: { BaseClass::setSuccess( false ); kvsMessageError("'uniform' grid type is only supported."); break; } } this->setVeclen( volume->veclen() ); this->setResolution( volume->resolution() ); this->setValues( volume->values() ); if ( volume->hasMinMaxValues() ) { this->setMinValue( volume->minValue() ); this->setMaxValue( volume->maxValue() ); } return this; } /*===========================================================================*/ /** * @brief Constructs a AVSField data from given object. * @param object [in] pointer to the structured volume object */ /*===========================================================================*/ StructuredVolumeExporter<kvs::AVSField>::StructuredVolumeExporter( const kvs::StructuredVolumeObject* object ) { this->exec( object ); } /*===========================================================================*/ /** * @brief Exports object to a AVSField data. * @param object [in] pointer to the structured volume object */ /*===========================================================================*/ kvs::AVSField* StructuredVolumeExporter<kvs::AVSField>::exec( const kvs::ObjectBase* object ) { BaseClass::setSuccess( true ); if ( !object ) { BaseClass::setSuccess( false ); kvsMessageError("Input object is NULL."); return NULL; } // Cast to the structured volume object. const kvs::StructuredVolumeObject* volume = kvs::StructuredVolumeObject::DownCast( object ); if ( !volume ) { BaseClass::setSuccess( false ); kvsMessageError("Input object is not structured volume object."); return NULL; } const std::type_info& type = volume->values().typeInfo()->type(); if ( type == typeid( kvs::Int8 ) ) { this->setBits( 8 ); this->setSigned( true ); this->setDataType( kvs::AVSField::Byte ); } else if ( type == typeid( kvs::UInt8 ) ) { this->setBits( 8 ); this->setSigned( false ); this->setDataType( kvs::AVSField::Byte ); } else if ( type == typeid( kvs::Int16 ) ) { this->setBits( 16 ); this->setSigned( true ); this->setDataType( kvs::AVSField::Short ); } else if ( type == typeid( kvs::UInt16 ) ) { this->setBits( 16 ); this->setSigned( false ); this->setDataType( kvs::AVSField::Short ); } else if ( type == typeid( kvs::Int32 ) ) { this->setBits( 32 ); this->setSigned( true ); this->setDataType( kvs::AVSField::Integer ); } else if ( type == typeid( kvs::UInt32 ) ) { this->setBits( 32 ); this->setSigned( false ); this->setDataType( kvs::AVSField::Integer ); } else if ( type == typeid( kvs::Real32 ) ) { this->setBits( 32 ); this->setSigned( true ); this->setDataType( kvs::AVSField::Float ); } else if ( type == typeid( kvs::Real64 ) ) { this->setBits( 64 ); this->setSigned( true ); this->setDataType( kvs::AVSField::Double ); } else { kvsMessageError("Unsupported data type '%s'.", volume->values().typeInfo()->typeName() ); } // Check the grid type of the given structured volume object. switch ( volume->gridType() ) { case kvs::StructuredVolumeObject::Uniform: { this->setFieldType( kvs::AVSField::Uniform ); this->setValues( volume->values() ); break; } /* case kvs::StructuredVolumeObject::Rectilinear: this->setFieldType( kvs::AVSField::Rectilinear ); this->setValues( volume->values() ); this->setCoords( volume->coords() ); break; case kvs::StructuredVolumeObject::Curvilinear: this->setFieldType( kvs::AVSField::Irregular ); this->setValues( volume->values() ); this->setCoords( volume->coords() ); break; */ default: { BaseClass::setSuccess( false ); kvsMessageError("Unknown grid type."); break; } } this->setVeclen( volume->veclen() ); this->setNSpace( 3 ); this->setNDim( 3 ); this->setDim( volume->resolution() ); return this; } } // end of namespace kvs
29.461207
99
0.533138
[ "object" ]
606bde9dcf5646f2d7b1e6054417f311b4fd5735
9,401
cpp
C++
src/HQPerformance/PipelinePerformaceTest.cpp
dale-wilson/HSQueue
04d01ed42707069d28e81b5494aba61904e6e591
[ "BSD-3-Clause" ]
2
2015-12-29T17:33:25.000Z
2021-12-20T02:30:44.000Z
src/HQPerformance/PipelinePerformaceTest.cpp
dale-wilson/HighQueue
04d01ed42707069d28e81b5494aba61904e6e591
[ "BSD-3-Clause" ]
null
null
null
src/HQPerformance/PipelinePerformaceTest.cpp
dale-wilson/HighQueue
04d01ed42707069d28e81b5494aba61904e6e591
[ "BSD-3-Clause" ]
null
null
null
#include <Common/HighQueuePch.hpp> #define BOOST_TEST_NO_MAIN HighQueuePerformanceTest #include <boost/test/unit_test.hpp> #include <HighQueue/Producer.hpp> #include <HighQueue/Consumer.hpp> #include <Common/Stopwatch.hpp> #include <Mocks/MockMessage.hpp> using namespace HighQueue; #define VALIDATE_OUTPUT 0 namespace { typedef MockMessage<13> ActualMessage; auto messageBytes = sizeof(ActualMessage); volatile std::atomic<uint32_t> threadsReady; volatile bool producerGo = false; void producerFunction(ConnectionPtr & connection, uint32_t producerNumber, uint32_t messageCount) { try { connection->willProduce(); // enable solo mode Producer producer(connection); Message producerMessage(connection); ++threadsReady; while(!producerGo) { std::this_thread::yield(); } for(uint32_t messageNumber = 0; messageNumber < messageCount; ++messageNumber) { auto testMessage = producerMessage.emplace<ActualMessage>(producerNumber, messageNumber); producer.publish(producerMessage); } // send an empty message producerMessage.setUsed(0); producer.publish(producerMessage); } catch(const std::exception & ex) { std::cout << "Producer Number " << producerNumber << "Failed " << ex.what() << std::endl; } } enum class CopyType { PassThru, BufferSwap, BinaryCopy, CopyConstruct }; inline std::ostream & operator << (std::ostream & out, CopyType type) { switch(type) { case CopyType::PassThru: return out << "PassThru"; case CopyType::BufferSwap: return out << "BufferSwap"; case CopyType::BinaryCopy: return out << "BinaryCopy"; case CopyType::CopyConstruct: return out << "CopyConstruct"; default: return out << "Unknown"; } } void copyFunction(ConnectionPtr & inConnection, ConnectionPtr & outConnection, CopyType copyType) { try { Consumer consumer(inConnection); Message consumerMessage(inConnection); outConnection->willProduce(); // enable solo mode Producer producer(outConnection); Message producerMessage(outConnection); ++threadsReady; switch(copyType) { case CopyType::PassThru: { while(consumer.getNext(consumerMessage)) { auto used = consumerMessage.getUsed(); producer.publish(consumerMessage); if(used == 0) { return; } } break; } case CopyType::BufferSwap: while(consumer.getNext(consumerMessage)) { auto used = consumerMessage.getUsed(); consumerMessage.moveTo(producerMessage); producer.publish(producerMessage); consumerMessage.destroy<ActualMessage>(); if(used == 0) { return; } } break; case CopyType::BinaryCopy: { while(consumer.getNext(consumerMessage)) { auto used = consumerMessage.getUsed(); producerMessage.appendBinaryCopy(consumerMessage.get(), used); producer.publish(producerMessage); if(used == 0) { return; } } break; } case CopyType::CopyConstruct: { { while(consumer.getNext(consumerMessage)) { auto used = consumerMessage.getUsed(); if(used == 0) { producerMessage.setUsed(0); producer.publish(producerMessage); return; } producerMessage.emplace<ActualMessage>(*consumerMessage.get<ActualMessage>()); producer.publish(producerMessage); consumerMessage.destroy<ActualMessage>(); } break; } } } } catch(const std::exception & ex) { std::cout << "Copy thread failed. " << ex.what() << std::endl; } } } #define ENABLE_PIPELINEPERFORMANCE 0 #if ENABLE_PIPELINEPERFORMANCE BOOST_AUTO_TEST_CASE(testPipelinePerformance) { static const size_t numberOfConsumers = 1; // Don't change this static const size_t maxNumberOfProducers = 1; // Don't change this static const size_t copyLimit = 6; // This you can change. static const size_t entryCount = 10000; static const uint32_t targetMessageCount = 100000000; //3000000; static const size_t queueCount = copyLimit + numberOfConsumers; // need a pool for each object that can receive messages // how many buffers do we need? static const size_t messageCount = entryCount * queueCount + numberOfConsumers + 2 * copyLimit + maxNumberOfProducers; static const size_t spinCount = 0; static const size_t yieldCount = 0;//1;//100; static const size_t sleepCount = WaitStrategy::FOREVER; static const std::chrono::nanoseconds sleepPeriod(2); CopyType copyType = //CopyType::BinaryCopy; // CopyType::BufferSwap; CopyType::PassThru; std::cout << "HighQueue Pipeline " << (maxNumberOfProducers + copyLimit + numberOfConsumers) << " stage. Copy type: " << copyType << ": "; WaitStrategy strategy(spinCount, yieldCount, sleepCount, sleepPeriod); bool discardMessagesIfNoConsumer = false; CreationParameters parameters(strategy, strategy, discardMessagesIfNoConsumer, entryCount, messageBytes); MemoryPoolPtr memoryPool(new MemoryPool(messageBytes, messageCount)); std::vector<std::shared_ptr<Connection> > connections; for(size_t nConn = 0; nConn < copyLimit + numberOfConsumers; ++nConn) { std::shared_ptr<Connection> connection(new Connection); connections.push_back(connection); std::stringstream name; name << "Connection " << nConn; connection->createLocal(name.str(), parameters, memoryPool); } // The consumer listens to the last connection Consumer consumer(connections.back()); Message consumerMessage(connections.back()); producerGo = false; threadsReady = 0; uint64_t nextMessage = 0u; // Each copy thread listens to connection N-1 and sends to thread N std::vector<std::thread> threads; for(size_t nCopy = connections.size() - 1; nCopy > 0; --nCopy) { threads.emplace_back(std::bind(copyFunction, connections[nCopy - 1], connections[nCopy], copyType) ); } // The producer sends targetMessageCount messages to connection 0 threads.emplace_back( std::bind(producerFunction, connections[0], 1, targetMessageCount)); // All wired up, ready to go. Wait for the threads to initialize. while(threadsReady < threads.size()) { std::this_thread::yield(); } Stopwatch timer; producerGo = true; for(uint64_t messageNumber = 0; messageNumber < targetMessageCount; ++messageNumber) { consumer.getNext(consumerMessage); #if VALIDATE_OUTPUT auto testMessage = consumerMessage.read<ActualMessage>(); testMessage->touch(); if(nextMessage != testMessage->getSequence()) { // the if avoids the performance hit of BOOST_CHECK_EQUAL unless it's needed. BOOST_CHECK_EQUAL(nextMessage, testMessage->getSequence()); } consumerMessage.destroy<ActualMessage>(); ++ nextMessage; #endif // VALIDATE_OUTPUT } auto lapse = timer.nanoseconds(); for(auto & thread: threads) { thread.join(); } std::cout << " Passed " << targetMessageCount << ' ' << messageBytes << " byte messages in " << std::setprecision(9) << double(lapse) / double(Stopwatch::nanosecondsPerSecond) << " seconds. "; if(lapse == 0) { std::cout << "Run time too short to measure. Increase targetMessageCount." << std::endl; } else { std::cout << lapse / targetMessageCount << " nsec./message " << std::setprecision(3) << (double(targetMessageCount) * 1000.0L) / double(lapse) << " MMsg/second " << std::endl; } consumer.writeStats(std::cerr); std::cerr << std::endl; } #endif // ENABLEORDEREDMERGEPERFORMANCE
34.690037
142
0.553239
[ "object", "vector" ]
606cb58a8fc33cdeb6f63ff59d64e177087d06c0
62,174
hpp
C++
cisco-ios-xr/ydk/models/cisco_ios_xr/Cisco_IOS_XR_tty_server_oper.hpp
CiscoDevNet/ydk-cpp
ef7d75970f2ef1154100e0f7b0a2ee823609b481
[ "ECL-2.0", "Apache-2.0" ]
17
2016-12-02T05:45:49.000Z
2022-02-10T19:32:54.000Z
cisco-ios-xr/ydk/models/cisco_ios_xr/Cisco_IOS_XR_tty_server_oper.hpp
CiscoDevNet/ydk-cpp
ef7d75970f2ef1154100e0f7b0a2ee823609b481
[ "ECL-2.0", "Apache-2.0" ]
2
2017-03-27T15:22:38.000Z
2019-11-05T08:30:16.000Z
cisco-ios-xr/ydk/models/cisco_ios_xr/Cisco_IOS_XR_tty_server_oper.hpp
CiscoDevNet/ydk-cpp
ef7d75970f2ef1154100e0f7b0a2ee823609b481
[ "ECL-2.0", "Apache-2.0" ]
11
2016-12-02T05:45:52.000Z
2019-11-07T08:28:17.000Z
#ifndef _CISCO_IOS_XR_TTY_SERVER_OPER_ #define _CISCO_IOS_XR_TTY_SERVER_OPER_ #include <memory> #include <vector> #include <string> #include <ydk/types.hpp> #include <ydk/errors.hpp> namespace cisco_ios_xr { namespace Cisco_IOS_XR_tty_server_oper { class Tty : public ydk::Entity { public: Tty(); ~Tty(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; std::shared_ptr<ydk::Entity> clone_ptr() const override; ydk::augment_capabilities_function get_augment_capabilities_function() const override; std::string get_bundle_yang_models_location() const override; std::string get_bundle_name() const override; std::map<std::pair<std::string, std::string>, std::string> get_namespace_identity_lookup() const override; class ConsoleNodes; //type: Tty::ConsoleNodes class VtyLines; //type: Tty::VtyLines class AuxiliaryNodes; //type: Tty::AuxiliaryNodes std::shared_ptr<cisco_ios_xr::Cisco_IOS_XR_tty_server_oper::Tty::ConsoleNodes> console_nodes; std::shared_ptr<cisco_ios_xr::Cisco_IOS_XR_tty_server_oper::Tty::VtyLines> vty_lines; std::shared_ptr<cisco_ios_xr::Cisco_IOS_XR_tty_server_oper::Tty::AuxiliaryNodes> auxiliary_nodes; }; // Tty class Tty::ConsoleNodes : public ydk::Entity { public: ConsoleNodes(); ~ConsoleNodes(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; std::string get_absolute_path() const override; class ConsoleNode; //type: Tty::ConsoleNodes::ConsoleNode ydk::YList console_node; }; // Tty::ConsoleNodes class Tty::ConsoleNodes::ConsoleNode : public ydk::Entity { public: ConsoleNode(); ~ConsoleNode(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; std::string get_absolute_path() const override; ydk::YLeaf id; //type: string class ConsoleLine; //type: Tty::ConsoleNodes::ConsoleNode::ConsoleLine std::shared_ptr<cisco_ios_xr::Cisco_IOS_XR_tty_server_oper::Tty::ConsoleNodes::ConsoleNode::ConsoleLine> console_line; }; // Tty::ConsoleNodes::ConsoleNode class Tty::ConsoleNodes::ConsoleNode::ConsoleLine : public ydk::Entity { public: ConsoleLine(); ~ConsoleLine(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; class ConsoleStatistics; //type: Tty::ConsoleNodes::ConsoleNode::ConsoleLine::ConsoleStatistics class State; //type: Tty::ConsoleNodes::ConsoleNode::ConsoleLine::State class Configuration; //type: Tty::ConsoleNodes::ConsoleNode::ConsoleLine::Configuration std::shared_ptr<cisco_ios_xr::Cisco_IOS_XR_tty_server_oper::Tty::ConsoleNodes::ConsoleNode::ConsoleLine::ConsoleStatistics> console_statistics; std::shared_ptr<cisco_ios_xr::Cisco_IOS_XR_tty_server_oper::Tty::ConsoleNodes::ConsoleNode::ConsoleLine::State> state; std::shared_ptr<cisco_ios_xr::Cisco_IOS_XR_tty_server_oper::Tty::ConsoleNodes::ConsoleNode::ConsoleLine::Configuration> configuration; }; // Tty::ConsoleNodes::ConsoleNode::ConsoleLine class Tty::ConsoleNodes::ConsoleNode::ConsoleLine::ConsoleStatistics : public ydk::Entity { public: ConsoleStatistics(); ~ConsoleStatistics(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; class Rs232; //type: Tty::ConsoleNodes::ConsoleNode::ConsoleLine::ConsoleStatistics::Rs232 class GeneralStatistics; //type: Tty::ConsoleNodes::ConsoleNode::ConsoleLine::ConsoleStatistics::GeneralStatistics class Exec; //type: Tty::ConsoleNodes::ConsoleNode::ConsoleLine::ConsoleStatistics::Exec class Aaa; //type: Tty::ConsoleNodes::ConsoleNode::ConsoleLine::ConsoleStatistics::Aaa std::shared_ptr<cisco_ios_xr::Cisco_IOS_XR_tty_server_oper::Tty::ConsoleNodes::ConsoleNode::ConsoleLine::ConsoleStatistics::Rs232> rs232; std::shared_ptr<cisco_ios_xr::Cisco_IOS_XR_tty_server_oper::Tty::ConsoleNodes::ConsoleNode::ConsoleLine::ConsoleStatistics::GeneralStatistics> general_statistics; std::shared_ptr<cisco_ios_xr::Cisco_IOS_XR_tty_server_oper::Tty::ConsoleNodes::ConsoleNode::ConsoleLine::ConsoleStatistics::Exec> exec; std::shared_ptr<cisco_ios_xr::Cisco_IOS_XR_tty_server_oper::Tty::ConsoleNodes::ConsoleNode::ConsoleLine::ConsoleStatistics::Aaa> aaa; }; // Tty::ConsoleNodes::ConsoleNode::ConsoleLine::ConsoleStatistics class Tty::ConsoleNodes::ConsoleNode::ConsoleLine::ConsoleStatistics::Rs232 : public ydk::Entity { public: Rs232(); ~Rs232(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf data_bits; //type: uint32 ydk::YLeaf exec_disabled; //type: boolean ydk::YLeaf hardware_flow_control_status; //type: uint32 ydk::YLeaf parity_status; //type: uint32 ydk::YLeaf baud_rate; //type: uint32 ydk::YLeaf stop_bits; //type: uint32 ydk::YLeaf overrun_error_count; //type: uint32 ydk::YLeaf framing_error_count; //type: uint32 ydk::YLeaf parity_error_count; //type: uint32 }; // Tty::ConsoleNodes::ConsoleNode::ConsoleLine::ConsoleStatistics::Rs232 class Tty::ConsoleNodes::ConsoleNode::ConsoleLine::ConsoleStatistics::GeneralStatistics : public ydk::Entity { public: GeneralStatistics(); ~GeneralStatistics(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf terminal_length; //type: uint32 ydk::YLeaf terminal_width; //type: uint32 ydk::YLeaf async_interface; //type: boolean ydk::YLeaf flow_control_start_character; //type: int8 ydk::YLeaf flow_control_stop_character; //type: int8 ydk::YLeaf domain_lookup_enabled; //type: boolean ydk::YLeaf motd_banner_enabled; //type: boolean ydk::YLeaf private_flag; //type: boolean ydk::YLeaf terminal_type; //type: string ydk::YLeaf absolute_timeout; //type: uint32 ydk::YLeaf idle_time; //type: uint32 }; // Tty::ConsoleNodes::ConsoleNode::ConsoleLine::ConsoleStatistics::GeneralStatistics class Tty::ConsoleNodes::ConsoleNode::ConsoleLine::ConsoleStatistics::Exec : public ydk::Entity { public: Exec(); ~Exec(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf time_stamp_enabled; //type: boolean }; // Tty::ConsoleNodes::ConsoleNode::ConsoleLine::ConsoleStatistics::Exec class Tty::ConsoleNodes::ConsoleNode::ConsoleLine::ConsoleStatistics::Aaa : public ydk::Entity { public: Aaa(); ~Aaa(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf user_name; //type: string }; // Tty::ConsoleNodes::ConsoleNode::ConsoleLine::ConsoleStatistics::Aaa class Tty::ConsoleNodes::ConsoleNode::ConsoleLine::State : public ydk::Entity { public: State(); ~State(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; class Template; //type: Tty::ConsoleNodes::ConsoleNode::ConsoleLine::State::Template class General; //type: Tty::ConsoleNodes::ConsoleNode::ConsoleLine::State::General std::shared_ptr<cisco_ios_xr::Cisco_IOS_XR_tty_server_oper::Tty::ConsoleNodes::ConsoleNode::ConsoleLine::State::Template> template_; std::shared_ptr<cisco_ios_xr::Cisco_IOS_XR_tty_server_oper::Tty::ConsoleNodes::ConsoleNode::ConsoleLine::State::General> general; }; // Tty::ConsoleNodes::ConsoleNode::ConsoleLine::State class Tty::ConsoleNodes::ConsoleNode::ConsoleLine::State::Template : public ydk::Entity { public: Template(); ~Template(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf name; //type: string }; // Tty::ConsoleNodes::ConsoleNode::ConsoleLine::State::Template class Tty::ConsoleNodes::ConsoleNode::ConsoleLine::State::General : public ydk::Entity { public: General(); ~General(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf operation_; //type: SessionOperation ydk::YLeaf general_state; //type: LineState }; // Tty::ConsoleNodes::ConsoleNode::ConsoleLine::State::General class Tty::ConsoleNodes::ConsoleNode::ConsoleLine::Configuration : public ydk::Entity { public: Configuration(); ~Configuration(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; class ConnectionConfiguration; //type: Tty::ConsoleNodes::ConsoleNode::ConsoleLine::Configuration::ConnectionConfiguration std::shared_ptr<cisco_ios_xr::Cisco_IOS_XR_tty_server_oper::Tty::ConsoleNodes::ConsoleNode::ConsoleLine::Configuration::ConnectionConfiguration> connection_configuration; }; // Tty::ConsoleNodes::ConsoleNode::ConsoleLine::Configuration class Tty::ConsoleNodes::ConsoleNode::ConsoleLine::Configuration::ConnectionConfiguration : public ydk::Entity { public: ConnectionConfiguration(); ~ConnectionConfiguration(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf acl_out; //type: string ydk::YLeaf acl_in; //type: string class TransportInput; //type: Tty::ConsoleNodes::ConsoleNode::ConsoleLine::Configuration::ConnectionConfiguration::TransportInput std::shared_ptr<cisco_ios_xr::Cisco_IOS_XR_tty_server_oper::Tty::ConsoleNodes::ConsoleNode::ConsoleLine::Configuration::ConnectionConfiguration::TransportInput> transport_input; }; // Tty::ConsoleNodes::ConsoleNode::ConsoleLine::Configuration::ConnectionConfiguration class Tty::ConsoleNodes::ConsoleNode::ConsoleLine::Configuration::ConnectionConfiguration::TransportInput : public ydk::Entity { public: TransportInput(); ~TransportInput(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf select; //type: TtyTransportProtocolSelect ydk::YLeaf protocol1; //type: TtyTransportProtocol ydk::YLeaf protocol2; //type: TtyTransportProtocol ydk::YLeaf none; //type: uint32 }; // Tty::ConsoleNodes::ConsoleNode::ConsoleLine::Configuration::ConnectionConfiguration::TransportInput class Tty::VtyLines : public ydk::Entity { public: VtyLines(); ~VtyLines(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; std::string get_absolute_path() const override; class VtyLine; //type: Tty::VtyLines::VtyLine ydk::YList vty_line; }; // Tty::VtyLines class Tty::VtyLines::VtyLine : public ydk::Entity { public: VtyLine(); ~VtyLine(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; std::string get_absolute_path() const override; ydk::YLeaf line_number; //type: uint32 class VtyStatistics; //type: Tty::VtyLines::VtyLine::VtyStatistics class State; //type: Tty::VtyLines::VtyLine::State class Configuration; //type: Tty::VtyLines::VtyLine::Configuration class Sessions; //type: Tty::VtyLines::VtyLine::Sessions std::shared_ptr<cisco_ios_xr::Cisco_IOS_XR_tty_server_oper::Tty::VtyLines::VtyLine::VtyStatistics> vty_statistics; std::shared_ptr<cisco_ios_xr::Cisco_IOS_XR_tty_server_oper::Tty::VtyLines::VtyLine::State> state; std::shared_ptr<cisco_ios_xr::Cisco_IOS_XR_tty_server_oper::Tty::VtyLines::VtyLine::Configuration> configuration; std::shared_ptr<cisco_ios_xr::Cisco_IOS_XR_tty_server_oper::Tty::VtyLines::VtyLine::Sessions> sessions; }; // Tty::VtyLines::VtyLine class Tty::VtyLines::VtyLine::VtyStatistics : public ydk::Entity { public: VtyStatistics(); ~VtyStatistics(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; class Connection; //type: Tty::VtyLines::VtyLine::VtyStatistics::Connection class GeneralStatistics; //type: Tty::VtyLines::VtyLine::VtyStatistics::GeneralStatistics class Exec; //type: Tty::VtyLines::VtyLine::VtyStatistics::Exec class Aaa; //type: Tty::VtyLines::VtyLine::VtyStatistics::Aaa std::shared_ptr<cisco_ios_xr::Cisco_IOS_XR_tty_server_oper::Tty::VtyLines::VtyLine::VtyStatistics::Connection> connection; std::shared_ptr<cisco_ios_xr::Cisco_IOS_XR_tty_server_oper::Tty::VtyLines::VtyLine::VtyStatistics::GeneralStatistics> general_statistics; std::shared_ptr<cisco_ios_xr::Cisco_IOS_XR_tty_server_oper::Tty::VtyLines::VtyLine::VtyStatistics::Exec> exec; std::shared_ptr<cisco_ios_xr::Cisco_IOS_XR_tty_server_oper::Tty::VtyLines::VtyLine::VtyStatistics::Aaa> aaa; }; // Tty::VtyLines::VtyLine::VtyStatistics class Tty::VtyLines::VtyLine::VtyStatistics::Connection : public ydk::Entity { public: Connection(); ~Connection(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf incoming_host_address; //type: string ydk::YLeaf host_address_family; //type: uint32 ydk::YLeaf service; //type: uint32 }; // Tty::VtyLines::VtyLine::VtyStatistics::Connection class Tty::VtyLines::VtyLine::VtyStatistics::GeneralStatistics : public ydk::Entity { public: GeneralStatistics(); ~GeneralStatistics(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf terminal_length; //type: uint32 ydk::YLeaf terminal_width; //type: uint32 ydk::YLeaf async_interface; //type: boolean ydk::YLeaf flow_control_start_character; //type: int8 ydk::YLeaf flow_control_stop_character; //type: int8 ydk::YLeaf domain_lookup_enabled; //type: boolean ydk::YLeaf motd_banner_enabled; //type: boolean ydk::YLeaf private_flag; //type: boolean ydk::YLeaf terminal_type; //type: string ydk::YLeaf absolute_timeout; //type: uint32 ydk::YLeaf idle_time; //type: uint32 }; // Tty::VtyLines::VtyLine::VtyStatistics::GeneralStatistics class Tty::VtyLines::VtyLine::VtyStatistics::Exec : public ydk::Entity { public: Exec(); ~Exec(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf time_stamp_enabled; //type: boolean }; // Tty::VtyLines::VtyLine::VtyStatistics::Exec class Tty::VtyLines::VtyLine::VtyStatistics::Aaa : public ydk::Entity { public: Aaa(); ~Aaa(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf user_name; //type: string }; // Tty::VtyLines::VtyLine::VtyStatistics::Aaa class Tty::VtyLines::VtyLine::State : public ydk::Entity { public: State(); ~State(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; class Template; //type: Tty::VtyLines::VtyLine::State::Template class General; //type: Tty::VtyLines::VtyLine::State::General std::shared_ptr<cisco_ios_xr::Cisco_IOS_XR_tty_server_oper::Tty::VtyLines::VtyLine::State::Template> template_; std::shared_ptr<cisco_ios_xr::Cisco_IOS_XR_tty_server_oper::Tty::VtyLines::VtyLine::State::General> general; }; // Tty::VtyLines::VtyLine::State class Tty::VtyLines::VtyLine::State::Template : public ydk::Entity { public: Template(); ~Template(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf name; //type: string }; // Tty::VtyLines::VtyLine::State::Template class Tty::VtyLines::VtyLine::State::General : public ydk::Entity { public: General(); ~General(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf operation_; //type: SessionOperation ydk::YLeaf general_state; //type: LineState }; // Tty::VtyLines::VtyLine::State::General class Tty::VtyLines::VtyLine::Configuration : public ydk::Entity { public: Configuration(); ~Configuration(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; class ConnectionConfiguration; //type: Tty::VtyLines::VtyLine::Configuration::ConnectionConfiguration std::shared_ptr<cisco_ios_xr::Cisco_IOS_XR_tty_server_oper::Tty::VtyLines::VtyLine::Configuration::ConnectionConfiguration> connection_configuration; }; // Tty::VtyLines::VtyLine::Configuration class Tty::VtyLines::VtyLine::Configuration::ConnectionConfiguration : public ydk::Entity { public: ConnectionConfiguration(); ~ConnectionConfiguration(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf acl_out; //type: string ydk::YLeaf acl_in; //type: string class TransportInput; //type: Tty::VtyLines::VtyLine::Configuration::ConnectionConfiguration::TransportInput std::shared_ptr<cisco_ios_xr::Cisco_IOS_XR_tty_server_oper::Tty::VtyLines::VtyLine::Configuration::ConnectionConfiguration::TransportInput> transport_input; }; // Tty::VtyLines::VtyLine::Configuration::ConnectionConfiguration class Tty::VtyLines::VtyLine::Configuration::ConnectionConfiguration::TransportInput : public ydk::Entity { public: TransportInput(); ~TransportInput(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf select; //type: TtyTransportProtocolSelect ydk::YLeaf protocol1; //type: TtyTransportProtocol ydk::YLeaf protocol2; //type: TtyTransportProtocol ydk::YLeaf none; //type: uint32 }; // Tty::VtyLines::VtyLine::Configuration::ConnectionConfiguration::TransportInput class Tty::VtyLines::VtyLine::Sessions : public ydk::Entity { public: Sessions(); ~Sessions(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; class OutgoingConnection; //type: Tty::VtyLines::VtyLine::Sessions::OutgoingConnection ydk::YList outgoing_connection; }; // Tty::VtyLines::VtyLine::Sessions class Tty::VtyLines::VtyLine::Sessions::OutgoingConnection : public ydk::Entity { public: OutgoingConnection(); ~OutgoingConnection(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf connection_id; //type: uint8 ydk::YLeaf host_name; //type: string ydk::YLeaf transport_protocol; //type: TransportService ydk::YLeaf is_last_active_session; //type: boolean ydk::YLeaf idle_time; //type: uint32 class HostAddress; //type: Tty::VtyLines::VtyLine::Sessions::OutgoingConnection::HostAddress std::shared_ptr<cisco_ios_xr::Cisco_IOS_XR_tty_server_oper::Tty::VtyLines::VtyLine::Sessions::OutgoingConnection::HostAddress> host_address; }; // Tty::VtyLines::VtyLine::Sessions::OutgoingConnection class Tty::VtyLines::VtyLine::Sessions::OutgoingConnection::HostAddress : public ydk::Entity { public: HostAddress(); ~HostAddress(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf af_name; //type: HostAfIdBase ydk::YLeaf ipv4_address; //type: string ydk::YLeaf ipv6_address; //type: string }; // Tty::VtyLines::VtyLine::Sessions::OutgoingConnection::HostAddress class Tty::AuxiliaryNodes : public ydk::Entity { public: AuxiliaryNodes(); ~AuxiliaryNodes(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; std::string get_absolute_path() const override; class AuxiliaryNode; //type: Tty::AuxiliaryNodes::AuxiliaryNode ydk::YList auxiliary_node; }; // Tty::AuxiliaryNodes class Tty::AuxiliaryNodes::AuxiliaryNode : public ydk::Entity { public: AuxiliaryNode(); ~AuxiliaryNode(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; std::string get_absolute_path() const override; ydk::YLeaf id; //type: string class AuxiliaryLine; //type: Tty::AuxiliaryNodes::AuxiliaryNode::AuxiliaryLine std::shared_ptr<cisco_ios_xr::Cisco_IOS_XR_tty_server_oper::Tty::AuxiliaryNodes::AuxiliaryNode::AuxiliaryLine> auxiliary_line; }; // Tty::AuxiliaryNodes::AuxiliaryNode class Tty::AuxiliaryNodes::AuxiliaryNode::AuxiliaryLine : public ydk::Entity { public: AuxiliaryLine(); ~AuxiliaryLine(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; class AuxiliaryStatistics; //type: Tty::AuxiliaryNodes::AuxiliaryNode::AuxiliaryLine::AuxiliaryStatistics class State; //type: Tty::AuxiliaryNodes::AuxiliaryNode::AuxiliaryLine::State class Configuration; //type: Tty::AuxiliaryNodes::AuxiliaryNode::AuxiliaryLine::Configuration std::shared_ptr<cisco_ios_xr::Cisco_IOS_XR_tty_server_oper::Tty::AuxiliaryNodes::AuxiliaryNode::AuxiliaryLine::AuxiliaryStatistics> auxiliary_statistics; std::shared_ptr<cisco_ios_xr::Cisco_IOS_XR_tty_server_oper::Tty::AuxiliaryNodes::AuxiliaryNode::AuxiliaryLine::State> state; std::shared_ptr<cisco_ios_xr::Cisco_IOS_XR_tty_server_oper::Tty::AuxiliaryNodes::AuxiliaryNode::AuxiliaryLine::Configuration> configuration; }; // Tty::AuxiliaryNodes::AuxiliaryNode::AuxiliaryLine class Tty::AuxiliaryNodes::AuxiliaryNode::AuxiliaryLine::AuxiliaryStatistics : public ydk::Entity { public: AuxiliaryStatistics(); ~AuxiliaryStatistics(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; class Rs232; //type: Tty::AuxiliaryNodes::AuxiliaryNode::AuxiliaryLine::AuxiliaryStatistics::Rs232 class GeneralStatistics; //type: Tty::AuxiliaryNodes::AuxiliaryNode::AuxiliaryLine::AuxiliaryStatistics::GeneralStatistics class Exec; //type: Tty::AuxiliaryNodes::AuxiliaryNode::AuxiliaryLine::AuxiliaryStatistics::Exec class Aaa; //type: Tty::AuxiliaryNodes::AuxiliaryNode::AuxiliaryLine::AuxiliaryStatistics::Aaa std::shared_ptr<cisco_ios_xr::Cisco_IOS_XR_tty_server_oper::Tty::AuxiliaryNodes::AuxiliaryNode::AuxiliaryLine::AuxiliaryStatistics::Rs232> rs232; std::shared_ptr<cisco_ios_xr::Cisco_IOS_XR_tty_server_oper::Tty::AuxiliaryNodes::AuxiliaryNode::AuxiliaryLine::AuxiliaryStatistics::GeneralStatistics> general_statistics; std::shared_ptr<cisco_ios_xr::Cisco_IOS_XR_tty_server_oper::Tty::AuxiliaryNodes::AuxiliaryNode::AuxiliaryLine::AuxiliaryStatistics::Exec> exec; std::shared_ptr<cisco_ios_xr::Cisco_IOS_XR_tty_server_oper::Tty::AuxiliaryNodes::AuxiliaryNode::AuxiliaryLine::AuxiliaryStatistics::Aaa> aaa; }; // Tty::AuxiliaryNodes::AuxiliaryNode::AuxiliaryLine::AuxiliaryStatistics class Tty::AuxiliaryNodes::AuxiliaryNode::AuxiliaryLine::AuxiliaryStatistics::Rs232 : public ydk::Entity { public: Rs232(); ~Rs232(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf data_bits; //type: uint32 ydk::YLeaf exec_disabled; //type: boolean ydk::YLeaf hardware_flow_control_status; //type: uint32 ydk::YLeaf parity_status; //type: uint32 ydk::YLeaf baud_rate; //type: uint32 ydk::YLeaf stop_bits; //type: uint32 ydk::YLeaf overrun_error_count; //type: uint32 ydk::YLeaf framing_error_count; //type: uint32 ydk::YLeaf parity_error_count; //type: uint32 }; // Tty::AuxiliaryNodes::AuxiliaryNode::AuxiliaryLine::AuxiliaryStatistics::Rs232 class Tty::AuxiliaryNodes::AuxiliaryNode::AuxiliaryLine::AuxiliaryStatistics::GeneralStatistics : public ydk::Entity { public: GeneralStatistics(); ~GeneralStatistics(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf terminal_length; //type: uint32 ydk::YLeaf terminal_width; //type: uint32 ydk::YLeaf async_interface; //type: boolean ydk::YLeaf flow_control_start_character; //type: int8 ydk::YLeaf flow_control_stop_character; //type: int8 ydk::YLeaf domain_lookup_enabled; //type: boolean ydk::YLeaf motd_banner_enabled; //type: boolean ydk::YLeaf private_flag; //type: boolean ydk::YLeaf terminal_type; //type: string ydk::YLeaf absolute_timeout; //type: uint32 ydk::YLeaf idle_time; //type: uint32 }; // Tty::AuxiliaryNodes::AuxiliaryNode::AuxiliaryLine::AuxiliaryStatistics::GeneralStatistics class Tty::AuxiliaryNodes::AuxiliaryNode::AuxiliaryLine::AuxiliaryStatistics::Exec : public ydk::Entity { public: Exec(); ~Exec(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf time_stamp_enabled; //type: boolean }; // Tty::AuxiliaryNodes::AuxiliaryNode::AuxiliaryLine::AuxiliaryStatistics::Exec class Tty::AuxiliaryNodes::AuxiliaryNode::AuxiliaryLine::AuxiliaryStatistics::Aaa : public ydk::Entity { public: Aaa(); ~Aaa(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf user_name; //type: string }; // Tty::AuxiliaryNodes::AuxiliaryNode::AuxiliaryLine::AuxiliaryStatistics::Aaa class Tty::AuxiliaryNodes::AuxiliaryNode::AuxiliaryLine::State : public ydk::Entity { public: State(); ~State(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; class Template; //type: Tty::AuxiliaryNodes::AuxiliaryNode::AuxiliaryLine::State::Template class General; //type: Tty::AuxiliaryNodes::AuxiliaryNode::AuxiliaryLine::State::General std::shared_ptr<cisco_ios_xr::Cisco_IOS_XR_tty_server_oper::Tty::AuxiliaryNodes::AuxiliaryNode::AuxiliaryLine::State::Template> template_; std::shared_ptr<cisco_ios_xr::Cisco_IOS_XR_tty_server_oper::Tty::AuxiliaryNodes::AuxiliaryNode::AuxiliaryLine::State::General> general; }; // Tty::AuxiliaryNodes::AuxiliaryNode::AuxiliaryLine::State class Tty::AuxiliaryNodes::AuxiliaryNode::AuxiliaryLine::State::Template : public ydk::Entity { public: Template(); ~Template(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf name; //type: string }; // Tty::AuxiliaryNodes::AuxiliaryNode::AuxiliaryLine::State::Template class Tty::AuxiliaryNodes::AuxiliaryNode::AuxiliaryLine::State::General : public ydk::Entity { public: General(); ~General(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf operation_; //type: SessionOperation ydk::YLeaf general_state; //type: LineState }; // Tty::AuxiliaryNodes::AuxiliaryNode::AuxiliaryLine::State::General class Tty::AuxiliaryNodes::AuxiliaryNode::AuxiliaryLine::Configuration : public ydk::Entity { public: Configuration(); ~Configuration(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; class ConnectionConfiguration; //type: Tty::AuxiliaryNodes::AuxiliaryNode::AuxiliaryLine::Configuration::ConnectionConfiguration std::shared_ptr<cisco_ios_xr::Cisco_IOS_XR_tty_server_oper::Tty::AuxiliaryNodes::AuxiliaryNode::AuxiliaryLine::Configuration::ConnectionConfiguration> connection_configuration; }; // Tty::AuxiliaryNodes::AuxiliaryNode::AuxiliaryLine::Configuration class Tty::AuxiliaryNodes::AuxiliaryNode::AuxiliaryLine::Configuration::ConnectionConfiguration : public ydk::Entity { public: ConnectionConfiguration(); ~ConnectionConfiguration(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf acl_out; //type: string ydk::YLeaf acl_in; //type: string class TransportInput; //type: Tty::AuxiliaryNodes::AuxiliaryNode::AuxiliaryLine::Configuration::ConnectionConfiguration::TransportInput std::shared_ptr<cisco_ios_xr::Cisco_IOS_XR_tty_server_oper::Tty::AuxiliaryNodes::AuxiliaryNode::AuxiliaryLine::Configuration::ConnectionConfiguration::TransportInput> transport_input; }; // Tty::AuxiliaryNodes::AuxiliaryNode::AuxiliaryLine::Configuration::ConnectionConfiguration class Tty::AuxiliaryNodes::AuxiliaryNode::AuxiliaryLine::Configuration::ConnectionConfiguration::TransportInput : public ydk::Entity { public: TransportInput(); ~TransportInput(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf select; //type: TtyTransportProtocolSelect ydk::YLeaf protocol1; //type: TtyTransportProtocol ydk::YLeaf protocol2; //type: TtyTransportProtocol ydk::YLeaf none; //type: uint32 }; // Tty::AuxiliaryNodes::AuxiliaryNode::AuxiliaryLine::Configuration::ConnectionConfiguration::TransportInput class LineState : public ydk::Enum { public: static const ydk::Enum::YLeaf none; static const ydk::Enum::YLeaf registered; static const ydk::Enum::YLeaf in_use; static int get_enum_value(const std::string & name) { if (name == "none") return 0; if (name == "registered") return 1; if (name == "in-use") return 2; return -1; } }; class SessionOperation : public ydk::Enum { public: static const ydk::Enum::YLeaf none; static const ydk::Enum::YLeaf setup; static const ydk::Enum::YLeaf shell; static const ydk::Enum::YLeaf transitioning; static const ydk::Enum::YLeaf packet; static int get_enum_value(const std::string & name) { if (name == "none") return 0; if (name == "setup") return 1; if (name == "shell") return 2; if (name == "transitioning") return 3; if (name == "packet") return 4; return -1; } }; } } #endif /* _CISCO_IOS_XR_TTY_SERVER_OPER_ */
53.004263
191
0.704957
[ "vector" ]
607038d9e87a5980215d351e61407c39bb4dc45d
6,667
cpp
C++
src/goto-instrument/contracts/utils.cpp
diffblue/cbmc
8c4d15b03050bf378e999a16a17568e7310cde7a
[ "BSD-4-Clause" ]
412
2016-04-02T01:14:27.000Z
2022-03-27T09:24:09.000Z
src/goto-instrument/contracts/utils.cpp
diffblue/cbmc
73a1414c164b1ef0b837ca8834de8616e43e2e69
[ "BSD-4-Clause" ]
4,671
2016-02-25T13:52:16.000Z
2022-03-31T22:14:46.000Z
src/goto-instrument/contracts/utils.cpp
diffblue/cbmc
8c4d15b03050bf378e999a16a17568e7310cde7a
[ "BSD-4-Clause" ]
266
2016-02-23T12:48:00.000Z
2022-03-22T18:15:51.000Z
/*******************************************************************\ Module: Utility functions for code contracts. Author: Saswat Padhi, saspadhi@amazon.com Date: September 2021 \*******************************************************************/ #include "utils.h" #include <goto-programs/cfg.h> #include <util/fresh_symbol.h> #include <util/graph.h> #include <util/message.h> #include <util/pointer_expr.h> #include <util/pointer_predicates.h> #include <util/simplify_expr.h> goto_programt::instructiont & add_pragma_disable_assigns_check(goto_programt::instructiont &instr) { instr.source_location_nonconst().add_pragma( CONTRACT_PRAGMA_DISABLE_ASSIGNS_CHECK); return instr; } goto_programt &add_pragma_disable_assigns_check(goto_programt &prog) { Forall_goto_program_instructions(it, prog) add_pragma_disable_assigns_check(*it); return prog; } static void append_safe_havoc_code_for_expr( const source_locationt location, const namespacet &ns, const exprt &expr, goto_programt &dest, const std::function<void()> &havoc_code_impl) { goto_programt skip_program; const auto skip_target = skip_program.add(goto_programt::make_skip(location)); // skip havocing only if all pointer derefs in the expression are valid // (to avoid spurious pointer deref errors) dest.add(goto_programt::make_goto( skip_target, not_exprt{all_dereferences_are_valid(expr, ns)}, location)); havoc_code_impl(); // add the final skip target dest.destructive_append(skip_program); } void havoc_if_validt::append_object_havoc_code_for_expr( const source_locationt location, const exprt &expr, goto_programt &dest) const { append_safe_havoc_code_for_expr(location, ns, expr, dest, [&]() { havoc_utilst::append_object_havoc_code_for_expr(location, expr, dest); }); } void havoc_if_validt::append_scalar_havoc_code_for_expr( const source_locationt location, const exprt &expr, goto_programt &dest) const { append_safe_havoc_code_for_expr(location, ns, expr, dest, [&]() { havoc_utilst::append_scalar_havoc_code_for_expr(location, expr, dest); }); } exprt all_dereferences_are_valid(const exprt &expr, const namespacet &ns) { exprt::operandst validity_checks; if(expr.id() == ID_dereference) validity_checks.push_back( good_pointer_def(to_dereference_expr(expr).pointer(), ns)); for(const auto &op : expr.operands()) validity_checks.push_back(all_dereferences_are_valid(op, ns)); return conjunction(validity_checks); } exprt generate_lexicographic_less_than_check( const std::vector<symbol_exprt> &lhs, const std::vector<symbol_exprt> &rhs) { PRECONDITION(lhs.size() == rhs.size()); if(lhs.empty()) { return false_exprt(); } // Store conjunctions of equalities. // For example, suppose that the two input vectors are <s1, s2, s3> and <l1, // l2, l3>. // Then this vector stores <s1 == l1, s1 == l1 && s2 == l2, // s1 == l1 && s2 == l2 && s3 == l3>. // In fact, the last element is unnecessary, so we do not create it. exprt::operandst equality_conjunctions(lhs.size()); equality_conjunctions[0] = binary_relation_exprt(lhs[0], ID_equal, rhs[0]); for(size_t i = 1; i < equality_conjunctions.size() - 1; i++) { binary_relation_exprt component_i_equality{lhs[i], ID_equal, rhs[i]}; equality_conjunctions[i] = and_exprt(equality_conjunctions[i - 1], component_i_equality); } // Store inequalities between the i-th components of the input vectors // (i.e. lhs and rhs). // For example, suppose that the two input vectors are <s1, s2, s3> and <l1, // l2, l3>. // Then this vector stores <s1 < l1, s1 == l1 && s2 < l2, s1 == l1 && // s2 == l2 && s3 < l3>. exprt::operandst lexicographic_individual_comparisons(lhs.size()); lexicographic_individual_comparisons[0] = binary_relation_exprt(lhs[0], ID_lt, rhs[0]); for(size_t i = 1; i < lexicographic_individual_comparisons.size(); i++) { binary_relation_exprt component_i_less_than{lhs[i], ID_lt, rhs[i]}; lexicographic_individual_comparisons[i] = and_exprt(equality_conjunctions[i - 1], component_i_less_than); } return disjunction(lexicographic_individual_comparisons); } void insert_before_swap_and_advance( goto_programt &destination, goto_programt::targett &target, goto_programt &payload) { const auto offset = payload.instructions.size(); destination.insert_before_swap(target, payload); std::advance(target, offset); } const symbolt &new_tmp_symbol( const typet &type, const source_locationt &location, const irep_idt &mode, symbol_table_baset &symtab, std::string suffix, bool is_auxiliary) { symbolt &new_symbol = get_fresh_aux_symbol( type, id2string(location.get_function()) + "::", suffix, location, mode, symtab); new_symbol.is_auxiliary = is_auxiliary; return new_symbol; } void disable_pointer_checks(source_locationt &source_location) { source_location.add_pragma("disable:pointer-check"); source_location.add_pragma("disable:pointer-primitive-check"); source_location.add_pragma("disable:pointer-overflow-check"); } void simplify_gotos(goto_programt &goto_program, namespacet &ns) { for(auto &instruction : goto_program.instructions) { if( instruction.is_goto() && simplify_expr(instruction.get_condition(), ns).is_false()) instruction.turn_into_skip(); } } bool is_loop_free( const goto_programt &goto_program, namespacet &ns, messaget &log) { // create cfg from instruction list cfg_baset<empty_cfg_nodet> cfg; cfg(goto_program); // check that all nodes are there INVARIANT( goto_program.instructions.size() == cfg.size(), "Instruction list vs CFG size mismatch."); // compute SCCs using idxt = graph_nodet<empty_cfg_nodet>::node_indext; std::vector<idxt> node_to_scc(cfg.size(), -1); auto nof_sccs = cfg.SCCs(node_to_scc); // compute size of each SCC std::vector<int> scc_size(nof_sccs, 0); for(auto scc : node_to_scc) { INVARIANT( 0 <= scc && scc < nof_sccs, "Could not determine SCC for instruction"); scc_size[scc]++; } // check they are all of size 1 for(size_t scc_id = 0; scc_id < nof_sccs; scc_id++) { auto size = scc_size[scc_id]; if(size > 1) { log.error() << "Found CFG SCC with size " << size << messaget::eom; for(const auto &node_id : node_to_scc) { if(node_to_scc[node_id] == scc_id) { const auto &pc = cfg[node_id].PC; goto_program.output_instruction(ns, "", log.error(), *pc); log.error() << messaget::eom; } } return false; } } return true; }
28.861472
80
0.697765
[ "vector" ]
6072dcc8c8ac1124f1588c570c6e61807d5d251f
650
cpp
C++
WinLib/Ctrl/Command.cpp
BartoszMilewski/CodeCoop
7d29f53ccf65b0d29ea7d6781a74507b52c08d0d
[ "MIT" ]
67
2018-03-02T10:50:02.000Z
2022-03-23T18:20:29.000Z
WinLib/Ctrl/Command.cpp
BartoszMilewski/CodeCoop
7d29f53ccf65b0d29ea7d6781a74507b52c08d0d
[ "MIT" ]
null
null
null
WinLib/Ctrl/Command.cpp
BartoszMilewski/CodeCoop
7d29f53ccf65b0d29ea7d6781a74507b52c08d0d
[ "MIT" ]
9
2018-03-01T16:38:28.000Z
2021-03-02T16:17:09.000Z
//--------------------------- // (c) Reliable Software 1998 //--------------------------- #include <WinLibBase.h> #include "Command.h" using namespace Cmd; // Returns -1 when command not found int Vector::GetIndex (char const * cmdName) const { int cmdIndex = -1; CmdMap::const_iterator iter = _cmdMap.find (cmdName); if (iter != _cmdMap.end ()) cmdIndex = iter->second; return cmdIndex; } // Returns -1 when command not found int Vector::Cmd2Id (char const * cmdName) const { int idx = GetIndex (cmdName); if (idx != -1) return idx + cmdIDBase; else return -1; } int Vector::Id2Index (int id) const { return id - cmdIDBase; }
18.571429
54
0.616923
[ "vector" ]
6073cb6cb842e3eef5d424cd7f162fbe1601da70
38,463
cpp
C++
util/scene.cpp
TheVaffel/ChameleonRT
deb7216ed448b3c59809a0b9a270ea81b48759a7
[ "MIT" ]
null
null
null
util/scene.cpp
TheVaffel/ChameleonRT
deb7216ed448b3c59809a0b9a270ea81b48759a7
[ "MIT" ]
null
null
null
util/scene.cpp
TheVaffel/ChameleonRT
deb7216ed448b3c59809a0b9a270ea81b48759a7
[ "MIT" ]
null
null
null
#include "scene.h" #include <algorithm> #include <iostream> #include <numeric> #include <stdexcept> #include <vector> #include "buffer_view.h" #include "file_mapping.h" #include "flatten_gltf.h" #include "gltf_types.h" #include "json.hpp" #include "phmap_utils.h" #include "stb_image.h" #include "tiny_gltf.h" #include "tiny_obj_loader.h" #include "util.h" #include <glm/ext.hpp> #include <glm/glm.hpp> #include <glm/gtc/type_ptr.hpp> QuadLight createLight(glm::vec3 pos, glm::vec3 normal, float size, float intensity) { QuadLight ql; ql.emission = glm::vec4(intensity); ql.normal = glm::vec4(glm::normalize(normal), 0); ql.position = glm::vec4(pos, 0); ortho_basis(ql.v_x, ql.v_y, glm::vec3(ql.normal)); ql.width = size; ql.height = size; return ql; } namespace std { template <> struct hash<glm::uvec3> { size_t operator()(glm::uvec3 const &v) const { return phmap::HashState().combine(0, v.x, v.y, v.z); } }; } bool operator==(const glm::uvec3 &a, const glm::uvec3 &b) { return a.x == b.x && a.y == b.y && a.z == b.z; } Scene::Scene(const std::string &fname) { const std::string ext = get_file_extension(fname); if (ext == "obj") { load_obj(fname); } else if (ext == "gltf" || ext == "glb") { load_gltf(fname); } else if (ext == "crts") { load_crts(fname); #ifdef PBRT_PARSER_ENABLED } else if (ext == "pbrt" || ext == "pbf") { load_pbrt(fname); #endif } else { std::cout << "Unsupported file type '" << ext << "'\n"; throw std::runtime_error("Unsupported file type " + ext); } } size_t Scene::unique_tris() const { return std::accumulate( meshes.begin(), meshes.end(), 0, [](const size_t &n, const Mesh &m) { return n + m.num_tris(); }); } size_t Scene::total_tris() const { return std::accumulate( instances.begin(), instances.end(), 0, [&](const size_t &n, const Instance &i) { return n + meshes[i.mesh_id].num_tris(); }); } size_t Scene::num_geometries() const { return std::accumulate( meshes.begin(), meshes.end(), 0, [](const size_t &n, const Mesh &m) { return n + m.geometries.size(); }); } void Scene::load_obj(const std::string &file) { std::cout << "Loading OBJ: " << file << "\n"; // Load the model w/ tinyobjloader. We just take any OBJ groups etc. stuff // that may be in the file and dump them all into a single OBJ model. tinyobj::attrib_t attrib; std::vector<tinyobj::shape_t> shapes; std::vector<tinyobj::material_t> obj_materials; std::string err, warn; const std::string obj_base_dir = file.substr(0, file.rfind('/')); bool ret = tinyobj::LoadObj( &attrib, &shapes, &obj_materials, &warn, &err, file.c_str(), obj_base_dir.c_str()); if (!warn.empty()) { std::cout << "TinyOBJ loading '" << file << "': " << warn << "\n"; } if (!ret || !err.empty()) { throw std::runtime_error("TinyOBJ Error loading " + file + " error: " + err); } Mesh mesh; std::vector<uint32_t> material_ids; for (size_t s = 0; s < shapes.size(); ++s) { // We load with triangulate on so we know the mesh will be all triangle faces const tinyobj::mesh_t &obj_mesh = shapes[s].mesh; // We've got to remap from 3 indices per-vert (independent for pos, normal & uv) used // by tinyobjloader over to single index per-vert (single for pos, normal & uv tuple) // used by renderers phmap::parallel_flat_hash_map<glm::uvec3, uint32_t> index_mapping; Geometry geom; // Note: not supporting per-primitive materials material_ids.push_back(obj_mesh.material_ids[0]); auto minmax_matid = std::minmax_element(obj_mesh.material_ids.begin(), obj_mesh.material_ids.end()); if (*minmax_matid.first != *minmax_matid.second) { std::cout << "Warning: per-face material IDs are not supported, materials may look " "wrong." " Please reexport your mesh with each material group as an OBJ group\n"; } for (size_t f = 0; f < obj_mesh.num_face_vertices.size(); ++f) { if (obj_mesh.num_face_vertices[f] != 3) { throw std::runtime_error("Non-triangle face found in " + file + "-" + shapes[s].name); } glm::uvec3 tri_indices; for (size_t i = 0; i < 3; ++i) { const glm::uvec3 idx(obj_mesh.indices[f * 3 + i].vertex_index, obj_mesh.indices[f * 3 + i].normal_index, obj_mesh.indices[f * 3 + i].texcoord_index); uint32_t vert_idx = 0; auto fnd = index_mapping.find(idx); if (fnd != index_mapping.end()) { vert_idx = fnd->second; } else { vert_idx = geom.vertices.size(); index_mapping[idx] = vert_idx; geom.vertices.emplace_back(attrib.vertices[3 * idx.x], attrib.vertices[3 * idx.x + 1], attrib.vertices[3 * idx.x + 2]); if (idx.y != uint32_t(-1)) { glm::vec3 n(attrib.normals[3 * idx.y], attrib.normals[3 * idx.y + 1], attrib.normals[3 * idx.y + 2]); geom.normals.push_back(glm::normalize(n)); } if (idx.z != uint32_t(-1)) { geom.uvs.emplace_back(attrib.texcoords[2 * idx.z], attrib.texcoords[2 * idx.z + 1]); } } tri_indices[i] = vert_idx; } geom.indices.push_back(tri_indices); } mesh.geometries.push_back(geom); } meshes.push_back(mesh); // OBJ has a single "instance" instances.emplace_back(glm::mat4(1.f), 0, material_ids); phmap::parallel_flat_hash_map<std::string, int32_t> texture_ids; // Parse the materials over to a similar DisneyMaterial representation for (const auto &m : obj_materials) { DisneyMaterial d; d.base_color = glm::vec3(m.diffuse[0], m.diffuse[1], m.diffuse[2]); d.specular = glm::clamp(m.shininess / 500.f, 0.f, 1.f); d.roughness = 1.f - d.specular; d.specular_transmission = glm::clamp(1.f - m.dissolve, 0.f, 1.f); if (!m.diffuse_texname.empty()) { std::string path = m.diffuse_texname; canonicalize_path(path); if (texture_ids.find(m.diffuse_texname) == texture_ids.end()) { texture_ids[m.diffuse_texname] = textures.size(); textures.emplace_back(obj_base_dir + "/" + path, m.diffuse_texname, SRGB); } const int32_t id = texture_ids[m.diffuse_texname]; uint32_t tex_mask = TEXTURED_PARAM_MASK; SET_TEXTURE_ID(tex_mask, id); d.base_color.r = *reinterpret_cast<float *>(&tex_mask); } materials.push_back(d); } validate_materials(); // OBJ will not have any lights in it, so just generate one std::cout << "Generating light for OBJ scene\n"; QuadLight light; light.emission = glm::vec4(20.f); light.normal = glm::vec4(glm::normalize(glm::vec3(0.5, -0.8, -0.5)), 0); light.position = -10.f * light.normal; ortho_basis(light.v_x, light.v_y, glm::vec3(light.normal)); light.width = 5.f; light.height = 5.f; lights.push_back(light); } void Scene::load_gltf(const std::string &fname) { std::cout << "Loading GLTF " << fname << "\n"; tinygltf::Model model; tinygltf::TinyGLTF context; std::string err, warn; bool ret = false; if (get_file_extension(fname) == "gltf") { ret = context.LoadASCIIFromFile(&model, &err, &warn, fname.c_str()); } else { ret = context.LoadBinaryFromFile(&model, &err, &warn, fname.c_str()); } if (!warn.empty()) { std::cout << "TinyGLTF loading: " << fname << " warnings: " << warn << "\n"; } if (!ret || !err.empty()) { throw std::runtime_error("TinyGLTF Error loading " + fname + " error: " + err); } if (model.defaultScene == -1) { model.defaultScene = 0; } flatten_gltf(model); std::vector<std::vector<uint32_t>> mesh_material_ids; // Load the meshes for (auto &m : model.meshes) { Mesh mesh; std::vector<uint32_t> material_ids; for (auto &p : m.primitives) { Geometry geom; material_ids.push_back(p.material); if (p.mode != TINYGLTF_MODE_TRIANGLES) { std::cout << "Unsupported primitive mode! File must contain only triangles\n"; throw std::runtime_error( "Unsupported primitive mode! Only triangles are supported"); } // Note: assumes there is a POSITION (is this required by the gltf spec?) Accessor<glm::vec3> pos_accessor(model.accessors[p.attributes["POSITION"]], model); for (size_t i = 0; i < pos_accessor.size(); ++i) { geom.vertices.push_back(pos_accessor[i]); } // Note: GLTF can have multiple texture coordinates used by different textures // (owch) I don't plan to support this auto fnd = p.attributes.find("TEXCOORD_0"); if (fnd != p.attributes.end()) { Accessor<glm::vec2> uv_accessor(model.accessors[fnd->second], model); for (size_t i = 0; i < uv_accessor.size(); ++i) { geom.uvs.push_back(uv_accessor[i]); } } #if 1 fnd = p.attributes.find("NORMAL"); if (fnd != p.attributes.end()) { Accessor<glm::vec3> normal_accessor(model.accessors[fnd->second], model); for (size_t i = 0; i < normal_accessor.size(); ++i) { geom.normals.push_back(normal_accessor[i]); } } #endif if (model.accessors[p.indices].componentType == TINYGLTF_COMPONENT_TYPE_UNSIGNED_SHORT) { Accessor<uint16_t> index_accessor(model.accessors[p.indices], model); for (size_t i = 0; i < index_accessor.size() / 3; ++i) { geom.indices.push_back(glm::uvec3(index_accessor[i * 3], index_accessor[i * 3 + 1], index_accessor[i * 3 + 2])); } } else if (model.accessors[p.indices].componentType == TINYGLTF_COMPONENT_TYPE_UNSIGNED_INT) { Accessor<uint32_t> index_accessor(model.accessors[p.indices], model); for (size_t i = 0; i < index_accessor.size() / 3; ++i) { geom.indices.push_back(glm::uvec3(index_accessor[i * 3], index_accessor[i * 3 + 1], index_accessor[i * 3 + 2])); } } else { std::cout << "Unsupported index type\n"; throw std::runtime_error("Unsupported index component type"); } mesh.geometries.push_back(geom); } mesh_material_ids.push_back(material_ids); meshes.push_back(mesh); } // Load images for (const auto &img : model.images) { if (img.component != 4) { std::cout << "WILL: Check non-4 component image support\n"; } if (img.pixel_type != TINYGLTF_COMPONENT_TYPE_UNSIGNED_BYTE) { std::cout << "Non-uchar images are not supported\n"; throw std::runtime_error("Unsupported image pixel type"); } Image texture; texture.name = img.name; texture.width = img.width; texture.height = img.height; texture.channels = img.component; texture.img = img.image; // Assume linear unless we find it used as a color texture texture.color_space = LINEAR; textures.push_back(texture); } // Load materials for (const auto &m : model.materials) { DisneyMaterial mat; mat.base_color.x = m.pbrMetallicRoughness.baseColorFactor[0]; mat.base_color.y = m.pbrMetallicRoughness.baseColorFactor[1]; mat.base_color.z = m.pbrMetallicRoughness.baseColorFactor[2]; mat.metallic = m.pbrMetallicRoughness.metallicFactor; mat.roughness = m.pbrMetallicRoughness.roughnessFactor; if (m.pbrMetallicRoughness.baseColorTexture.index != -1) { const int32_t id = model.textures[m.pbrMetallicRoughness.baseColorTexture.index].source; textures[id].color_space = SRGB; uint32_t tex_mask = TEXTURED_PARAM_MASK; SET_TEXTURE_ID(tex_mask, id); mat.base_color.r = *reinterpret_cast<float *>(&tex_mask); } // glTF: metallic is blue channel, roughness is green channel if (m.pbrMetallicRoughness.metallicRoughnessTexture.index != -1) { const int32_t id = model.textures[m.pbrMetallicRoughness.metallicRoughnessTexture.index].source; textures[id].color_space = LINEAR; uint32_t tex_mask = TEXTURED_PARAM_MASK; SET_TEXTURE_ID(tex_mask, id); SET_TEXTURE_CHANNEL(tex_mask, 2); mat.metallic = *reinterpret_cast<float *>(&tex_mask); tex_mask = TEXTURED_PARAM_MASK; SET_TEXTURE_ID(tex_mask, id); SET_TEXTURE_CHANNEL(tex_mask, 1); mat.roughness = *reinterpret_cast<float *>(&tex_mask); } materials.push_back(mat); } for (const auto &nid : model.scenes[model.defaultScene].nodes) { const tinygltf::Node &n = model.nodes[nid]; if (n.mesh != -1) { const glm::mat4 transform = read_node_transform(n); instances.emplace_back(transform, n.mesh, mesh_material_ids[n.mesh]); } } validate_materials(); // Does GLTF have lights in the file? If one is missing we should generate one, // otherwise we can load them std::cout << "Generating light for GLTF scene\n"; QuadLight light; light = createLight(glm::vec3(0.0, 2.5f, 0.0), glm::vec3(0.0, -1.0, 0.0), 2.0f, 40.0f); std::cout << "Light position = " << light.position.x << ", " << light.position.y << ", " << light.position.z << std::endl; lights.push_back(light); } void Scene::load_crts(const std::string &file) { using json = nlohmann::json; std::cout << "Loading CRTS " << file << "\n"; auto mapping = std::make_shared<FileMapping>(file); const uint64_t json_header_size = *reinterpret_cast<const uint64_t *>(mapping->data()); const uint64_t total_header_size = json_header_size + sizeof(uint64_t); json header = json::parse(mapping->data() + sizeof(uint64_t), mapping->data() + total_header_size); const uint8_t *data_base = mapping->data() + total_header_size; // Blender only supports a single geometry per-mesh so this works kind of like a blend of // GLTF and OBJ for (size_t i = 0; i < header["meshes"].size(); ++i) { auto &m = header["meshes"][i]; Geometry geom; { const uint64_t view_id = m["positions"].get<uint64_t>(); auto &v = header["buffer_views"][view_id]; const DTYPE dtype = parse_dtype(v["type"]); BufferView view(data_base + v["byte_offset"].get<uint64_t>(), v["byte_length"].get<uint64_t>(), dtype_stride(dtype)); Accessor<glm::vec3> accessor(view); geom.vertices = std::vector<glm::vec3>(accessor.begin(), accessor.end()); } { const uint64_t view_id = m["indices"].get<uint64_t>(); auto &v = header["buffer_views"][view_id]; const DTYPE dtype = parse_dtype(v["type"]); BufferView view(data_base + v["byte_offset"].get<uint64_t>(), v["byte_length"].get<uint64_t>(), dtype_stride(dtype)); Accessor<glm::uvec3> accessor(view); geom.indices = std::vector<glm::uvec3>(accessor.begin(), accessor.end()); } if (m.find("texcoords") != m.end()) { const uint64_t view_id = m["texcoords"].get<uint64_t>(); auto &v = header["buffer_views"][view_id]; const DTYPE dtype = parse_dtype(v["type"]); BufferView view(data_base + v["byte_offset"].get<uint64_t>(), v["byte_length"].get<uint64_t>(), dtype_stride(dtype)); Accessor<glm::vec2> accessor(view); geom.uvs = std::vector<glm::vec2>(accessor.begin(), accessor.end()); } #if 0 if (m.find("normals") != m.end()) { const uint64_t view_id = m["normals"].get<uint64_t>(); auto &v = header["buffer_views"][view_id]; const DTYPE dtype = parse_dtype(v["type"]); BufferView view(data_base + v["byte_offset"].get<uint64_t>(), v["byte_length"].get<uint64_t>(), dtype_stride(dtype)); Accessor<glm::vec3> accessor(view); geom.normals = std::vector<glm::vec3>(accessor.begin(), accessor.end()); } #endif Mesh mesh; mesh.geometries.push_back(geom); meshes.push_back(mesh); } for (size_t i = 0; i < header["images"].size(); ++i) { auto &img = header["images"][i]; const uint64_t view_id = img["view"].get<uint64_t>(); auto &v = header["buffer_views"][view_id]; const DTYPE dtype = parse_dtype(v["type"]); BufferView view(data_base + v["byte_offset"].get<uint64_t>(), v["byte_length"].get<uint64_t>(), dtype_stride(dtype)); Accessor<uint8_t> accessor(view); stbi_set_flip_vertically_on_load(1); int x, y, n; uint8_t *img_data = stbi_load_from_memory(accessor.begin(), accessor.size(), &x, &y, &n, 4); stbi_set_flip_vertically_on_load(0); if (!img_data) { std::cout << "Failed to load " << img["name"].get<std::string>() << " from view\n"; throw std::runtime_error("Failed to load " + img["name"].get<std::string>()); } ColorSpace color_space = SRGB; if (img["color_space"].get<std::string>() == "LINEAR") { color_space = LINEAR; } textures.emplace_back(img_data, x, y, 4, img["name"].get<std::string>(), color_space); stbi_image_free(img_data); } for (size_t i = 0; i < header["materials"].size(); ++i) { auto &m = header["materials"][i]; DisneyMaterial mat; const auto base_color_data = m["base_color"].get<std::vector<float>>(); mat.base_color = glm::make_vec3(base_color_data.data()); if (m.find("base_color_texture") != m.end()) { const int32_t id = m["base_color_texture"].get<int32_t>(); uint32_t tex_mask = TEXTURED_PARAM_MASK; SET_TEXTURE_ID(tex_mask, id); mat.base_color.r = *reinterpret_cast<float *>(&tex_mask); } auto parse_float_param = [&](const std::string &param, float &val) { val = m[param].get<float>(); const std::string texture_name = param + "_texture"; if (m.find(texture_name) != m.end()) { const int32_t id = m[texture_name]["texture"].get<int32_t>(); const uint32_t channel = m[texture_name]["channel"].get<uint32_t>(); uint32_t tex_mask = TEXTURED_PARAM_MASK; SET_TEXTURE_ID(tex_mask, id); SET_TEXTURE_CHANNEL(tex_mask, channel); val = *reinterpret_cast<float *>(&tex_mask); } }; parse_float_param("metallic", mat.metallic); parse_float_param("specular", mat.specular); parse_float_param("roughness", mat.roughness); parse_float_param("specular_tint", mat.specular_tint); parse_float_param("anisotropic", mat.anisotropy); parse_float_param("sheen", mat.sheen); parse_float_param("sheen_tint", mat.sheen_tint); parse_float_param("clearcoat", mat.clearcoat); // TODO: May need to invert this param coming from Blender to give clearcoat gloss? // or does the disney gloss term = roughness? parse_float_param("clearcoat_roughness", mat.clearcoat_gloss); parse_float_param("ior", mat.ior); parse_float_param("transmission", mat.specular_transmission); materials.push_back(mat); } for (size_t i = 0; i < header["objects"].size(); ++i) { auto &n = header["objects"][i]; const std::string type = n["type"]; const glm::mat4 matrix = glm::make_mat4(n["matrix"].get<std::vector<float>>().data()); if (type == "MESH") { const auto mat_id = std::vector<uint32_t>{n["material"].get<uint32_t>()}; instances.emplace_back(matrix, n["mesh"].get<uint64_t>(), mat_id); } else if (type == "LIGHT") { QuadLight light; const auto color = glm::make_vec3(n["color"].get<std::vector<float>>().data()); light.emission = glm::vec4(color * n["energy"].get<float>(), 1.f); light.position = glm::column(matrix, 3); light.normal = -glm::normalize(glm::column(matrix, 2)); light.v_x = glm::normalize(glm::column(matrix, 0)); light.v_y = glm::normalize(glm::column(matrix, 1)); light.width = n["size"][0].get<float>(); light.height = n["size"][1].get<float>(); lights.push_back(light); } else if (type == "CAMERA") { Camera camera; camera.position = glm::column(matrix, 3); const glm::vec3 dir(glm::normalize(-glm::column(matrix, 2))); camera.center = camera.position + dir * 10.f; camera.up = glm::normalize(glm::column(matrix, 1)); // TODO: Not sure on why I need to scale fovy down to match Blender, // it doesn't quite line up either but this is pretty close. camera.fov_y = n["fov_y"].get<float>() / 1.18f; cameras.push_back(camera); } else { throw std::runtime_error("Unsupported object type: not a mesh or camera?"); } } validate_materials(); if (lights.empty()) { // TODO: Should add support for other light types? Then autogenerate a directional // light? std::cout << "No lights found in scene, generating one\n"; QuadLight light; light.emission = glm::vec4(10.f); light.normal = glm::vec4(glm::normalize(glm::vec3(0.5, -0.8, -0.5)), 0); light.position = -10.f * light.normal; ortho_basis(light.v_x, light.v_y, glm::vec3(light.normal)); light.width = 5.f; light.height = 5.f; lights.push_back(light); } } #ifdef PBRT_PARSER_ENABLED void Scene::load_pbrt(const std::string &file) { std::shared_ptr<pbrt::Scene> scene = nullptr; try { if (get_file_extension(file) == "pbrt") { scene = pbrt::importPBRT(file); } else { scene = pbrt::Scene::loadFrom(file); } if (!scene) { throw std::runtime_error("Failed to load PBRT scene from " + file); } scene->makeSingleLevel(); } catch (const std::runtime_error &e) { std::cout << "Error loading PBRT scene " << file << "\n"; throw e; } const std::string pbrt_base_dir = file.substr(0, file.rfind('/')); // TODO: The world can also have some top-level things we may need to load. But is this // common? Or does Ingo's make single level flatten these down to a shape? for (const auto &obj : scene->world->shapes) { if (obj->material) { std::cout << "Top level Mat: " << obj->material->toString() << "\n"; } // What would these top-level textures be used for? if (!obj->textures.empty()) { std::cout << "top level textures " << obj->textures.size() << "\n"; for (const auto &t : obj->textures) { auto img_tex = std::dynamic_pointer_cast<pbrt::ImageTexture>(t.second); if (img_tex) { std::cout << "Image texture: " << t.first << " from file " << img_tex->fileName << "\n"; } else { std::cout << "Unsupported non-image texture used by texture '" << t.first << "'\n"; } } } if (obj->areaLight) { std::cout << "Encountered area light\n"; } if (pbrt::TriangleMesh::SP mesh = std::dynamic_pointer_cast<pbrt::TriangleMesh>(obj)) { std::cout << "Found root level triangle mesh w/ " << mesh->index.size() << " triangles: " << mesh->toString() << "\n"; } else if (pbrt::QuadMesh::SP mesh = std::dynamic_pointer_cast<pbrt::QuadMesh>(obj)) { std::cout << "Encountered root level quadmesh (unsupported type). Will TODO maybe " "triangulate\n"; } else { std::cout << "un-handled root level geometry type : " << obj->toString() << std::endl; } } // For PBRTv3 Each Mesh corresponds to a PBRT Object, consisting of potentially // multiple Shapes. This maps to a Mesh with multiple geometries, which can then be // instanced phmap::parallel_flat_hash_map<pbrt::Material::SP, size_t> pbrt_materials; phmap::parallel_flat_hash_map<pbrt::Texture::SP, size_t> pbrt_textures; phmap::parallel_flat_hash_map<std::string, size_t> pbrt_objects; for (const auto &inst : scene->world->instances) { // Note: Materials are per-shape, so we should parse them and the IDs when loading // the shapes // Check if this object has already been loaded for the instance auto fnd = pbrt_objects.find(inst->object->name); size_t mesh_id = -1; std::vector<uint32_t> material_ids; if (fnd == pbrt_objects.end()) { std::cout << "Loading newly encountered instanced object " << inst->object->name << "\n"; // TODO: materials for pbrt std::vector<Geometry> geometries; for (const auto &g : inst->object->shapes) { if (pbrt::TriangleMesh::SP mesh = std::dynamic_pointer_cast<pbrt::TriangleMesh>(g)) { std::cout << "Object triangle mesh w/ " << mesh->index.size() << " triangles: " << mesh->toString() << "\n"; uint32_t material_id = -1; if (mesh->material) { material_id = load_pbrt_materials(mesh->material, mesh->textures, pbrt_base_dir, pbrt_materials, pbrt_textures); } material_ids.push_back(material_id); Geometry geom; geom.vertices.reserve(mesh->vertex.size()); std::transform( mesh->vertex.begin(), mesh->vertex.end(), std::back_inserter(geom.vertices), [](const pbrt::vec3f &v) { return glm::vec3(v.x, v.y, v.z); }); geom.indices.reserve(mesh->index.size()); std::transform( mesh->index.begin(), mesh->index.end(), std::back_inserter(geom.indices), [](const pbrt::vec3i &v) { return glm::ivec3(v.x, v.y, v.z); }); geom.uvs.reserve(mesh->texcoord.size()); std::transform(mesh->texcoord.begin(), mesh->texcoord.end(), std::back_inserter(geom.uvs), [](const pbrt::vec2f &v) { return glm::vec2(v.x, v.y); }); geometries.push_back(geom); } else if (pbrt::QuadMesh::SP mesh = std::dynamic_pointer_cast<pbrt::QuadMesh>(g)) { std::cout << "Encountered instanced quadmesh (unsupported type). Will " "TODO maybe triangulate\n"; } else { std::cout << "un-handled instanced geometry type : " << g->toString() << std::endl; } } if (inst->object->instances.size() > 0) { std::cout << "Warning: Potentially multilevel instancing is in the scene after " "flattening?\n"; } // Mesh only contains unsupported objects, skip it if (geometries.empty()) { std::cout << "WARNING: Instance contains only unsupported geometries, " "skipping\n"; continue; } mesh_id = meshes.size(); pbrt_objects[inst->object->name] = meshes.size(); meshes.emplace_back(geometries); } else { // TODO: The instance needs to get the material ids for its shapes if we found it mesh_id = fnd->second; for (const auto &g : inst->object->shapes) { if (pbrt::TriangleMesh::SP mesh = std::dynamic_pointer_cast<pbrt::TriangleMesh>(g)) { uint32_t material_id = -1; if (mesh->material) { material_id = load_pbrt_materials(mesh->material, mesh->textures, pbrt_base_dir, pbrt_materials, pbrt_textures); } material_ids.push_back(material_id); } } } glm::mat4 transform(1.f); transform[0] = glm::vec4(inst->xfm.l.vx.x, inst->xfm.l.vx.y, inst->xfm.l.vx.z, 0.f); transform[1] = glm::vec4(inst->xfm.l.vy.x, inst->xfm.l.vy.y, inst->xfm.l.vy.z, 0.f); transform[2] = glm::vec4(inst->xfm.l.vz.x, inst->xfm.l.vz.y, inst->xfm.l.vz.z, 0.f); transform[3] = glm::vec4(inst->xfm.p.x, inst->xfm.p.y, inst->xfm.p.z, 1.f); instances.emplace_back(transform, mesh_id, material_ids); } validate_materials(); std::cout << "Generating light for PBRT scene, TODO Will: Load them from the file\n"; QuadLight light; light.emission = glm::vec4(20.f); light.normal = glm::vec4(glm::normalize(glm::vec3(0.5, -0.8, -0.5)), 0); light.position = -10.f * light.normal; ortho_basis(light.v_x, light.v_y, glm::vec3(light.normal)); light.width = 5.f; light.height = 5.f; lights.push_back(light); } uint32_t Scene::load_pbrt_materials( const pbrt::Material::SP &mat, const std::map<std::string, pbrt::Texture::SP> &texture_overrides, const std::string &pbrt_base_dir, phmap::parallel_flat_hash_map<pbrt::Material::SP, size_t> &pbrt_materials, phmap::parallel_flat_hash_map<pbrt::Texture::SP, size_t> &pbrt_textures) { auto fnd = pbrt_materials.find(mat); if (fnd != pbrt_materials.end()) { return fnd->second; } // TODO: The way some of the texturing can work is that the object's attached textures // can override the material parameters in some way if (!texture_overrides.empty()) { std::cout << "TODO: per-shape texture override support\n"; for (const auto &t : texture_overrides) { std::cout << t.first << "\n"; } } DisneyMaterial loaded_mat; if (auto m = std::dynamic_pointer_cast<pbrt::DisneyMaterial>(mat)) { loaded_mat.anisotropy = m->anisotropic; loaded_mat.clearcoat = m->clearCoat; loaded_mat.clearcoat_gloss = m->clearCoatGloss; loaded_mat.base_color = glm::vec3(m->color.x, m->color.y, m->color.z); loaded_mat.ior = m->eta; loaded_mat.metallic = m->metallic; loaded_mat.roughness = m->roughness; loaded_mat.sheen = m->sheen; loaded_mat.sheen_tint = m->sheenTint; loaded_mat.specular_tint = m->specularTint; // PBRT Doesn't use the specular parameter or have textures for the Disney // Material? loaded_mat.specular = 0.f; } else if (auto m = std::dynamic_pointer_cast<pbrt::PlasticMaterial>(mat)) { loaded_mat.base_color = glm::vec3(m->kd.x, m->kd.y, m->kd.z); if (m->map_kd) { if (auto const_tex = std::dynamic_pointer_cast<pbrt::ConstantTexture>(m->map_kd)) { loaded_mat.base_color = glm::vec3(const_tex->value.x, const_tex->value.y, const_tex->value.z); } else { const uint32_t tex_id = load_pbrt_texture(m->map_kd, pbrt_base_dir, pbrt_textures); if (tex_id != uint32_t(-1)) { uint32_t tex_mask = TEXTURED_PARAM_MASK; SET_TEXTURE_ID(tex_mask, tex_id); loaded_mat.base_color.r = *reinterpret_cast<float *>(&tex_mask); } } } const glm::vec3 ks(m->ks.x, m->ks.y, m->ks.z); loaded_mat.specular = luminance(ks); loaded_mat.roughness = m->roughness; } else if (auto m = std::dynamic_pointer_cast<pbrt::MatteMaterial>(mat)) { loaded_mat.base_color = glm::vec3(m->kd.x, m->kd.y, m->kd.z); if (m->map_kd) { if (auto const_tex = std::dynamic_pointer_cast<pbrt::ConstantTexture>(m->map_kd)) { loaded_mat.base_color = glm::vec3(const_tex->value.x, const_tex->value.y, const_tex->value.z); } else { const uint32_t tex_id = load_pbrt_texture(m->map_kd, pbrt_base_dir, pbrt_textures); if (tex_id != uint32_t(-1)) { uint32_t tex_mask = TEXTURED_PARAM_MASK; SET_TEXTURE_ID(tex_mask, tex_id); loaded_mat.base_color.r = *reinterpret_cast<float *>(&tex_mask); } } } } else if (auto m = std::dynamic_pointer_cast<pbrt::SubstrateMaterial>(mat)) { loaded_mat.base_color = glm::vec3(m->kd.x, m->kd.y, m->kd.z); if (m->map_kd) { if (auto const_tex = std::dynamic_pointer_cast<pbrt::ConstantTexture>(m->map_kd)) { loaded_mat.base_color = glm::vec3(const_tex->value.x, const_tex->value.y, const_tex->value.z); } else { const uint32_t tex_id = load_pbrt_texture(m->map_kd, pbrt_base_dir, pbrt_textures); if (tex_id != uint32_t(-1)) { uint32_t tex_mask = TEXTURED_PARAM_MASK; SET_TEXTURE_ID(tex_mask, tex_id); loaded_mat.base_color.r = *reinterpret_cast<float *>(&tex_mask); } } } // Sounds like this is kind of what the SubstrateMaterial acts like? Diffuse with a // specular and clearcoat? const glm::vec3 ks(m->ks.x, m->ks.y, m->ks.z); loaded_mat.specular = luminance(ks); loaded_mat.roughness = 1.f; loaded_mat.clearcoat = 1.f; loaded_mat.clearcoat_gloss = luminance(ks); } else { std::cout << "Unsupported material type " << mat->toString() << "\n"; return -1; } const uint32_t mat_id = materials.size(); pbrt_materials[mat] = mat_id; materials.push_back(loaded_mat); return mat_id; } uint32_t Scene::load_pbrt_texture( const pbrt::Texture::SP &texture, const std::string &pbrt_base_dir, phmap::parallel_flat_hash_map<pbrt::Texture::SP, size_t> &pbrt_textures) { auto fnd = pbrt_textures.find(texture); if (fnd != pbrt_textures.end()) { return fnd->second; } if (auto t = std::dynamic_pointer_cast<pbrt::ImageTexture>(texture)) { std::string path = t->fileName; canonicalize_path(path); try { Image img(pbrt_base_dir + "/" + path, t->fileName, SRGB); const uint32_t id = textures.size(); pbrt_textures[texture] = id; textures.push_back(img); std::cout << "Loaded image texture: " << t->fileName << "\n"; return id; } catch (const std::runtime_error &) { std::cout << "Unsupported file format or failed to load file: " << t->fileName << "\n"; return -1; } } std::cout << "Texture type " << texture->toString() << " is not supported\n"; return -1; } #endif void Scene::validate_materials() { const bool need_default_mat = std::find_if(instances.begin(), instances.end(), [](const Instance &i) { return std::find(i.material_ids.begin(), i.material_ids.end(), uint32_t(-1)) != i.material_ids.end(); }) != instances.end(); if (need_default_mat) { std::cout << "No materials assigned for some objects, generating a default\n"; const uint32_t default_mat_id = materials.size(); materials.push_back(DisneyMaterial()); for (auto &i : instances) { for (auto &m : i.material_ids) { if (m == -1) { m = default_mat_id; } } } } }
41.269313
126
0.546031
[ "mesh", "geometry", "object", "shape", "vector", "model", "transform" ]
6075c7c575869cbf82ebcf2d2a1904a262979510
22,246
hh
C++
libgringo/gringo/domain.hh
0x326/clingo
225f1b482ed68797211855db014d18e88d0ddc7b
[ "MIT" ]
null
null
null
libgringo/gringo/domain.hh
0x326/clingo
225f1b482ed68797211855db014d18e88d0ddc7b
[ "MIT" ]
1
2019-08-30T15:34:43.000Z
2019-08-30T16:45:51.000Z
libgringo/gringo/domain.hh
0x326/clingo
225f1b482ed68797211855db014d18e88d0ddc7b
[ "MIT" ]
null
null
null
// {{{ MIT License // Copyright 2017 Roland Kaminski // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to // deal in the Software without restriction, including without limitation the // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or // sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS // IN THE SOFTWARE. // }}} #ifndef _GRINGO_DOMAIN_HH #define _GRINGO_DOMAIN_HH #include <cassert> #include <gringo/base.hh> #include <gringo/types.hh> #include <deque> #include <gringo/hash_set.hh> namespace Gringo { // {{{ declaration of BinderType enum class BinderType { NEW, OLD, ALL }; inline std::ostream &operator<<(std::ostream &out, BinderType x) { switch (x) { case BinderType::NEW: { out << "NEW"; break; } case BinderType::OLD: { out << "OLD"; break; } case BinderType::ALL: { out << "ALL"; break; } } return out; } // }}} // {{{ declaration of IndexUpdater class IndexUpdater { public: // Updates the index with fresh atoms from the domain. // First traverses the atoms in the domain skipping undefined atoms and // afterwards traversing undefined atoms that have been defined later. virtual bool update() = 0; virtual ~IndexUpdater() { } }; using SValVec = std::vector<Term::SVal>; // }}} // {{{ declaration of BindIndex template <class Domain> class BindIndexEntry { public: struct Hash { size_t operator()(BindIndexEntry const &e) const { return e.hash(); }; size_t operator()(SymVec const &e) const { return hash_range(e.begin(), e.end()); }; }; using SizeType = typename Domain::SizeType; using DataVec = std::vector<uint64_t>; BindIndexEntry(SymVec const &bound) : end_(0) , reserved_(1) , data_(nullptr) , begin_(nullptr) { data_ = reinterpret_cast<uint64_t*>(malloc(sizeof(uint64_t) * bound.size() + sizeof(SizeType))); if (!data_) { throw std::bad_alloc(); } begin_ = reinterpret_cast<SizeType*>(data_ + bound.size()); uint64_t *it = data_; for (auto &sym : bound) { *it++ = sym.rep(); } } BindIndexEntry(BindIndexEntry const &) = delete; BindIndexEntry(BindIndexEntry &&e) : end_(0) , reserved_(0) , data_(nullptr) , begin_(nullptr) { *this = std::move(e); } BindIndexEntry &operator=(BindIndexEntry const &) = delete; BindIndexEntry &operator=(BindIndexEntry &&e) { std::swap(data_, e.data_); std::swap(begin_, e.begin_); std::swap(end_, e.end_); std::swap(reserved_, e.reserved_); return *this; } ~BindIndexEntry() { free(data_); } SizeType const *begin() const { return begin_; } SizeType const *end() const { return begin_ + end_; } void push(SizeType x) { assert(reserved_ > 0 && end_ <= reserved_); if (end_ == reserved_) { size_t bound = reinterpret_cast<uint64_t const*>(begin_) - data_; size_t oldsize = sizeof(uint64_t) * bound + sizeof(SizeType) * end_; size_t size = oldsize + sizeof(SizeType) * end_; if (size < oldsize) { throw std::runtime_error("size limit exceeded"); } uint64_t *ret = reinterpret_cast<uint64_t*>(realloc(data_, size)); if (!ret) { throw std::bad_alloc(); } reserved_ = 2 * end_; if (data_ != ret) { data_ = ret; begin_ = reinterpret_cast<SizeType*>(data_ + bound); } } begin_[end_++] = x; } size_t hash() const { return hash_range(data_, reinterpret_cast<uint64_t *>(begin_)); } bool operator==(BindIndexEntry const &x) const { return std::equal(x.data_, reinterpret_cast<uint64_t const *>(x.begin_), data_, [](uint64_t a, uint64_t b) { return a == b; }); } bool operator==(SymVec const &vec) const { return std::equal(vec.begin(), vec.end(), data_, [](Symbol const &a, uint64_t b) { return a.rep() == b; }); } private: Id_t end_; Id_t reserved_; uint64_t* data_; SizeType* begin_; }; // An index for a positive literal occurrence // with at least one variable bound and one variable unbound. template <class Domain> class BindIndex : public IndexUpdater { public: using SizeType = typename Domain::SizeType; using OffsetVec = std::vector<SizeType>; using Iterator = SizeType const *; using Entry = BindIndexEntry<Domain>; using Index = UniqueVec<Entry, typename Entry::Hash, EqualTo>; struct OffsetRange { bool next(Id_t &offset, Term const &repr, BindIndex &idx) { if (current != end) { offset = *current++; repr.match(idx.domain_[offset]); return true; } return false; } Iterator current; Iterator end; }; BindIndex(Domain &domain, SValVec &&bound, UTerm &&repr) : repr_(std::move(repr)) , domain_(domain) , bound_(std::move(bound)) { assert(!bound_.empty()); } bool update() override { return domain_.update([this](SizeType offset) { add(offset); }, *repr_, imported_, importedDelayed_); } // Returns a range of offsets corresponding to atoms that match the given bound variables. OffsetRange lookup(SValVec const &bound, BinderType type, Logger &) { boundVals_.clear(); for (auto &&x : bound) { boundVals_.emplace_back(*x); } auto it(data_.find(boundVals_)); if (it != data_.end()) { auto cmp = [this](SizeType a, SizeType gen) { return domain_[a].generation() < gen; }; switch (type) { case BinderType::NEW: { return { std::lower_bound(it->begin(), it->end(), domain_.generation(), cmp), it->end() }; } case BinderType::OLD: { return { it->begin(), std::lower_bound(it->begin(), it->end(), domain_.generation(), cmp) }; } case BinderType::ALL: { return { it->begin(), it->end() }; } } } return { nullptr, nullptr }; } // The equality and hash functions are used to prevent adding structurally equivalent indices twice. bool operator==(BindIndex const &x) const { return *repr_ == *x.repr_; } size_t hash() const { return repr_->hash(); } virtual ~BindIndex() noexcept = default; private: // Adds an atom given by its offset to the index. // Assumes that the atom matches and has not been added previously. void add(Id_t offset) { boundVals_.clear(); for (auto &y : bound_) { boundVals_.emplace_back(*y); } auto jt = data_.findPush(boundVals_, boundVals_).first; jt->push(offset); } private: UTerm const repr_; Domain &domain_; SValVec bound_; SymVec boundVals_; Index data_; Id_t imported_ = 0; Id_t importedDelayed_ = 0; }; // }}} // {{{ declaration of FullIndex // An index for a positive literal occurrence with all literals unbound. // The matches are represented as ranges. // This means a literal of form p(X,Y) where both X and Y are unbound has an index with just one range. template <class Domain> class FullIndex : public IndexUpdater { public: using SizeType = typename Domain::SizeType; using IntervalVec = std::vector<std::pair<SizeType, SizeType>>; using Iterator = typename IntervalVec::iterator; struct OffsetRange { bool next(SizeType &offset, Term const &repr, FullIndex &idx) { // For Old and All atoms, iterate forward until the atoms in the index are exceeded. // For Old atoms stop early if the atoms do not belong to previous generations anymore. if (type != BinderType::NEW) { if (rangeOffset == idx.index_.size()) { return false; } if (intervalOffset == idx.index_[rangeOffset].second) { ++rangeOffset; if (rangeOffset == idx.index_.size()) { return false; } intervalOffset = idx.index_[rangeOffset].first; } offset = intervalOffset++; auto &atom = idx.domain_[offset]; if (type == BinderType::OLD && atom.generation() >= idx.domain_.generation()) { rangeOffset = static_cast<SizeType>(idx.index_.size()); return false; } } // For New atoms iterate backward until the atoms do not belong to the current generation anymore. else { if (rangeOffset == 0) { return false; } if (intervalOffset == idx.index_[rangeOffset - 1].first) { --rangeOffset; if (rangeOffset == 0) { return false; } intervalOffset = idx.index_[rangeOffset-1].second; } offset = --intervalOffset; auto &atom = idx.domain_[offset]; if (atom.generation() < idx.domain_.generation()) { rangeOffset = 0; return false; } } repr.match(idx.domain_[offset]); return true; } BinderType type; SizeType rangeOffset; SizeType intervalOffset; }; // This index can be initialized to skip some atoms in a domain. // The number of skipped atoms are part of the equality and hash comparisons of the index. // This is used to implement projection in the incremental case. FullIndex(Domain &domain, UTerm &&repr, Id_t imported) : repr_(std::move(repr)) , domain_(domain) , imported_(imported) , initialImport_(imported) { } // Returns a range of offsets corresponding to matching atoms. OffsetRange lookup(BinderType type, Logger &) { switch (type) { case BinderType::OLD: case BinderType::ALL: { return { type, 0, !index_.empty() ? index_.front().first : 0 }; } case BinderType::NEW: { return { type, static_cast<SizeType>(index_.size()), !index_.empty() ? index_.back().second : 0 }; } } throw std::logic_error("cannot happen"); } bool update() override { return domain_.update([this](SizeType offset) { add(offset); return true; }, *repr_, imported_, importedDelayed_); } bool operator==(FullIndex const &x) const { return *repr_ == *x.repr_ && initialImport_ == x.initialImport_; } size_t hash() const { return get_value_hash(repr_, initialImport_); } virtual ~FullIndex() noexcept = default; private: // Adds an atom offset to the index. // The offset is merged into the last interval if possible. // Maintains the generation order by always inserting at the end. void add(SizeType offset) { if (!index_.empty() && index_.back().second == offset) { index_.back().second++; } else { index_.emplace_back(offset, offset + 1); } } private: UTerm repr_; Domain &domain_; IntervalVec index_; Id_t imported_; Id_t importedDelayed_ = 0; Id_t initialImport_; }; // }}} // {{{ declaration of Domain class Domain { public: virtual void init() = 0; virtual void enqueue() = 0; virtual bool dequeue() = 0; virtual bool isEnqueued() const = 0; // Advances the domain to the next generation. // Returns true if there are fresh atoms that have to be incorporated into the indices. virtual void nextGeneration() = 0; virtual void setDomainOffset(Id_t offset) = 0; virtual Id_t domainOffset() const = 0; virtual ~Domain() { } }; using UDom = std::unique_ptr<Domain>; using UDomVec = std::vector<UDom>; // }}} // {{{ declaration of AbstractDomain template <class T> class AbstractDomain : public Domain { public: using Atom = T; using Atoms = UniqueVec<Atom, HashKey<Symbol>, EqualToKey<Symbol>>; using BindIndex = Gringo::BindIndex<AbstractDomain>; using FullIndex = Gringo::FullIndex<AbstractDomain>; using BindIndices = std::unordered_set<BindIndex, call_hash<BindIndex>>; using FullIndices = std::unordered_set<FullIndex, call_hash<FullIndex>>; using AtomVec = typename Atoms::Vec; using Iterator = typename AtomVec::iterator; using ConstIterator = typename AtomVec::const_iterator; using SizeType = typename Atoms::SizeType; using OffsetVec = std::vector<SizeType>; AbstractDomain() = default; AbstractDomain(AbstractDomain const &) = delete; AbstractDomain(AbstractDomain &&) = delete; // All indices that use a domain have to be registered with it. BindIndex &add(SValVec &&bound, UTerm &&repr) { auto ret(indices_.emplace(*this, std::move(bound), std::move(repr))); auto &idx = const_cast<BindIndex&>(*ret.first); idx.update(); return idx; } FullIndex &add(UTerm &&repr, Id_t imported) { auto ret(fullIndices_.emplace(*this, std::move(repr), imported)); auto &idx = const_cast<FullIndex&>(*ret.first); idx.update(); return idx; } // Function to lookup negative literals or non-recursive atoms. bool lookup(SizeType &offset, Term const &repr, RECNAF naf, Logger &log) { bool undefined = false; switch (naf) { case RECNAF::POS: { // Note: intended for non-recursive case only auto it = atoms_.find(repr.eval(undefined, log)); if (!undefined && it != atoms_.end() && it->defined()) { offset = static_cast<SizeType>(it - begin()); return true; } break; } case RECNAF::NOT: { auto it = atoms_.find(repr.eval(undefined, log)); if (!undefined && it != atoms_.end()) { if (!it->fact()) { offset = static_cast<SizeType>(it - begin()); return true; } } else if (!undefined) { // This can only happen if literals are used negatively and non-recursively. // Example: a :- not b. offset = std::numeric_limits<SizeType>::max(); return true; } break; } case RECNAF::RECNOT: { auto it = reserve(repr.eval(undefined, log)); if (!undefined && !it->fact()) { offset = static_cast<SizeType>(it - begin()); return true; } break; } case RECNAF::NOTNOT: { // Note: intended for recursive case only auto it = reserve(repr.eval(undefined, log)); if (!undefined) { offset = static_cast<SizeType>(it - begin()); return true; } break; } } offset = std::numeric_limits<SizeType>::max(); return false; } // Function to lookup recursive atoms. bool lookup(SizeType &offset, Term const &repr, BinderType type, Logger &log) { // Note: intended for recursive case only bool undefined = false; auto it = atoms_.find(repr.eval(undefined, log)); if (!undefined && it != atoms_.end() && it->defined()) { switch (type) { case BinderType::OLD: { if (it->generation() < generation_) { offset = static_cast<SizeType>(it - begin()); return true; } break; } case BinderType::ALL: { if (it->generation() <= generation_) { offset = static_cast<SizeType>(it - begin()); return true; } break; } case BinderType::NEW: { if (it->generation() == generation_) { offset = static_cast<SizeType>(it - begin()); return true; } break; } } } offset = std::numeric_limits<SizeType>::max(); return false; } // Loops over all atoms that might have to be imported into an index. // Already seen atoms are indicated with the two offset parameters. // Returns true if a maching atom was falls. // Furthermore, accepts a callback f that receives the offset of a matching atom. // If the callback returns false the search for matching atoms is stopped and the function returns true. template <typename F> bool update(F f, Term const &repr, SizeType &imported, SizeType &importedDelayed) { bool ret = false; for (auto it(atoms_.begin() + imported), ie(atoms_.end()); it < ie; ++it, ++imported) { if (it->defined()) { if (!it->delayed() && repr.match(*it)) { ret = true; f(imported); } } else { it->markDelayed(); } } for (auto it(delayed_.begin() + importedDelayed), ie(delayed_.end()); it < ie; ++it) { auto &atom = operator[](*it); if (repr.match(atom)) { ret = true; f(*it); } } importedDelayed = static_cast<SizeType>(delayed_.size()); return ret; } bool empty() const { return atoms_.empty(); } void clear() { atoms_.clear(); indices_.clear(); fullIndices_.clear(); generation_ = 0; } void reset() { indices_.clear(); fullIndices_.clear(); } // Returns the current generation. // The generation corresponds to the number of grounding iterations // the domain was involved in. SizeType generation() const { return generation_; } // Resevers an atom for a recursive negative literal. // This does not set a generation. Iterator reserve(Symbol x) { return atoms_.findPush(x, x).first; } // Defines (adds) an atom setting its generation. std::pair<Iterator, bool> define(Symbol value) { auto ret = atoms_.findPush(value, value); if (ret.second) { ret.first->setGeneration(generation() + 1); } else if (!ret.first->defined()) { ret.second = true; ret.first->setGeneration(generation() + 1); if (ret.first->delayed()) { delayed_.emplace_back(numeric_cast<typename OffsetVec::value_type>(ret.first - begin())); } } return ret; } void define(SizeType offset) { auto &atm = operator[](offset); if (!atm.defined()) { atm.setGeneration(generation() + 1); if (atm.delayed()) { delayed_.emplace_back(offset); } } } // Sets the generation of the domain and all atoms back to zero. void init() override { generation_ = 0; for (auto it = begin() + initOffset_, ie = end(); it != ie; ++it) { if (it->defined()) { it->setGeneration(0); } else { it->markDelayed(); } } initOffset_ = atoms_.size(); for (auto it = delayed_.begin() + initDelayedOffset_, ie = delayed_.end(); it != ie; ++it) { operator[](*it).setGeneration(0); } initDelayedOffset_ = static_cast<Id_t>(delayed_.size()); } // A domain is enqueued for two grounding iterations. // This gives atoms a chance to go from state Open -> New -> Old. void enqueue() override { enqueued_ = 2; } bool dequeue() override { --enqueued_; assert(0 <= enqueued_ && enqueued_ <= 2); return enqueued_ > 0; } bool isEnqueued() const override { return enqueued_ > 0; } void nextGeneration() override { ++generation_; } OffsetVec &delayed() { return delayed_; } Iterator find(Symbol x) { return atoms_.find(x); } ConstIterator find(Symbol x) const { return atoms_.find(x); } Id_t size() const { return atoms_.size(); } Iterator begin() { return atoms_.begin(); } Iterator end() { return atoms_.end(); } ConstIterator begin() const { return atoms_.begin(); } ConstIterator end() const { return atoms_.end(); } Atom &operator[](Id_t x) { return atoms_[x]; } void setDomainOffset(Id_t offset) override { domainOffset_ = offset; } Id_t domainOffset() const override { return domainOffset_; } virtual ~AbstractDomain() noexcept { } protected: void hide(Iterator it) { atoms_.hide(it); } protected: BindIndices indices_; FullIndices fullIndices_; Atoms atoms_; OffsetVec delayed_; Id_t enqueued_ = 0; Id_t generation_ = 0; Id_t initOffset_ = 0; Id_t initDelayedOffset_ = 0; Id_t domainOffset_ = InvalidId; }; // }}} } // namespace Gringo #endif // _GRINGO_DOMAIN_HH
36.468852
136
0.571294
[ "vector" ]
6077d8701e05a8165335147d330faf75d429de69
5,046
cpp
C++
src/GafferArnold/IECoreArnoldPreview/VDBAlgo.cpp
sebaDesmet/gaffer
47b2d093c40452bd77947e3b5bd0722a366c8d59
[ "BSD-3-Clause" ]
49
2018-08-27T07:52:25.000Z
2022-02-08T13:54:05.000Z
src/GafferArnold/IECoreArnoldPreview/VDBAlgo.cpp
rkoschmitzky/gaffer
ec6262ae1292767bdeb9520d1447d65a4a511884
[ "BSD-3-Clause" ]
21
2018-11-27T16:00:32.000Z
2022-03-23T20:01:55.000Z
src/GafferArnold/IECoreArnoldPreview/VDBAlgo.cpp
rkoschmitzky/gaffer
ec6262ae1292767bdeb9520d1447d65a4a511884
[ "BSD-3-Clause" ]
4
2018-12-23T16:16:41.000Z
2021-06-16T09:04:01.000Z
////////////////////////////////////////////////////////////////////////// // // Copyright (c) 2016, Image Engine Design Inc. All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // // * Neither the name of Image Engine Design nor the names of any // other contributors to this software may be used to endorse or // promote products derived from this software without specific prior // written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS // IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, // THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF // LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING // NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // ////////////////////////////////////////////////////////////////////////// #include "IECoreVDB/VDBObject.h" #include "IECoreArnold/NodeAlgo.h" #include "IECoreArnold/ParameterAlgo.h" #include "IECoreScene/Renderer.h" #include "IECore/CompoundData.h" #include "IECore/Exception.h" #include "IECore/MessageHandler.h" #include "IECore/SimpleTypedData.h" #include "openvdb/io/Stream.h" #include "openvdb/openvdb.h" #include "boost/iostreams/categories.hpp" #include "boost/iostreams/stream.hpp" using namespace std; using namespace Imath; using namespace IECore; using namespace IECoreArnold; namespace { IECore::InternedString g_filedataParam("filedata"); IECore::InternedString g_filenameParam("filename"); IECore::InternedString g_gridParam("grids"); AtString g_volume("volume"); ///! utility to allow us to stream directly into a UCharVectorData struct UCharVectorDataSink { typedef char char_type; typedef boost::iostreams::sink_tag category; UCharVectorDataSink( IECore::UCharVectorData *storage ) : m_storage( storage->writable() ) { } std::streamsize write( const char *s, std::streamsize n ) { m_storage.insert( m_storage.end(), s, s + n ); return n; } std::vector<unsigned char> &m_storage; }; UCharVectorDataPtr createMemoryBuffer(const IECoreVDB::VDBObject* vdbObject) { // estimate the size of the memory required to hand the VDB to arnold. // This is required so we can reserve the right amount of space in the output // buffer. int64_t totalSizeBytes = 0; openvdb::GridCPtrVec gridsToWrite; std::vector<std::string> gridNames = vdbObject->gridNames(); try { for( const std::string& gridName : gridNames ) { openvdb::GridBase::ConstPtr grid = vdbObject->findGrid( gridName ); totalSizeBytes += grid->metaValue<int64_t>( "file_mem_bytes" ); gridsToWrite.push_back( grid ); } } catch( const std::exception &e ) { IECore::msg( IECore::MessageHandler::Warning, "VDBObject::memoryBuffer", "Unable to estimate vdb size." ); } IECore::UCharVectorDataPtr buffer = new IECore::UCharVectorData(); buffer->writable().reserve( totalSizeBytes ); UCharVectorDataSink sink( buffer.get() ); boost::iostreams::stream<UCharVectorDataSink> memoryStream( sink ); openvdb::io::Stream vdbStream( memoryStream ); vdbStream.write( gridsToWrite ); return buffer; } CompoundDataPtr createParameters(const IECoreVDB::VDBObject* vdbObject) { CompoundDataPtr parameters = new CompoundData(); CompoundDataMap& compoundData = parameters->writable(); compoundData[g_gridParam] = new StringVectorData( vdbObject->gridNames() ); if ( vdbObject->unmodifiedFromFile() ) { compoundData[g_filenameParam] = new StringData( vdbObject->fileName() ); } else { compoundData[g_filedataParam] = createMemoryBuffer( vdbObject ); } return parameters; } AtNode *convert( const IECoreVDB::VDBObject *vdbObject, const std::string & name, const AtNode* parent ) { AtNode *node = AiNode( g_volume, AtString( name.c_str() ), parent ); CompoundDataPtr parameters = createParameters( vdbObject ); ParameterAlgo::setParameters( node, parameters->readable() ); return node; } } namespace { NodeAlgo::ConverterDescription<IECoreVDB::VDBObject> g_description( ::convert ); } // namespace
32.140127
109
0.713436
[ "vector" ]
60789f2f4f949149e96ff776d873bda54e810152
1,406
hpp
C++
include/interface/view/BoundingBox.hpp
Tastyep/Tank-20
08ca5d027388d04549fda624661d8936e68e1903
[ "MIT" ]
null
null
null
include/interface/view/BoundingBox.hpp
Tastyep/Tank-20
08ca5d027388d04549fda624661d8936e68e1903
[ "MIT" ]
null
null
null
include/interface/view/BoundingBox.hpp
Tastyep/Tank-20
08ca5d027388d04549fda624661d8936e68e1903
[ "MIT" ]
null
null
null
#ifndef INTERFACE_VIEW_BOUNDING_BOX_HPP #define INTERFACE_VIEW_BOUNDING_BOX_HPP #include "interface/Tile.hpp" #include "interface/view/View.hpp" #include <PlayRho/Collision/Shapes/DiskShapeConf.hpp> #include <PlayRho/Dynamics/World.hpp> #include <entt/entity/registry.hpp> #include <memory> namespace playrho::d2 { class DiskShapeConf; } // namespace playrho::d2 namespace Interface::View { class BoundingBox final : public View { public: BoundingBox(std::shared_ptr<entt::registry> registry, std::shared_ptr<playrho::d2::World> world); ~BoundingBox() override = default; BoundingBox(const BoundingBox &) = delete; BoundingBox(BoundingBox &&) = default; BoundingBox &operator=(const BoundingBox &) = delete; BoundingBox &operator=(BoundingBox &&) = default; void render(sf::RenderWindow &window) override; private: void drawPolygon(sf::RenderWindow & window, const playrho::d2::DistanceProxy & polygon, const playrho::d2::Transformation &xfm); void drawCircle(sf::RenderWindow & window, const playrho::d2::DiskShapeConf & shape, const playrho::d2::Transformation &xfm); private: std::shared_ptr<entt::registry> _registry; std::shared_ptr<playrho::d2::World> _world; }; } // namespace Interface::View #endif // INTERFACE_VIEW_BOUNDING_BOX_HPP
28.12
62
0.689189
[ "render", "shape" ]
607c6eec73c7f4a5b9f7c42e76912df9ee31d50a
13,162
cc
C++
src/TransformController_TEST.cc
Levi-Armstrong/ign-rendering
dfcf7c4a574b6b0e94419b7ba1ab3ebce64055f3
[ "ECL-2.0", "Apache-2.0" ]
25
2020-04-15T16:59:45.000Z
2022-02-09T00:07:34.000Z
src/TransformController_TEST.cc
Levi-Armstrong/ign-rendering
dfcf7c4a574b6b0e94419b7ba1ab3ebce64055f3
[ "ECL-2.0", "Apache-2.0" ]
510
2020-04-20T23:26:31.000Z
2022-03-31T14:33:36.000Z
src/TransformController_TEST.cc
srmainwaring/ign-rendering
46dd20ae11fdf2dd2ce25d7ee93299545ef8b224
[ "ECL-2.0", "Apache-2.0" ]
30
2020-05-22T17:41:38.000Z
2022-02-28T17:07:19.000Z
/* * Copyright (C) 2019 Open Source Robotics Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ #include <gtest/gtest.h> #include <ignition/common/Console.hh> #include "test_config.h" // NOLINT(build/include) #include "ignition/rendering/Camera.hh" #include "ignition/rendering/RenderEngine.hh" #include "ignition/rendering/RenderingIface.hh" #include "ignition/rendering/Scene.hh" #include "ignition/rendering/TransformController.hh" using namespace ignition; using namespace rendering; class TransformControllerTest : public testing::Test, public testing::WithParamInterface<const char *> { /// \brief Test basic api public: void TransformControl(const std::string &_renderEngine); /// \brief test rotate, translate, scale transformations in world space public: void WorldSpace(const std::string &_renderEngine); /// \brief test rotate, translate, scale transformations in local space public: void LocalSpace(const std::string &_renderEngine); /// \brief test rotate, translate, scale transformations from 2d movements public: void Control2d(const std::string &_renderEngine); }; ///////////////////////////////////////////////// void TransformControllerTest::TransformControl(const std::string &_renderEngine) { RenderEngine *engine = rendering::engine(_renderEngine); if (!engine) { igndbg << "Engine '" << _renderEngine << "' is not supported" << std::endl; return; } ScenePtr scene = engine->CreateScene("scene"); EXPECT_NE(scene, nullptr); CameraPtr camera = scene->CreateCamera("camera"); EXPECT_NE(camera, nullptr); TransformController transformControl; // verify intial values EXPECT_EQ(nullptr, transformControl.Camera()); EXPECT_EQ(nullptr, transformControl.Node()); EXPECT_FALSE(transformControl.Active()); EXPECT_EQ(TransformMode::TM_NONE, transformControl.Mode()); EXPECT_EQ(TransformSpace::TS_LOCAL, transformControl.Space()); EXPECT_EQ(math::Vector3d::Zero, transformControl.ActiveAxis()); // create visual node for testing VisualPtr visual = scene->CreateVisual(); ASSERT_NE(nullptr, visual); // test attaching / detaching node transformControl.Attach(visual); EXPECT_EQ(visual, transformControl.Node()); transformControl.Detach(); EXPECT_EQ(nullptr, transformControl.Node()); // attach node again for subsequent tests transformControl.Attach(visual); // test setting camera transformControl.SetCamera(camera); EXPECT_EQ(camera, transformControl.Camera()); // test setting transform space transformControl.SetTransformSpace(TransformSpace::TS_WORLD); EXPECT_EQ(TransformSpace::TS_WORLD, transformControl.Space()); // test setting transform axis transformControl.SetActiveAxis(math::Vector3d::UnitZ); EXPECT_EQ(math::Vector3d::UnitZ, transformControl.ActiveAxis()); // test setting transform mode transformControl.SetTransformMode(TransformMode::TM_ROTATION); EXPECT_EQ(TransformMode::TM_ROTATION, transformControl.Mode()); // verify active state transformControl.Start(); EXPECT_TRUE(transformControl.Active()); transformControl.Stop(); EXPECT_FALSE(transformControl.Active()); // test axis conversion EXPECT_EQ(math::Vector3d::UnitX, transformControl.ToAxis(TransformAxis::TA_TRANSLATION_X)); EXPECT_EQ(math::Vector3d::UnitY, transformControl.ToAxis(TransformAxis::TA_TRANSLATION_Y)); EXPECT_EQ(math::Vector3d::UnitZ, transformControl.ToAxis(TransformAxis::TA_TRANSLATION_Z)); EXPECT_EQ(math::Vector3d::UnitX, transformControl.ToAxis(TransformAxis::TA_ROTATION_X)); EXPECT_EQ(math::Vector3d::UnitY, transformControl.ToAxis(TransformAxis::TA_ROTATION_Y)); EXPECT_EQ(math::Vector3d::UnitZ, transformControl.ToAxis(TransformAxis::TA_ROTATION_Z)); EXPECT_EQ(math::Vector3d::UnitX, transformControl.ToAxis(TransformAxis::TA_SCALE_X)); EXPECT_EQ(math::Vector3d::UnitY, transformControl.ToAxis(TransformAxis::TA_SCALE_Y)); EXPECT_EQ(math::Vector3d::UnitZ, transformControl.ToAxis(TransformAxis::TA_SCALE_Z)); // Clean up engine->DestroyScene(scene); rendering::unloadEngine(engine->Name()); } ///////////////////////////////////////////////// void TransformControllerTest::WorldSpace(const std::string &_renderEngine) { RenderEngine *engine = rendering::engine(_renderEngine); if (!engine) { igndbg << "Engine '" << _renderEngine << "' is not supported" << std::endl; return; } ScenePtr scene = engine->CreateScene("scene"); ASSERT_NE(nullptr, scene); CameraPtr camera = scene->CreateCamera("camera"); ASSERT_NE(nullptr, camera); camera->SetImageWidth(320); camera->SetImageHeight(240); TransformController transformControl; // test setting camera transformControl.SetCamera(camera); EXPECT_EQ(camera, transformControl.Camera()); // create visual node for testing VisualPtr visual = scene->CreateVisual(); ASSERT_NE(nullptr, visual); transformControl.Attach(visual); EXPECT_EQ(visual, transformControl.Node()); // test translation in world space transformControl.SetTransformMode(TransformMode::TM_TRANSLATION); transformControl.SetTransformSpace(TransformSpace::TS_WORLD); transformControl.SetActiveAxis(math::Vector3d::UnitZ); transformControl.Translate(math::Vector3d(0, 0, 2)); EXPECT_EQ(visual->WorldPosition(), math::Vector3d(0, 0, 2)); EXPECT_EQ(visual->WorldRotation(), math::Quaterniond::Identity); EXPECT_EQ(visual->WorldScale(), math::Vector3d::One); // test rotation in world space transformControl.SetTransformMode(TransformMode::TM_ROTATION); transformControl.SetTransformSpace(TransformSpace::TS_WORLD); transformControl.SetActiveAxis(math::Vector3d::UnitX); transformControl.Rotate(math::Quaterniond(IGN_PI, 0, 0)); EXPECT_EQ(visual->WorldPosition(), math::Vector3d(0, 0, 2)); EXPECT_EQ(visual->WorldRotation(), math::Quaterniond(IGN_PI, 0, 0)); EXPECT_EQ(visual->WorldScale(), math::Vector3d::One); // test scaling in world space transformControl.SetTransformMode(TransformMode::TM_SCALE); transformControl.SetTransformSpace(TransformSpace::TS_WORLD); transformControl.SetActiveAxis(math::Vector3d::UnitY); transformControl.Scale(math::Vector3d(1.0, 0.3, 1.0)); EXPECT_EQ(visual->WorldPosition(), math::Vector3d(0, 0, 2)); EXPECT_EQ(visual->WorldRotation(), math::Quaterniond(IGN_PI, 0, 0)); EXPECT_EQ(visual->WorldScale(), math::Vector3d(1.0, 0.3, 1.0)); // Clean up engine->DestroyScene(scene); rendering::unloadEngine(engine->Name()); } ///////////////////////////////////////////////// void TransformControllerTest::LocalSpace(const std::string &_renderEngine) { RenderEngine *engine = rendering::engine(_renderEngine); if (!engine) { igndbg << "Engine '" << _renderEngine << "' is not supported" << std::endl; return; } ScenePtr scene = engine->CreateScene("scene"); ASSERT_NE(nullptr, scene); CameraPtr camera = scene->CreateCamera("camera"); ASSERT_NE(nullptr, camera); camera->SetImageWidth(320); camera->SetImageHeight(240); TransformController transformControl; // test setting camera transformControl.SetCamera(camera); EXPECT_EQ(camera, transformControl.Camera()); // create a visual node and intiialize it with a rotation // for testing transfoms in local space VisualPtr visual = scene->CreateVisual(); ASSERT_NE(nullptr, visual); math::Quaterniond initialRot(IGN_PI * 0.5, 0, 0); visual->SetLocalRotation(initialRot); EXPECT_EQ(initialRot, visual->WorldRotation()); transformControl.Attach(visual); EXPECT_EQ(visual, transformControl.Node()); // test translation in local space transformControl.SetTransformMode(TransformMode::TM_TRANSLATION); transformControl.SetTransformSpace(TransformSpace::TS_LOCAL); transformControl.SetActiveAxis(math::Vector3d::UnitZ); transformControl.Translate(math::Vector3d(0, 0, 2)); EXPECT_EQ(visual->WorldPosition(), math::Vector3d(0, -2, 0)); EXPECT_EQ(visual->WorldRotation(), initialRot); EXPECT_EQ(visual->WorldScale(), math::Vector3d::One); // test rotation in local space transformControl.SetTransformMode(TransformMode::TM_ROTATION); transformControl.SetTransformSpace(TransformSpace::TS_LOCAL); transformControl.SetActiveAxis(math::Vector3d::UnitX); transformControl.Rotate(math::Quaterniond(IGN_PI, 0, 0)); EXPECT_EQ(visual->WorldPosition(), math::Vector3d(0, -2, 0)); EXPECT_EQ(visual->WorldRotation(), math::Quaterniond(IGN_PI, 0, 0) * initialRot); EXPECT_EQ(visual->WorldScale(), math::Vector3d::One); // test scaling in local space transformControl.SetTransformMode(TransformMode::TM_SCALE); transformControl.SetTransformSpace(TransformSpace::TS_LOCAL); transformControl.SetActiveAxis(math::Vector3d::UnitY); transformControl.Scale(math::Vector3d(1.0, 0.3, 1.0)); EXPECT_EQ(visual->WorldPosition(), math::Vector3d(0, -2, 0)); EXPECT_EQ(visual->WorldRotation(), math::Quaterniond(IGN_PI, 0, 0) * initialRot); EXPECT_EQ(visual->WorldScale(), math::Vector3d(1.0, 0.3, 1.0)); // Clean up engine->DestroyScene(scene); rendering::unloadEngine(engine->Name()); } ///////////////////////////////////////////////// void TransformControllerTest::Control2d(const std::string &_renderEngine) { RenderEngine *engine = rendering::engine(_renderEngine); if (!engine) { igndbg << "Engine '" << _renderEngine << "' is not supported" << std::endl; return; } ScenePtr scene = engine->CreateScene("scene"); ASSERT_NE(nullptr, scene); CameraPtr camera = scene->CreateCamera("camera"); ASSERT_NE(nullptr, camera); camera->SetWorldPosition(-5, 0, 0); EXPECT_EQ(math::Vector3d(-5, 0, 0), camera->WorldPosition()); camera->SetImageWidth(320); camera->SetImageHeight(240); TransformController transformControl; // test setting camera transformControl.SetCamera(camera); EXPECT_EQ(camera, transformControl.Camera()); // create a dummy node visual node and attach to the controller VisualPtr visual = scene->CreateVisual(); ASSERT_NE(nullptr, visual); transformControl.Attach(visual); EXPECT_EQ(visual, transformControl.Node()); // test translation from 2d transformControl.SetTransformMode(TransformMode::TM_TRANSLATION); transformControl.SetTransformSpace(TransformSpace::TS_LOCAL); transformControl.SetActiveAxis(math::Vector3d::UnitZ); transformControl.Start(); math::Vector2d start(0.5, 0.5); math::Vector2d end(0.5, 0.8); math::Vector3d translation = transformControl.TranslationFrom2d(math::Vector3d::UnitZ, start, end); transformControl.Stop(); EXPECT_DOUBLE_EQ(translation.X(), 0); EXPECT_DOUBLE_EQ(translation.Y(), 0); EXPECT_GT(translation.Z(), 0); // test rotation from 2d transformControl.SetTransformMode(TransformMode::TM_ROTATION); transformControl.SetTransformSpace(TransformSpace::TS_LOCAL); transformControl.SetActiveAxis(math::Vector3d::UnitX); transformControl.Start(); start = math::Vector2d(0.5, 0.5); end = math::Vector2d(0.5, -0.8); math::Quaterniond rotation = transformControl.RotationFrom2d(math::Vector3d::UnitX, start, end); transformControl.Stop(); math::Vector3d euler = rotation.Euler(); EXPECT_GT(euler.X(), 0); EXPECT_DOUBLE_EQ(euler.Y(), 0); EXPECT_DOUBLE_EQ(euler.Z(), 0); // test scaling from 2d transformControl.SetTransformMode(TransformMode::TM_SCALE); transformControl.SetTransformSpace(TransformSpace::TS_LOCAL); transformControl.SetActiveAxis(math::Vector3d::UnitY); transformControl.Start(); math::Vector3d scale = transformControl.ScaleFrom2d(math::Vector3d::UnitY, start, end); transformControl.Stop(); EXPECT_DOUBLE_EQ(scale.X(), 1); EXPECT_GT(scale.Y(), 0); EXPECT_DOUBLE_EQ(scale.Z(), 1); // Clean up engine->DestroyScene(scene); rendering::unloadEngine(engine->Name()); } ///////////////////////////////////////////////// TEST_P(TransformControllerTest, TransformControl) { TransformControl(GetParam()); } ///////////////////////////////////////////////// TEST_P(TransformControllerTest, WorldSpace) { WorldSpace(GetParam()); } ///////////////////////////////////////////////// TEST_P(TransformControllerTest, LocalSpace) { LocalSpace(GetParam()); } ///////////////////////////////////////////////// TEST_P(TransformControllerTest, Control2d) { Control2d(GetParam()); } INSTANTIATE_TEST_CASE_P(TransformController, TransformControllerTest, RENDER_ENGINE_VALUES, ignition::rendering::PrintToStringParam()); int main(int argc, char **argv) { ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); }
34.728232
80
0.718812
[ "transform" ]
607e27919d659bad5c45d2da1e057890a798ca9e
8,334
cpp
C++
src/gut_opengl/Mesh.cpp
Lehdari/GraphicsUtils
da1c02e6dc1c5541de593141003194d054f59724
[ "CC0-1.0" ]
2
2020-07-29T16:48:53.000Z
2020-08-20T10:49:03.000Z
src/gut_opengl/Mesh.cpp
Lehdari/GraphicsUtils
da1c02e6dc1c5541de593141003194d054f59724
[ "CC0-1.0" ]
null
null
null
src/gut_opengl/Mesh.cpp
Lehdari/GraphicsUtils
da1c02e6dc1c5541de593141003194d054f59724
[ "CC0-1.0" ]
null
null
null
// // Project: GraphicsUtils // File: Mesh.cpp // // Copyright (c) 2019 Miika 'Lehdari' Lehtimäki // You may use, distribute and modify this code under the terms // of the licence specified in file LICENSE which is distributed // with this source code package. // #include "Mesh.hpp" #include "Shader.hpp" #include "Camera.hpp" #include "gut_utils/VertexData.hpp" #include <vector> #include <array> #include <map> #include <memory> #include <cstdio> #include <cstring> #include <cctype> using namespace gut; Mesh::Mesh(void) : _vertexArrayObjectId (0), _positionBufferId (0), _normalBufferId (0), _texCoordBufferId (0), _colorBufferId (0), _elementBufferId (0), _nIndices (0), _usingNormals (false), _usingTexCoords (false), _usingColors (false) {} Mesh::Mesh(Mesh&& other) noexcept : _vertexArrayObjectId (other._vertexArrayObjectId), _positionBufferId (other._positionBufferId), _normalBufferId (other._normalBufferId), _texCoordBufferId (other._texCoordBufferId), _colorBufferId (other._colorBufferId), _elementBufferId (other._elementBufferId), _nIndices (other._nIndices), _usingNormals (other._usingNormals), _usingTexCoords (other._usingTexCoords), _usingColors (other._usingColors) { other._vertexArrayObjectId = 0; other._positionBufferId = 0; other._normalBufferId = 0; other._texCoordBufferId = 0; other._colorBufferId = 0; other._elementBufferId = 0; other._nIndices = 0; other._usingNormals = false; other._usingTexCoords = false; other._usingColors = false; } Mesh& Mesh::operator=(Mesh&& other) noexcept { _vertexArrayObjectId = other._vertexArrayObjectId; _positionBufferId = other._positionBufferId; _normalBufferId = other._normalBufferId; _texCoordBufferId = other._texCoordBufferId; _colorBufferId = other._colorBufferId; _elementBufferId = other._elementBufferId; _nIndices = other._nIndices; _usingNormals = other._usingNormals; _usingTexCoords = other._usingTexCoords; _usingColors = other._usingColors; other._vertexArrayObjectId = 0; other._positionBufferId = 0; other._normalBufferId = 0; other._texCoordBufferId = 0; other._colorBufferId = 0; other._elementBufferId = 0; other._nIndices = 0; other._usingNormals = false; other._usingTexCoords = false; other._usingColors = false; return *this; } Mesh::~Mesh(void) { reset(); } void Mesh::loadFromVertexData(const VertexData& vertexData) { if (!vertexData.isValid()) { fprintf(stderr, "ERROR: Invalid VertexData\n"); // TODO logging return; } auto* positionContainer = vertexData.accessData("position"); if (positionContainer == nullptr) { fprintf(stderr, "ERROR: No position data in VertexData\n"); // TODO logging return; } // Check position data type if (positionContainer->type != VertexData::DataType::VEC3F) { fprintf(stderr, "ERROR: Invalid data type for position data\n"); // TODO logging return; } auto* normalContainer = vertexData.accessData("normal"); bool usingNormals = false; if (normalContainer != nullptr) { if (normalContainer->type != VertexData::DataType::VEC3F) { fprintf(stderr, "ERROR: Invalid data type for normal data\n"); // TODO logging return; } usingNormals = true; } auto* texCoordContainer = vertexData.accessData("texCoord"); bool usingTexCoords = false; if (texCoordContainer != nullptr) { if (texCoordContainer->type != VertexData::DataType::VEC2F) { fprintf(stderr, "ERROR: Invalid data type for texture coordinate data\n"); // TODO logging return; } usingTexCoords = true; } auto* colorContainer = vertexData.accessData("color"); bool usingColors = false; if (colorContainer != nullptr) { if (colorContainer->type != VertexData::DataType::VEC3F) { fprintf(stderr, "ERROR: Invalid data type for color data\n"); // TODO logging return; } usingColors = true; } auto& indices = vertexData.getIndices(); auto& positions = *static_cast<Vector<Vec3f>*>(positionContainer->v); Vector<Vec3f>* normals = nullptr; if (usingNormals) normals = static_cast<Vector<Vec3f>*>(normalContainer->v); Vector<Vec2f>* texCoords = nullptr; if (usingTexCoords) texCoords = static_cast<Vector<Vec2f>*>(texCoordContainer->v); Vector<Vec3f>* colors = nullptr; if (usingColors) colors = static_cast<Vector<Vec3f>*>(colorContainer->v); // release the used resources reset(); _nIndices = indices.size(); _usingNormals = usingNormals; _usingTexCoords = usingTexCoords; _usingColors = usingColors; // create and bind the VAO glGenVertexArrays(1, &_vertexArrayObjectId); glBindVertexArray(_vertexArrayObjectId); // upload the vertex data to GPU and set up the vertex attribute arrays glGenBuffers(1, &_positionBufferId); glBindBuffer(GL_ARRAY_BUFFER, _positionBufferId); glBufferData(GL_ARRAY_BUFFER, positions.size() * sizeof(Vec3f), positions.data(), GL_STATIC_DRAW); glEnableVertexAttribArray(0); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, (GLvoid*)0); if (_usingNormals) { glGenBuffers(1, &_normalBufferId); glBindBuffer(GL_ARRAY_BUFFER, _normalBufferId); glBufferData(GL_ARRAY_BUFFER, normals->size() * sizeof(Vec3f), normals->data(), GL_STATIC_DRAW); glEnableVertexAttribArray(1); glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 0, (GLvoid*)0); } if (_usingTexCoords) { glGenBuffers(1, &_texCoordBufferId); glBindBuffer(GL_ARRAY_BUFFER, _texCoordBufferId); glBufferData(GL_ARRAY_BUFFER, texCoords->size() * sizeof(Vec2f), texCoords->data(), GL_STATIC_DRAW); glEnableVertexAttribArray(2); glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, 0, (GLvoid*)0); } if (_usingColors) { glGenBuffers(1, &_colorBufferId); glBindBuffer(GL_ARRAY_BUFFER, _colorBufferId); glBufferData(GL_ARRAY_BUFFER, colors->size() * sizeof(Vec3f), colors->data(), GL_STATIC_DRAW); glEnableVertexAttribArray(3); glVertexAttribPointer(3, 3, GL_FLOAT, GL_FALSE, 0, (GLvoid*)0); } glGenBuffers(1, &_elementBufferId); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, _elementBufferId); glBufferData(GL_ELEMENT_ARRAY_BUFFER, _nIndices * sizeof(unsigned), indices.data(), GL_STATIC_DRAW); // unbind the VAO so it won't be changed outside this function glBindVertexArray(0); } void Mesh::render( Shader& shader, const Camera& camera, const Mat4f& orientation, GLenum mode) const { shader.use(); shader.setUniform("objectToWorld", orientation); if (_usingNormals) shader.setUniform("normalToWorld", Mat3f(Mat4f(orientation.inverse().transpose()).block<3,3>(0,0))); shader.setUniform("worldToClip", camera.worldToClip()); glBindVertexArray(_vertexArrayObjectId); glDrawElements(mode, _nIndices, GL_UNSIGNED_INT, (GLvoid*)0); glBindVertexArray(0); } void Mesh::render(Shader& shader, GLenum mode) const { shader.use(); glBindVertexArray(_vertexArrayObjectId); glDrawElements(mode, _nIndices, GL_UNSIGNED_INT, (GLvoid*)0); glBindVertexArray(0); } void Mesh::reset() { if (_vertexArrayObjectId != 0) glDeleteVertexArrays(1, &_vertexArrayObjectId); if (_positionBufferId != 0) glDeleteBuffers(1, &_positionBufferId); if (_normalBufferId != 0) glDeleteBuffers(1, &_normalBufferId); if (_texCoordBufferId != 0) glDeleteBuffers(1, &_texCoordBufferId); if (_elementBufferId != 0) glDeleteBuffers(1, &_elementBufferId); _vertexArrayObjectId = 0; _positionBufferId = 0; _normalBufferId = 0; _texCoordBufferId = 0; _elementBufferId = 0; _nIndices = 0; _usingNormals = false; _usingTexCoords = false; }
32.428016
108
0.663907
[ "mesh", "render", "vector" ]
608462e1544c6d4a3bd659a4cb7231bd647f8e72
11,245
cpp
C++
Gems/ScriptCanvasDeveloper/Code/Editor/Source/AutomationActions/FullyConnectedNodePaletteCreation.cpp
Schneidex69/o3de
d9ec159f0e07ff86957e15212232413c4ff4d1dc
[ "Apache-2.0", "MIT" ]
1
2021-07-19T23:54:05.000Z
2021-07-19T23:54:05.000Z
Gems/ScriptCanvasDeveloper/Code/Editor/Source/AutomationActions/FullyConnectedNodePaletteCreation.cpp
Schneidex69/o3de
d9ec159f0e07ff86957e15212232413c4ff4d1dc
[ "Apache-2.0", "MIT" ]
null
null
null
Gems/ScriptCanvasDeveloper/Code/Editor/Source/AutomationActions/FullyConnectedNodePaletteCreation.cpp
Schneidex69/o3de
d9ec159f0e07ff86957e15212232413c4ff4d1dc
[ "Apache-2.0", "MIT" ]
null
null
null
/* * Copyright (c) Contributors to the Open 3D Engine Project. * For complete copyright and license terms please see the LICENSE at the root of this distribution. * * SPDX-License-Identifier: Apache-2.0 OR MIT * */ #include "precompiled.h" #include <QMenu> #include <GraphCanvas/Components/GridBus.h> #include <GraphCanvas/Components/Nodes/NodeBus.h> #include <GraphCanvas/Components/SceneBus.h> #include <GraphCanvas/Components/VisualBus.h> #include <GraphCanvas/Editor/EditorTypes.h> #include <GraphCanvas/Utils/GraphUtils.h> #include <GraphCanvas/Widgets/GraphCanvasGraphicsView/GraphCanvasGraphicsView.h> #include <GraphCanvas/Widgets/NodePalette/NodePaletteWidget.h> #include <GraphCanvas/Widgets/NodePalette/NodePaletteDockWidget.h> #include <GraphCanvas/Widgets/NodePalette/TreeItems/NodePaletteTreeItem.h> #include <ScriptCanvas/Bus/RequestBus.h> #include <ScriptCanvas/GraphCanvas/NodeDescriptorBus.h> #include <Editor/Include/ScriptCanvas/Bus/NodeIdPair.h> #include <Editor/View/Widgets/NodePalette/CreateNodeMimeEvent.h> #include <Editor/View/Widgets/NodePalette/GeneralNodePaletteTreeItemTypes.h> #include <ScriptCanvasDeveloperEditor/AutomationActions/NodePaletteFullCreation.h> #include <ScriptCanvasDeveloperEditor/DeveloperUtils.h> namespace ScriptCanvasDeveloperEditor { namespace NodePaletteFullCreation { class CreateFullyConnectedNodePaletteInterface : public ProcessNodePaletteInterface { public: CreateFullyConnectedNodePaletteInterface(DeveloperUtils::ConnectionStyle connectionStyle, bool skipHandlers = false) { m_chainConfig.m_connectionStyle = connectionStyle; m_chainConfig.m_skipHandlers = skipHandlers; } void SetupInterface(const AZ::EntityId& activeGraphCanvasGraphId, const ScriptCanvas::ScriptCanvasId& scriptCanvasId) { m_graphCanvasGraphId = activeGraphCanvasGraphId; m_scriptCanvasId = scriptCanvasId; GraphCanvas::SceneRequestBus::EventResult(m_viewId, activeGraphCanvasGraphId, &GraphCanvas::SceneRequests::GetViewId); GraphCanvas::SceneRequestBus::EventResult(m_gridId, activeGraphCanvasGraphId, &GraphCanvas::SceneRequests::GetGrid); GraphCanvas::GridRequestBus::EventResult(m_minorPitch, m_gridId, &GraphCanvas::GridRequests::GetMinorPitch); QGraphicsScene* graphicsScene = nullptr; GraphCanvas::SceneRequestBus::EventResult(graphicsScene, activeGraphCanvasGraphId, &GraphCanvas::SceneRequests::AsQGraphicsScene); if (graphicsScene) { QRectF sceneArea = graphicsScene->sceneRect(); sceneArea.adjust(m_minorPitch.GetX(), m_minorPitch.GetY(), -m_minorPitch.GetX(), -m_minorPitch.GetY()); GraphCanvas::ViewRequestBus::Event(m_viewId, &GraphCanvas::ViewRequests::CenterOnArea, sceneArea); QApplication::processEvents(); } GraphCanvas::ViewRequestBus::EventResult(m_nodeCreationPos, m_viewId, &GraphCanvas::ViewRequests::GetViewSceneCenter); GraphCanvas::GraphCanvasGraphicsView* graphicsView = nullptr; GraphCanvas::ViewRequestBus::EventResult(graphicsView, m_viewId, &GraphCanvas::ViewRequests::AsGraphicsView); m_viewportRectangle = graphicsView->mapToScene(graphicsView->viewport()->geometry()).boundingRect(); // Temporary work around until the extra automation tools can be merged over that have better ways of doing this. const GraphCanvas::GraphCanvasTreeItem* treeItem = nullptr; ScriptCanvasEditor::AutomationRequestBus::BroadcastResult(treeItem, &ScriptCanvasEditor::AutomationRequests::GetNodePaletteRoot); const GraphCanvas::NodePaletteTreeItem* onGraphStartItem = nullptr; if (treeItem) { AZStd::unordered_set< const GraphCanvas::GraphCanvasTreeItem* > unexploredSet = { treeItem }; while (!unexploredSet.empty()) { const GraphCanvas::GraphCanvasTreeItem* treeItem = (*unexploredSet.begin()); unexploredSet.erase(unexploredSet.begin()); const GraphCanvas::NodePaletteTreeItem* nodePaletteTreeItem = azrtti_cast<const GraphCanvas::NodePaletteTreeItem*>(treeItem); if (nodePaletteTreeItem && nodePaletteTreeItem->GetName().compare("On Graph Start") == 0) { onGraphStartItem = nodePaletteTreeItem; break; } for (int i = 0; i < treeItem->GetChildCount(); ++i) { const GraphCanvas::GraphCanvasTreeItem* childItem = treeItem->FindChildByRow(i); if (childItem) { unexploredSet.insert(childItem); } } } } if (onGraphStartItem) { ProcessItem(onGraphStartItem); } } int m_counter = 60; bool ShouldProcessItem(const GraphCanvas::NodePaletteTreeItem* nodePaletteTreeItem) const { return m_counter > 0; } void ProcessItem(const GraphCanvas::NodePaletteTreeItem* nodePaletteTreeItem) { GraphCanvas::GraphCanvasMimeEvent* mimeEvent = nodePaletteTreeItem->CreateMimeEvent(); if (ScriptCanvasEditor::MultiCreateNodeMimeEvent* multiCreateMimeEvent = azrtti_cast<ScriptCanvasEditor::MultiCreateNodeMimeEvent*>(mimeEvent)) { --m_counter; AZStd::vector< GraphCanvas::GraphCanvasMimeEvent* > mimeEvents = multiCreateMimeEvent->CreateMimeEvents(); for (GraphCanvas::GraphCanvasMimeEvent* currentEvent : mimeEvents) { ScriptCanvasEditor::NodeIdPair createdPair = DeveloperUtils::HandleMimeEvent(currentEvent, m_graphCanvasGraphId, m_viewportRectangle, m_widthOffset, m_heightOffset, m_maxRowHeight, m_minorPitch); delete currentEvent; if (DeveloperUtils::CreateConnectedChain(createdPair, m_chainConfig)) { m_createdNodes.emplace_back(createdPair); } else { m_nodesToDelete.insert(GraphCanvas::GraphUtils::FindOutermostNode(createdPair.m_graphCanvasId)); } } } else if (mimeEvent) { --m_counter; ScriptCanvasEditor::NodeIdPair createdPair = DeveloperUtils::HandleMimeEvent(mimeEvent, m_graphCanvasGraphId, m_viewportRectangle, m_widthOffset, m_heightOffset, m_maxRowHeight, m_minorPitch); if (DeveloperUtils::CreateConnectedChain(createdPair, m_chainConfig)) { m_createdNodes.emplace_back(createdPair); } else { m_nodesToDelete.insert(GraphCanvas::GraphUtils::FindOutermostNode(createdPair.m_graphCanvasId)); } } delete mimeEvent; } private: void OnProcessingComplete() override { GraphCanvas::SceneRequestBus::Event(m_graphCanvasGraphId, &GraphCanvas::SceneRequests::Delete, m_nodesToDelete); } DeveloperUtils::CreateConnectedChainConfig m_chainConfig; AZStd::vector<ScriptCanvasEditor::NodeIdPair> m_createdNodes; AZStd::unordered_set<AZ::EntityId> m_nodesToDelete; AZ::EntityId m_graphCanvasGraphId; ScriptCanvas::ScriptCanvasId m_scriptCanvasId; AZ::Vector2 m_nodeCreationPos = AZ::Vector2::CreateZero(); AZ::EntityId m_viewId; AZ::EntityId m_gridId; AZ::Vector2 m_minorPitch = AZ::Vector2::CreateZero(); QRectF m_viewportRectangle; int m_widthOffset = 0; int m_heightOffset = 0; int m_maxRowHeight = 0; }; void CreateSingleExecutionConnectedNodePaletteAction() { ScriptCanvasEditor::AutomationRequestBus::Broadcast(&ScriptCanvasEditor::AutomationRequests::SignalAutomationBegin); CreateFullyConnectedNodePaletteInterface nodePaletteInterface(DeveloperUtils::ConnectionStyle::SingleExecutionConnection); DeveloperUtils::ProcessNodePalette(nodePaletteInterface); ScriptCanvasEditor::AutomationRequestBus::Broadcast(&ScriptCanvasEditor::AutomationRequests::SignalAutomationEnd); } void CreateSingleExecutionConnectedNodePaletteExcludeHandlersAction() { ScriptCanvasEditor::AutomationRequestBus::Broadcast(&ScriptCanvasEditor::AutomationRequests::SignalAutomationBegin); CreateFullyConnectedNodePaletteInterface nodePaletteInterface(DeveloperUtils::ConnectionStyle::SingleExecutionConnection, true); DeveloperUtils::ProcessNodePalette(nodePaletteInterface); ScriptCanvasEditor::AutomationRequestBus::Broadcast(&ScriptCanvasEditor::AutomationRequests::SignalAutomationEnd); } QAction* FullyConnectedNodePaletteCreation(QMenu* mainMenu) { QAction* createNodePaletteAction = nullptr; if (mainMenu) { { createNodePaletteAction = mainMenu->addAction(QAction::tr("Create Execution Connected Node Palette")); createNodePaletteAction->setAutoRepeat(false); createNodePaletteAction->setToolTip("Tries to create every node in the node palette and will attempt to create an execution path through them."); QObject::connect(createNodePaletteAction, &QAction::triggered, &CreateSingleExecutionConnectedNodePaletteAction); } { createNodePaletteAction = mainMenu->addAction(QAction::tr("Create Execution Connected Node Palette sans Handlers")); createNodePaletteAction->setAutoRepeat(false); createNodePaletteAction->setToolTip("Tries to create every node in the node palette(except EBus Handlers) and attempt to create an execution path through them.."); QObject::connect(createNodePaletteAction, &QAction::triggered, &CreateSingleExecutionConnectedNodePaletteExcludeHandlersAction); } } return createNodePaletteAction; } } }
46.086066
219
0.627568
[ "geometry", "vector", "3d" ]
60875a9e3508250ea9e0062e00e6c8f76c5fb0cb
7,364
cpp
C++
Userland/Utilities/dd.cpp
CagatayCanK/serenity
abf83f24427da10676da7fd6205dc77f32971b3c
[ "BSD-2-Clause" ]
1
2021-07-03T11:58:58.000Z
2021-07-03T11:58:58.000Z
Userland/Utilities/dd.cpp
CagatayCanK/serenity
abf83f24427da10676da7fd6205dc77f32971b3c
[ "BSD-2-Clause" ]
1
2021-06-02T21:04:00.000Z
2021-06-02T21:04:29.000Z
Userland/Utilities/dd.cpp
maxtrussell/serenity
67a5e9f0184eac51a7451f540845e49dfdc0b34a
[ "BSD-2-Clause" ]
null
null
null
/* * Copyright (c) 2021, János Tóth <toth-janos@outlook.com> * * SPDX-License-Identifier: BSD-2-Clause */ #include <AK/Optional.h> #include <AK/String.h> #include <AK/Vector.h> #include <fcntl.h> #include <stdint.h> #include <stdio.h> #include <string.h> #include <sys/types.h> #include <unistd.h> const char* usage = "usage:\n" "\tdd <options>\n" "options:\n" "\tif=<file>\tinput file (default: stdin)\n" "\tof=<file>\toutput file (default: stdout)\n" "\tbs=<size>\tblocks size may be followed by multiplicate suffixes: k=1024, M=1024*1024, G=1024*1024*1024 (default: 512)\n" "\tcount=<size>\t<size> blocks to copy (default: 0 (until end-of-file))\n" "\tseek=<size>\tskip <size> blocks at start of output (default: 0)\n" "\tskip=<size>\tskip <size> blocks at start of input (default: 0)\n" "\tstatus=<level>\tlevel of output (default: default)\n" "\t\t\tdefault - error messages + final statistics\n" "\t\t\tnone - just error messages\n" "\t\t\tnoxfer - no final statistics\n" "\t--help\t\tshows this text\n"; enum Status { Default, None, Noxfer }; static String split_at_equals(const char* argument) { String string_value(argument); auto values = string_value.split('='); if (values.size() != 2) { fprintf(stderr, "Unable to parse: %s\n", argument); return {}; } else { return values[1]; } } static int handle_io_file_arguments(int& fd, int flags, const char* argument) { auto value = split_at_equals(argument); if (value.is_empty()) { return -1; } fd = open(value.characters(), flags, 0666); if (fd == -1) { fprintf(stderr, "Unable to open: %s\n", value.characters()); return -1; } else { return 0; } } static int handle_size_arguments(size_t& numeric_value, const char* argument) { auto value = split_at_equals(argument); if (value.is_empty()) { return -1; } unsigned suffix_multiplier = 1; switch (value.to_lowercase()[value.length() - 1]) { case 'k': suffix_multiplier = KiB; value = value.substring(0, value.length() - 1); break; case 'm': suffix_multiplier = MiB; value = value.substring(0, value.length() - 1); break; case 'g': suffix_multiplier = GiB; value = value.substring(0, value.length() - 1); break; } Optional<unsigned> numeric_optional = value.to_uint(); if (!numeric_optional.has_value()) { fprintf(stderr, "Invalid size-value: %s\n", value.characters()); return -1; } numeric_value = numeric_optional.value() * suffix_multiplier; if (numeric_value < 1) { fprintf(stderr, "Invalid size-value: %lu\n", numeric_value); return -1; } else { return 0; } } static int handle_status_arguments(Status& status, const char* argument) { auto value = split_at_equals(argument); if (value.is_empty()) { return -1; } if (value == "default") { status = Default; return 0; } else if (value == "noxfer") { status = Noxfer; return 0; } else if (value == "none") { status = None; return 0; } else { fprintf(stderr, "Unknown status: %s\n", value.characters()); return -1; } } int main(int argc, char** argv) { int input_fd = 0; int input_flags = O_RDONLY; int output_fd = 1; int output_flags = O_CREAT | O_WRONLY | O_TRUNC; size_t block_size = 512; size_t count = 0; size_t skip = 0; size_t seek = 0; Status status = Default; size_t total_bytes_copied = 0; size_t total_blocks_in = 0, partial_blocks_in = 0; size_t total_blocks_out = 0, partial_blocks_out = 0; uint8_t* buffer = nullptr; ssize_t nread = 0, nwritten = 0; for (int a = 1; a < argc; a++) { if (!strcmp(argv[a], "--help")) { printf("%s", usage); return 0; } else if (!strncmp(argv[a], "if=", 3)) { if (handle_io_file_arguments(input_fd, input_flags, argv[a]) < 0) { return 1; } } else if (!strncmp(argv[a], "of=", 3)) { if (handle_io_file_arguments(output_fd, output_flags, argv[a]) < 0) { return 1; } } else if (!strncmp(argv[a], "bs=", 3)) { if (handle_size_arguments(block_size, argv[a]) < 0) { return 1; } } else if (!strncmp(argv[a], "count=", 6)) { if (handle_size_arguments(count, argv[a]) < 0) { return 1; } } else if (!strncmp(argv[a], "seek=", 5)) { if (handle_size_arguments(seek, argv[a]) < 0) { return 1; } } else if (!strncmp(argv[a], "skip=", 5)) { if (handle_size_arguments(skip, argv[a]) < 0) { return 1; } } else if (!strncmp(argv[a], "status=", 7)) { if (handle_status_arguments(status, argv[a]) < 0) { return 1; } } else { fprintf(stderr, "%s", usage); return 1; } } if ((buffer = (uint8_t*)malloc(block_size)) == nullptr) { fprintf(stderr, "Unable to allocate %lu bytes for the buffer.\n", block_size); return -1; } if (seek > 0) { if (lseek(output_fd, seek * block_size, SEEK_SET) < 0) { fprintf(stderr, "Unable to seek %lu bytes.\n", seek * block_size); return -1; } } while (1) { nread = read(input_fd, buffer, block_size); if (nread < 0) { fprintf(stderr, "Cannot read from the input.\n"); break; } else if (nread == 0) { break; } else { if ((size_t)nread != block_size) { partial_blocks_in++; } else { total_blocks_in++; } if (partial_blocks_in + total_blocks_in <= skip) { continue; } nwritten = write(output_fd, buffer, nread); if (nwritten < 0) { fprintf(stderr, "Cannot write to the output.\n"); break; } else if (nwritten == 0) { break; } else { if ((size_t)nwritten < block_size) { partial_blocks_out++; } else { total_blocks_out++; } total_bytes_copied += nwritten; if (count > 0 && (partial_blocks_out + total_blocks_out) >= count) { break; } } } } if (status == Default) { fprintf(stderr, "%lu+%lu blocks in\n", total_blocks_in, partial_blocks_in); fprintf(stderr, "%lu+%lu blocks out\n", total_blocks_out, partial_blocks_out); fprintf(stderr, "%lu bytes copied.\n", total_bytes_copied); } free(buffer); if (input_fd != 0) { close(input_fd); } if (output_fd != 1) { close(output_fd); } return 0; }
29.106719
143
0.516839
[ "vector" ]
608d3e6b3346499c24471a99881f8383d32f2d8d
7,691
cpp
C++
lammps-master/src/compute_msd.cpp
rajkubp020/helloword
4bd22691de24b30a0f5b73821c35a7ac0666b034
[ "MIT" ]
null
null
null
lammps-master/src/compute_msd.cpp
rajkubp020/helloword
4bd22691de24b30a0f5b73821c35a7ac0666b034
[ "MIT" ]
null
null
null
lammps-master/src/compute_msd.cpp
rajkubp020/helloword
4bd22691de24b30a0f5b73821c35a7ac0666b034
[ "MIT" ]
null
null
null
/* ---------------------------------------------------------------------- LAMMPS - Large-scale Atomic/Molecular Massively Parallel Simulator http://lammps.sandia.gov, Sandia National Laboratories Steve Plimpton, sjplimp@sandia.gov Copyright (2003) Sandia Corporation. Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation, the U.S. Government retains certain rights in this software. This software is distributed under the GNU General Public License. See the README file in the top-level LAMMPS directory. ------------------------------------------------------------------------- */ #include <cstring> #include "compute_msd.h" #include "atom.h" #include "update.h" #include "group.h" #include "domain.h" #include "modify.h" #include "fix_store.h" #include "error.h" using namespace LAMMPS_NS; /* ---------------------------------------------------------------------- */ ComputeMSD::ComputeMSD(LAMMPS *lmp, int narg, char **arg) : Compute(lmp, narg, arg), id_fix(NULL) { if (narg < 3) error->all(FLERR,"Illegal compute msd command"); vector_flag = 1; size_vector = 4; extvector = 0; create_attribute = 1; dynamic_group_allow = 0; // optional args comflag = 0; avflag = 0; int iarg = 3; while (iarg < narg) { if (strcmp(arg[iarg],"com") == 0) { if (iarg+2 > narg) error->all(FLERR,"Illegal compute msd command"); if (strcmp(arg[iarg+1],"no") == 0) comflag = 0; else if (strcmp(arg[iarg+1],"yes") == 0) comflag = 1; else error->all(FLERR,"Illegal compute msd command"); iarg += 2; } else if (strcmp(arg[iarg],"average") == 0) { if (iarg+2 > narg) error->all(FLERR,"Illegal compute msd command"); if (strcmp(arg[iarg+1],"no") == 0) avflag = 0; else if (strcmp(arg[iarg+1],"yes") == 0) avflag = 1; else error->all(FLERR,"Illegal compute msd command"); iarg += 2; } else error->all(FLERR,"Illegal compute msd command"); } // create a new fix STORE style for reference positions // id = compute-ID + COMPUTE_STORE, fix group = compute group int n = strlen(id) + strlen("_COMPUTE_STORE") + 1; id_fix = new char[n]; strcpy(id_fix,id); strcat(id_fix,"_COMPUTE_STORE"); char **newarg = new char*[6]; newarg[0] = id_fix; newarg[1] = group->names[igroup]; newarg[2] = (char *) "STORE"; newarg[3] = (char *) "peratom"; newarg[4] = (char *) "1"; newarg[5] = (char *) "3"; modify->add_fix(6,newarg); fix = (FixStore *) modify->fix[modify->nfix-1]; delete [] newarg; // calculate xu,yu,zu for fix store array // skip if reset from restart file if (fix->restart_reset) fix->restart_reset = 0; else { double **xoriginal = fix->astore; double **x = atom->x; int *mask = atom->mask; imageint *image = atom->image; int nlocal = atom->nlocal; for (int i = 0; i < nlocal; i++) if (mask[i] & groupbit) domain->unmap(x[i],image[i],xoriginal[i]); else xoriginal[i][0] = xoriginal[i][1] = xoriginal[i][2] = 0.0; // adjust for COM if requested if (comflag) { double cm[3]; masstotal = group->mass(igroup); group->xcm(igroup,masstotal,cm); for (int i = 0; i < nlocal; i++) if (mask[i] & groupbit) { xoriginal[i][0] -= cm[0]; xoriginal[i][1] -= cm[1]; xoriginal[i][2] -= cm[2]; } } // initialize counter for average positions if requested naverage = 0; } // displacement vector vector = new double[size_vector]; } /* ---------------------------------------------------------------------- */ ComputeMSD::~ComputeMSD() { // check nfix in case all fixes have already been deleted if (modify->nfix) modify->delete_fix(id_fix); delete [] id_fix; delete [] vector; } /* ---------------------------------------------------------------------- */ void ComputeMSD::init() { // set fix which stores reference atom coords int ifix = modify->find_fix(id_fix); if (ifix < 0) error->all(FLERR,"Could not find compute msd fix ID"); fix = (FixStore *) modify->fix[ifix]; // nmsd = # of atoms in group nmsd = group->count(igroup); masstotal = group->mass(igroup); } /* ---------------------------------------------------------------------- */ void ComputeMSD::compute_vector() { invoked_vector = update->ntimestep; // cm = current center of mass double cm[3]; if (comflag) group->xcm(igroup,masstotal,cm); else cm[0] = cm[1] = cm[2] = 0.0; // dx,dy,dz = displacement of atom from reference position // reference unwrapped position is stored by fix // relative to center of mass if comflag is set // for triclinic, need to unwrap current atom coord via h matrix double **xoriginal = fix->astore; double **x = atom->x; int *mask = atom->mask; imageint *image = atom->image; int nlocal = atom->nlocal; double *h = domain->h; double xprd = domain->xprd; double yprd = domain->yprd; double zprd = domain->zprd; double dx,dy,dz; int xbox,ybox,zbox; double msd[4]; msd[0] = msd[1] = msd[2] = msd[3] = 0.0; double xtmp, ytmp, ztmp; // update number of averages if requested double navfac; if (avflag) { naverage++; navfac = 1.0/(naverage+1); } if (domain->triclinic == 0) { for (int i = 0; i < nlocal; i++) if (mask[i] & groupbit) { xbox = (image[i] & IMGMASK) - IMGMAX; ybox = (image[i] >> IMGBITS & IMGMASK) - IMGMAX; zbox = (image[i] >> IMG2BITS) - IMGMAX; xtmp = x[i][0] + xbox*xprd - cm[0]; ytmp = x[i][1] + ybox*yprd - cm[1]; ztmp = x[i][2] + zbox*zprd - cm[2]; // use running average position for reference if requested if (avflag) { xoriginal[i][0] = (xoriginal[i][0]*naverage + xtmp)*navfac; xoriginal[i][1] = (xoriginal[i][1]*naverage + ytmp)*navfac; xoriginal[i][2] = (xoriginal[i][2]*naverage + ztmp)*navfac; } dx = xtmp - xoriginal[i][0]; dy = ytmp - xoriginal[i][1]; dz = ztmp - xoriginal[i][2]; msd[0] += dx*dx; msd[1] += dy*dy; msd[2] += dz*dz; msd[3] += dx*dx + dy*dy + dz*dz; } } else { for (int i = 0; i < nlocal; i++) if (mask[i] & groupbit) { xbox = (image[i] & IMGMASK) - IMGMAX; ybox = (image[i] >> IMGBITS & IMGMASK) - IMGMAX; zbox = (image[i] >> IMG2BITS) - IMGMAX; xtmp = x[i][0] + h[0]*xbox + h[5]*ybox + h[4]*zbox - cm[0]; ytmp = x[i][1] + h[1]*ybox + h[3]*zbox - cm[1]; ztmp = x[i][2] + h[2]*zbox - cm[2]; // use running average position for reference if requested if (avflag) { xoriginal[i][0] = (xoriginal[i][0]*naverage + xtmp)*navfac; xoriginal[i][1] = (xoriginal[i][0]*naverage + xtmp)*navfac; xoriginal[i][2] = (xoriginal[i][0]*naverage + xtmp)*navfac; } dx = xtmp - xoriginal[i][0]; dy = ytmp - xoriginal[i][1]; dz = ztmp - xoriginal[i][2]; msd[0] += dx*dx; msd[1] += dy*dy; msd[2] += dz*dz; msd[3] += dx*dx + dy*dy + dz*dz; } } MPI_Allreduce(msd,vector,4,MPI_DOUBLE,MPI_SUM,world); if (nmsd) { vector[0] /= nmsd; vector[1] /= nmsd; vector[2] /= nmsd; vector[3] /= nmsd; } } /* ---------------------------------------------------------------------- initialize one atom's storage values, called when atom is created ------------------------------------------------------------------------- */ void ComputeMSD::set_arrays(int i) { double **xoriginal = fix->astore; double **x = atom->x; xoriginal[i][0] = x[i][0]; xoriginal[i][1] = x[i][1]; xoriginal[i][2] = x[i][2]; }
28.380074
76
0.539982
[ "vector" ]
608ea3eb219939daee8144f74c60e72a52f070f9
5,016
cpp
C++
src/core/filter.cpp
neil-lindquist/nekRS
723cd46baee78f53f40eb67147dfcaad95d60aa9
[ "BSD-3-Clause" ]
1
2022-01-06T16:16:08.000Z
2022-01-06T16:16:08.000Z
src/core/filter.cpp
neil-lindquist/nekRS
723cd46baee78f53f40eb67147dfcaad95d60aa9
[ "BSD-3-Clause" ]
null
null
null
src/core/filter.cpp
neil-lindquist/nekRS
723cd46baee78f53f40eb67147dfcaad95d60aa9
[ "BSD-3-Clause" ]
null
null
null
#include "nrs.hpp" void filterFunctionRelaxation1D(int Nmodes, int Nc, dfloat* A); void filterVandermonde1D(int N, int Np, dfloat* r, dfloat* V); dfloat filterSimplex3D(dfloat a, dfloat b, dfloat c, int i, int j, int k); dfloat filterJacobiP(dfloat a, dfloat alpha, dfloat beta, int N); dfloat filterFactorial(int n); void filterSetup(nrs_t* nrs) { mesh_t* mesh = nrs->meshV; // First construct filter function nrs->filterS = 10.0; // filter Weight... platform->options.getArgs("HPFRT STRENGTH", nrs->filterS); platform->options.getArgs("HPFRT MODES", nrs->filterNc); nrs->filterS = -1.0 * fabs(nrs->filterS); // Construct Filter Function int Nmodes = mesh->N + 1; // N+1, 1D GLL points // Vandermonde matrix dfloat* V = (dfloat*) calloc(Nmodes * Nmodes, sizeof(dfloat)); // Filter matrix, diagonal dfloat* A = (dfloat*) calloc(Nmodes * Nmodes, sizeof(dfloat)); // Construct Filter Function filterFunctionRelaxation1D(Nmodes, nrs->filterNc, A); // Construct Vandermonde Matrix filterVandermonde1D(mesh->N, Nmodes, mesh->r, V); // Invert the Vandermonde int INFO; int N = Nmodes; int LWORK = N * N; double* WORK = (double*) calloc(LWORK, sizeof(double)); int* IPIV = (int*) calloc(Nmodes + 1,sizeof(int)); double* iV = (double*) calloc(Nmodes * Nmodes, sizeof(double)); for(int n = 0; n < (Nmodes + 1); n++) IPIV[n] = 1; for(int n = 0; n < Nmodes * Nmodes; ++n) iV[n] = V[n]; dgetrf_(&N,&N,(double*)iV,&N,IPIV,&INFO); dgetri_(&N,(double*)iV,&N,IPIV,(double*)WORK,&LWORK,&INFO); if(INFO) { printf("DGE_TRI/TRF error: %d \n", INFO); ABORT(EXIT_FAILURE); } // V*A*V^-1 in row major char TRANSA = 'T'; char TRANSB = 'T'; double ALPHA = 1.0, BETA = 0.0; int MD = Nmodes; int ND = Nmodes; int KD = Nmodes; int LDA = Nmodes; int LDB = Nmodes; double* C = (double*) calloc(Nmodes * Nmodes, sizeof(double)); int LDC = Nmodes; dgemm_(&TRANSA, &TRANSB, &MD, &ND, &KD, &ALPHA, A, &LDA, iV, &LDB, &BETA, C, &LDC); TRANSA = 'T'; TRANSB = 'N'; dgemm_(&TRANSA, &TRANSB, &MD, &ND, &KD, &ALPHA, V, &LDA, C, &LDB, &BETA, A, &LDC); // store filter matrix (row major) nrs->filterM = (dfloat*) calloc(Nmodes * Nmodes, sizeof(dfloat)); for(int c = 0; c < Nmodes; c++) for(int r = 0; r < Nmodes; r++) nrs->filterM[c + r * Nmodes] = A[r + c * Nmodes]; nrs->o_filterMT = platform->device.malloc(Nmodes * Nmodes * sizeof(dfloat), A); // copy Tranpose if(platform->comm.mpiRank == 0) printf("High pass filter relaxation: chi = %.4f using %d mode(s)\n", fabs(nrs->filterS), nrs->filterNc); free(A); free(C); free(V); free(iV); free(IPIV); free(WORK); } // low Pass void filterFunctionRelaxation1D(int Nmodes, int Nc, dfloat* A) { // Set all diagonal to 1 for(int n = 0; n < Nmodes; n++) A[n * Nmodes + n] = 1.0; int k0 = Nmodes - Nc; for (int k = k0; k < Nmodes; k++) { dfloat amp = ((k + 1.0 - k0) * (k + 1.0 - k0)) / (Nc * Nc); A[k + Nmodes * k] = 1.0 - amp; } } void filterVandermonde1D(int N, int Np, dfloat* r, dfloat* V) { int sk = 0; for(int i = 0; i <= N; i++) { for(int n = 0; n < Np; n++) V[n * Np + sk] = filterJacobiP(r[n],0,0,i); sk++; } } dfloat filterSimplex3D(dfloat a, dfloat b, dfloat c, int i, int j, int k) { // dfloat p1 = filterJacobiP(a,0,0,i); dfloat p2 = filterJacobiP(b,2 * i + 1,0,j); dfloat p3 = filterJacobiP(c,2 * (i + j) + 2,0,k); dfloat P = 2.0 * sqrt(2.0) * p1 * p2 * pow(1 - b,i) * p3 * pow(1 - c,i + j); return P; } // jacobi polynomials at [-1,1] for GLL dfloat filterJacobiP(dfloat a, dfloat alpha, dfloat beta, int N) { dfloat ax = a; dfloat* P = (dfloat*) calloc((N + 1), sizeof(dfloat)); // Zero order dfloat gamma0 = pow(2, (alpha + beta + 1)) / (alpha + beta + 1) * filterFactorial(alpha) * filterFactorial(beta) / filterFactorial(alpha + beta); dfloat p0 = 1.0 / sqrt(gamma0); if (N == 0) { free(P); return p0; } P[0] = p0; // first order dfloat gamma1 = (alpha + 1) * (beta + 1) / (alpha + beta + 3) * gamma0; dfloat p1 = ((alpha + beta + 2) * ax / 2 + (alpha - beta) / 2) / sqrt(gamma1); if (N == 1) { free(P); return p1; } P[1] = p1; /// Repeat value in recurrence. dfloat aold = 2 / (2 + alpha + beta) * sqrt((alpha + 1.) * (beta + 1.) / (alpha + beta + 3.)); /// Forward recurrence using the symmetry of the recurrence. for(int i = 1; i <= N - 1; ++i) { dfloat h1 = 2. * i + alpha + beta; dfloat anew = 2. / (h1 + 2.) * sqrt( (i + 1.) * (i + 1. + alpha + beta) * (i + 1 + alpha) * (i + 1 + beta) / (h1 + 1) / (h1 + 3)); dfloat bnew = -(alpha * alpha - beta * beta) / h1 / (h1 + 2); P[i + 1] = 1. / anew * ( -aold * P[i - 1] + (ax - bnew) * P[i]); aold = anew; } dfloat pN = P[N]; free(P); return pN; } dfloat filterFactorial(int n) { if(n == 0) return 1; else return n * filterFactorial(n - 1); }
27.113514
99
0.569378
[ "mesh" ]
60900530c7f290275a4212ab8cdae344402137d1
5,361
hxx
C++
Modules/Filtering/BiasCorrection/include/itkMRASlabIdentifier.hxx
eile/ITK
2f09e6e2f9e0a4a7269ac83c597f97b04f915dc1
[ "Apache-2.0" ]
null
null
null
Modules/Filtering/BiasCorrection/include/itkMRASlabIdentifier.hxx
eile/ITK
2f09e6e2f9e0a4a7269ac83c597f97b04f915dc1
[ "Apache-2.0" ]
null
null
null
Modules/Filtering/BiasCorrection/include/itkMRASlabIdentifier.hxx
eile/ITK
2f09e6e2f9e0a4a7269ac83c597f97b04f915dc1
[ "Apache-2.0" ]
null
null
null
/*========================================================================= * * Copyright Insight Software Consortium * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0.txt * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * *=========================================================================*/ #ifndef __itkMRASlabIdentifier_hxx #define __itkMRASlabIdentifier_hxx #include <algorithm> #include <vector> #include <queue> #include "itkMRASlabIdentifier.h" #include "itkImageRegionIterator.h" #include "vnl/vnl_math.h" namespace itk { template< typename TInputImage > MRASlabIdentifier< TInputImage > ::MRASlabIdentifier() { m_Image = ITK_NULLPTR; m_NumberOfSamples = 10; m_BackgroundMinimumThreshold = NumericTraits< ImagePixelType >::min(); m_Tolerance = 0.0; // default slicing axis is z m_SlicingDirection = 2; } template< typename TInputImage > void MRASlabIdentifier< TInputImage > ::GenerateSlabRegions(void) { // this method only works with 3D MRI image if ( ImageType::ImageDimension != 3 ) { itkExceptionMacro("ERROR: This algorithm only works with 3D images."); } ImageSizeType size; ImageRegionType region; ImageIndexType index; region = m_Image->GetLargestPossibleRegion(); size = region.GetSize(); index = region.GetIndex(); IndexValueType firstSlice = index[m_SlicingDirection]; IndexValueType lastSlice = firstSlice + size[m_SlicingDirection]; SizeValueType totalSlices = size[m_SlicingDirection]; double sum; std::vector< double > avgMin(totalSlices); // calculate minimum intensities for each slice ImagePixelType pixel; for ( int i = 0; i < 3; i++ ) { if ( i != m_SlicingDirection ) { index[i] = 0; } } size[m_SlicingDirection] = 1; region.SetSize(size); SizeValueType count = 0; IndexValueType currentSlice = firstSlice; while ( currentSlice < lastSlice ) { index[m_SlicingDirection] = currentSlice; region.SetIndex(index); ImageRegionConstIterator< TInputImage > iter(m_Image, region); iter.GoToBegin(); std::priority_queue< ImagePixelType > mins; for ( unsigned int i = 0; i < m_NumberOfSamples; ++i ) { mins.push( NumericTraits< ImagePixelType >::max() ); } while ( !iter.IsAtEnd() ) { pixel = iter.Get(); if ( pixel > m_BackgroundMinimumThreshold ) { if ( mins.top() > pixel ) { mins.pop(); mins.push(pixel); } } ++iter; } sum = 0.0; while ( !mins.empty() ) { sum += mins.top(); mins.pop(); } avgMin[count] = sum / (double)m_NumberOfSamples; ++count; ++currentSlice; } // calculate overall average sum = 0.0; std::vector< double >::iterator am_iter = avgMin.begin(); while ( am_iter != avgMin.end() ) { sum += *am_iter; ++am_iter; } double average = sum / (double)totalSlices; // determine slabs am_iter = avgMin.begin(); double prevSign = *am_iter - average; double avgMinValue; ImageIndexType slabIndex; ImageRegionType slabRegion; ImageSizeType slabSize; SizeValueType slabLength = 0; IndexValueType slabBegin = firstSlice; slabSize = size; slabIndex = index; while ( am_iter != avgMin.end() ) { avgMinValue = *am_iter; double sign = avgMinValue - average; if ( ( sign * prevSign < 0 ) && ( vnl_math_abs(sign) > m_Tolerance ) ) { slabIndex[m_SlicingDirection] = slabBegin; slabSize[m_SlicingDirection] = slabLength; slabRegion.SetSize(slabSize); slabRegion.SetIndex(slabIndex); m_Slabs.push_back(slabRegion); prevSign = sign; slabBegin += slabLength; slabLength = 0; } am_iter++; slabLength++; } slabIndex[m_SlicingDirection] = slabBegin; slabSize[m_SlicingDirection] = slabLength; slabRegion.SetIndex(slabIndex); slabRegion.SetSize(slabSize); m_Slabs.push_back(slabRegion); } template< typename TInputImage > typename MRASlabIdentifier< TInputImage >::SlabRegionVectorType MRASlabIdentifier< TInputImage > ::GetSlabRegionVector(void) { return m_Slabs; } template< typename TInputImage > void MRASlabIdentifier< TInputImage > ::PrintSelf(std::ostream & os, Indent indent) const { Superclass::PrintSelf(os, indent); if ( m_Image ) { os << indent << "Image: " << m_Image << std::endl; } else { os << indent << "Image: " << "(None)" << std::endl; } os << indent << "NumberOfSamples: " << m_NumberOfSamples << std::endl; os << indent << "SlicingDirection: " << m_SlicingDirection << std::endl; os << indent << "Background Pixel Minimum Intensity Threshold: " << m_BackgroundMinimumThreshold << std::endl; os << indent << "Tolerance: " << m_Tolerance << std::endl; } } // end namespace itk #endif /* __itkMRASlabIdentifier_hxx */
26.15122
77
0.643723
[ "vector", "3d" ]
609122c76f31b36f5ea6784915b1e3e0e58e7b00
3,691
cpp
C++
src/serlio/PRTContext.cpp
ArcGIS/serlio
4413ae0e0d83815fb6b78e956cc7ecb988f01d56
[ "Apache-2.0" ]
17
2019-09-19T16:04:09.000Z
2021-12-27T18:48:53.000Z
src/serlio/PRTContext.cpp
ArcGIS/serlio
4413ae0e0d83815fb6b78e956cc7ecb988f01d56
[ "Apache-2.0" ]
76
2019-07-31T07:05:05.000Z
2022-03-08T12:58:27.000Z
src/serlio/PRTContext.cpp
ArcGIS/serlio
4413ae0e0d83815fb6b78e956cc7ecb988f01d56
[ "Apache-2.0" ]
5
2019-09-04T16:07:30.000Z
2020-10-01T07:55:06.000Z
/** * Serlio - Esri CityEngine Plugin for Autodesk Maya * * See https://github.com/esri/serlio for build and usage instructions. * * Copyright (c) 2012-2019 Esri R&D Center Zurich * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "PRTContext.h" #include "utils/LogHandler.h" #include <mutex> namespace { constexpr bool DBG = false; constexpr const wchar_t* SRL_TMP_PREFIX = L"serlio_"; constexpr const wchar_t* PRT_EXT_SUBDIR = L"ext"; constexpr prt::LogLevel PRT_LOG_LEVEL = prt::LOG_INFO; constexpr bool ENABLE_LOG_CONSOLE = true; constexpr bool ENABLE_LOG_FILE = false; bool verifyMayaEncoder() { constexpr const wchar_t* ENC_ID_MAYA = L"MayaEncoder"; const auto mayaEncOpts = prtu::createValidatedOptions(ENC_ID_MAYA); return static_cast<bool>(mayaEncOpts); } } // namespace PRTContext& PRTContext::get() { static PRTContext prtCtx; return prtCtx; } PRTContext::PRTContext(const std::vector<std::wstring>& addExtDirs) : mPluginRootPath(prtu::getPluginRoot()) { if (ENABLE_LOG_CONSOLE) { theLogHandler = prt::ConsoleLogHandler::create(prt::LogHandler::ALL, prt::LogHandler::ALL_COUNT); prt::addLogHandler(theLogHandler); } if (ENABLE_LOG_FILE) { const std::wstring logPath = mPluginRootPath + prtu::getDirSeparator<wchar_t>() + L"serlio.log"; theFileLogHandler = prt::FileLogHandler::create(prt::LogHandler::ALL, prt::LogHandler::ALL_COUNT, logPath.c_str()); prt::addLogHandler(theFileLogHandler); } // Not the best place, but here we are sure the console logger is running and we are before PRT init info LOG_INF << "Initializing Serlio Version " << SRL_VERSION << " ..."; if (DBG) LOG_DBG << "initialized prt logger, plugin root path is " << mPluginRootPath; std::vector<std::wstring> extensionPaths = {mPluginRootPath + PRT_EXT_SUBDIR}; extensionPaths.insert(extensionPaths.end(), addExtDirs.begin(), addExtDirs.end()); if (DBG) LOG_DBG << "looking for prt extensions at\n" << extensionPaths; prt::Status status = prt::STATUS_UNSPECIFIED_ERROR; const auto extensionPathPtrs = prtu::toPtrVec(extensionPaths); thePRT.reset(prt::init(extensionPathPtrs.data(), extensionPathPtrs.size(), PRT_LOG_LEVEL, &status)); // early sanity check for maya encoder if (!verifyMayaEncoder()) { LOG_FTL << "Unable to load Maya encoder extension!"; status = prt::STATUS_ENCODER_NOT_FOUND; } if (!thePRT || status != prt::STATUS_OK) { LOG_FTL << "Could not initialize PRT: " << prt::getStatusDescription(status); thePRT.reset(); } else { theCache.reset(prt::CacheObject::create(prt::CacheObject::CACHE_TYPE_DEFAULT)); mResolveMapCache = std::make_unique<ResolveMapCache>(prtu::getProcessTempDir(SRL_TMP_PREFIX)); } } PRTContext::~PRTContext() { // the cache needs to be destructed before PRT, so reset them explicitely in the right order here theCache.reset(); thePRT.reset(); if (ENABLE_LOG_CONSOLE && (theLogHandler != nullptr)) { prt::removeLogHandler(theLogHandler); theLogHandler->destroy(); theLogHandler = nullptr; } if (ENABLE_LOG_FILE && (theFileLogHandler != nullptr)) { prt::removeLogHandler(theFileLogHandler); theFileLogHandler->destroy(); theFileLogHandler = nullptr; } }
33.252252
110
0.739908
[ "vector" ]
6091ce72e0755cbc8e49ee7f2111a9955063ff9b
7,337
hpp
C++
engine/gems/bayes_filters/extended_kalman_filter.hpp
stereoboy/isaac_sdk_20191213
73c863254e626c8d498870189fbfb20be4e10fb3
[ "FSFAP" ]
1
2020-04-14T13:55:16.000Z
2020-04-14T13:55:16.000Z
engine/gems/bayes_filters/extended_kalman_filter.hpp
stereoboy/isaac_sdk_20191213
73c863254e626c8d498870189fbfb20be4e10fb3
[ "FSFAP" ]
4
2020-09-25T22:34:29.000Z
2022-02-09T23:45:12.000Z
engine/gems/bayes_filters/extended_kalman_filter.hpp
stereoboy/isaac_sdk_20191213
73c863254e626c8d498870189fbfb20be4e10fb3
[ "FSFAP" ]
1
2020-07-02T11:51:17.000Z
2020-07-02T11:51:17.000Z
/* Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved. NVIDIA CORPORATION and its licensors retain all intellectual property and proprietary rights in and to this software, related documentation and any modifications thereto. Any use, reproduction, disclosure or distribution of this software and related documentation without an express license agreement from NVIDIA CORPORATION is strictly prohibited. */ #pragma once #include <functional> #include "engine/core/assert.hpp" #include "engine/core/math/types.hpp" #include "engine/gems/state/state.hpp" namespace isaac { // This file contains helper classes and functions to implement an extended Kalman filter. // // An extended Kalman filter is the non-linear extension of the Kalman filter. // """A Kalman filter is an algorithm that uses a series of measurements observed over time, // containing statistical noise and other inaccuracies, and produces estimates of unknown // variables that tend to be more accurate than those based on a single measurement alone, by // estimating a joint probability distribution over the variables for each timeframe.""" // See Wikipedia (https://en.wikipedia.org/wiki/Extended_Kalman_filter) for more details. // // EkfPredictionModel and EkfObservationModel hold the prediction and observation models of an // extended Kalman filter. Together they can be used to implement an extended Kalman filter. // The prediction and observation models are separate to allow an easy recombination of different // models into different filters, or even dynamically exchange a model in a specific situations. // // Kalman filters use the state::State type for state, control and observation vectors. The // state::State type provides named access to elements in the state vector. This mechanics helps to // avoid index erros when setting elements in the state vectors or computing Jacobians. // A special type which can be used when there is no control vector. Identical to state::State<K,0>. template <typename K> using EkfNoControl = state::State<K, 0>; using EkfNoControlF = EkfNoControl<float>; using EkfNoControlD = EkfNoControl<double>; // Convenience types to get types for the state covariance matrices and jacobians template <typename State> using EkfCovariance = Matrix<typename State::Scalar, State::kDimension, State::kDimension>; template <typename State> using EkfPredictJacobian = Matrix<typename State::Scalar, State::kDimension, State::kDimension>; template <typename State, typename Observation> using EkfObserveJacobian = Matrix<typename State::Scalar, Observation::kDimension, State::kDimension>; namespace details_ekf { // Computes A * X * A^t template <typename K, int N, int M> Matrix<K, M, M> AXAt(const Matrix<K, N, N>& X, const Matrix<K, M, N>& A) { // TODO: Use optimized implementation return A * X * A.transpose(); } // Makes sure that a matrix is symmetric template <typename Derived> auto EnforceSymmetry(const Eigen::MatrixBase<Derived>& A) { // returns a matrix of same type as A using K = typename Derived::Scalar; static_assert(std::is_floating_point<K>::value, "This function only works for floating points"); auto A_eval = A.eval(); return (K(0.5) * (A_eval + A_eval.transpose())).eval(); } } // namespace details_ekf // Prediction model for the Extended Kalman filter // // K: type of scalar // NX: dimension of the state space X (or Eigen::Dynamic for runtime size) // NU: dimension of the control space U (or Eigen::Dynamic for runtime size) template <typename X, typename U = EkfNoControl<typename X::Scalar>> struct EkfPredictionModel { using K = typename X::Scalar; static_assert(std::is_same<K, typename U::Scalar>::value, "Scalar type for state and control must be identical"); static constexpr int NX = X::kDimension; static constexpr int NU = U::kDimension; // Various linear algebra types for state vectors and covariance matrices using P_t = EkfCovariance<X>; using F_t = EkfPredictJacobian<X>; using Q_t = EkfCovariance<X>; // State transition function f: X x U -> X std::function<void(X& x, K dt, const U& u)> predict_state; // Jacobian of the state transition function // This is a matrix of derivatives of the state prediction function f. Each row i contains the // the derivatives df_i / dx_j for every element in the state vector x. std::function<F_t(const X& x, K dt, const U& u)> predict_jacobian; // State transition noise per time // Warning: This must return a symmetric matrix! std::function<Q_t(const X& x)> predict_noise; // Performs a single prediction step for an extended Kalman filter void predict(X& x, P_t& P, K dt, const U& u) const { P = details_ekf::EnforceSymmetry(details_ekf::AXAt(P, predict_jacobian(x, dt, u)) + std::sqrt(dt) * predict_noise(x)); predict_state(x, dt, u); } // Performs a single prediction step for an extended Kalman filter without control space void predict(X& x, P_t& P, K dt) const { static_assert(NU == 0, "Can only omit control vector if control state space has dimension 0"); return predict(x, P, dt, U{}); } }; // Observation model for the Extended Kalman filter // // K: type of scalar // NX: dimension of the state space X (or Eigen::Dynamic for runtime size) // NZ: dimension of the observation space Z (or Eigen::Dynamic for runtime size) template <typename X, typename Z> struct EkfObservationModel { using K = typename X::Scalar; static_assert(std::is_same<K, typename Z::Scalar>::value, "Scalar type for state and observation must be identical"); static constexpr int NX = X::kDimension; static constexpr int NZ = Z::kDimension; // Various linear algebra types for state vectors and covariance matrices using P_t = EkfCovariance<X>; using H_t = EkfObserveJacobian<X, Z>; using R_t = EkfCovariance<Z>; // State observation function h: X -> Z std::function<Z(const X& x)> observe_state; // Computes the difference "lhs - rhs" between two observations. std::function<Z(const Z& lhs, const Z& rhs)> observe_state_difference; // Jacobian of the state observation function // This is a matrix of derivatives of the state observation function h. The element J_ij with row // row index i and col index j is the derivative dh_i / dx_j. std::function<H_t(const X& x)> observe_jacobian; // State observation noise // Warning: This must return a symmetric matrix! std::function<R_t(const X& x, const Z& z)> observe_noise; // Performs a single observation step for an extended Kalman filter void observe(X& x, P_t& P, const Z& z) const { H_t H = observe_jacobian(x); Matrix<K, NZ, NZ> S = details_ekf::EnforceSymmetry(details_ekf::AXAt(P, H) + observe_noise(x, z)); // To compute K = P * H^t * S^-1 we solve the linear equation K * S = P * H^t for S. // This is identical to solving S^t K^t = H * P^t. Matrix<K, NX, NZ> gain = S.transpose().colPivHouseholderQr().solve(H * P.transpose()).transpose(); x.elements += gain * observe_state_difference(z, observe_state(x)).elements; const int nx = x.elements.size(); // Need to pass the actual size in case of Eigen::Dynamic P = details_ekf::EnforceSymmetry((Matrix<K, NX, NX>::Identity(nx, nx) - gain * H) * P); } }; } // namespace isaac
45.85625
100
0.727
[ "vector", "model" ]
60956a377fd3b43a237f97c646b3fdd0de498ece
4,784
cpp
C++
apps/rawlog-edit/rawlog-edit_filters.cpp
tg1716/SLAM
b8583fb98a4241d87ae08ac78b0420c154f5e1a5
[ "BSD-3-Clause" ]
4
2017-08-04T15:44:04.000Z
2021-02-02T02:00:18.000Z
apps/rawlog-edit/rawlog-edit_filters.cpp
tg1716/SLAM
b8583fb98a4241d87ae08ac78b0420c154f5e1a5
[ "BSD-3-Clause" ]
null
null
null
apps/rawlog-edit/rawlog-edit_filters.cpp
tg1716/SLAM
b8583fb98a4241d87ae08ac78b0420c154f5e1a5
[ "BSD-3-Clause" ]
2
2017-10-03T23:10:09.000Z
2018-07-29T09:41:33.000Z
/* +------------------------------------------------------------------------+ | Mobile Robot Programming Toolkit (MRPT) | | http://www.mrpt.org/ | | | | Copyright (c) 2005-2017, Individual contributors, see AUTHORS file | | See: http://www.mrpt.org/Authors - All rights reserved. | | Released under BSD License. See details in http://www.mrpt.org/License | +------------------------------------------------------------------------+ */ #include "rawlog-edit-declarations.h" using namespace mrpt; using namespace mrpt::utils; using namespace mrpt::obs; using namespace mrpt::system; using namespace mrpt::rawlogtools; using namespace std; // ====================================================================== // op_remove_label // ====================================================================== DECLARE_OP_FUNCTION(op_remove_label) { // A class to do this operation: class CRawlogProcessor_RemoveLabel : public CRawlogProcessorFilterObservations { protected: vector<string> m_filter_labels; public: CRawlogProcessor_RemoveLabel( mrpt::utils::CFileGZInputStream& in_rawlog, TCLAP::CmdLine& cmdline, bool verbose, CFileGZOutputStream& out_rawlog, const std::string& filter_label) : CRawlogProcessorFilterObservations( in_rawlog, cmdline, verbose, out_rawlog) { mrpt::system::tokenize(filter_label, " ,", m_filter_labels); ASSERT_(!m_filter_labels.empty()) if (verbose) for (size_t i = 0; i < m_filter_labels.size(); i++) cout << "Removing label: '" << m_filter_labels[i] << "'\n"; } /** To be implemented by users: return false means the observation is */ virtual bool tellIfThisObsPasses(mrpt::obs::CObservation::Ptr& obs) { for (size_t i = 0; i < m_filter_labels.size(); i++) if (obs->sensorLabel == m_filter_labels[i]) { return false; } return true; } }; // Process // --------------------------------- string filter_label; if (!getArgValue<string>(cmdline, "remove-label", filter_label) || filter_label.empty()) throw std::runtime_error( "remove-label: This operation needs a non-empty argument."); TOutputRawlogCreator outrawlog; CRawlogProcessor_RemoveLabel proc( in_rawlog, cmdline, verbose, outrawlog.out_rawlog, filter_label); proc.doProcessRawlog(); // Dump statistics: // --------------------------------- VERBOSE_COUT << "Time to process file (sec) : " << proc.m_timToParse << "\n"; VERBOSE_COUT << "Analyzed entries : " << proc.m_entries_parsed << "\n"; VERBOSE_COUT << "Removed entries : " << proc.m_entries_removed << "\n"; } // ====================================================================== // op_keep_label // ====================================================================== DECLARE_OP_FUNCTION(op_keep_label) { // A class to do this operation: class CRawlogProcessor_KeepLabel : public CRawlogProcessorFilterObservations { protected: vector<string> m_filter_labels; public: CRawlogProcessor_KeepLabel( mrpt::utils::CFileGZInputStream& in_rawlog, TCLAP::CmdLine& cmdline, bool verbose, CFileGZOutputStream& out_rawlog, const std::string& filter_label) : CRawlogProcessorFilterObservations( in_rawlog, cmdline, verbose, out_rawlog) { mrpt::system::tokenize(filter_label, " ,", m_filter_labels); ASSERT_(!m_filter_labels.empty()) if (verbose) for (size_t i = 0; i < m_filter_labels.size(); i++) cout << "Keeping label: '" << m_filter_labels[i] << "'\n"; } /** To be implemented by users: return false means the observation is */ virtual bool tellIfThisObsPasses(mrpt::obs::CObservation::Ptr& obs) { for (size_t i = 0; i < m_filter_labels.size(); i++) if (obs->sensorLabel == m_filter_labels[i]) { return true; } return false; } }; // Process // --------------------------------- string filter_label; if (!getArgValue<string>(cmdline, "keep-label", filter_label) || filter_label.empty()) throw std::runtime_error( "keep-label: This operation needs a non-empty argument."); TOutputRawlogCreator outrawlog; CRawlogProcessor_KeepLabel proc( in_rawlog, cmdline, verbose, outrawlog.out_rawlog, filter_label); proc.doProcessRawlog(); // Dump statistics: // --------------------------------- VERBOSE_COUT << "Time to process file (sec) : " << proc.m_timToParse << "\n"; VERBOSE_COUT << "Analyzed entries : " << proc.m_entries_parsed << "\n"; VERBOSE_COUT << "Removed entries : " << proc.m_entries_removed << "\n"; }
33.929078
80
0.571697
[ "vector" ]
6099990884aca6da78ee42e3ff723edeb0fe41d2
3,424
cpp
C++
mandelbrot.cpp
oddek/Mandelbrot_img-gif_gen
d2833231eff93f3a7ff94cdb1a7609cd0d07f624
[ "MIT" ]
null
null
null
mandelbrot.cpp
oddek/Mandelbrot_img-gif_gen
d2833231eff93f3a7ff94cdb1a7609cd0d07f624
[ "MIT" ]
null
null
null
mandelbrot.cpp
oddek/Mandelbrot_img-gif_gen
d2833231eff93f3a7ff94cdb1a7609cd0d07f624
[ "MIT" ]
null
null
null
#include "Mandelbrot.h" Mandelbrot::Mandelbrot() { img = new IMG(output_file, width, height); gifw = new GifWriter(); GifBegin(gifw, outputgif, width, height, mspf); } Mandelbrot::~Mandelbrot() { delete img; delete gifw; } void Mandelbrot::create_img() { calc(); img->encodeOneStep(); } void Mandelbrot::update_min_max(char axis) { if(axis == 'x') { double inc_fact = (zoom_inc/abs(x_max-x_min)); x_min += inc_fact * abs(x_center-x_min); x_max -= inc_fact * abs(x_center-x_max); x_inc = abs(x_max - x_min)/(double)width; } else if(axis == 'y') { double inc_fact = (zoom_inc/abs(y_max-y_min)); y_min += inc_fact * abs(y_center-y_min); y_max -= inc_fact * abs(y_center-y_max); y_inc = abs(y_max - y_min)/(double)height; } } vector<unsigned char> Mandelbrot::get_buffer() { calc(); cout << "Done calc()" << endl; return img->buffer; } void Mandelbrot::create_gif() { auto start = chrono::high_resolution_clock::now(); int n = 0; while(n < frames) { SetThreadExecutionState(ES_CONTINUOUS | ES_SYSTEM_REQUIRED | ES_AWAYMODE_REQUIRED); if(x_min >= x_max || y_min >= y_max) break; calc(); static_assert(std::is_same<unsigned char, uint8_t>::value, "uint8_t is not unsigned char"); uint8_t* data = img->buffer.data(); GifWriteFrame(gifw, data, width, height, mspf); update_min_max('x'); update_min_max('y'); zoom_inc = min(abs(y_center-y_min), min(abs(y_center-y_max), min(abs(x_center-x_max), abs(x_center-x_min)))); cout << "zoom_inc: " << zoom_inc << endl; printf("x_min: %.16G x_max: %.16G\ny_min: %.16Gy_max: %.16G\n", x_min, x_max, y_min, y_max); cout << "N: " << n << endl; n++; } SetThreadExecutionState(ES_CONTINUOUS); GifEnd(gifw); auto end = chrono::high_resolution_clock::now(); chrono::duration<double> diff = end - start; cout << "Ferdig!" << endl; cout << "Gif tok: " << diff.count() << " sekunder" <<endl; } void Mandelbrot::calc() { for(double y = y_max; y >= y_min; y -= y_inc) { for(double x = x_min; x <= x_max; x += x_inc) { iterate(x, y); } } } void Mandelbrot::iterate(double x, double y) { //complex<double> c(x, y); //complex<double> z(0, 0); double z_real = 0; double z_imag = 0; int no_of_iterations = 0; for(no_of_iterations; no_of_iterations <= iterations; no_of_iterations++) { double old_z_real = z_real; z_real = pow(z_real, 2) - pow(z_imag, 2) + x; z_imag = 2*old_z_real*z_imag + y; if(pow(z_real,2)+pow(z_imag,2) > magic_number) break; } long index = 4*(map_onto(y, y_max, y_min, 0, height)*width + map_onto(x, x_min, x_max, 0, width)); //Skjønner ikke helt hvorfor denne er nødvendig, men får for stor index i blant. //Antakelig noe tull når det blir mange desimaler if(index >= img->buffer.size()) { return; } if(no_of_iterations > iterations*0.84) { img->buffer.at(index) = 0; img->buffer.at(index+1) = 0; img->buffer.at(index+2) = 0; img->buffer.at(index+3) = 255; } else { img->buffer.at(index) = get_color(no_of_iterations, 1,0); img->buffer.at(index+1) = get_color(no_of_iterations, 1, 120); img->buffer.at(index+2) = get_color(no_of_iterations, 1,240); img->buffer.at(index+3) = 255; } } long Mandelbrot::map_onto(double x, double a, double b, double c, double d) { long i = abs(((x-a)*((d-c)/(b-a))+c)); //if(i > 49) return 49; return i; } int Mandelbrot::get_color(int x,int f,int p) { return 255*pow((cos(sqrt(x)*f + p)), 2); }
23.944056
94
0.651869
[ "vector" ]
609befc13da486711eb487f15cf814516a900dd5
37,116
cpp
C++
HelperFunctions/getVkPhysicalDeviceVulkan12Features.cpp
dkaip/jvulkan-natives-Linux-x86_64
ea7932f74e828953c712feea11e0b01751f9dc9b
[ "Apache-2.0" ]
null
null
null
HelperFunctions/getVkPhysicalDeviceVulkan12Features.cpp
dkaip/jvulkan-natives-Linux-x86_64
ea7932f74e828953c712feea11e0b01751f9dc9b
[ "Apache-2.0" ]
null
null
null
HelperFunctions/getVkPhysicalDeviceVulkan12Features.cpp
dkaip/jvulkan-natives-Linux-x86_64
ea7932f74e828953c712feea11e0b01751f9dc9b
[ "Apache-2.0" ]
null
null
null
/* * Copyright 2020 Douglas Kaip * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * getVkPhysicalDeviceVulkan12Features.cpp * * Created on: Sep 9, 2020 * Author: Douglas Kaip */ #include "JVulkanHelperFunctions.hh" #include "slf4j.hh" namespace jvulkan { void getVkPhysicalDeviceVulkan12Features( JNIEnv *env, jobject jVkPhysicalDeviceVulkan12FeaturesObject, VkPhysicalDeviceVulkan12Features *vkPhysicalDeviceVulkan12Features, std::vector<void *> *memoryToFree) { jclass theClass = env->GetObjectClass(jVkPhysicalDeviceVulkan12FeaturesObject); if (env->ExceptionOccurred()) { LOGERROR(env, "%s", "Could not get class for jVkPhysicalDeviceVulkan12FeaturesObject"); return; } //////////////////////////////////////////////////////////////////////// VkStructureType sTypeValue = getSType(env, jVkPhysicalDeviceVulkan12FeaturesObject); if (env->ExceptionOccurred()) { LOGERROR(env, "%s", "Call to getSType failed."); return; } //////////////////////////////////////////////////////////////////////// jobject jpNextObject = getpNextObject(env, jVkPhysicalDeviceVulkan12FeaturesObject); if (env->ExceptionOccurred()) { LOGERROR(env, "%s", "Call to getpNext failed."); return; } void *pNext = nullptr; if (jpNextObject != nullptr) { getpNextChain( env, jpNextObject, &pNext, memoryToFree); if (env->ExceptionOccurred()) { LOGERROR(env, "%s", "Call to getpNextChain failed."); return; } } //////////////////////////////////////////////////////////////////////// jmethodID methodId = env->GetMethodID(theClass, "isSamplerMirrorClampToEdge", "()Z"); if (env->ExceptionOccurred()) { LOGERROR(env, "%s", "Could not find method id for isSamplerMirrorClampToEdge."); return; } VkBool32 samplerMirrorClampToEdge = (VkBool32)env->CallBooleanMethod(jVkPhysicalDeviceVulkan12FeaturesObject, methodId); if (env->ExceptionOccurred()) { LOGERROR(env, "%s", "Error calling CallBooleanMethod."); return; } //////////////////////////////////////////////////////////////////////// methodId = env->GetMethodID(theClass, "isDrawIndirectCount", "()Z"); if (env->ExceptionOccurred()) { LOGERROR(env, "%s", "Could not find method id for isDrawIndirectCount."); return; } VkBool32 drawIndirectCount = (VkBool32)env->CallBooleanMethod(jVkPhysicalDeviceVulkan12FeaturesObject, methodId); if (env->ExceptionOccurred()) { LOGERROR(env, "%s", "Error calling CallBooleanMethod."); return; } //////////////////////////////////////////////////////////////////////// methodId = env->GetMethodID(theClass, "isStorageBuffer8BitAccess", "()Z"); if (env->ExceptionOccurred()) { LOGERROR(env, "%s", "Could not find method id for isStorageBuffer8BitAccess."); return; } VkBool32 storageBuffer8BitAccess = (VkBool32)env->CallBooleanMethod(jVkPhysicalDeviceVulkan12FeaturesObject, methodId); if (env->ExceptionOccurred()) { LOGERROR(env, "%s", "Error calling CallBooleanMethod."); return; } //////////////////////////////////////////////////////////////////////// methodId = env->GetMethodID(theClass, "isUniformAndStorageBuffer8BitAccess", "()Z"); if (env->ExceptionOccurred()) { LOGERROR(env, "%s", "Could not find method id for isUniformAndStorageBuffer8BitAccess."); return; } VkBool32 uniformAndStorageBuffer8BitAccess = (VkBool32)env->CallBooleanMethod(jVkPhysicalDeviceVulkan12FeaturesObject, methodId); if (env->ExceptionOccurred()) { LOGERROR(env, "%s", "Error calling CallBooleanMethod."); return; } //////////////////////////////////////////////////////////////////////// methodId = env->GetMethodID(theClass, "isStoragePushConstant8", "()Z"); if (env->ExceptionOccurred()) { LOGERROR(env, "%s", "Could not find method id for isStoragePushConstant8."); return; } VkBool32 storagePushConstant8 = (VkBool32)env->CallBooleanMethod(jVkPhysicalDeviceVulkan12FeaturesObject, methodId); if (env->ExceptionOccurred()) { LOGERROR(env, "%s", "Error calling CallBooleanMethod."); return; } //////////////////////////////////////////////////////////////////////// methodId = env->GetMethodID(theClass, "isShaderBufferInt64Atomics", "()Z"); if (env->ExceptionOccurred()) { LOGERROR(env, "%s", "Could not find method id for isShaderBufferInt64Atomics."); return; } VkBool32 shaderBufferInt64Atomics = (VkBool32)env->CallBooleanMethod(jVkPhysicalDeviceVulkan12FeaturesObject, methodId); if (env->ExceptionOccurred()) { LOGERROR(env, "%s", "Error calling CallBooleanMethod."); return; } //////////////////////////////////////////////////////////////////////// methodId = env->GetMethodID(theClass, "isShaderSharedInt64Atomics", "()Z"); if (env->ExceptionOccurred()) { LOGERROR(env, "%s", "Could not find method id for isShaderSharedInt64Atomics."); return; } VkBool32 shaderSharedInt64Atomics = (VkBool32)env->CallBooleanMethod(jVkPhysicalDeviceVulkan12FeaturesObject, methodId); if (env->ExceptionOccurred()) { LOGERROR(env, "%s", "Error calling CallBooleanMethod."); return; } //////////////////////////////////////////////////////////////////////// methodId = env->GetMethodID(theClass, "isShaderFloat16", "()Z"); if (env->ExceptionOccurred()) { LOGERROR(env, "%s", "Could not find method id for isShaderFloat16."); return; } VkBool32 shaderFloat16 = (VkBool32)env->CallBooleanMethod(jVkPhysicalDeviceVulkan12FeaturesObject, methodId); if (env->ExceptionOccurred()) { LOGERROR(env, "%s", "Error calling CallBooleanMethod."); return; } //////////////////////////////////////////////////////////////////////// methodId = env->GetMethodID(theClass, "isShaderInt8", "()Z"); if (env->ExceptionOccurred()) { LOGERROR(env, "%s", "Could not find method id for isShaderInt8."); return; } VkBool32 shaderInt8 = (VkBool32)env->CallBooleanMethod(jVkPhysicalDeviceVulkan12FeaturesObject, methodId); if (env->ExceptionOccurred()) { LOGERROR(env, "%s", "Error calling CallBooleanMethod."); return; } //////////////////////////////////////////////////////////////////////// methodId = env->GetMethodID(theClass, "isDescriptorIndexing", "()Z"); if (env->ExceptionOccurred()) { LOGERROR(env, "%s", "Could not find method id for isDescriptorIndexing."); return; } VkBool32 descriptorIndexing = (VkBool32)env->CallBooleanMethod(jVkPhysicalDeviceVulkan12FeaturesObject, methodId); if (env->ExceptionOccurred()) { LOGERROR(env, "%s", "Error calling CallBooleanMethod."); return; } //////////////////////////////////////////////////////////////////////// methodId = env->GetMethodID(theClass, "isShaderInputAttachmentArrayDynamicIndexing", "()Z"); if (env->ExceptionOccurred()) { LOGERROR(env, "%s", "Could not find method id for isShaderInputAttachmentArrayDynamicIndexing."); return; } VkBool32 shaderInputAttachmentArrayDynamicIndexing = (VkBool32)env->CallBooleanMethod(jVkPhysicalDeviceVulkan12FeaturesObject, methodId); if (env->ExceptionOccurred()) { LOGERROR(env, "%s", "Error calling CallBooleanMethod."); return; } //////////////////////////////////////////////////////////////////////// methodId = env->GetMethodID(theClass, "isShaderUniformTexelBufferArrayDynamicIndexing", "()Z"); if (env->ExceptionOccurred()) { LOGERROR(env, "%s", "Could not find method id for isShaderUniformTexelBufferArrayDynamicIndexing."); return; } VkBool32 shaderUniformTexelBufferArrayDynamicIndexing = (VkBool32)env->CallBooleanMethod(jVkPhysicalDeviceVulkan12FeaturesObject, methodId); if (env->ExceptionOccurred()) { LOGERROR(env, "%s", "Error calling CallBooleanMethod."); return; } //////////////////////////////////////////////////////////////////////// methodId = env->GetMethodID(theClass, "isShaderStorageTexelBufferArrayDynamicIndexing", "()Z"); if (env->ExceptionOccurred()) { LOGERROR(env, "%s", "Could not find method id for isShaderStorageTexelBufferArrayDynamicIndexing."); return; } VkBool32 shaderStorageTexelBufferArrayDynamicIndexing = (VkBool32)env->CallBooleanMethod(jVkPhysicalDeviceVulkan12FeaturesObject, methodId); if (env->ExceptionOccurred()) { LOGERROR(env, "%s", "Error calling CallBooleanMethod."); return; } //////////////////////////////////////////////////////////////////////// methodId = env->GetMethodID(theClass, "isShaderUniformBufferArrayNonUniformIndexing", "()Z"); if (env->ExceptionOccurred()) { LOGERROR(env, "%s", "Could not find method id for isShaderUniformBufferArrayNonUniformIndexing."); return; } VkBool32 shaderUniformBufferArrayNonUniformIndexing = (VkBool32)env->CallBooleanMethod(jVkPhysicalDeviceVulkan12FeaturesObject, methodId); if (env->ExceptionOccurred()) { LOGERROR(env, "%s", "Error calling CallBooleanMethod."); return; } //////////////////////////////////////////////////////////////////////// methodId = env->GetMethodID(theClass, "isShaderSampledImageArrayNonUniformIndexing", "()Z"); if (env->ExceptionOccurred()) { LOGERROR(env, "%s", "Could not find method id for isShaderSampledImageArrayNonUniformIndexing."); return; } VkBool32 shaderSampledImageArrayNonUniformIndexing = (VkBool32)env->CallBooleanMethod(jVkPhysicalDeviceVulkan12FeaturesObject, methodId); if (env->ExceptionOccurred()) { LOGERROR(env, "%s", "Error calling CallBooleanMethod."); return; } //////////////////////////////////////////////////////////////////////// methodId = env->GetMethodID(theClass, "isShaderStorageBufferArrayNonUniformIndexing", "()Z"); if (env->ExceptionOccurred()) { LOGERROR(env, "%s", "Could not find method id for isShaderStorageBufferArrayNonUniformIndexing."); return; } VkBool32 shaderStorageBufferArrayNonUniformIndexing = (VkBool32)env->CallBooleanMethod(jVkPhysicalDeviceVulkan12FeaturesObject, methodId); if (env->ExceptionOccurred()) { LOGERROR(env, "%s", "Error calling CallBooleanMethod."); return; } //////////////////////////////////////////////////////////////////////// methodId = env->GetMethodID(theClass, "isShaderStorageImageArrayNonUniformIndexing", "()Z"); if (env->ExceptionOccurred()) { LOGERROR(env, "%s", "Could not find method id for isShaderStorageImageArrayNonUniformIndexing."); return; } VkBool32 shaderStorageImageArrayNonUniformIndexing = (VkBool32)env->CallBooleanMethod(jVkPhysicalDeviceVulkan12FeaturesObject, methodId); if (env->ExceptionOccurred()) { LOGERROR(env, "%s", "Error calling CallBooleanMethod."); return; } //////////////////////////////////////////////////////////////////////// methodId = env->GetMethodID(theClass, "isShaderInputAttachmentArrayNonUniformIndexing", "()Z"); if (env->ExceptionOccurred()) { LOGERROR(env, "%s", "Could not find method id for isShaderInputAttachmentArrayNonUniformIndexing."); return; } VkBool32 shaderInputAttachmentArrayNonUniformIndexing = (VkBool32)env->CallBooleanMethod(jVkPhysicalDeviceVulkan12FeaturesObject, methodId); if (env->ExceptionOccurred()) { LOGERROR(env, "%s", "Error calling CallBooleanMethod."); return; } //////////////////////////////////////////////////////////////////////// methodId = env->GetMethodID(theClass, "isShaderUniformTexelBufferArrayNonUniformIndexing", "()Z"); if (env->ExceptionOccurred()) { LOGERROR(env, "%s", "Could not find method id for isShaderUniformTexelBufferArrayNonUniformIndexing."); return; } VkBool32 shaderUniformTexelBufferArrayNonUniformIndexing = (VkBool32)env->CallBooleanMethod(jVkPhysicalDeviceVulkan12FeaturesObject, methodId); if (env->ExceptionOccurred()) { LOGERROR(env, "%s", "Error calling CallBooleanMethod."); return; } //////////////////////////////////////////////////////////////////////// methodId = env->GetMethodID(theClass, "isShaderStorageTexelBufferArrayNonUniformIndexing", "()Z"); if (env->ExceptionOccurred()) { LOGERROR(env, "%s", "Could not find method id for isShaderStorageTexelBufferArrayNonUniformIndexing."); return; } VkBool32 shaderStorageTexelBufferArrayNonUniformIndexing = (VkBool32)env->CallBooleanMethod(jVkPhysicalDeviceVulkan12FeaturesObject, methodId); if (env->ExceptionOccurred()) { LOGERROR(env, "%s", "Error calling CallBooleanMethod."); return; } //////////////////////////////////////////////////////////////////////// methodId = env->GetMethodID(theClass, "isDescriptorBindingUniformBufferUpdateAfterBind", "()Z"); if (env->ExceptionOccurred()) { LOGERROR(env, "%s", "Could not find method id for isDescriptorBindingUniformBufferUpdateAfterBind."); return; } VkBool32 descriptorBindingUniformBufferUpdateAfterBind = (VkBool32)env->CallBooleanMethod(jVkPhysicalDeviceVulkan12FeaturesObject, methodId); if (env->ExceptionOccurred()) { LOGERROR(env, "%s", "Error calling CallBooleanMethod."); return; } //////////////////////////////////////////////////////////////////////// methodId = env->GetMethodID(theClass, "isDescriptorBindingSampledImageUpdateAfterBind", "()Z"); if (env->ExceptionOccurred()) { LOGERROR(env, "%s", "Could not find method id for isDescriptorBindingSampledImageUpdateAfterBind."); return; } VkBool32 descriptorBindingSampledImageUpdateAfterBind = (VkBool32)env->CallBooleanMethod(jVkPhysicalDeviceVulkan12FeaturesObject, methodId); if (env->ExceptionOccurred()) { LOGERROR(env, "%s", "Error calling CallBooleanMethod."); return; } //////////////////////////////////////////////////////////////////////// methodId = env->GetMethodID(theClass, "isDescriptorBindingStorageImageUpdateAfterBind", "()Z"); if (env->ExceptionOccurred()) { LOGERROR(env, "%s", "Could not find method id for isDescriptorBindingStorageImageUpdateAfterBind."); return; } VkBool32 descriptorBindingStorageImageUpdateAfterBind = (VkBool32)env->CallBooleanMethod(jVkPhysicalDeviceVulkan12FeaturesObject, methodId); if (env->ExceptionOccurred()) { LOGERROR(env, "%s", "Error calling CallBooleanMethod."); return; } //////////////////////////////////////////////////////////////////////// methodId = env->GetMethodID(theClass, "isDescriptorBindingStorageBufferUpdateAfterBind", "()Z"); if (env->ExceptionOccurred()) { LOGERROR(env, "%s", "Could not find method id for isDescriptorBindingStorageBufferUpdateAfterBind."); return; } VkBool32 descriptorBindingStorageBufferUpdateAfterBind = (VkBool32)env->CallBooleanMethod(jVkPhysicalDeviceVulkan12FeaturesObject, methodId); if (env->ExceptionOccurred()) { LOGERROR(env, "%s", "Error calling CallBooleanMethod."); return; } //////////////////////////////////////////////////////////////////////// methodId = env->GetMethodID(theClass, "isDescriptorBindingUniformTexelBufferUpdateAfterBind", "()Z"); if (env->ExceptionOccurred()) { LOGERROR(env, "%s", "Could not find method id for isDescriptorBindingUniformTexelBufferUpdateAfterBind."); return; } VkBool32 descriptorBindingUniformTexelBufferUpdateAfterBind = (VkBool32)env->CallBooleanMethod(jVkPhysicalDeviceVulkan12FeaturesObject, methodId); if (env->ExceptionOccurred()) { LOGERROR(env, "%s", "Error calling CallBooleanMethod."); return; } //////////////////////////////////////////////////////////////////////// methodId = env->GetMethodID(theClass, "isDescriptorBindingStorageTexelBufferUpdateAfterBind", "()Z"); if (env->ExceptionOccurred()) { LOGERROR(env, "%s", "Could not find method id for isDescriptorBindingStorageTexelBufferUpdateAfterBind."); return; } VkBool32 descriptorBindingStorageTexelBufferUpdateAfterBind = (VkBool32)env->CallBooleanMethod(jVkPhysicalDeviceVulkan12FeaturesObject, methodId); if (env->ExceptionOccurred()) { LOGERROR(env, "%s", "Error calling CallBooleanMethod."); return; } //////////////////////////////////////////////////////////////////////// methodId = env->GetMethodID(theClass, "isDescriptorBindingUpdateUnusedWhilePending", "()Z"); if (env->ExceptionOccurred()) { LOGERROR(env, "%s", "Could not find method id for isDescriptorBindingUpdateUnusedWhilePending."); return; } VkBool32 descriptorBindingUpdateUnusedWhilePending = (VkBool32)env->CallBooleanMethod(jVkPhysicalDeviceVulkan12FeaturesObject, methodId); if (env->ExceptionOccurred()) { LOGERROR(env, "%s", "Error calling CallBooleanMethod."); return; } //////////////////////////////////////////////////////////////////////// methodId = env->GetMethodID(theClass, "isDescriptorBindingPartiallyBound", "()Z"); if (env->ExceptionOccurred()) { LOGERROR(env, "%s", "Could not find method id for isDescriptorBindingPartiallyBound."); return; } VkBool32 descriptorBindingPartiallyBound = (VkBool32)env->CallBooleanMethod(jVkPhysicalDeviceVulkan12FeaturesObject, methodId); if (env->ExceptionOccurred()) { LOGERROR(env, "%s", "Error calling CallBooleanMethod."); return; } //////////////////////////////////////////////////////////////////////// methodId = env->GetMethodID(theClass, "isDescriptorBindingVariableDescriptorCount", "()Z"); if (env->ExceptionOccurred()) { LOGERROR(env, "%s", "Could not find method id for isDescriptorBindingVariableDescriptorCount."); return; } VkBool32 descriptorBindingVariableDescriptorCount = (VkBool32)env->CallBooleanMethod(jVkPhysicalDeviceVulkan12FeaturesObject, methodId); if (env->ExceptionOccurred()) { LOGERROR(env, "%s", "Error calling CallBooleanMethod."); return; } //////////////////////////////////////////////////////////////////////// methodId = env->GetMethodID(theClass, "isRuntimeDescriptorArray", "()Z"); if (env->ExceptionOccurred()) { LOGERROR(env, "%s", "Could not find method id for isRuntimeDescriptorArray."); return; } VkBool32 runtimeDescriptorArray = (VkBool32)env->CallBooleanMethod(jVkPhysicalDeviceVulkan12FeaturesObject, methodId); if (env->ExceptionOccurred()) { LOGERROR(env, "%s", "Error calling CallBooleanMethod."); return; } //////////////////////////////////////////////////////////////////////// methodId = env->GetMethodID(theClass, "isSamplerFilterMinmax", "()Z"); if (env->ExceptionOccurred()) { LOGERROR(env, "%s", "Could not find method id for isSamplerFilterMinmax."); return; } VkBool32 samplerFilterMinmax = (VkBool32)env->CallBooleanMethod(jVkPhysicalDeviceVulkan12FeaturesObject, methodId); if (env->ExceptionOccurred()) { LOGERROR(env, "%s", "Error calling CallBooleanMethod."); return; } //////////////////////////////////////////////////////////////////////// methodId = env->GetMethodID(theClass, "isScalarBlockLayout", "()Z"); if (env->ExceptionOccurred()) { LOGERROR(env, "%s", "Could not find method id for isScalarBlockLayout."); return; } VkBool32 scalarBlockLayout = (VkBool32)env->CallBooleanMethod(jVkPhysicalDeviceVulkan12FeaturesObject, methodId); if (env->ExceptionOccurred()) { LOGERROR(env, "%s", "Error calling CallBooleanMethod."); return; } //////////////////////////////////////////////////////////////////////// methodId = env->GetMethodID(theClass, "isImagelessFramebuffer", "()Z"); if (env->ExceptionOccurred()) { LOGERROR(env, "%s", "Could not find method id for isImagelessFramebuffer."); return; } VkBool32 imagelessFramebuffer = (VkBool32)env->CallBooleanMethod(jVkPhysicalDeviceVulkan12FeaturesObject, methodId); if (env->ExceptionOccurred()) { LOGERROR(env, "%s", "Error calling CallBooleanMethod."); return; } //////////////////////////////////////////////////////////////////////// methodId = env->GetMethodID(theClass, "isUniformBufferStandardLayout", "()Z"); if (env->ExceptionOccurred()) { LOGERROR(env, "%s", "Could not find method id for isUniformBufferStandardLayout."); return; } VkBool32 uniformBufferStandardLayout = (VkBool32)env->CallBooleanMethod(jVkPhysicalDeviceVulkan12FeaturesObject, methodId); if (env->ExceptionOccurred()) { LOGERROR(env, "%s", "Error calling CallBooleanMethod."); return; } //////////////////////////////////////////////////////////////////////// methodId = env->GetMethodID(theClass, "isShaderSubgroupExtendedTypes", "()Z"); if (env->ExceptionOccurred()) { LOGERROR(env, "%s", "Could not find method id for isShaderSubgroupExtendedTypes."); return; } VkBool32 shaderSubgroupExtendedTypes = (VkBool32)env->CallBooleanMethod(jVkPhysicalDeviceVulkan12FeaturesObject, methodId); if (env->ExceptionOccurred()) { LOGERROR(env, "%s", "Error calling CallBooleanMethod."); return; } //////////////////////////////////////////////////////////////////////// methodId = env->GetMethodID(theClass, "isSeparateDepthStencilLayouts", "()Z"); if (env->ExceptionOccurred()) { LOGERROR(env, "%s", "Could not find method id for isSeparateDepthStencilLayouts."); return; } VkBool32 separateDepthStencilLayouts = (VkBool32)env->CallBooleanMethod(jVkPhysicalDeviceVulkan12FeaturesObject, methodId); if (env->ExceptionOccurred()) { LOGERROR(env, "%s", "Error calling CallBooleanMethod."); return; } //////////////////////////////////////////////////////////////////////// methodId = env->GetMethodID(theClass, "isHostQueryReset", "()Z"); if (env->ExceptionOccurred()) { LOGERROR(env, "%s", "Could not find method id for isHostQueryReset."); return; } VkBool32 hostQueryReset = (VkBool32)env->CallBooleanMethod(jVkPhysicalDeviceVulkan12FeaturesObject, methodId); if (env->ExceptionOccurred()) { LOGERROR(env, "%s", "Error calling CallBooleanMethod."); return; } //////////////////////////////////////////////////////////////////////// methodId = env->GetMethodID(theClass, "isTimelineSemaphore", "()Z"); if (env->ExceptionOccurred()) { LOGERROR(env, "%s", "Could not find method id for isTimelineSemaphore."); return; } VkBool32 timelineSemaphore = (VkBool32)env->CallBooleanMethod(jVkPhysicalDeviceVulkan12FeaturesObject, methodId); if (env->ExceptionOccurred()) { LOGERROR(env, "%s", "Error calling CallBooleanMethod."); return; } //////////////////////////////////////////////////////////////////////// methodId = env->GetMethodID(theClass, "isBufferDeviceAddress", "()Z"); if (env->ExceptionOccurred()) { LOGERROR(env, "%s", "Could not find method id for isBufferDeviceAddress."); return; } VkBool32 bufferDeviceAddress = (VkBool32)env->CallBooleanMethod(jVkPhysicalDeviceVulkan12FeaturesObject, methodId); if (env->ExceptionOccurred()) { LOGERROR(env, "%s", "Error calling CallBooleanMethod."); return; } //////////////////////////////////////////////////////////////////////// methodId = env->GetMethodID(theClass, "isBufferDeviceAddressCaptureReplay", "()Z"); if (env->ExceptionOccurred()) { LOGERROR(env, "%s", "Could not find method id for isBufferDeviceAddressCaptureReplay."); return; } VkBool32 bufferDeviceAddressCaptureReplay = (VkBool32)env->CallBooleanMethod(jVkPhysicalDeviceVulkan12FeaturesObject, methodId); if (env->ExceptionOccurred()) { LOGERROR(env, "%s", "Error calling CallBooleanMethod."); return; } //////////////////////////////////////////////////////////////////////// methodId = env->GetMethodID(theClass, "isBufferDeviceAddressMultiDevice", "()Z"); if (env->ExceptionOccurred()) { LOGERROR(env, "%s", "Could not find method id for isBufferDeviceAddressMultiDevice."); return; } VkBool32 bufferDeviceAddressMultiDevice = (VkBool32)env->CallBooleanMethod(jVkPhysicalDeviceVulkan12FeaturesObject, methodId); if (env->ExceptionOccurred()) { LOGERROR(env, "%s", "Error calling CallBooleanMethod."); return; } //////////////////////////////////////////////////////////////////////// methodId = env->GetMethodID(theClass, "isVulkanMemoryModel", "()Z"); if (env->ExceptionOccurred()) { LOGERROR(env, "%s", "Could not find method id for isVulkanMemoryModel."); return; } VkBool32 vulkanMemoryModel = (VkBool32)env->CallBooleanMethod(jVkPhysicalDeviceVulkan12FeaturesObject, methodId); if (env->ExceptionOccurred()) { LOGERROR(env, "%s", "Error calling CallBooleanMethod."); return; } //////////////////////////////////////////////////////////////////////// methodId = env->GetMethodID(theClass, "isVulkanMemoryModelDeviceScope", "()Z"); if (env->ExceptionOccurred()) { LOGERROR(env, "%s", "Could not find method id for isVulkanMemoryModelDeviceScope."); return; } VkBool32 vulkanMemoryModelDeviceScope = (VkBool32)env->CallBooleanMethod(jVkPhysicalDeviceVulkan12FeaturesObject, methodId); if (env->ExceptionOccurred()) { LOGERROR(env, "%s", "Error calling CallBooleanMethod."); return; } //////////////////////////////////////////////////////////////////////// methodId = env->GetMethodID(theClass, "isVulkanMemoryModelAvailabilityVisibilityChains", "()Z"); if (env->ExceptionOccurred()) { LOGERROR(env, "%s", "Could not find method id for isVulkanMemoryModelAvailabilityVisibilityChains."); return; } VkBool32 vulkanMemoryModelAvailabilityVisibilityChains = (VkBool32)env->CallBooleanMethod(jVkPhysicalDeviceVulkan12FeaturesObject, methodId); if (env->ExceptionOccurred()) { LOGERROR(env, "%s", "Error calling CallBooleanMethod."); return; } //////////////////////////////////////////////////////////////////////// methodId = env->GetMethodID(theClass, "isShaderOutputViewportIndex", "()Z"); if (env->ExceptionOccurred()) { LOGERROR(env, "%s", "Could not find method id for isShaderOutputViewportIndex."); return; } VkBool32 shaderOutputViewportIndex = (VkBool32)env->CallBooleanMethod(jVkPhysicalDeviceVulkan12FeaturesObject, methodId); if (env->ExceptionOccurred()) { LOGERROR(env, "%s", "Error calling CallBooleanMethod."); return; } //////////////////////////////////////////////////////////////////////// methodId = env->GetMethodID(theClass, "isShaderOutputLayer", "()Z"); if (env->ExceptionOccurred()) { LOGERROR(env, "%s", "Could not find method id for isShaderOutputLayer."); return; } VkBool32 shaderOutputLayer = (VkBool32)env->CallBooleanMethod(jVkPhysicalDeviceVulkan12FeaturesObject, methodId); if (env->ExceptionOccurred()) { LOGERROR(env, "%s", "Error calling CallBooleanMethod."); return; } //////////////////////////////////////////////////////////////////////// methodId = env->GetMethodID(theClass, "isSubgroupBroadcastDynamicId", "()Z"); if (env->ExceptionOccurred()) { LOGERROR(env, "%s", "Could not find method id for isSubgroupBroadcastDynamicId."); return; } VkBool32 subgroupBroadcastDynamicId = (VkBool32)env->CallBooleanMethod(jVkPhysicalDeviceVulkan12FeaturesObject, methodId); if (env->ExceptionOccurred()) { LOGERROR(env, "%s", "Error calling CallBooleanMethod."); return; } vkPhysicalDeviceVulkan12Features->sType = sTypeValue; vkPhysicalDeviceVulkan12Features->pNext = (void *)pNext; vkPhysicalDeviceVulkan12Features->samplerMirrorClampToEdge = samplerMirrorClampToEdge; vkPhysicalDeviceVulkan12Features->drawIndirectCount = drawIndirectCount; vkPhysicalDeviceVulkan12Features->storageBuffer8BitAccess = storageBuffer8BitAccess; vkPhysicalDeviceVulkan12Features->uniformAndStorageBuffer8BitAccess = uniformAndStorageBuffer8BitAccess; vkPhysicalDeviceVulkan12Features->storagePushConstant8 = storagePushConstant8; vkPhysicalDeviceVulkan12Features->shaderBufferInt64Atomics = shaderBufferInt64Atomics; vkPhysicalDeviceVulkan12Features->shaderSharedInt64Atomics = shaderSharedInt64Atomics; vkPhysicalDeviceVulkan12Features->shaderFloat16 = shaderFloat16; vkPhysicalDeviceVulkan12Features->shaderInt8 = shaderInt8; vkPhysicalDeviceVulkan12Features->descriptorIndexing = descriptorIndexing; vkPhysicalDeviceVulkan12Features->shaderInputAttachmentArrayDynamicIndexing = shaderInputAttachmentArrayDynamicIndexing; vkPhysicalDeviceVulkan12Features->shaderUniformTexelBufferArrayDynamicIndexing = shaderUniformTexelBufferArrayDynamicIndexing; vkPhysicalDeviceVulkan12Features->shaderStorageTexelBufferArrayDynamicIndexing = shaderStorageTexelBufferArrayDynamicIndexing; vkPhysicalDeviceVulkan12Features->shaderUniformBufferArrayNonUniformIndexing = shaderUniformBufferArrayNonUniformIndexing; vkPhysicalDeviceVulkan12Features->shaderSampledImageArrayNonUniformIndexing = shaderSampledImageArrayNonUniformIndexing; vkPhysicalDeviceVulkan12Features->shaderStorageBufferArrayNonUniformIndexing = shaderStorageBufferArrayNonUniformIndexing; vkPhysicalDeviceVulkan12Features->shaderStorageImageArrayNonUniformIndexing = shaderStorageImageArrayNonUniformIndexing; vkPhysicalDeviceVulkan12Features->shaderInputAttachmentArrayNonUniformIndexing = shaderInputAttachmentArrayNonUniformIndexing; vkPhysicalDeviceVulkan12Features->shaderUniformTexelBufferArrayNonUniformIndexing = shaderUniformTexelBufferArrayNonUniformIndexing; vkPhysicalDeviceVulkan12Features->shaderStorageTexelBufferArrayNonUniformIndexing = shaderStorageTexelBufferArrayNonUniformIndexing; vkPhysicalDeviceVulkan12Features->descriptorBindingUniformBufferUpdateAfterBind = descriptorBindingUniformBufferUpdateAfterBind; vkPhysicalDeviceVulkan12Features->descriptorBindingSampledImageUpdateAfterBind = descriptorBindingSampledImageUpdateAfterBind; vkPhysicalDeviceVulkan12Features->descriptorBindingStorageImageUpdateAfterBind = descriptorBindingStorageImageUpdateAfterBind; vkPhysicalDeviceVulkan12Features->descriptorBindingStorageBufferUpdateAfterBind = descriptorBindingStorageBufferUpdateAfterBind; vkPhysicalDeviceVulkan12Features->descriptorBindingUniformTexelBufferUpdateAfterBind = descriptorBindingUniformTexelBufferUpdateAfterBind; vkPhysicalDeviceVulkan12Features->descriptorBindingStorageTexelBufferUpdateAfterBind = descriptorBindingStorageTexelBufferUpdateAfterBind; vkPhysicalDeviceVulkan12Features->descriptorBindingUpdateUnusedWhilePending = descriptorBindingUpdateUnusedWhilePending; vkPhysicalDeviceVulkan12Features->descriptorBindingPartiallyBound = descriptorBindingPartiallyBound; vkPhysicalDeviceVulkan12Features->descriptorBindingVariableDescriptorCount = descriptorBindingVariableDescriptorCount; vkPhysicalDeviceVulkan12Features->runtimeDescriptorArray = runtimeDescriptorArray; vkPhysicalDeviceVulkan12Features->samplerFilterMinmax = samplerFilterMinmax; vkPhysicalDeviceVulkan12Features->scalarBlockLayout = scalarBlockLayout; vkPhysicalDeviceVulkan12Features->imagelessFramebuffer = imagelessFramebuffer; vkPhysicalDeviceVulkan12Features->uniformBufferStandardLayout = uniformBufferStandardLayout; vkPhysicalDeviceVulkan12Features->shaderSubgroupExtendedTypes = shaderSubgroupExtendedTypes; vkPhysicalDeviceVulkan12Features->separateDepthStencilLayouts = separateDepthStencilLayouts; vkPhysicalDeviceVulkan12Features->hostQueryReset = hostQueryReset; vkPhysicalDeviceVulkan12Features->timelineSemaphore = timelineSemaphore; vkPhysicalDeviceVulkan12Features->bufferDeviceAddress = bufferDeviceAddress; vkPhysicalDeviceVulkan12Features->bufferDeviceAddressCaptureReplay = bufferDeviceAddressCaptureReplay; vkPhysicalDeviceVulkan12Features->bufferDeviceAddressMultiDevice = bufferDeviceAddressMultiDevice; vkPhysicalDeviceVulkan12Features->vulkanMemoryModel = vulkanMemoryModel; vkPhysicalDeviceVulkan12Features->vulkanMemoryModelDeviceScope = vulkanMemoryModelDeviceScope; vkPhysicalDeviceVulkan12Features->vulkanMemoryModelAvailabilityVisibilityChains = vulkanMemoryModelAvailabilityVisibilityChains; vkPhysicalDeviceVulkan12Features->shaderOutputViewportIndex = shaderOutputViewportIndex; vkPhysicalDeviceVulkan12Features->shaderOutputLayer = shaderOutputLayer; vkPhysicalDeviceVulkan12Features->subgroupBroadcastDynamicId = subgroupBroadcastDynamicId; } }
44.772014
154
0.592386
[ "vector" ]
60a0b67c803a2c77c8d9957a38004b68fc82ea67
8,853
cpp
C++
Modules/Pharmacokinetics/cmdapps/MRSignal2ConcentrationMiniApp.cpp
SVRTK/MITK
52252d60e42702e292d188e30f6717fe50c23962
[ "BSD-3-Clause" ]
null
null
null
Modules/Pharmacokinetics/cmdapps/MRSignal2ConcentrationMiniApp.cpp
SVRTK/MITK
52252d60e42702e292d188e30f6717fe50c23962
[ "BSD-3-Clause" ]
null
null
null
Modules/Pharmacokinetics/cmdapps/MRSignal2ConcentrationMiniApp.cpp
SVRTK/MITK
52252d60e42702e292d188e30f6717fe50c23962
[ "BSD-3-Clause" ]
null
null
null
/*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ // std includes #include <string> // itk includes #include "itksys/SystemTools.hxx" // CTK includes #include "mitkCommandLineParser.h" // MITK includes #include <mitkIOUtil.h> #include <mitkImageTimeSelector.h> #include <mitkImageCast.h> #include <mitkPreferenceListReaderOptionsFunctor.h> #include <mitkModelFitUIDHelper.h> #include <mitkConcentrationCurveGenerator.h> std::string inFilename; std::string outFileName; mitk::Image::Pointer image; bool verbose(false); bool t1_absolute(false); bool t1_relative(false); bool t1_flash(false); bool t2(false); float k(1.0); float te(0); float rec_time(0); float relaxivity(0); float rel_time(0); void setupParser(mitkCommandLineParser& parser) { // set general information about your MiniApp parser.setCategory("Dynamic Data Analysis Tools"); parser.setTitle("MR Signal to Concentration Converter"); parser.setDescription("MiniApp that allows to convert a T1 or T2 signal image into a concentration image for perfusion analysis."); parser.setContributor("DKFZ MIC"); //! [create parser] //! [add arguments] // how should arguments be prefixed parser.setArgumentPrefix("--", "-"); // add each argument, unless specified otherwise each argument is optional // see mitkCommandLineParser::addArgument for more information parser.beginGroup("Required I/O parameters"); parser.addArgument( "input", "i", mitkCommandLineParser::File, "Input file", "input 3D+t image file", us::Any(), false, false, false, mitkCommandLineParser::Input); parser.addArgument("output", "o", mitkCommandLineParser::File, "Output file", "where to save the output concentration image.", us::Any(), false, false, false, mitkCommandLineParser::Output); parser.endGroup(); parser.beginGroup("Conversion parameters"); parser.addArgument( "t1-absolute", "", mitkCommandLineParser::Bool, "T1 absolute signal enhancement", "Activate conversion for T1 absolute signal enhancement."); parser.addArgument( "t1-relative", "", mitkCommandLineParser::Bool, "T1 relative signal enhancement", "Activate conversion for T1 relative signal enhancement."); parser.addArgument( "t1-flash", "", mitkCommandLineParser::Bool, "T1 turbo flash", "Activate specific conversion for T1 turbo flash sequences."); parser.addArgument( "t2", "", mitkCommandLineParser::Bool, "T2 signal conversion", "Activate conversion for T2 signal enhancement to concentration."); parser.addArgument( "k", "k", mitkCommandLineParser::Float, "Conversion factor k", "Needed for the following conversion modes: T1-absolute, T1-relative, T2. Default value is 1.", us::Any(1)); parser.addArgument( "recovery-time", "", mitkCommandLineParser::Float, "Recovery time", "Needed for the following conversion modes: T1-flash."); parser.addArgument( "relaxivity", "", mitkCommandLineParser::Float, "Relaxivity", "Needed for the following conversion modes: T1-flash."); parser.addArgument( "relaxation-time", "", mitkCommandLineParser::Float, "Relaxation time", "Needed for the following conversion modes: T1-flash."); parser.addArgument( "te", "", mitkCommandLineParser::Float, "Echo time TE", "Needed for the following conversion modes: T2.", us::Any(1)); parser.beginGroup("Optional parameters"); parser.addArgument( "verbose", "v", mitkCommandLineParser::Bool, "Verbose Output", "Whether to produce verbose output"); parser.addArgument("help", "h", mitkCommandLineParser::Bool, "Help:", "Show this help text"); parser.endGroup(); //! [add arguments] } bool configureApplicationSettings(std::map<std::string, us::Any> parsedArgs) { if (parsedArgs.size() == 0) return false; inFilename = us::any_cast<std::string>(parsedArgs["input"]); outFileName = us::any_cast<std::string>(parsedArgs["output"]); verbose = false; if (parsedArgs.count("verbose")) { verbose = us::any_cast<bool>(parsedArgs["verbose"]); } t1_absolute = false; if (parsedArgs.count("t1-absolute")) { t1_absolute = us::any_cast<bool>(parsedArgs["t1-absolute"]); } t1_relative = false; if (parsedArgs.count("t1-relative")) { t1_relative = us::any_cast<bool>(parsedArgs["t1-relative"]); } t1_flash = false; if (parsedArgs.count("t1-flash")) { t1_flash = us::any_cast<bool>(parsedArgs["t1-flash"]); } t2 = false; if (parsedArgs.count("t2")) { t2 = us::any_cast<bool>(parsedArgs["t2"]); } k = 0.0; if (parsedArgs.count("k")) { k = us::any_cast<float>(parsedArgs["k"]); } relaxivity = 0.0; if (parsedArgs.count("relaxivity")) { relaxivity = us::any_cast<float>(parsedArgs["relaxivity"]); } rec_time = 0.0; if (parsedArgs.count("recovery-time")) { rec_time = us::any_cast<float>(parsedArgs["recovery-time"]); } rel_time = 0.0; if (parsedArgs.count("relaxation-time")) { rel_time = us::any_cast<float>(parsedArgs["relaxation-time"]); } te = 0.0; if (parsedArgs.count("te")) { te = us::any_cast<float>(parsedArgs["te"]); } //consistency checks int modeCount = 0; if (t1_absolute) ++modeCount; if (t1_flash) ++modeCount; if (t1_relative) ++modeCount; if (t2) ++modeCount; if (modeCount==0) { mitkThrow() << "Invalid program call. Please select the type of conversion."; } if (modeCount >1) { mitkThrow() << "Invalid program call. Please select only ONE type of conversion."; } if (!k && (t2 || t1_absolute || t1_relative)) { mitkThrow() << "Invalid program call. Please set 'k', if you use t1-absolute, t1-relative or t2."; } if (!te && t2) { mitkThrow() << "Invalid program call. Please set 'te', if you use t2 mode."; } if ((!rec_time||!rel_time||!relaxivity) && t1_flash) { mitkThrow() << "Invalid program call. Please set 'recovery-time', 'relaxation-time' and 'relaxivity', if you use t1-flash mode."; } return true; } void doConversion() { mitk::ConcentrationCurveGenerator::Pointer concentrationGen = mitk::ConcentrationCurveGenerator::New(); concentrationGen->SetDynamicImage(image); concentrationGen->SetisTurboFlashSequence(t1_flash); concentrationGen->SetAbsoluteSignalEnhancement(t1_absolute); concentrationGen->SetRelativeSignalEnhancement(t1_relative); concentrationGen->SetisT2weightedImage(t2); if (t1_flash) { concentrationGen->SetRecoveryTime(rec_time); concentrationGen->SetRelaxationTime(rel_time); concentrationGen->SetRelaxivity(relaxivity); } else if (t2) { concentrationGen->SetT2Factor(k); concentrationGen->SetT2EchoTime(te); } else { concentrationGen->SetFactor(k); } mitk::Image::Pointer concentrationImage = concentrationGen->GetConvertedImage(); mitk::EnsureModelFitUID(concentrationImage); mitk::IOUtil::Save(concentrationImage, outFileName); std::cout << "Store result: " << outFileName << std::endl; } int main(int argc, char* argv[]) { mitkCommandLineParser parser; setupParser(parser); const std::map<std::string, us::Any>& parsedArgs = parser.parseArguments(argc, argv); if (!configureApplicationSettings(parsedArgs)) { return EXIT_FAILURE; }; mitk::PreferenceListReaderOptionsFunctor readerFilterFunctor = mitk::PreferenceListReaderOptionsFunctor({ "MITK DICOM Reader v2 (classic config)" }, { "MITK DICOM Reader" }); // Show a help message if (parsedArgs.count("help") || parsedArgs.count("h")) { std::cout << parser.helpText(); return EXIT_SUCCESS; } //! [do processing] try { image = mitk::IOUtil::Load<mitk::Image>(inFilename, &readerFilterFunctor); std::cout << "Input: " << inFilename << std::endl; doConversion(); std::cout << "Processing finished." << std::endl; return EXIT_SUCCESS; } catch (const itk::ExceptionObject& e) { MITK_ERROR << e.what(); return EXIT_FAILURE; } catch (const std::exception& e) { MITK_ERROR << e.what(); return EXIT_FAILURE; } catch (...) { MITK_ERROR << "Unexpected error encountered."; return EXIT_FAILURE; } }
30.527586
178
0.649497
[ "3d" ]
60a0d227b86cbfa07b93a4f71181e96803044cde
14,309
cpp
C++
mapviz_plugins/src/plan_route_plugin.cpp
austindodson/mapviz
34cdd6674cccb20fc7101e1de85fa79adcdeaf19
[ "BSD-3-Clause" ]
null
null
null
mapviz_plugins/src/plan_route_plugin.cpp
austindodson/mapviz
34cdd6674cccb20fc7101e1de85fa79adcdeaf19
[ "BSD-3-Clause" ]
null
null
null
mapviz_plugins/src/plan_route_plugin.cpp
austindodson/mapviz
34cdd6674cccb20fc7101e1de85fa79adcdeaf19
[ "BSD-3-Clause" ]
null
null
null
// ***************************************************************************** // // Copyright (c) 2014, Southwest Research Institute® (SwRI®) // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of Southwest Research Institute® (SwRI®) nor the // names of its contributors may be used to endorse or promote products // derived from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY // DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND // ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // ***************************************************************************** #include <mapviz_plugins/plan_route_plugin.h> // C++ standard libraries #include <cstdio> #include <vector> // QT libraries #include <QDateTime> #include <QDialog> #include <QGLWidget> #include <QMouseEvent> #include <QPainter> #include <QPalette> #include <QStaticText> #include <opencv2/core/core.hpp> // ROS libraries #include <ros/master.h> #include <swri_route_util/util.h> #include <swri_transform_util/frames.h> #include <marti_nav_msgs/PlanRoute.h> // Declare plugin #include <pluginlib/class_list_macros.h> PLUGINLIB_EXPORT_CLASS(mapviz_plugins::PlanRoutePlugin, mapviz::MapvizPlugin) namespace mnm = marti_nav_msgs; namespace sru = swri_route_util; namespace stu = swri_transform_util; namespace mapviz_plugins { PlanRoutePlugin::PlanRoutePlugin() : config_widget_(new QWidget()), map_canvas_(NULL), failed_service_(false), selected_point_(-1), is_mouse_down_(false), max_ms_(Q_INT64_C(500)), max_distance_(2.0) { ui_.setupUi(config_widget_); ui_.color->setColor(Qt::green); // Set background white QPalette p(config_widget_->palette()); p.setColor(QPalette::Background, Qt::white); config_widget_->setPalette(p); // Set status text red QPalette p3(ui_.status->palette()); p3.setColor(QPalette::Text, Qt::red); ui_.status->setPalette(p3); QObject::connect(ui_.service, SIGNAL(editingFinished()), this, SLOT(PlanRoute())); QObject::connect(ui_.publish, SIGNAL(clicked()), this, SLOT(PublishRoute())); QObject::connect(ui_.clear, SIGNAL(clicked()), this, SLOT(Clear())); } PlanRoutePlugin::~PlanRoutePlugin() { if (map_canvas_) { map_canvas_->removeEventFilter(this); } } void PlanRoutePlugin::PublishRoute() { if (route_preview_) { if (route_topic_ != ui_.topic->text().toStdString()) { route_topic_ = ui_.topic->text().toStdString(); route_pub_.shutdown(); route_pub_ = node_.advertise<sru::Route>(route_topic_, 1, true); } route_pub_.publish(route_preview_); } } void PlanRoutePlugin::PlanRoute() { route_preview_ = sru::RoutePtr(); bool start_from_vehicle = ui_.start_from_vehicle->isChecked(); if (waypoints_.size() + start_from_vehicle < 2) { return; } std::string service = ui_.service->text().toStdString(); ros::ServiceClient client = node_.serviceClient<mnm::PlanRoute>(service); mnm::PlanRoute plan_route; plan_route.request.header.frame_id = stu::_wgs84_frame; plan_route.request.header.stamp = ros::Time::now(); plan_route.request.plan_from_vehicle = static_cast<unsigned char>(start_from_vehicle); plan_route.request.waypoints = waypoints_; if (client.call(plan_route)) { if (plan_route.response.success) { route_preview_ = boost::make_shared<sru::Route>(plan_route.response.route); failed_service_ = false; } else { PrintError(plan_route.response.message); failed_service_ = true; } } else { PrintError("Failed to plan route."); failed_service_ = true; } } void PlanRoutePlugin::Retry(const ros::TimerEvent& e) { PlanRoute(); } void PlanRoutePlugin::Clear() { waypoints_.clear(); route_preview_ = sru::RoutePtr(); } void PlanRoutePlugin::PrintError(const std::string& message) { PrintErrorHelper(ui_.status, message, 1.0); } void PlanRoutePlugin::PrintInfo(const std::string& message) { PrintInfoHelper(ui_.status, message, 1.0); } void PlanRoutePlugin::PrintWarning(const std::string& message) { PrintWarningHelper(ui_.status, message, 1.0); } QWidget* PlanRoutePlugin::GetConfigWidget(QWidget* parent) { config_widget_->setParent(parent); return config_widget_; } bool PlanRoutePlugin::Initialize(QGLWidget* canvas) { map_canvas_ = static_cast<mapviz::MapCanvas*>(canvas); map_canvas_->installEventFilter(this); retry_timer_ = node_.createTimer(ros::Duration(1), &PlanRoutePlugin::Retry, this); initialized_ = true; return true; } bool PlanRoutePlugin::eventFilter(QObject *object, QEvent* event) { switch (event->type()) { case QEvent::MouseButtonPress: return handleMousePress(static_cast<QMouseEvent*>(event)); case QEvent::MouseButtonRelease: return handleMouseRelease(static_cast<QMouseEvent*>(event)); case QEvent::MouseMove: return handleMouseMove(static_cast<QMouseEvent*>(event)); default: return false; } } bool PlanRoutePlugin::handleMousePress(QMouseEvent* event) { selected_point_ = -1; int closest_point = 0; double closest_distance = std::numeric_limits<double>::max(); #if QT_VERSION >= 0x050000 QPointF point = event->localPos(); #else QPointF point = event->posF(); #endif stu::Transform transform; if (tf_manager_.GetTransform(target_frame_, stu::_wgs84_frame, transform)) { for (size_t i = 0; i < waypoints_.size(); i++) { tf::Vector3 waypoint( waypoints_[i].position.x, waypoints_[i].position.y, 0.0); waypoint = transform * waypoint; QPointF transformed = map_canvas_->FixedFrameToMapGlCoord(QPointF(waypoint.x(), waypoint.y())); double distance = QLineF(transformed, point).length(); if (distance < closest_distance) { closest_distance = distance; closest_point = static_cast<int>(i); } } } if (event->button() == Qt::LeftButton) { if (closest_distance < 15) { selected_point_ = closest_point; return true; } else { is_mouse_down_ = true; #if QT_VERSION >= 0x050000 mouse_down_pos_ = event->localPos(); #else mouse_down_pos_ = event->posF(); #endif mouse_down_time_ = QDateTime::currentMSecsSinceEpoch(); return false; } } else if (event->button() == Qt::RightButton) { if (closest_distance < 15) { waypoints_.erase(waypoints_.begin() + closest_point); PlanRoute(); return true; } } return false; } bool PlanRoutePlugin::handleMouseRelease(QMouseEvent* event) { #if QT_VERSION >= 0x050000 QPointF point = event->localPos(); #else QPointF point = event->posF(); #endif if (selected_point_ >= 0 && static_cast<size_t>(selected_point_) < waypoints_.size()) { stu::Transform transform; if (tf_manager_.GetTransform(stu::_wgs84_frame, target_frame_, transform)) { QPointF transformed = map_canvas_->MapGlCoordToFixedFrame(point); tf::Vector3 position(transformed.x(), transformed.y(), 0.0); position = transform * position; waypoints_[selected_point_].position.x = position.x(); waypoints_[selected_point_].position.y = position.y(); PlanRoute(); } selected_point_ = -1; return true; } else if (is_mouse_down_) { qreal distance = QLineF(mouse_down_pos_, point).length(); qint64 msecsDiff = QDateTime::currentMSecsSinceEpoch() - mouse_down_time_; // Only fire the event if the mouse has moved less than the maximum distance // and was held for shorter than the maximum time.. This prevents click // events from being fired if the user is dragging the mouse across the map // or just holding the cursor in place. if (msecsDiff < max_ms_ && distance <= max_distance_) { QPointF transformed = map_canvas_->MapGlCoordToFixedFrame(point); stu::Transform transform; tf::Vector3 position(transformed.x(), transformed.y(), 0.0); if (tf_manager_.GetTransform(stu::_wgs84_frame, target_frame_, transform)) { position = transform * position; geometry_msgs::Pose pose; pose.position.x = position.x(); pose.position.y = position.y(); waypoints_.push_back(pose); PlanRoute(); } } } is_mouse_down_ = false; return false; } bool PlanRoutePlugin::handleMouseMove(QMouseEvent* event) { if (selected_point_ >= 0 && static_cast<size_t>(selected_point_) < waypoints_.size()) { #if QT_VERSION >= 0x050000 QPointF point = event->localPos(); #else QPointF point = event->posF(); #endif stu::Transform transform; if (tf_manager_.GetTransform(stu::_wgs84_frame, target_frame_, transform)) { QPointF transformed = map_canvas_->MapGlCoordToFixedFrame(point); tf::Vector3 position(transformed.x(), transformed.y(), 0.0); position = transform * position; waypoints_[selected_point_].position.y = position.y(); waypoints_[selected_point_].position.x = position.x(); PlanRoute(); } return true; } return false; } void PlanRoutePlugin::Draw(double x, double y, double scale) { stu::Transform transform; if (tf_manager_.GetTransform(target_frame_, stu::_wgs84_frame, transform)) { if (!failed_service_) { if (route_preview_) { sru::Route route = *route_preview_; sru::transform(route, transform, target_frame_); glLineWidth(2); const QColor color = ui_.color->color(); glColor4d(color.redF(), color.greenF(), color.blueF(), 1.0); glBegin(GL_LINE_STRIP); for (size_t i = 0; i < route.points.size(); i++) { glVertex2d(route.points[i].position().x(), route.points[i].position().y()); } glEnd(); } PrintInfo("OK"); } // Draw waypoints glPointSize(20); glColor4f(0.0, 1.0, 1.0, 1.0); glBegin(GL_POINTS); for (size_t i = 0; i < waypoints_.size(); i++) { tf::Vector3 point(waypoints_[i].position.x, waypoints_[i].position.y, 0); point = transform * point; glVertex2d(point.x(), point.y()); } glEnd(); } else { PrintError("Failed to transform."); } } void PlanRoutePlugin::Paint(QPainter* painter, double x, double y, double scale) { painter->save(); painter->resetTransform(); QPen pen(QBrush(QColor(Qt::darkCyan).darker()), 1); painter->setPen(pen); painter->setFont(QFont("DejaVu Sans Mono", 7)); stu::Transform transform; if (tf_manager_.GetTransform(target_frame_, stu::_wgs84_frame, transform)) { for (size_t i = 0; i < waypoints_.size(); i++) { tf::Vector3 point(waypoints_[i].position.x, waypoints_[i].position.y, 0); point = transform * point; QPointF gl_point = map_canvas_->FixedFrameToMapGlCoord(QPointF(point.x(), point.y())); QPointF corner(gl_point.x() - 20, gl_point.y() - 20); QRectF rect(corner, QSizeF(40, 40)); painter->drawText(rect, Qt::AlignHCenter | Qt::AlignVCenter, QString::fromStdString(boost::lexical_cast<std::string>(i + 1))); } } painter->restore(); } void PlanRoutePlugin::LoadConfig(const YAML::Node& node, const std::string& path) { if (node["route_topic"]) { std::string route_topic; node["route_topic"] >> route_topic; ui_.topic->setText(route_topic.c_str()); } if (node["color"]) { std::string color; node["color"] >> color; ui_.color->setColor(QColor(color.c_str())); } if (node["service"]) { std::string service; node["service"] >> service; ui_.service->setText(service.c_str()); } if (node["start_from_vehicle"]) { bool start_from_vehicle; node["start_from_vehicle"] >> start_from_vehicle; ui_.start_from_vehicle->setChecked(start_from_vehicle); } PlanRoute(); } void PlanRoutePlugin::SaveConfig(YAML::Emitter& emitter, const std::string& path) { std::string route_topic = ui_.topic->text().toStdString(); emitter << YAML::Key << "route_topic" << YAML::Value << route_topic; std::string color = ui_.color->color().name().toStdString(); emitter << YAML::Key << "color" << YAML::Value << color; std::string service = ui_.service->text().toStdString(); emitter << YAML::Key << "service" << YAML::Value << service; bool start_from_vehicle = ui_.start_from_vehicle->isChecked(); emitter << YAML::Key << "start_from_vehicle" << YAML::Value << start_from_vehicle; } }
29.935146
134
0.640157
[ "object", "vector", "transform" ]
60a0e227063e660b4982beb53ce24e0f4697f177
2,534
cpp
C++
query_optimizer/logical/MultiwayCartesianJoin.cpp
Hacker0912/quickstep-datalog
1de22e7ab787b5efa619861a167a097ff6a4f549
[ "Apache-2.0" ]
82
2016-04-18T03:59:06.000Z
2019-02-04T11:46:08.000Z
query_optimizer/logical/MultiwayCartesianJoin.cpp
Hacker0912/quickstep-datalog
1de22e7ab787b5efa619861a167a097ff6a4f549
[ "Apache-2.0" ]
265
2016-04-19T17:52:43.000Z
2018-10-11T17:55:08.000Z
query_optimizer/logical/MultiwayCartesianJoin.cpp
Hacker0912/quickstep-datalog
1de22e7ab787b5efa619861a167a097ff6a4f549
[ "Apache-2.0" ]
68
2016-04-18T05:00:34.000Z
2018-10-30T12:41:02.000Z
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. **/ #include "query_optimizer/logical/MultiwayCartesianJoin.hpp" #include <string> #include <vector> #include "query_optimizer/OptimizerTree.hpp" #include "utility/Cast.hpp" #include "glog/logging.h" namespace quickstep { namespace optimizer { namespace logical { namespace E = ::quickstep::optimizer::expressions; std::vector<E::AttributeReferencePtr> MultiwayCartesianJoin::getOutputAttributes() const { std::vector<E::AttributeReferencePtr> output_attributes; for (const LogicalPtr &operand : operands()) { const std::vector<E::AttributeReferencePtr> output_attributes_in_operand = operand->getOutputAttributes(); output_attributes.insert(output_attributes.end(), output_attributes_in_operand.begin(), output_attributes_in_operand.end()); } return output_attributes; } LogicalPtr MultiwayCartesianJoin::copyWithNewChildren( const std::vector<LogicalPtr> &new_children) const { DCHECK_EQ(new_children.size(), children().size()); return MultiwayCartesianJoin::Create(new_children); } void MultiwayCartesianJoin::getFieldStringItems( std::vector<std::string> *inline_field_names, std::vector<std::string> *inline_field_values, std::vector<std::string> *non_container_child_field_names, std::vector<OptimizerTreeBaseNodePtr> *non_container_child_fields, std::vector<std::string> *container_child_field_names, std::vector<std::vector<OptimizerTreeBaseNodePtr>> *container_child_fields) const { container_child_field_names->push_back(""); container_child_fields->push_back(CastSharedPtrVector<OptimizerTreeBase>(operands_)); } } // namespace logical } // namespace optimizer } // namespace quickstep
37.264706
90
0.75296
[ "vector" ]
60a1e5439fae9ea54f954fba183427a22f51738c
937
cpp
C++
LeetCode/Solutions/LC0210.cpp
Mohammed-Shoaib/HackerRank-Problems
ccfb9fc2f0d8dff454439d75ce519cf83bad7c3b
[ "MIT" ]
54
2019-05-13T12:13:09.000Z
2022-02-27T02:59:00.000Z
LeetCode/Solutions/LC0210.cpp
Mohammed-Shoaib/HackerRank-Problems
ccfb9fc2f0d8dff454439d75ce519cf83bad7c3b
[ "MIT" ]
2
2020-10-02T07:16:43.000Z
2020-10-19T04:36:19.000Z
LeetCode/Solutions/LC0210.cpp
Mohammed-Shoaib/HackerRank-Problems
ccfb9fc2f0d8dff454439d75ce519cf83bad7c3b
[ "MIT" ]
20
2020-05-26T09:48:13.000Z
2022-03-18T15:18:27.000Z
/* Problem Statement: https://leetcode.com/problems/course-schedule-ii/ Time: O(V + E) Space: O(V + E) Author: Mohammed Shoaib, github.com/Mohammed-Shoaib */ class Solution { public: vector<int> findOrder(int numCourses, vector<vector<int>>& prerequisites) { bool has_cycle = false; vector<int> order; vector<int> visited(numCourses); vector<vector<int>> adj(numCourses); // helper function to perform topological sort function<void(int)> dfs = [&](int s) { visited[s] = 1; for (int& u: adj[s]) { if (!visited[u]) dfs(u); else if (visited[u] == 1) has_cycle = true; } visited[s] = 2; order.push_back(s); }; // construct adjacency list for (auto& edge: prerequisites) adj[edge[1]].push_back(edge[0]); for (int i = 0; i < numCourses; i++) if (!visited[i]) dfs(i); reverse(order.begin(), order.end()); if (has_cycle) order.clear(); return order; } };
21.790698
76
0.622199
[ "vector" ]
60a5f7cc292f668fc237663e86cb8bd4763d2d27
4,146
cpp
C++
projects/PathosEngine/src/pathos/light/shadow_omni.cpp
codeonwort/pathosengine
ea568afeac9af3ebe3f2e53cc5abeecb40714466
[ "MIT" ]
11
2016-08-30T12:01:35.000Z
2021-12-29T15:34:03.000Z
projects/PathosEngine/src/pathos/light/shadow_omni.cpp
codeonwort/pathosengine
ea568afeac9af3ebe3f2e53cc5abeecb40714466
[ "MIT" ]
9
2016-05-19T03:14:22.000Z
2021-01-17T05:45:52.000Z
projects/PathosEngine/src/pathos/light/shadow_omni.cpp
codeonwort/pathosengine
ea568afeac9af3ebe3f2e53cc5abeecb40714466
[ "MIT" ]
null
null
null
#include "shadow_omni.h" #include "point_light_component.h" #include "pathos/scene/scene.h" #include "pathos/render/render_device.h" #include "pathos/render/scene_render_targets.h" #include "pathos/shader/shader_program.h" #include "pathos/mesh/geometry.h" #include "pathos/mesh/static_mesh_component.h" #include "pathos/util/math_lib.h" #include "badger/assertion/assertion.h" namespace pathos { struct UBO_OmniShadow { matrix4 model; matrix4 viewproj; vector4 lightPositionAndZFar; }; class OmniShadowVS : public ShaderStage { public: OmniShadowVS() : ShaderStage(GL_VERTEX_SHADER, "OmniShadowVS") { addDefine("VERTEX_SHADER 1"); setFilepath("omni_shadow_map.glsl"); } }; class OmniShadowFS : public ShaderStage { public: OmniShadowFS() : ShaderStage(GL_FRAGMENT_SHADER, "OmniShadowFS") { addDefine("FRAGMENT_SHADER 1"); setFilepath("omni_shadow_map.glsl"); } }; DEFINE_SHADER_PROGRAM2(Program_OmniShadow, OmniShadowVS, OmniShadowFS); } namespace pathos { const uint32 OmniShadowPass::SHADOW_MAP_SIZE = 256; void OmniShadowPass::initializeResources(RenderCommandList& cmdList) { gRenderDevice->createFramebuffers(1, &fbo); cmdList.objectLabel(GL_FRAMEBUFFER, fbo, -1, "FBO_OmniShadowMap"); ubo.init<UBO_OmniShadow>(); } void OmniShadowPass::destroyResources(RenderCommandList& cmdList) { gRenderDevice->deleteFramebuffers(1, &fbo); } void OmniShadowPass::renderShadowMaps(RenderCommandList& cmdList, const Scene* scene, const Camera* camera) { SCOPED_DRAW_EVENT(OmniShadowMaps); SceneRenderTargets& sceneContext = *cmdList.sceneRenderTargets; static const GLfloat clear_depth_one[] = { 1.0f }; uint32 numLights = 0; for (PointLightProxy* light : scene->proxyList_pointLight) { if (light->castsShadow) numLights += 1; } sceneContext.reallocOmniShadowMaps(cmdList, numLights, SHADOW_MAP_SIZE, SHADOW_MAP_SIZE); GLuint shadowMaps = sceneContext.omniShadowMaps; // cubemap array // Early exit if (numLights == 0) { return; } ShaderProgram& program = FIND_SHADER_PROGRAM(Program_OmniShadow); cmdList.useProgram(program.getGLName()); cmdList.enable(GL_DEPTH_TEST); cmdList.depthFunc(GL_LESS); cmdList.bindFramebuffer(GL_FRAMEBUFFER, fbo); cmdList.namedFramebufferDrawBuffers(fbo, 0, nullptr); cmdList.viewport(0, 0, SHADOW_MAP_SIZE, SHADOW_MAP_SIZE); vector3 faceDirections[6] = { vector3(1.0f, 0.0f, 0.0f), vector3(-1.0f, 0.0f, 0.0f), vector3(0.0f, 1.0f, 0.0f), vector3(0.0f, -1.0f, 0.0f), vector3(0.0f, 0.0f, 1.0f), vector3(0.0f, 0.0f, -1.0f) }; vector3 upDirections[6] = { vector3(0.0f, -1.0f, 0.0f), vector3(0.0f, -1.0f, 0.0f), vector3(0.0f, 0.0f, 1.0f), vector3(0.0f, 0.0f, -1.0f), vector3(0.0f, -1.0f, 0.0f), vector3(0.0f, -1.0f, 0.0f) }; for (uint32 lightIx = 0; lightIx < numLights; ++lightIx) { SCOPED_DRAW_EVENT(OmniShadowMap); PointLightProxy* light = scene->proxyList_pointLight[lightIx]; if (light->castsShadow == false) { continue; } constexpr float zNear = 0.0f; const float zFar = pathos::max(1.0f, light->attenuationRadius); const vector3 up(0.0f, 1.0f, 0.0f); matrix4 projection = glm::perspective(glm::radians(90.0f), 1.0f, zNear, zFar); for (uint32 faceIx = 0; faceIx < 6; ++faceIx) { cmdList.namedFramebufferTextureLayer(fbo, GL_DEPTH_ATTACHMENT, shadowMaps, 0, lightIx * 6 + faceIx); cmdList.clearBufferfv(GL_DEPTH, 0, clear_depth_one); matrix4 lightView = glm::lookAt(light->worldPosition, light->worldPosition + faceDirections[faceIx], upDirections[faceIx]); matrix4 viewproj = projection * lightView; UBO_OmniShadow uboData; uboData.viewproj = viewproj; uboData.lightPositionAndZFar = vector4(light->worldPosition, zFar); // #todo-shadow: Discard geometries too far from the light source for (ShadowMeshProxy* batch : scene->proxyList_shadowMesh) { uboData.model = batch->modelMatrix; ubo.update(cmdList, 1, &uboData); batch->geometry->activate_position(cmdList); batch->geometry->activateIndexBuffer(cmdList); batch->geometry->drawPrimitive(cmdList); } } } } }
30.043478
127
0.720453
[ "mesh", "geometry", "render", "model" ]
60a6001a33c58e2b26c5c8d8724735a303cc68c8
3,635
cpp
C++
src/navigation-kinetic-devel/base_local_planner/src/map_grid_visualizer.cpp
mowtian/Projektarbeit
43d575f6cf06690e869da4f995ed271fe4088f69
[ "MIT" ]
48
2016-11-10T06:00:27.000Z
2022-03-01T12:57:23.000Z
src/navigation-kinetic-devel/base_local_planner/src/map_grid_visualizer.cpp
mowtian/Projektarbeit
43d575f6cf06690e869da4f995ed271fe4088f69
[ "MIT" ]
6
2017-04-03T05:39:06.000Z
2017-07-27T02:35:44.000Z
src/navigation-kinetic-devel/base_local_planner/src/map_grid_visualizer.cpp
mowtian/Projektarbeit
43d575f6cf06690e869da4f995ed271fe4088f69
[ "MIT" ]
20
2017-02-28T13:24:31.000Z
2021-12-06T12:36:46.000Z
/********************************************************************* * Software License Agreement (BSD License) * * Copyright (c) 2010, Eric Perko * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * Neither the name of Eric Perko nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. *********************************************************************/ #include <base_local_planner/map_grid_visualizer.h> #include <base_local_planner/map_cell.h> #include <vector> #include <pcl_conversions/pcl_conversions.h> namespace base_local_planner { MapGridVisualizer::MapGridVisualizer() {} void MapGridVisualizer::initialize(const std::string& name, std::string frame_id, boost::function<bool (int cx, int cy, float &path_cost, float &goal_cost, float &occ_cost, float &total_cost)> cost_function) { name_ = name; cost_function_ = cost_function; ns_nh_ = ros::NodeHandle("~/" + name_); cost_cloud_ = new pcl::PointCloud<MapGridCostPoint>; cost_cloud_->header.frame_id = frame_id; pub_.advertise(ns_nh_, "cost_cloud", 1); } void MapGridVisualizer::publishCostCloud(const costmap_2d::Costmap2D* costmap_p_) { unsigned int x_size = costmap_p_->getSizeInCellsX(); unsigned int y_size = costmap_p_->getSizeInCellsY(); double z_coord = 0.0; double x_coord, y_coord; MapGridCostPoint pt; cost_cloud_->points.clear(); std_msgs::Header header = pcl_conversions::fromPCL(cost_cloud_->header); header.stamp = ros::Time::now(); cost_cloud_->header = pcl_conversions::toPCL(header); float path_cost, goal_cost, occ_cost, total_cost; for (unsigned int cx = 0; cx < x_size; cx++) { for (unsigned int cy = 0; cy < y_size; cy++) { costmap_p_->mapToWorld(cx, cy, x_coord, y_coord); if (cost_function_(cx, cy, path_cost, goal_cost, occ_cost, total_cost)) { pt.x = x_coord; pt.y = y_coord; pt.z = z_coord; pt.path_cost = path_cost; pt.goal_cost = goal_cost; pt.occ_cost = occ_cost; pt.total_cost = total_cost; cost_cloud_->push_back(pt); } } } pub_.publish(*cost_cloud_); ROS_DEBUG("Cost PointCloud published"); } };
42.764706
211
0.681706
[ "vector" ]
60aa1e82d27323589865b4cd6ae2b2aef8e20fea
1,697
cpp
C++
AlgorithmCpp/Leetcode题解/L004.cpp
PusenYang/OoAlgorithm
3e34517894f5c84f49a17c42bccb09004dd92ba4
[ "MIT" ]
null
null
null
AlgorithmCpp/Leetcode题解/L004.cpp
PusenYang/OoAlgorithm
3e34517894f5c84f49a17c42bccb09004dd92ba4
[ "MIT" ]
null
null
null
AlgorithmCpp/Leetcode题解/L004.cpp
PusenYang/OoAlgorithm
3e34517894f5c84f49a17c42bccb09004dd92ba4
[ "MIT" ]
null
null
null
/* 给定两个大小为 m 和 n 的有序数组 nums1 和 nums2。 请你找出这两个有序数组的中位数,并且要求算法的时间复杂度为 O(log(m + n))。 你可以假设 nums1 和 nums2 不会同时为空。 示例 1: nums1 = [1, 3] nums2 = [2] 则中位数是 2.0 */ /* 思路: 合并两个有序数组, 然后找中位数 */ #include<iostream> #include<vector> using namespace std; double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) { int m = nums1.size(), n = nums2.size(); vector<int> list; if (m == 0 && n == 0) { return 0.0; } // 双指针遍历合并 int i = 0, j = 0; for(; i < m && j < n; ) { // 找出小的, 把它的指针后移 if (nums1[i] <= nums2[j]) { list.push_back(nums1[i]); i ++; } else { list.push_back(nums2[j]); j ++; } } // 对于长的那个数组, 把没放完的元素放完 if (i < m) { for(int x = i; x < m; x++) { list.push_back(nums1[x]); } } if (j < n) { for(int x = j; x < n; x++) { list.push_back(nums2[x]); } } for (int i = 0; i < list.size(); i++) { cout << "shuzu ==="<< list[i] << endl; } double ans = 0.0; if (list.size() % 2 == 0) { //cout << list.size() << "----" << endl; ans = (list[list.size()/2] + list[list.size()/2-1])/2.0; } else { //cout << list.size()/2; ans = list[list.size()/2]; } return ans; } int main() { int count1, count2; cin >> count1 >> count2; vector<int> nums1(count1); vector<int> nums2(count2); for (int i = 0; i < count1; i ++) { cin >> nums1[i]; } for (int i = 0; i < count2; i ++) { cin >> nums2[i]; } cout << findMedianSortedArrays(nums1, nums2) << endl; return 0; }
16.97
71
0.453742
[ "vector" ]
60abfa1c51e23c752dd85fb1679818181fb24425
981
hpp
C++
libs/core/include/fcppt/mpl/list/push_front.hpp
freundlich/fcppt
17df1b1ad08bf2435f6902d5465e3bc3fe5e3022
[ "BSL-1.0" ]
13
2015-02-21T18:35:14.000Z
2019-12-29T14:08:29.000Z
libs/core/include/fcppt/mpl/list/push_front.hpp
cpreh/fcppt
17df1b1ad08bf2435f6902d5465e3bc3fe5e3022
[ "BSL-1.0" ]
5
2016-08-27T07:35:47.000Z
2019-04-21T10:55:34.000Z
libs/core/include/fcppt/mpl/list/push_front.hpp
freundlich/fcppt
17df1b1ad08bf2435f6902d5465e3bc3fe5e3022
[ "BSL-1.0" ]
8
2015-01-10T09:22:37.000Z
2019-12-01T08:31:12.000Z
// Copyright Carl Philipp Reh 2009 - 2021. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #ifndef FCPPT_MPL_LIST_PUSH_FRONT_HPP_INCLUDED #define FCPPT_MPL_LIST_PUSH_FRONT_HPP_INCLUDED #include <fcppt/mpl/list/object.hpp> #include <fcppt/mpl/list/object_concept.hpp> namespace fcppt::mpl::list { namespace detail { template<typename L, typename T> struct push_front; template<typename... E, typename T> struct push_front<fcppt::mpl::list::object<E...>, T> { using type = fcppt::mpl::list::object<T, E...>; }; } /** \brief Adds an element to the front of a list. \ingroup fcpptmpl If <code>List = list::object<L_1,...,L_n></code>, then the result is \code list::object<T,L_1,...,L_n> \endcode */ template<fcppt::mpl::list::object_concept List, typename T> using push_front = typename fcppt::mpl::list::detail::push_front<List,T>::type; } #endif
24.525
79
0.718654
[ "object" ]
60bd31940a9c05bcfdaa7a109396c5046aa178cb
15,795
cpp
C++
polymetis/polymetis/src/clients/franka_panda_client/franka_panda_client.cpp
BearerPipelineTest/fairo
a5691de7037a2a62832f986dc0e7369bcb8ad6bb
[ "MIT" ]
73
2021-09-14T19:24:45.000Z
2022-03-27T06:43:26.000Z
polymetis/polymetis/src/clients/franka_panda_client/franka_panda_client.cpp
BearerPipelineTest/fairo
a5691de7037a2a62832f986dc0e7369bcb8ad6bb
[ "MIT" ]
268
2021-09-14T22:40:23.000Z
2022-03-31T23:01:54.000Z
polymetis/polymetis/src/clients/franka_panda_client/franka_panda_client.cpp
BearerPipelineTest/fairo
a5691de7037a2a62832f986dc0e7369bcb8ad6bb
[ "MIT" ]
20
2021-09-14T19:24:47.000Z
2022-03-30T19:03:44.000Z
// Copyright (c) Facebook, Inc. and its affiliates. // This source code is licensed under the MIT license found in the // LICENSE file in the root directory of this source tree. #include "polymetis/clients/franka_panda_client.hpp" #include "real_time.hpp" #include "spdlog/spdlog.h" #include "yaml-cpp/yaml.h" #include <Eigen/Dense> #include <math.h> #include <stdexcept> #include <string> #include <time.h> #include <unistd.h> #include <fstream> #include <sstream> #include <grpc/grpc.h> using grpc::ClientContext; using grpc::Status; FrankaTorqueControlClient::FrankaTorqueControlClient( std::shared_ptr<grpc::Channel> channel, YAML::Node config) : stub_(PolymetisControllerServer::NewStub(channel)) { std::string robot_client_metadata_path = config["robot_client_metadata_path"].as<std::string>(); // Load robot client metadata std::ifstream file(robot_client_metadata_path); assert(file); std::stringstream buffer; buffer << file.rdbuf(); file.close(); RobotClientMetadata metadata; assert(metadata.ParseFromString(buffer.str())); // Initialize robot client with metadata ClientContext context; Empty empty; Status status = stub_->InitRobotClient(&context, metadata, &empty); assert(status.ok()); // Connect to robot mock_franka_ = config["mock"].as<bool>(); readonly_mode_ = config["readonly"].as<bool>(); if (!mock_franka_) { spdlog::info("Connecting to Franka Emika..."); robot_ptr_.reset(new franka::Robot(config["robot_ip"].as<std::string>())); model_ptr_.reset(new franka::Model(robot_ptr_->loadModel())); spdlog::info("Connected."); } else { spdlog::info( "Launching Franka client in mock mode. No robot is connected."); } if (readonly_mode_) { spdlog::info("Launching Franka client in read only mode. No control will " "be executed."); } // Set initial state & action for (int i = 0; i < NUM_DOFS; i++) { torque_commanded_[i] = 0.0; torque_safety_[i] = 0.0; torque_applied_prev_[i] = 0.0; torque_command_.add_joint_torques(0.0); robot_state_.add_joint_positions(0.0); robot_state_.add_joint_velocities(0.0); robot_state_.add_prev_joint_torques_computed(0.0); robot_state_.add_prev_joint_torques_computed_safened(0.0); robot_state_.add_motor_torques_measured(0.0); robot_state_.add_motor_torques_external(0.0); robot_state_.add_motor_torques_desired(0.0); } // Parse yaml limit_rate_ = config["limit_rate"].as<bool>(); lpf_cutoff_freq_ = config["lpf_cutoff_frequency"].as<double>(); cartesian_pos_ulimits_ = config["limits"]["cartesian_pos_upper"].as<std::array<double, 3>>(); cartesian_pos_llimits_ = config["limits"]["cartesian_pos_lower"].as<std::array<double, 3>>(); joint_pos_ulimits_ = config["limits"]["joint_pos_upper"].as<std::array<double, NUM_DOFS>>(); joint_pos_llimits_ = config["limits"]["joint_pos_lower"].as<std::array<double, NUM_DOFS>>(); joint_vel_limits_ = config["limits"]["joint_vel"].as<std::array<double, NUM_DOFS>>(); elbow_vel_limit_ = config["limits"]["elbow_vel"].as<double>(); joint_torques_limits_ = config["limits"]["joint_torques"].as<std::array<double, NUM_DOFS>>(); is_safety_controller_active_ = config["safety_controller"]["is_active"].as<bool>(); margin_cartesian_pos_ = config["safety_controller"]["margins"]["cartesian_pos"].as<double>(); margin_joint_pos_ = config["safety_controller"]["margins"]["joint_pos"].as<double>(); margin_joint_vel_ = config["safety_controller"]["margins"]["joint_vel"].as<double>(); k_cartesian_pos_ = config["safety_controller"]["stiffness"]["cartesian_pos"].as<double>(); k_joint_pos_ = config["safety_controller"]["stiffness"]["joint_pos"].as<double>(); k_joint_vel_ = config["safety_controller"]["stiffness"]["joint_vel"].as<double>(); // Set collision behavior if (!mock_franka_) { robot_ptr_->setCollisionBehavior( config["collision_behavior"]["lower_torque"] .as<std::array<double, NUM_DOFS>>(), config["collision_behavior"]["upper_torque"] .as<std::array<double, NUM_DOFS>>(), config["collision_behavior"]["lower_force"].as<std::array<double, 6>>(), config["collision_behavior"]["upper_force"] .as<std::array<double, 6>>()); } } void FrankaTorqueControlClient::run() { // Create callback function that relays information between gRPC server and // robot auto control_callback = [&](const franka::RobotState &libfranka_robot_state, franka::Duration) -> franka::Torques { // Compute torque components updateServerCommand(libfranka_robot_state, torque_commanded_); checkStateLimits(libfranka_robot_state, torque_safety_); // Aggregate & clamp torques for (int i = 0; i < NUM_DOFS; i++) { torque_applied_[i] = torque_commanded_[i] + torque_safety_[i]; } postprocessTorques(torque_applied_); // Record final applied torques for (int i = 0; i < NUM_DOFS; i++) { robot_state_.set_prev_joint_torques_computed_safened(i, torque_applied_[i]); } return torque_applied_; }; // Run robot if (!mock_franka_ && !readonly_mode_) { bool is_robot_operational = true; while (is_robot_operational) { // Send lambda function try { robot_ptr_->control(control_callback, limit_rate_, lpf_cutoff_freq_); } catch (const std::exception &ex) { spdlog::error("Robot is unable to be controlled: {}", ex.what()); is_robot_operational = false; } // Automatic recovery spdlog::warn("Performing automatic error recovery. This calls " "franka::Robot::automaticErrorRecovery, which is equivalent " "to pressing and releasing the external activation device."); for (int i = 0; i < RECOVERY_MAX_TRIES; i++) { spdlog::warn("Automatic error recovery attempt {}/{}...", i + 1, RECOVERY_MAX_TRIES); // Wait usleep(1000000 * RECOVERY_WAIT_SECS); // Attempt recovery try { robot_ptr_->automaticErrorRecovery(); spdlog::warn("Robot operation recovered."); is_robot_operational = true; break; } catch (const std::exception &ex) { spdlog::error("Recovery failed: {}", ex.what()); } } } } else { // Run mocked robot control loops franka::RobotState robot_state; franka::Duration duration; int period = 1.0 / FRANKA_HZ; int period_ns = period * 1.0e9; struct timespec abs_target_time; while (true) { clock_gettime(CLOCK_REALTIME, &abs_target_time); abs_target_time.tv_nsec += period_ns; // Pull data from robot if in readonly mode if (readonly_mode_) { robot_state = robot_ptr_->readOnce(); } // Perform control loop with dummy variables (robot_state is populated if // in readonly mode) control_callback(robot_state, duration); clock_nanosleep(CLOCK_REALTIME, TIMER_ABSTIME, &abs_target_time, nullptr); } } } void FrankaTorqueControlClient::updateServerCommand( /* * Send robot states and receive torque command via a request to the * controller server. */ const franka::RobotState &libfranka_robot_state, std::array<double, NUM_DOFS> &torque_out) { // Record robot states if (!mock_franka_) { bool prev_command_successful = false; for (int i = 0; i < NUM_DOFS; i++) { robot_state_.set_joint_positions(i, libfranka_robot_state.q[i]); robot_state_.set_joint_velocities(i, libfranka_robot_state.dq[i]); robot_state_.set_motor_torques_measured(i, libfranka_robot_state.tau_J[i]); robot_state_.set_motor_torques_external( i, libfranka_robot_state.tau_ext_hat_filtered[i]); // Check if previous command is successful by checking whether // constant torque policy for packet drops is applied // (If applied, desired torques will be exactly the same as last timestep) if (!prev_command_successful && float(libfranka_robot_state.tau_J_d[i]) != robot_state_.motor_torques_desired(i)) { prev_command_successful = true; } robot_state_.set_motor_torques_desired(i, libfranka_robot_state.tau_J_d[i]); } robot_state_.set_prev_command_successful(prev_command_successful); // Error code: can only set to 0 if no errors and 1 if any errors exist for // now robot_state_.set_error_code(bool(libfranka_robot_state.current_errors)); } setTimestampToNow(robot_state_.mutable_timestamp()); // Retrieve torques grpc::ClientContext context; long int pre_update_ns = getNanoseconds(); status_ = stub_->ControlUpdate(&context, robot_state_, &torque_command_); long int post_update_ns = getNanoseconds(); if (!status_.ok()) { std::string error_msg = "ControlUpdate rpc failed. "; throw std::runtime_error(error_msg + status_.error_message()); } robot_state_.set_prev_controller_latency_ms( float(post_update_ns - pre_update_ns) / 1e6); assert(torque_command_.joint_torques_size() == NUM_DOFS); for (int i = 0; i < NUM_DOFS; i++) { torque_out[i] = torque_command_.joint_torques(i); robot_state_.set_prev_joint_torques_computed( i, torque_command_.joint_torques(i)); } } void FrankaTorqueControlClient::checkStateLimits( const franka::RobotState &libfranka_robot_state, std::array<double, NUM_DOFS> &torque_out) { /* * Compute robot state limit violations and apply safety mechanisms. */ std::array<double, 3> ee_pos_buf, force_buf; std::array<double, 1> elbow_vel_buf, elbow_lim_buf, dummy; // No safety checks in mock mode if (mock_franka_) { return; } // Reset reflex torques for (int i = 0; i < NUM_DOFS; i++) { torque_out[i] = 0.0; } for (int i = 0; i < 3; i++) { force_buf[i] = 0.0; } // Cartesian position limits for (int i = 0; i < 3; i++) { ee_pos_buf[i] = libfranka_robot_state.O_T_EE[12 + i]; } computeSafetyReflex(ee_pos_buf, cartesian_pos_llimits_, cartesian_pos_ulimits_, false, force_buf, margin_cartesian_pos_, k_cartesian_pos_, "EE position"); std::array<double, 6 *NUM_DOFS> jacobian_array = model_ptr_->zeroJacobian( franka::Frame::kEndEffector, libfranka_robot_state); Eigen::Map<const Eigen::Matrix<double, 6, NUM_DOFS>> jacobian( jacobian_array.data()); Eigen::Map<const Eigen::Vector3d> force_xyz_vec(force_buf.data()); Eigen::VectorXd force_vec(6); force_vec.head(3) << force_xyz_vec; force_vec.tail(3) << Eigen::Vector3d::Zero(); Eigen::VectorXd torque_vec(NUM_DOFS); torque_vec << jacobian.transpose() * force_vec; Eigen::VectorXd::Map(&torque_out[0], NUM_DOFS) = torque_vec; // Joint position limits computeSafetyReflex(libfranka_robot_state.q, joint_pos_llimits_, joint_pos_ulimits_, false, torque_out, margin_joint_pos_, k_joint_pos_, "Joint position"); // Joint velocity limits computeSafetyReflex(libfranka_robot_state.dq, joint_vel_limits_, joint_vel_limits_, true, torque_out, margin_joint_vel_, k_joint_vel_, "Joint velocity"); // Miscellaneous velocity limits elbow_vel_buf[0] = libfranka_robot_state.delbow_c[0]; elbow_lim_buf[0] = elbow_vel_limit_; computeSafetyReflex(elbow_vel_buf, elbow_lim_buf, elbow_lim_buf, true, dummy, 0.0, 0.0, "Elbow velocity"); } void FrankaTorqueControlClient::postprocessTorques( /* * Filter & clamp torque to limits */ std::array<double, NUM_DOFS> &torque_applied) { for (int i = 0; i < 7; i++) { // Clamp torques if (torque_applied[i] > joint_torques_limits_[i]) { torque_applied[i] = joint_torques_limits_[i]; } if (torque_applied[i] < -joint_torques_limits_[i]) { torque_applied[i] = -joint_torques_limits_[i]; } } } template <std::size_t N> void FrankaTorqueControlClient::computeSafetyReflex( std::array<double, N> values, std::array<double, N> lower_limit, std::array<double, N> upper_limit, bool invert_lower, std::array<double, N> &safety_torques, double margin, double k, const char *item_name) { /* * Apply safety mechanisms for a vector based on input values and limits. * Throws an error if limits are violated. * Also computes & outputs safety controller torques. * (Note: invert_lower flips the sign of the lower limit. Used for velocities * and torques.) */ double upper_violation, lower_violation; double lower_sign = 1.0; bool safety_constraint_triggered = false; std::string item_name_str(item_name); if (invert_lower) { lower_sign = -1.0; } // Init constraint active map if (active_constraints_map_.find(item_name_str) == active_constraints_map_.end()) { active_constraints_map_.emplace(std::make_pair(item_name_str, false)); } // Check limits & compute safety controller for (int i = 0; i < N; i++) { upper_violation = values[i] - upper_limit[i]; lower_violation = lower_sign * lower_limit[i] - values[i]; // Check hard limits (use active_constraints_map_ to prevent flooding // terminal) if (upper_violation > 0 || lower_violation > 0) { safety_constraint_triggered = true; if (!active_constraints_map_[item_name_str]) { active_constraints_map_[item_name_str] = true; spdlog::warn("Safety limits exceeded: " "\n\ttype = \"{}\"" "\n\tdim = {}" "\n\tlimits = {}, {}" "\n\tvalue = {}", item_name_str, i, lower_sign * lower_limit[i], upper_limit[i], values[i]); std::string error_str = "Safety limits exceeded in FrankaTorqueControlClient. "; if (!readonly_mode_) { throw std::runtime_error(error_str + "\n"); } else { spdlog::warn(error_str + "Ignoring issue during readonly mode."); } } } // Check soft limits & compute feedback forces (safety controller) if (is_safety_controller_active_) { if (upper_violation > -margin) { safety_torques[i] -= k * (margin + upper_violation); } else if (lower_violation > -margin) { safety_torques[i] += k * (margin + lower_violation); } } } // Reset constraint active map if (!safety_constraint_triggered && active_constraints_map_[item_name_str]) { active_constraints_map_[item_name_str] = false; spdlog::info("Safety limits no longer violated: \"{}\"", item_name_str); } } void *rt_main(void *cfg_ptr) { YAML::Node &config = *(static_cast<YAML::Node *>(cfg_ptr)); // Launch adapter std::string control_address = config["control_ip"].as<std::string>() + ":" + config["control_port"].as<std::string>(); FrankaTorqueControlClient franka_panda_client( grpc::CreateChannel(control_address, grpc::InsecureChannelCredentials()), config); franka_panda_client.run(); return NULL; } int main(int argc, char *argv[]) { if (argc != 2) { spdlog::error("Usage: franka_panda_client /path/to/cfg.yaml"); return 1; } YAML::Node config = YAML::LoadFile(argv[1]); void *config_void_ptr = static_cast<void *>(&config); // Launch thread create_real_time_thread(rt_main, config_void_ptr); // Termination spdlog::info("Wait for shutdown; press CTRL+C to close."); return 0; }
34.411765
80
0.663754
[ "vector", "model" ]
60c108d23a0fc6cbe160da1605206b39c4ef14be
1,281
cpp
C++
projects/Ader2_CPP/src/GameCore/Camera.cpp
nfwGytautas/Ader2
c32789ca4e8efb0da47a81c81779727298618f3e
[ "Apache-2.0" ]
null
null
null
projects/Ader2_CPP/src/GameCore/Camera.cpp
nfwGytautas/Ader2
c32789ca4e8efb0da47a81c81779727298618f3e
[ "Apache-2.0" ]
null
null
null
projects/Ader2_CPP/src/GameCore/Camera.cpp
nfwGytautas/Ader2
c32789ca4e8efb0da47a81c81779727298618f3e
[ "Apache-2.0" ]
null
null
null
#include "Camera.h" Camera::Camera(AderScene* pScene) : m_pScene(pScene) { } void Camera::update() { // If the camera doesn't need updating do nothing if (!m_needsUpdate) { return; } // Up vector for the camera glm::vec3 up = glm::vec3(0.0f, 1.0f, 0.0f); // Type alias float pitch = m_rotation.x; float yaw = m_rotation.y; float roll = m_rotation.z; // Calculate the direction of the camera from the rotation glm::vec3 direction; direction.x = cos(glm::radians(yaw)) * cos(glm::radians(pitch)); direction.y = sin(glm::radians(pitch)); direction.z = sin(glm::radians(yaw)) * cos(glm::radians(pitch)); // Normalize direction to get camera front vector glm::vec3 front = glm::normalize(direction); // Calculate view matrix m_viewMatrix = glm::lookAt( m_position, m_position + front, up); // Remove update flag m_needsUpdate = false; } const glm::vec3& Camera::getPosition() const { return m_position; } void Camera::setPosition(const glm::vec3& value) { m_needsUpdate = true; m_position = value; } const glm::vec3& Camera::getRotation() const { return m_rotation; } void Camera::setRotation(const glm::vec3& value) { m_needsUpdate = true; m_rotation = value; } const glm::mat4& Camera::getViewMatrix() const { return m_viewMatrix; }
18.565217
65
0.69555
[ "vector" ]
60c1e76ece29d1ffe9ba3cffa3eb1137493b891b
561
hpp
C++
engine/renderer/window.hpp
MSBarbieri/engine
ce0c6e41385788d168ff6ab4ef35e6bf0c1e5cc8
[ "MIT" ]
null
null
null
engine/renderer/window.hpp
MSBarbieri/engine
ce0c6e41385788d168ff6ab4ef35e6bf0c1e5cc8
[ "MIT" ]
null
null
null
engine/renderer/window.hpp
MSBarbieri/engine
ce0c6e41385788d168ff6ab4ef35e6bf0c1e5cc8
[ "MIT" ]
null
null
null
#ifndef ENGINE_WINDOW_H #define ENGINE_WINDOW_H #define GLFW_INCLUDE_VULKAN #include <GLFW/glfw3.h> #define GLFW_EXPOSE_NATIVE_WIN32 #include <GLFW/glfw3native.h>> #include "renderer.hpp" extern "C" class Window { private: GLFWwindow* _window = nullptr; Renderer* _renderer = nullptr; PFN_vkCreateInstance _pfnCreateInstance = NULL; public: Window(); ~Window(); void init(int width, int height, const char* name, Renderer* renderer); std::vector<const char*> GetVulkanExtensions(); int loop(); void destroy(); }; #endif
20.035714
73
0.716578
[ "vector" ]
60c8c4ee1ce469f2b571de1e492433bc18391799
2,585
cpp
C++
src/modules/keystore/SessionKeyManager.cpp
burntjam/keto
dbe32916a3bbc92fa0bbcb97d9de493d7ed63fd8
[ "MIT" ]
1
2020-03-04T10:38:00.000Z
2020-03-04T10:38:00.000Z
src/modules/keystore/SessionKeyManager.cpp
burntjam/keto
dbe32916a3bbc92fa0bbcb97d9de493d7ed63fd8
[ "MIT" ]
null
null
null
src/modules/keystore/SessionKeyManager.cpp
burntjam/keto
dbe32916a3bbc92fa0bbcb97d9de493d7ed63fd8
[ "MIT" ]
1
2020-03-04T10:38:01.000Z
2020-03-04T10:38:01.000Z
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ /* * File: SessionKeyManager.cpp * Author: ubuntu * * Created on February 17, 2018, 8:46 AM */ #include <botan/hash.h> #include <botan/rsa.h> #include <botan/rng.h> #include <botan/p11_randomgenerator.h> #include <botan/auto_rng.h> #include <botan/pkcs8.h> #include <botan/hex.h> #include "keto/keystore/SessionKeyManager.hpp" #include "KeyStore.pb.h" #include "keto/server_common/VectorUtils.hpp" #include "keto/server_common/EventUtils.hpp" #include "keto/crypto/SecureVectorUtils.hpp" #include "include/keto/keystore/SessionKeyManager.hpp" namespace keto { namespace keystore { SessionKeyManager::SessionKeyManager() : rng(new Botan::AutoSeeded_RNG) { } SessionKeyManager::~SessionKeyManager() { } keto::event::Event SessionKeyManager::requestKey(const keto::event::Event& event) { keto::proto::SessionKeyRequest request = keto::server_common::fromEvent<keto::proto::SessionKeyRequest>(event); std::vector<uint8_t> sessionHash = keto::server_common::VectorUtils().copyStringToVector( request.session_hash()); std::lock_guard<std::mutex> guard(mutex); if (!this->sessionKeys.count(sessionHash)) { Botan::RSA_PrivateKey privateKey(*rng.get(), 2048); this->sessionKeys[sessionHash] = Botan::PKCS8::BER_encode( privateKey ); } keto::proto::SessionKeyResponse response; response.set_session_hash(request.session_hash()); response.set_session_key(keto::server_common::VectorUtils().copyVectorToString( keto::crypto::SecureVectorUtils().copyFromSecure(this->sessionKeys[sessionHash]))); return keto::server_common::toEvent<keto::proto::SessionKeyResponse>(response); } keto::event::Event SessionKeyManager::removeKey(const keto::event::Event& event) { keto::proto::SessionKeyExpireRequest request = keto::server_common::fromEvent<keto::proto::SessionKeyExpireRequest>(event); std::vector<uint8_t> sessionHash = keto::server_common::VectorUtils().copyStringToVector( request.session_hash()); std::lock_guard<std::mutex> guard(mutex); if (this->sessionKeys.count(sessionHash)) { this->sessionKeys.erase(sessionHash); } keto::proto::SessionKeyExpireResponse response; response.set_session_hash(request.session_hash()); response.set_success(true); return keto::server_common::toEvent<keto::proto::SessionKeyExpireResponse>(response); } } }
34.013158
127
0.731528
[ "vector" ]
60c8c9bbd95a40ead7cc964eec9c601e3dc35a7d
4,118
hpp
C++
dev/Basic/shared/buffering/Buffered.hpp
gusugusu1018/simmobility-prod
d30a5ba353673f8fd35f4868c26994a0206a40b6
[ "MIT" ]
50
2018-12-21T08:21:38.000Z
2022-01-24T09:47:59.000Z
dev/Basic/shared/buffering/Buffered.hpp
gusugusu1018/simmobility-prod
d30a5ba353673f8fd35f4868c26994a0206a40b6
[ "MIT" ]
2
2018-12-19T13:42:47.000Z
2019-05-13T04:11:45.000Z
dev/Basic/shared/buffering/Buffered.hpp
gusugusu1018/simmobility-prod
d30a5ba353673f8fd35f4868c26994a0206a40b6
[ "MIT" ]
27
2018-11-28T07:30:34.000Z
2022-02-05T02:22:26.000Z
//Copyright (c) 2013 Singapore-MIT Alliance for Research and Technology //Licensed under the terms of the MIT License, as described in the file: // license.txt (http://opensource.org/licenses/MIT) #pragma once #include "BufferedDataManager.hpp" namespace sim_mob { /** * Templatized wrapper for buffered objects. * * \author LIM Fung Chai * \author Seth N. Hetu * * A Buffered datum handle multiple readers and a single writer without * locking. The "flip" method is used to update the current value after calling "set". * * The spoken semantics of this template are sensible; for example: * Buffered<int> * ...is a "Buffered int". * * \note * Do not delete this class until we decide what to do with it. See Shared.hpp for more information. * * \todo Currently, Buffered types don't work well with classes. For example, if * we have a "Buffered<Point> pos", then calling "pos.get().xPos = 10" will * not work. You need to do something like "Point newPos(10, 20); pos.set(newPos)", which * is pretty arbitrary and counter-intuitive. One option is to make a BufferedPoint2D class * which extends BufferedBase, and give it "setXPos()" and "setYPos()" methods. * * \par * However, I think there must be a better way to do this without sacrificing the Buffered class's * nice template syntax. This will only really become an issue later, when we release the API, so * I'd rather think about a good solution for a while, instead of creating tons of customized BufferedXYZ * pseudo-wrappers. * * \par * ~Seth * * \note * Since get returns a constant ref, pos.get().xPos = 10 won't compile anyway. But we may still need a solution. */ template <typename T> class Buffered : public BufferedBase { public: /** * Create a new Buffered data type. * * \param value The initial value. You can also set an initial value using "force". */ explicit Buffered (const T& value = T()) : BufferedBase(), current_ (value), next_ (value) {} virtual ~Buffered() {} /** * Retrieve the current value. Get the current value of the data type. This can * also be thought of as being one flip "behind" the actual value. */ const T& get() const { return current_; } /** * Set the next value. Set the next value of the data type. This value will * only take effect when "flip" is called. */ void set (const T& value) { next_ = value; } /** * Skips processing for this time tick. If an agent won't be updating a particular * Buffered type during its time tick, it should call skip() on that type. * * \note * This is intended for later, when we have pointers to arrays of data to update. * But modelers should definitely respect the limitations of Buffere<> types now. */ void skip() { this->set(this->get()); } /** * Evaluates as the current value. * * Used in an expression, the object will be evaluated as its current value. Example: * \code * enum Color { GREEN, YELLOW, RED }; * Buffered<Color> color; * ... * switch (color) * { * case GREEN: ... break; * case YELLOW: ... break; * case RED: ... break; * } * \endcode * * Another example: * \code * Buffered<uint32_t> passenger_count; * ... * if (passenger_count == 10) ... * std::cout << "There are " << passenger_count << " passengers on the bus\n"; * \endcode * * Take care that this conversion is not called when \p T is big struct. */ operator T() const { return current_; } /** * Force a new value into effect. Set the current and next value without a call to flip(). * This is usually only needed when loading values from a config file. */ void force(const T& value) { next_ = current_ = value; } protected: void flip() { current_ = next_; } T current_; T next_; }; }
28.013605
114
0.621175
[ "object" ]
60c93f2e222b6c9b8b59869e4aa0da4960ddcf76
20,897
cpp
C++
Direct3D10/Tutorials/Direct3D10Workshop/Exercise02_Solved/Exercise02.cpp
walbourn/directx-sdk-legacy-samples
93e8cc554b5ecb5cd574a06071ed784b6cb73fc5
[ "MIT" ]
27
2021-03-01T23:50:39.000Z
2022-03-04T03:27:17.000Z
Direct3D10/Tutorials/Direct3D10Workshop/Exercise02/Exercise02.cpp
walbourn/directx-sdk-legacy-samples
93e8cc554b5ecb5cd574a06071ed784b6cb73fc5
[ "MIT" ]
3
2021-03-02T00:39:56.000Z
2021-12-02T19:50:03.000Z
Direct3D10/Tutorials/Direct3D10Workshop/Exercise02_Solved/Exercise02.cpp
walbourn/directx-sdk-legacy-samples
93e8cc554b5ecb5cd574a06071ed784b6cb73fc5
[ "MIT" ]
3
2021-03-29T16:23:54.000Z
2022-03-05T08:35:05.000Z
//-------------------------------------------------------------------------------------- // Exercise02.cpp // Direct3D 10 Shader Model 4.0 Workshop // Copyright (c) Microsoft Corporation. // Licensed under the MIT License (MIT). //-------------------------------------------------------------------------------------- #include "dxut.h" #include "DXUTCamera.h" #include "DXUTGui.h" #include "DXUTSettingsDlg.h" #include "SDKmisc.h" #include "SDKMesh.h" #include "resource.h" #define MAX_SPRITES 200 //----------------------------------------------------------------------------------------- // o/__ <-- Breakdancin' Bob will guide you through the exercise // | (\ //----------------------------------------------------------------------------------------- //-------------------------------------------------------------------------------------- // DXUT Specific variables //-------------------------------------------------------------------------------------- CModelViewerCamera g_Camera; // A model viewing camera CDXUTDialogResourceManager g_DialogResourceManager; // manager for shared resources of dialogs CD3DSettingsDlg g_D3DSettingsDlg; // Device settings dialog CDXUTDialog g_HUD; // manages the 3D UI CDXUTDialog g_SampleUI; // dialog for sample specific controls //-------------------------------------------------------------------------------------- // Button and Text Rendering Variables //-------------------------------------------------------------------------------------- ID3DX10Font* g_pFont10 = NULL; ID3DX10Sprite* g_pSprite10 = NULL; //-------------------------------------------------------------------------------------- // Mesh Specific Variables //-------------------------------------------------------------------------------------- CDXUTSDKMesh g_Mesh; ID3D10InputLayout* g_pVertexLayout = NULL; UINT g_SizeVB = 0; UINT g_NumIndices = 0; UINT g_VertStride = 0; ID3D10ShaderResourceView* g_pMeshTexRV = NULL; //-------------------------------------------------------------------------------------- // Effect variables //-------------------------------------------------------------------------------------- ID3D10Effect* g_pEffect10 = NULL; ID3D10EffectTechnique* g_pRenderTextured = NULL; ID3D10EffectTechnique* g_pRenderPiece = NULL; ID3D10EffectMatrixVariable* g_pmWorldViewProj = NULL; ID3D10EffectMatrixVariable* g_pmWorldView = NULL; ID3D10EffectMatrixVariable* g_pmWorld = NULL; ID3D10EffectMatrixVariable* g_pmProj = NULL; ID3D10EffectVectorVariable* g_pViewSpaceLightDir = NULL; ID3D10EffectShaderResourceVariable* g_pDiffuseTex = NULL; //-------------------------------------------------------------------------------------- // UI control IDs //-------------------------------------------------------------------------------------- #define IDC_TOGGLEFULLSCREEN 1 #define IDC_TOGGLEREF 3 #define IDC_CHANGEDEVICE 4 //-------------------------------------------------------------------------------------- // Forward declarations //-------------------------------------------------------------------------------------- bool CALLBACK ModifyDeviceSettings( DXUTDeviceSettings* pDeviceSettings, void* pUserContext ); void CALLBACK OnFrameMove( double fTime, float fElapsedTime, void* pUserContext ); LRESULT CALLBACK MsgProc( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam, bool* pbNoFurtherProcessing, void* pUserContext ); void CALLBACK KeyboardProc( UINT nChar, bool bKeyDown, bool bAltDown, void* pUserContext ); void CALLBACK OnGUIEvent( UINT nEvent, int nControlID, CDXUTControl* pControl, void* pUserContext ); bool CALLBACK IsD3D10DeviceAcceptable( UINT Adapter, UINT Output, D3D10_DRIVER_TYPE DeviceType, DXGI_FORMAT BackBufferFormat, bool bWindowed, void* pUserContext ); HRESULT CALLBACK OnD3D10CreateDevice( ID3D10Device* pd3dDevice, const DXGI_SURFACE_DESC* pBackBufferSurfaceDesc, void* pUserContext ); HRESULT CALLBACK OnD3D10SwapChainResized( ID3D10Device* pd3dDevice, IDXGISwapChain* pSwapChain, const DXGI_SURFACE_DESC* pBackBufferSurfaceDesc, void* pUserContext ); void CALLBACK OnD3D10FrameRender( ID3D10Device* pd3dDevice, double fTime, float fElapsedTime, void* pUserContext ); void CALLBACK OnD3D10ReleasingSwapChain( void* pUserContext ); void CALLBACK OnD3D10DestroyDevice( void* pUserContext ); void InitApp(); HRESULT LoadMesh( ID3D10Device* pd3dDevice ); //-------------------------------------------------------------------------------------- // Entry point to the program. Initializes everything and goes into a message processing // loop. Idle time is used to render the scene. //-------------------------------------------------------------------------------------- INT WINAPI WinMain( HINSTANCE, HINSTANCE, LPSTR, int ) { // Enable run-time memory check for debug builds. #if defined(DEBUG) | defined(_DEBUG) _CrtSetDbgFlag( _CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF ); #endif // DXUT will create and use the best device (either D3D9 or D3D10) // that is available on the system depending on which D3D callbacks are set below // Set DXUT callbacks DXUTSetCallbackDeviceChanging( ModifyDeviceSettings ); DXUTSetCallbackMsgProc( MsgProc ); DXUTSetCallbackKeyboard( KeyboardProc ); DXUTSetCallbackFrameMove( OnFrameMove ); DXUTSetCallbackD3D10DeviceAcceptable( IsD3D10DeviceAcceptable ); DXUTSetCallbackD3D10DeviceCreated( OnD3D10CreateDevice ); DXUTSetCallbackD3D10SwapChainResized( OnD3D10SwapChainResized ); DXUTSetCallbackD3D10SwapChainReleasing( OnD3D10ReleasingSwapChain ); DXUTSetCallbackD3D10DeviceDestroyed( OnD3D10DestroyDevice ); DXUTSetCallbackD3D10FrameRender( OnD3D10FrameRender ); InitApp(); DXUTInit( true, true, NULL ); // Parse the command line, show msgboxes on error, no extra command line params DXUTSetCursorSettings( true, true ); // Show the cursor and clip it when in full screen DXUTCreateWindow( L"D3D10 Shader Model 4.0 Workshop: Exercise02" ); DXUTCreateDevice( true, 800, 600 ); DXUTMainLoop(); // Enter into the DXUT render loop return DXUTGetExitCode(); } //-------------------------------------------------------------------------------------- // Initialize the app //-------------------------------------------------------------------------------------- void InitApp() { g_D3DSettingsDlg.Init( &g_DialogResourceManager ); g_HUD.Init( &g_DialogResourceManager ); g_SampleUI.Init( &g_DialogResourceManager ); g_HUD.SetCallback( OnGUIEvent ); int iY = 10; g_HUD.AddButton( IDC_TOGGLEFULLSCREEN, L"Toggle full screen", 35, iY, 125, 22 ); g_HUD.AddButton( IDC_TOGGLEREF, L"Toggle REF (F3)", 35, iY += 24, 125, 22, VK_F3 ); g_HUD.AddButton( IDC_CHANGEDEVICE, L"Change device (F2)", 35, iY += 24, 125, 22, VK_F2 ); g_SampleUI.SetCallback( OnGUIEvent ); iY = 10; } //-------------------------------------------------------------------------------------- // Called right before creating a D3D9 or D3D10 device, allowing the app to modify the device settings as needed //-------------------------------------------------------------------------------------- bool CALLBACK ModifyDeviceSettings( DXUTDeviceSettings* pDeviceSettings, void* pUserContext ) { return true; } //-------------------------------------------------------------------------------------- // Handle updates to the scene. This is called regardless of which D3D API is used //-------------------------------------------------------------------------------------- void CALLBACK OnFrameMove( double fTime, float fElapsedTime, void* pUserContext ) { // Update the camera's position based on user input g_Camera.FrameMove( fElapsedTime ); } //-------------------------------------------------------------------------------------- // Handle messages to the application //-------------------------------------------------------------------------------------- LRESULT CALLBACK MsgProc( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam, bool* pbNoFurtherProcessing, void* pUserContext ) { // Pass messages to dialog resource manager calls so GUI state is updated correctly *pbNoFurtherProcessing = g_DialogResourceManager.MsgProc( hWnd, uMsg, wParam, lParam ); if( *pbNoFurtherProcessing ) return 0; // Pass messages to settings dialog if its active if( g_D3DSettingsDlg.IsActive() ) { g_D3DSettingsDlg.MsgProc( hWnd, uMsg, wParam, lParam ); return 0; } // Give the dialogs a chance to handle the message first *pbNoFurtherProcessing = g_HUD.MsgProc( hWnd, uMsg, wParam, lParam ); if( *pbNoFurtherProcessing ) return 0; *pbNoFurtherProcessing = g_SampleUI.MsgProc( hWnd, uMsg, wParam, lParam ); if( *pbNoFurtherProcessing ) return 0; // Pass all remaining windows messages to camera so it can respond to user input g_Camera.HandleMessages( hWnd, uMsg, wParam, lParam ); return 0; } //-------------------------------------------------------------------------------------- // Handle key presses //-------------------------------------------------------------------------------------- void CALLBACK KeyboardProc( UINT nChar, bool bKeyDown, bool bAltDown, void* pUserContext ) { } //-------------------------------------------------------------------------------------- // Handles the GUI events //-------------------------------------------------------------------------------------- void CALLBACK OnGUIEvent( UINT nEvent, int nControlID, CDXUTControl* pControl, void* pUserContext ) { switch( nControlID ) { case IDC_TOGGLEFULLSCREEN: DXUTToggleFullScreen(); break; case IDC_TOGGLEREF: DXUTToggleREF(); break; case IDC_CHANGEDEVICE: g_D3DSettingsDlg.SetActive( !g_D3DSettingsDlg.IsActive() ); break; } } //-------------------------------------------------------------------------------------- // Reject any D3D10 devices that aren't acceptable by returning false //-------------------------------------------------------------------------------------- bool CALLBACK IsD3D10DeviceAcceptable( UINT Adapter, UINT Output, D3D10_DRIVER_TYPE DeviceType, DXGI_FORMAT BackBufferFormat, bool bWindowed, void* pUserContext ) { return true; } //-------------------------------------------------------------------------------------- // Create any D3D10 resources that aren't dependant on the back buffer //-------------------------------------------------------------------------------------- HRESULT CALLBACK OnD3D10CreateDevice( ID3D10Device* pd3dDevice, const DXGI_SURFACE_DESC* pBackBufferSurfaceDesc, void* pUserContext ) { HRESULT hr; V_RETURN( g_DialogResourceManager.OnD3D10CreateDevice( pd3dDevice ) ); V_RETURN( g_D3DSettingsDlg.OnD3D10CreateDevice( pd3dDevice ) ); V_RETURN( D3DX10CreateFont( pd3dDevice, 15, 0, FW_BOLD, 1, FALSE, DEFAULT_CHARSET, OUT_DEFAULT_PRECIS, DEFAULT_QUALITY, DEFAULT_PITCH | FF_DONTCARE, L"Arial", &g_pFont10 ) ); V_RETURN( D3DX10CreateSprite( pd3dDevice, MAX_SPRITES, &g_pSprite10 ) ); V_RETURN( CDXUTDirectionWidget::StaticOnD3D10CreateDevice( pd3dDevice ) ); // Read the D3DX effect file WCHAR str[MAX_PATH]; DWORD dwShaderFlags = D3D10_SHADER_ENABLE_BACKWARDS_COMPATIBILITY; #if defined( DEBUG ) || defined( _DEBUG ) // Set the D3D10_SHADER_DEBUG flag to embed debug information in the shaders. // Setting this flag improves the shader debugging experience, but still allows // the shaders to be optimized and to run exactly the way they will run in // the release configuration of this program. dwShaderFlags |= D3D10_SHADER_DEBUG; #endif V_RETURN( DXUTFindDXSDKMediaFileCch( str, MAX_PATH, L"Exercise02.fx" ) ); V_RETURN( D3DX10CreateEffectFromFile( str, NULL, NULL, "fx_4_0", dwShaderFlags, 0, pd3dDevice, NULL, NULL, &g_pEffect10, NULL, NULL ) ); // Obtain the technique handles g_pRenderTextured = g_pEffect10->GetTechniqueByName( "RenderTextured" ); g_pRenderPiece = g_pEffect10->GetTechniqueByName( "RenderPiece" ); // Obtain the parameter handles g_pmWorldViewProj = g_pEffect10->GetVariableByName( "g_mWorldViewProj" )->AsMatrix(); g_pmWorldView = g_pEffect10->GetVariableByName( "g_mWorldView" )->AsMatrix(); g_pmWorld = g_pEffect10->GetVariableByName( "g_mWorld" )->AsMatrix(); g_pmProj = g_pEffect10->GetVariableByName( "g_mProj" )->AsMatrix(); g_pViewSpaceLightDir = g_pEffect10->GetVariableByName( "g_ViewSpaceLightDir" )->AsVector(); g_pDiffuseTex = g_pEffect10->GetVariableByName( "g_txDiffuse" )->AsShaderResource(); // Define our vertex data layout const D3D10_INPUT_ELEMENT_DESC layout[] = { { "POS", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D10_INPUT_PER_VERTEX_DATA, 0 }, { "NORMAL", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 12, D3D10_INPUT_PER_VERTEX_DATA, 0 }, { "TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, 24, D3D10_INPUT_PER_VERTEX_DATA, 0 }, }; UINT numElements = sizeof( layout ) / sizeof( layout[0] ); D3D10_PASS_DESC PassDesc; g_pRenderPiece->GetPassByIndex( 0 )->GetDesc( &PassDesc ); V_RETURN( pd3dDevice->CreateInputLayout( layout, numElements, PassDesc.pIAInputSignature, PassDesc.IAInputSignatureSize, &g_pVertexLayout ) ); // Load our IB and VB with mesh data V_RETURN( LoadMesh( pd3dDevice ) ); // Setup the camera's view parameters D3DXVECTOR3 vecEye( 0.0f, 0.0f, -8.0f ); D3DXVECTOR3 vecAt( 0.0f,0.0f,0.0f ); g_Camera.SetViewParams( &vecEye, &vecAt ); return S_OK; } //-------------------------------------------------------------------------------------- // Create any D3D10 resources that depend on the back buffer //-------------------------------------------------------------------------------------- HRESULT CALLBACK OnD3D10SwapChainResized( ID3D10Device* pd3dDevice, IDXGISwapChain* pSwapChain, const DXGI_SURFACE_DESC* pBackBufferSurfaceDesc, void* pUserContext ) { HRESULT hr = S_OK; // Setup the camera's projection parameters float fAspectRatio = pBackBufferSurfaceDesc->Width / ( FLOAT )pBackBufferSurfaceDesc->Height; g_Camera.SetProjParams( D3DX_PI / 4, fAspectRatio, 0.05f, 500.0f ); g_Camera.SetWindow( pBackBufferSurfaceDesc->Width, pBackBufferSurfaceDesc->Height ); g_Camera.SetButtonMasks( MOUSE_LEFT_BUTTON, MOUSE_WHEEL, MOUSE_MIDDLE_BUTTON ); g_HUD.SetLocation( pBackBufferSurfaceDesc->Width - 170, 0 ); g_HUD.SetSize( 170, 170 ); g_SampleUI.SetLocation( pBackBufferSurfaceDesc->Width - 170, pBackBufferSurfaceDesc->Height - 300 ); g_SampleUI.SetSize( 170, 300 ); return hr; } //-------------------------------------------------------------------------------------- // Render the scene using the D3D10 device //-------------------------------------------------------------------------------------- void CALLBACK OnD3D10FrameRender( ID3D10Device* pd3dDevice, double fTime, float fElapsedTime, void* pUserContext ) { // Clear the render target float ClearColor[4] = { 0.9569f, 0.9569f, 1.0f, 0.0f }; ID3D10RenderTargetView* pRTV = DXUTGetD3D10RenderTargetView(); pd3dDevice->ClearRenderTargetView( pRTV, ClearColor ); ID3D10DepthStencilView* pDSV = DXUTGetD3D10DepthStencilView(); pd3dDevice->ClearDepthStencilView( pDSV, D3D10_CLEAR_DEPTH, 1.0, 0 ); D3DXMATRIX mWorld; D3DXMATRIX mView; D3DXMATRIX mProj; D3DXMATRIX mWorldView; D3DXMATRIX mWorldViewProj; mWorld = *g_Camera.GetWorldMatrix(); mProj = *g_Camera.GetProjMatrix(); mView = *g_Camera.GetViewMatrix(); mWorldView = mWorld * mView; mWorldViewProj = mWorldView * mProj; // Set variables g_pmWorldViewProj->SetMatrix( ( float* )&mWorldViewProj ); g_pmWorldView->SetMatrix( ( float* )&mWorldView ); g_pmWorld->SetMatrix( ( float* )&mWorld ); g_pmProj->SetMatrix( ( float* )&mProj ); g_pDiffuseTex->SetResource( g_pMeshTexRV ); D3DXVECTOR3 lightDir( -1,1,-1 ); D3DXVECTOR3 viewLightDir; D3DXVec3TransformNormal( &viewLightDir, &lightDir, &mView ); D3DXVec3Normalize( &viewLightDir, &viewLightDir ); g_pViewSpaceLightDir->SetFloatVector( ( float* )&viewLightDir ); // Get VB and IB UINT offset = 0; UINT stride = g_Mesh.GetVertexStride( 0, 0 ); ID3D10Buffer* pVB = g_Mesh.GetVB10( 0, 0 ); ID3D10Buffer* pIB = g_Mesh.GetAdjIB10( 0 ); // Set Input Assembler params pd3dDevice->IASetInputLayout( g_pVertexLayout ); pd3dDevice->IASetIndexBuffer( pIB, g_Mesh.GetIBFormat10( 0 ), 0 ); pd3dDevice->IASetVertexBuffers( 0, 1, &pVB, &stride, &offset ); pd3dDevice->IASetPrimitiveTopology( D3D10_PRIMITIVE_TOPOLOGY_TRIANGLELIST_ADJ ); // Render using the technique g_pRenderTextured SDKMESH_SUBSET* pSubset = NULL; D3D10_TECHNIQUE_DESC techDesc; g_pRenderTextured->GetDesc( &techDesc ); for( UINT p = 0; p < techDesc.Passes; p++ ) { g_pRenderTextured->GetPassByIndex( p )->Apply( 0 ); for( UINT subset = 0; subset < g_Mesh.GetNumSubsets( 0 ); subset++ ) { pSubset = g_Mesh.GetSubset( 0, subset ); pd3dDevice->DrawIndexed( ( UINT )pSubset->IndexCount * 2, ( UINT )pSubset->IndexStart, ( UINT )pSubset->VertexStart ); } } // Render the chess piece just for show // Render using the technique g_pRenderPiece g_pRenderPiece->GetDesc( &techDesc ); for( UINT p = 0; p < techDesc.Passes; p++ ) { g_pRenderPiece->GetPassByIndex( p )->Apply( 0 ); for( UINT subset = 0; subset < g_Mesh.GetNumSubsets( 0 ); subset++ ) { pSubset = g_Mesh.GetSubset( 0, subset ); pd3dDevice->DrawIndexed( ( UINT )pSubset->IndexCount * 2, ( UINT )pSubset->IndexStart, ( UINT )pSubset->VertexStart ); } } } //-------------------------------------------------------------------------------------- // Release D3D10 resources created in OnD3D10ResizedSwapChain //-------------------------------------------------------------------------------------- void CALLBACK OnD3D10ReleasingSwapChain( void* pUserContext ) { } //-------------------------------------------------------------------------------------- // Release D3D10 resources created in OnD3D10CreateDevice //-------------------------------------------------------------------------------------- void CALLBACK OnD3D10DestroyDevice( void* pUserContext ) { g_DialogResourceManager.OnD3D10DestroyDevice(); g_D3DSettingsDlg.OnD3D10DestroyDevice(); CDXUTDirectionWidget::StaticOnD3D10DestroyDevice(); SAFE_RELEASE( g_pFont10 ); SAFE_RELEASE( g_pSprite10 ); SAFE_RELEASE( g_pEffect10 ); SAFE_RELEASE( g_pVertexLayout ); g_Mesh.Destroy(); SAFE_RELEASE( g_pMeshTexRV ); } //-------------------------------------------------------------------------------------- // Helper to load a VB and IB from a mesh //-------------------------------------------------------------------------------------- HRESULT LoadMesh( ID3D10Device* pd3dDevice ) { HRESULT hr = S_OK; struct OLD_VERT { D3DXVECTOR3 Pos; D3DXVECTOR3 Norm; D3DXVECTOR2 Tex; }; V_RETURN( g_Mesh.Create( pd3dDevice, L"rook.sdkmesh", true ) ); // Load the Texture WCHAR strPath[MAX_PATH] = {0}; DXUTFindDXSDKMediaFileCch( strPath, sizeof( strPath ) / sizeof( WCHAR ), L"rook_diff.dds" ); hr = D3DX10CreateShaderResourceViewFromFile( pd3dDevice, strPath, NULL, NULL, &g_pMeshTexRV, NULL ); return hr; }
45.927473
116
0.546155
[ "mesh", "render", "model", "3d" ]
60ce5952eed2f99c811c927e423a10b3fbce5c03
7,944
hpp
C++
willow/include/popart/op/matmul.hpp
gglin001/popart
3225214343f6d98550b6620e809a3544e8bcbfc6
[ "MIT" ]
61
2020-07-06T17:11:46.000Z
2022-03-12T14:42:51.000Z
willow/include/popart/op/matmul.hpp
gglin001/popart
3225214343f6d98550b6620e809a3544e8bcbfc6
[ "MIT" ]
1
2021-02-25T01:30:29.000Z
2021-11-09T11:13:14.000Z
willow/include/popart/op/matmul.hpp
gglin001/popart
3225214343f6d98550b6620e809a3544e8bcbfc6
[ "MIT" ]
6
2020-07-15T12:33:13.000Z
2021-11-07T06:55:00.000Z
// Copyright (c) 2018 Graphcore Ltd. All rights reserved. #ifndef GUARD_NEURALNET_MATMUL_HPP #define GUARD_NEURALNET_MATMUL_HPP #include <string> #include <popart/op.hpp> #include <popart/vendored/optional.hpp> namespace popart { enum class MatMulPartialsType { HALF, FLOAT }; std::string toString(const MatMulPartialsType &); std::ostream &operator<<(std::ostream &, const MatMulPartialsType &); class MatMulBaseOp : public Op { public: // The phase of the matmul. Needed so when grad matmuls are // converted to normal matmuls in preperation for outlining, // they remember what they where originally so we can use the // correct poplar fullyConnectedPass option enum class Phase { Fwd, BwdLHS, BwdRHS }; struct SerialiseSettings { enum class Mode { None, InputChannels, ReducingDim, OutputChannels }; Mode mode = Mode::None; uint32_t factor = 0; bool keep_precision = false; }; MatMulBaseOp(const OperatorIdentifier &_opid, const Op::Settings &settings_, const Phase phase_, const nonstd::optional<float> availableMemoryProportion_, const SerialiseSettings &serialization_, const OptionalDataType outputType_, const MatMulPartialsType partialsType_, const bool enableFullyConnectedPass_ = true); MatMulBaseOp(const MatMulBaseOp &) = default; ~MatMulBaseOp() override = default; // Return the expanded shape of the lhs input to matmul // minium shape G x N x M virtual Shape getExpandedLhsShape() const = 0; // Return the expended shape of the rhs input to matmul // minium shape G x N x M virtual Shape getExpandedRhsShape() const = 0; bool useFullyConnectedPass() const; void setUseFullyConnectedPass(bool b) { enableFullyConnectedPass = b; } nonstd::optional<float> getAvailableMemoryProportion() const { return availableMemoryProportion; } void setAvailableMemoryProportion(const nonstd::optional<float> v) { availableMemoryProportion = v; } const SerialiseSettings &getSerialiseSettings() const { return serialization; } SerialiseSettings &getSerialiseSettings() { return serialization; } OptionalDataType getOutputType() const { return outputType; } Phase getPhase() const { return phase; } void setPhase(Phase p) { phase = p; } void appendOutlineAttributes(OpSerialiserBase &os) const override; void appendMore(OpSerialiserBase &os) const override; MatMulPartialsType getPartialsType() const { return partialsType; } void setPartialsType(const MatMulPartialsType &pt) { partialsType = pt; } bool canShard() const override { return true; } protected: Phase phase; bool enableFullyConnectedPass; nonstd::optional<float> availableMemoryProportion; SerialiseSettings serialization; // Using optional as the input info is not known when initialising OptionalDataType outputType; MatMulPartialsType partialsType; }; class MatMulOp : public MatMulBaseOp { public: MatMulOp(const OperatorIdentifier &_opid, const Op::Settings &settings_, const nonstd::optional<float> &availableMemoryProportion, const SerialiseSettings &serialization_, const OptionalDataType &outputType, const MatMulPartialsType &partialsType_ = MatMulPartialsType::FLOAT); MatMulOp(const MatMulOp &) = default; MatMulOp &operator=(const MatMulOp &) = delete; ~MatMulOp() override = default; std::vector<std::unique_ptr<Op>> getGradOps() final; void setup() final; std::unique_ptr<Op> clone() const final; static InIndex getLhsInIndex() { return 0; } static InIndex getRhsInIndex() { return 1; } static OutIndex getOutIndex() { return 0; } const Tensor *lhsIn() const; const Tensor *rhsIn() const; const Tensor *out() const; // Return the expanded shape of the inputs & output to matmul Shape getExpandedLhsShape() const override { return lhsShape; } Shape getExpandedRhsShape() const override { return rhsShape; } Shape getExpandedOutShape() const { return outShape; } // set/get the option for matmul to create it's inputs void setCanCreateInputs(bool value) { canCreateInputs = value; } bool getCanCreateInputs() const { return canCreateInputs; } float getSubgraphValue() const final { return getHighSubgraphValue(); } // Follow the numpy matmul broadcasting rules for the output shape Shape npMatMulOut(Shape lhs, Shape rhs); private: // Verifies the input shapes are valid and throws and exception if not void verifyInputShapes(const Shape &lhs, const Shape &rhs) const; // Flag to indicate if mat mul can create it's inputs. // MatMulGradXXOps converted to MatMulOps don't create their inputs bool canCreateInputs = true; // The expanded shapes of inputs & outputs. They will // be a minium of a 3D shapes Shape lhsShape; Shape rhsShape; Shape outShape; }; class MatMulBaseGradOp : public MatMulBaseOp { public: MatMulBaseGradOp(const OperatorIdentifier &_opid, const MatMulOp &fwdOp, Phase phase); MatMulBaseGradOp(const MatMulBaseGradOp &) = default; ~MatMulBaseGradOp() override = default; const MatMulOp *getCloneOfCreator() const; float getSubgraphValue() const override { return getHighSubgraphValue(); } protected: TensorInfo fwdOpOutputGrad; TensorInfo fwdOpLhsInfo; TensorInfo fwdOpRhsInfo; std::shared_ptr<Op> cloneOfCreator; }; class MatMulLhsGradOp : public MatMulBaseGradOp { public: MatMulLhsGradOp(const MatMulOp &op_); MatMulLhsGradOp(const MatMulLhsGradOp &) = default; MatMulLhsGradOp &operator=(const MatMulLhsGradOp &) = delete; ~MatMulLhsGradOp() override = default; static InIndex getGradInIndex() { return 0; } static InIndex getRhsInIndex() { return 1; } static OutIndex getOutIndex() { return 0; } void setup() final; std::unique_ptr<Op> clone() const override; const std::vector<GradInOutMapper> &gradInputInfo() const final; const std::map<int, int> &gradOutToNonGradIn() const final; // Return the expanded shape of the inputs. Note that the tranpose of the rhs // is done inside the matmul Shape getExpandedLhsShape() const override { return getCloneOfCreator()->getExpandedOutShape(); } Shape getExpandedRhsShape() const override { return getCloneOfCreator()->getExpandedRhsShape(); } // The ONNX tensor shape // The shape of the grad op's gradient input Shape getGradInputShape() const; // The shape of the grad op's rhs input Shape getRhsInputShape() const; // The shape of the grad op's output Shape getOutputShape() const; }; class MatMulRhsGradOp : public MatMulBaseGradOp { public: MatMulRhsGradOp(const MatMulOp &op_); MatMulRhsGradOp(const MatMulRhsGradOp &) = default; MatMulRhsGradOp &operator=(const MatMulRhsGradOp &) = delete; ~MatMulRhsGradOp() override = default; static InIndex getGradInIndex() { return 0; } static InIndex getLhsInIndex() { return 1; } static OutIndex getOutIndex() { return 0; } void setup() final; std::unique_ptr<Op> clone() const override; const std::vector<GradInOutMapper> &gradInputInfo() const final; const std::map<int, int> &gradOutToNonGradIn() const final; // Return the expanded shape of the inputs. Note that the tranpose of the rhs // is done inside the matmul Shape getExpandedLhsShape() const override { return getCloneOfCreator()->getExpandedLhsShape(); } Shape getExpandedRhsShape() const override { return getCloneOfCreator()->getExpandedOutShape(); } // The ONNX tensor shape // The shape of the grad op's gradient input Shape getLhsInputShape() const; // The shape of the grad op's rhs input Shape getGradInputShape() const; // The shape of the grad op's output Shape getOutputShape() const; }; } // namespace popart #endif
33.238494
80
0.720166
[ "shape", "vector", "3d" ]
60ce80661346954b41cee1401e90432eeccb8447
17,255
cc
C++
components/signin/internal/identity_manager/account_fetcher_service.cc
chromium/chromium
df46e572c3449a4b108d6e02fbe4f6d24cf98381
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
14,668
2015-01-01T01:57:10.000Z
2022-03-31T23:33:32.000Z
components/signin/internal/identity_manager/account_fetcher_service.cc
chromium/chromium
df46e572c3449a4b108d6e02fbe4f6d24cf98381
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
86
2015-10-21T13:02:42.000Z
2022-03-14T07:50:50.000Z
components/signin/internal/identity_manager/account_fetcher_service.cc
chromium/chromium
df46e572c3449a4b108d6e02fbe4f6d24cf98381
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
5,941
2015-01-02T11:32:21.000Z
2022-03-31T16:35:46.000Z
// Copyright 2015 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "components/signin/internal/identity_manager/account_fetcher_service.h" #include <string> #include <utility> #include <vector> #include "base/bind.h" #include "base/command_line.h" #include "base/metrics/field_trial.h" #include "base/metrics/histogram_functions.h" #include "base/trace_event/trace_event.h" #include "base/values.h" #include "build/build_config.h" #include "build/chromeos_buildflags.h" #include "components/image_fetcher/core/image_decoder.h" #include "components/image_fetcher/core/image_fetcher_impl.h" #include "components/prefs/pref_registry_simple.h" #include "components/prefs/pref_service.h" #include "components/signin/internal/identity_manager/account_capabilities_fetcher.h" #include "components/signin/internal/identity_manager/account_info_fetcher.h" #include "components/signin/internal/identity_manager/account_tracker_service.h" #include "components/signin/internal/identity_manager/profile_oauth2_token_service.h" #include "components/signin/public/base/avatar_icon_util.h" #include "components/signin/public/base/signin_client.h" #include "components/signin/public/base/signin_switches.h" #include "components/signin/public/identity_manager/account_capabilities.h" #include "net/http/http_status_code.h" #include "services/network/public/cpp/shared_url_loader_factory.h" #if BUILDFLAG(IS_CHROMEOS_ASH) #include "ash/constants/ash_features.h" #endif #if defined(OS_ANDROID) #include "components/signin/internal/identity_manager/child_account_info_fetcher_android.h" #include "components/signin/public/identity_manager/tribool.h" #endif namespace { const base::TimeDelta kRefreshFromTokenServiceDelay = base::Hours(24); } // namespace const char kImageFetcherUmaClient[] = "AccountFetcherService"; // This pref used to be in the AccountTrackerService, hence its string value. const char AccountFetcherService::kLastUpdatePref[] = "account_tracker_service_last_update"; // AccountFetcherService implementation AccountFetcherService::AccountFetcherService() = default; AccountFetcherService::~AccountFetcherService() { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); token_service_->RemoveObserver(this); #if defined(OS_ANDROID) // child_info_request_ is an invalidation handler and needs to be // unregistered during the lifetime of the invalidation service. child_info_request_.reset(); #endif } // static void AccountFetcherService::RegisterPrefs(PrefRegistrySimple* user_prefs) { user_prefs->RegisterTimePref(AccountFetcherService::kLastUpdatePref, base::Time()); } void AccountFetcherService::Initialize( SigninClient* signin_client, ProfileOAuth2TokenService* token_service, AccountTrackerService* account_tracker_service, std::unique_ptr<image_fetcher::ImageDecoder> image_decoder) { DCHECK(signin_client); DCHECK(!signin_client_); signin_client_ = signin_client; DCHECK(account_tracker_service); DCHECK(!account_tracker_service_); account_tracker_service_ = account_tracker_service; DCHECK(token_service); DCHECK(!token_service_); token_service_ = token_service; token_service_->AddObserver(this); DCHECK(image_decoder); DCHECK(!image_decoder_); image_decoder_ = std::move(image_decoder); repeating_timer_ = std::make_unique<signin::PersistentRepeatingTimer>( signin_client_->GetPrefs(), AccountFetcherService::kLastUpdatePref, kRefreshFromTokenServiceDelay, base::BindRepeating(&AccountFetcherService::RefreshAllAccountInfo, base::Unretained(this), /*only_fetch_if_invalid=*/false)); // Tokens may have already been loaded and we will not receive a // notification-on-registration for |token_service_->AddObserver(this)| few // lines above. if (token_service_->AreAllCredentialsLoaded()) OnRefreshTokensLoaded(); } bool AccountFetcherService::IsAllUserInfoFetched() const { return user_info_requests_.empty(); } bool AccountFetcherService::AreAllAccountCapabilitiesFetched() const { return account_capabilities_requests_.empty(); } void AccountFetcherService::OnNetworkInitialized() { DCHECK(!network_initialized_); DCHECK(!network_fetches_enabled_); #if defined(OS_ANDROID) DCHECK(!child_info_request_); #endif network_initialized_ = true; MaybeEnableNetworkFetches(); } void AccountFetcherService::EnableNetworkFetchesForTest() { if (!network_initialized_) OnNetworkInitialized(); if (!refresh_tokens_loaded_) OnRefreshTokensLoaded(); } void AccountFetcherService::EnableAccountRemovalForTest() { enable_account_removal_for_test_ = true; } void AccountFetcherService::EnableAccountCapabilitiesFetcherForTest( bool enabled) { enable_account_capabilities_fetcher_for_test_ = enabled; } void AccountFetcherService::RefreshAllAccountInfo(bool only_fetch_if_invalid) { for (const auto& account : token_service_->GetAccounts()) { RefreshAccountInfo(account, only_fetch_if_invalid); } } // Child account status is refreshed through invalidations which are only // available for the primary account. Finding the primary account requires a // dependency on PrimaryAccountManager which we get around by only allowing a // single account. This is possible since we only support a single account to be // a child anyway. #if defined(OS_ANDROID) void AccountFetcherService::RefreshAccountInfoIfStale( const CoreAccountId& account_id) { DCHECK(network_fetches_enabled_); RefreshAccountInfo(account_id, /*only_fetch_if_invalid=*/true); } void AccountFetcherService::UpdateChildInfo() { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); std::vector<CoreAccountId> accounts = token_service_->GetAccounts(); if (accounts.size() >= 1) { // If a child account is present then there can be only one child account, // and it must be the first account on the device. // // TODO(crbug/1268858): consider removing this assumption. const CoreAccountId& candidate = accounts[0]; if (candidate == child_request_account_id_) return; if (!child_request_account_id_.empty()) ResetChildInfo(); child_request_account_id_ = candidate; StartFetchingChildInfo(candidate); } else { ResetChildInfo(); } } #endif void AccountFetcherService::MaybeEnableNetworkFetches() { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); if (!network_initialized_ || !refresh_tokens_loaded_) return; if (!network_fetches_enabled_) { network_fetches_enabled_ = true; repeating_timer_->Start(); } RefreshAllAccountInfo(/*only_fetch_if_invalid=*/true); #if defined(OS_ANDROID) UpdateChildInfo(); #endif } // Starts fetching user information. This is called periodically to refresh. void AccountFetcherService::StartFetchingUserInfo( const CoreAccountId& account_id) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); DCHECK(network_fetches_enabled_); std::unique_ptr<AccountInfoFetcher>& request = user_info_requests_[account_id]; if (!request) { DVLOG(1) << "StartFetching " << account_id; std::unique_ptr<AccountInfoFetcher> fetcher = std::make_unique<AccountInfoFetcher>( token_service_, signin_client_->GetURLLoaderFactory(), this, account_id); request = std::move(fetcher); user_info_fetch_start_times_[account_id] = base::TimeTicks::Now(); request->Start(); } } #if defined(OS_ANDROID) // Starts fetching whether this is a child account. Handles refresh internally. void AccountFetcherService::StartFetchingChildInfo( const CoreAccountId& account_id) { child_info_request_ = ChildAccountInfoFetcherAndroid::Create(this, child_request_account_id_); } void AccountFetcherService::ResetChildInfo() { if (!child_request_account_id_.empty()) { AccountInfo account_info = account_tracker_service_->GetAccountInfo(child_request_account_id_); // TODO(https://crbug.com/1226501): Reset the status to kUnknown, rather // than kFalse. if (account_info.is_child_account != signin::Tribool::kUnknown) SetIsChildAccount(child_request_account_id_, false); } child_request_account_id_ = CoreAccountId(); child_info_request_.reset(); } void AccountFetcherService::SetIsChildAccount(const CoreAccountId& account_id, bool is_child_account) { if (child_request_account_id_ == account_id) account_tracker_service_->SetIsChildAccount(account_id, is_child_account); } #endif bool AccountFetcherService::IsAccountCapabilitiesFetcherEnabled() { if (enable_account_capabilities_fetcher_for_test_) return true; #if BUILDFLAG(IS_CHROMEOS_ASH) return ash::features::IsMinorModeRestrictionEnabled(); #else return false; #endif } void AccountFetcherService::StartFetchingAccountCapabilities( const CoreAccountId& account_id) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); DCHECK(network_fetches_enabled_); std::unique_ptr<AccountCapabilitiesFetcher>& request = account_capabilities_requests_[account_id]; if (!request) { request = std::make_unique<AccountCapabilitiesFetcher>( token_service_, signin_client_->GetURLLoaderFactory(), this, account_id); request->Start(); } } void AccountFetcherService::RefreshAccountInfo(const CoreAccountId& account_id, bool only_fetch_if_invalid) { DCHECK(network_fetches_enabled_); account_tracker_service_->StartTrackingAccount(account_id); const AccountInfo& info = account_tracker_service_->GetAccountInfo(account_id); if ((!only_fetch_if_invalid || !info.capabilities.AreAllCapabilitiesKnown()) && IsAccountCapabilitiesFetcherEnabled()) { StartFetchingAccountCapabilities(account_id); } // |only_fetch_if_invalid| is false when the service is due for a timed // update. if (!only_fetch_if_invalid || !info.IsValid()) { // Fetching the user info will also fetch the account image. StartFetchingUserInfo(account_id); return; } // User info is already valid and does not need to be downloaded again. // Fetch the account image in case it was not fetched previously. // // Note: |FetchAccountImage()| does not fetch the account image if the // account image was already downloaded. So it is fine to call this method // even when |only_fetch_if_invalid| is true. FetchAccountImage(account_id); } void AccountFetcherService::OnUserInfoFetchSuccess( const CoreAccountId& account_id, std::unique_ptr<base::DictionaryValue> user_info) { account_tracker_service_->SetAccountInfoFromUserInfo(account_id, user_info.get()); auto it = user_info_fetch_start_times_.find(account_id); if (it != user_info_fetch_start_times_.end()) { base::UmaHistogramMediumTimes( "Signin.AccountFetcher.AccountUserInfoFetchTime", base::TimeTicks::Now() - it->second); user_info_fetch_start_times_.erase(it); } FetchAccountImage(account_id); user_info_requests_.erase(account_id); } image_fetcher::ImageFetcherImpl* AccountFetcherService::GetOrCreateImageFetcher() { // Lazy initialization of |image_fetcher_| because the request context might // not be available yet when |Initialize| is called. if (!image_fetcher_) { image_fetcher_ = std::make_unique<image_fetcher::ImageFetcherImpl>( std::move(image_decoder_), signin_client_->GetURLLoaderFactory()); } return image_fetcher_.get(); } void AccountFetcherService::FetchAccountImage(const CoreAccountId& account_id) { DCHECK(signin_client_); AccountInfo account_info = account_tracker_service_->GetAccountInfo(account_id); std::string picture_url_string = account_info.picture_url; GURL picture_url(picture_url_string); if (!picture_url.is_valid()) { DVLOG(1) << "Invalid avatar picture URL: \"" + picture_url_string + "\""; return; } GURL image_url_with_size(signin::GetAvatarImageURLWithOptions( picture_url, signin::kAccountInfoImageSize, true /* no_silhouette */)); if (image_url_with_size.spec() == account_info.last_downloaded_image_url_with_size) { return; } net::NetworkTrafficAnnotationTag traffic_annotation = net::DefineNetworkTrafficAnnotation("accounts_image_fetcher", R"( semantics { sender: "Image fetcher for GAIA accounts" description: "To use a GAIA web account to log into Chrome in the user menu, the" "account images of the signed-in GAIA accounts are displayed." trigger: "At startup." data: "Account picture URL of signed-in GAIA accounts." destination: GOOGLE_OWNED_SERVICE } policy { cookies_allowed: YES cookies_store: "user" setting: "This feature cannot be disabled by settings, " "however, it will only be requested if the user " "has signed into the web." policy_exception_justification: "Not implemented, considered not useful as no content is being " "uploaded or saved; this request merely downloads the web account" "profile image." })"); auto callback = base::BindOnce(&AccountFetcherService::OnImageFetched, base::Unretained(this), account_id, image_url_with_size.spec()); image_fetcher::ImageFetcherParams params(traffic_annotation, kImageFetcherUmaClient); user_avatar_fetch_start_times_[account_id] = base::TimeTicks::Now(); GetOrCreateImageFetcher()->FetchImage(image_url_with_size, std::move(callback), std::move(params)); } void AccountFetcherService::OnUserInfoFetchFailure( const CoreAccountId& account_id) { LOG(WARNING) << "Failed to get UserInfo for " << account_id; user_info_fetch_start_times_.erase(account_id); // |account_id| is owned by the request. Cannot be used after this line. user_info_requests_.erase(account_id); } void AccountFetcherService::OnAccountCapabilitiesFetchSuccess( const CoreAccountId& account_id, const AccountCapabilities& account_capabilities) { account_tracker_service_->SetAccountCapabilities(account_id, account_capabilities); account_capabilities_requests_.erase(account_id); } void AccountFetcherService::OnAccountCapabilitiesFetchFailure( const CoreAccountId& account_id) { VLOG(1) << "Failed to get AccountCapabilities for " << account_id; // |account_id| is owned by the request. Cannot be used after this line. account_capabilities_requests_.erase(account_id); } void AccountFetcherService::OnRefreshTokenAvailable( const CoreAccountId& account_id) { TRACE_EVENT1("AccountFetcherService", "AccountFetcherService::OnRefreshTokenAvailable", "account_id", account_id.ToString()); DVLOG(1) << "AVAILABLE " << account_id; // The SigninClient needs a "final init" in order to perform some actions // (such as fetching the signin token "handle" in order to look for password // changes) once everything is initialized and the refresh token is present. signin_client_->DoFinalInit(); if (!network_fetches_enabled_) return; RefreshAccountInfo(account_id, /*only_fetch_if_invalid=*/true); #if defined(OS_ANDROID) UpdateChildInfo(); #endif } void AccountFetcherService::OnRefreshTokenRevoked( const CoreAccountId& account_id) { TRACE_EVENT1("AccountFetcherService", "AccountFetcherService::OnRefreshTokenRevoked", "account_id", account_id.ToString()); DVLOG(1) << "REVOKED " << account_id; // Short-circuit out if network fetches are not enabled. if (!network_fetches_enabled_) { if (enable_account_removal_for_test_) { account_tracker_service_->StopTrackingAccount(account_id); } return; } user_info_requests_.erase(account_id); account_capabilities_requests_.erase(account_id); #if defined(OS_ANDROID) UpdateChildInfo(); #endif account_tracker_service_->StopTrackingAccount(account_id); } void AccountFetcherService::OnRefreshTokensLoaded() { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); refresh_tokens_loaded_ = true; MaybeEnableNetworkFetches(); } void AccountFetcherService::OnImageFetched( const CoreAccountId& account_id, const std::string& image_url_with_size, const gfx::Image& image, const image_fetcher::RequestMetadata& metadata) { if (metadata.http_response_code != net::HTTP_OK) { DCHECK(image.IsEmpty()); return; } account_tracker_service_->SetAccountImage(account_id, image_url_with_size, image); auto it = user_avatar_fetch_start_times_.find(account_id); if (it != user_avatar_fetch_start_times_.end()) { base::UmaHistogramMediumTimes( "Signin.AccountFetcher.AccountAvatarFetchTime", base::TimeTicks::Now() - it->second); user_avatar_fetch_start_times_.erase(it); } }
36.948608
91
0.743958
[ "vector" ]
f5a1f17b3bdaa2cf9be8495a7b72b303c0e942f5
8,155
cc
C++
passes/cmds/splitnets.cc
kallisti5/yosys
0b9bb852c66ec2a6e9b4b510b3e2e32b8c6a6b16
[ "ISC" ]
3
2018-09-11T16:41:23.000Z
2020-07-11T07:18:32.000Z
passes/cmds/splitnets.cc
kallisti5/yosys
0b9bb852c66ec2a6e9b4b510b3e2e32b8c6a6b16
[ "ISC" ]
1
2018-08-28T15:05:04.000Z
2018-08-28T15:05:04.000Z
passes/cmds/splitnets.cc
kallisti5/yosys
0b9bb852c66ec2a6e9b4b510b3e2e32b8c6a6b16
[ "ISC" ]
1
2022-02-23T12:49:53.000Z
2022-02-23T12:49:53.000Z
/* * yosys -- Yosys Open SYnthesis Suite * * Copyright (C) 2012 Clifford Wolf <clifford@clifford.at> * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. * */ #include "kernel/register.h" #include "kernel/celltypes.h" #include "kernel/rtlil.h" #include "kernel/log.h" USING_YOSYS_NAMESPACE PRIVATE_NAMESPACE_BEGIN struct SplitnetsWorker { std::map<RTLIL::Wire*, std::vector<RTLIL::SigBit>> splitmap; void append_wire(RTLIL::Module *module, RTLIL::Wire *wire, int offset, int width, std::string format) { std::string new_wire_name = wire->name.str(); if (format.size() > 0) new_wire_name += format.substr(0, 1); if (width > 1) { if (wire->upto) new_wire_name += stringf("%d", wire->start_offset+wire->width-(offset+width)-1); else new_wire_name += stringf("%d", wire->start_offset+offset+width-1); if (format.size() > 2) new_wire_name += format.substr(2, 1); else new_wire_name += ":"; } if (wire->upto) new_wire_name += stringf("%d", wire->start_offset+wire->width-offset-1); else new_wire_name += stringf("%d", wire->start_offset+offset); if (format.size() > 1) new_wire_name += format.substr(1, 1); RTLIL::Wire *new_wire = module->addWire(module->uniquify(new_wire_name), width); new_wire->port_id = wire->port_id ? wire->port_id + offset : 0; new_wire->port_input = wire->port_input; new_wire->port_output = wire->port_output; if (wire->attributes.count("\\src")) new_wire->attributes["\\src"] = wire->attributes.at("\\src"); if (wire->attributes.count("\\keep")) new_wire->attributes["\\keep"] = wire->attributes.at("\\keep"); if (wire->attributes.count("\\init")) { Const old_init = wire->attributes.at("\\init"), new_init; for (int i = offset; i < offset+width; i++) new_init.bits.push_back(i < GetSize(old_init) ? old_init.bits.at(i) : State::Sx); new_wire->attributes["\\init"] = new_init; } std::vector<RTLIL::SigBit> sigvec = RTLIL::SigSpec(new_wire).to_sigbit_vector(); splitmap[wire].insert(splitmap[wire].end(), sigvec.begin(), sigvec.end()); } void operator()(RTLIL::SigSpec &sig) { for (auto &bit : sig) if (splitmap.count(bit.wire) > 0) bit = splitmap.at(bit.wire).at(bit.offset); } }; struct SplitnetsPass : public Pass { SplitnetsPass() : Pass("splitnets", "split up multi-bit nets") { } void help() YS_OVERRIDE { // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---| log("\n"); log(" splitnets [options] [selection]\n"); log("\n"); log("This command splits multi-bit nets into single-bit nets.\n"); log("\n"); log(" -format char1[char2[char3]]\n"); log(" the first char is inserted between the net name and the bit index, the\n"); log(" second char is appended to the netname. e.g. -format () creates net\n"); log(" names like 'mysignal(42)'. the 3rd character is the range separation\n"); log(" character when creating multi-bit wires. the default is '[]:'.\n"); log("\n"); log(" -ports\n"); log(" also split module ports. per default only internal signals are split.\n"); log("\n"); log(" -driver\n"); log(" don't blindly split nets in individual bits. instead look at the driver\n"); log(" and split nets so that no driver drives only part of a net.\n"); log("\n"); } void execute(std::vector<std::string> args, RTLIL::Design *design) YS_OVERRIDE { bool flag_ports = false; bool flag_driver = false; std::string format = "[]:"; log_header(design, "Executing SPLITNETS pass (splitting up multi-bit signals).\n"); size_t argidx; for (argidx = 1; argidx < args.size(); argidx++) { if (args[argidx] == "-format" && argidx+1 < args.size()) { format = args[++argidx]; continue; } if (args[argidx] == "-ports") { flag_ports = true; continue; } if (args[argidx] == "-driver") { flag_driver = true; continue; } break; } extra_args(args, argidx, design); // module_ports_db[module_name][old_port_name] = new_port_name_list dict<IdString, dict<IdString, vector<IdString>>> module_ports_db; for (auto module : design->selected_modules()) { SplitnetsWorker worker; if (flag_ports) { int normalized_port_factor = 0; for (auto wire : module->wires()) if (wire->port_id != 0) { normalized_port_factor = max(normalized_port_factor, wire->port_id+1); normalized_port_factor = max(normalized_port_factor, GetSize(wire)+1); } for (auto wire : module->wires()) wire->port_id *= normalized_port_factor; } if (flag_driver) { CellTypes ct(design); std::map<RTLIL::Wire*, std::set<int>> split_wires_at; for (auto &c : module->cells_) for (auto &p : c.second->connections()) { if (!ct.cell_known(c.second->type)) continue; if (!ct.cell_output(c.second->type, p.first)) continue; RTLIL::SigSpec sig = p.second; for (auto &chunk : sig.chunks()) { if (chunk.wire == NULL) continue; if (chunk.wire->port_id == 0 || flag_ports) { if (chunk.offset != 0) split_wires_at[chunk.wire].insert(chunk.offset); if (chunk.offset + chunk.width < chunk.wire->width) split_wires_at[chunk.wire].insert(chunk.offset + chunk.width); } } } for (auto &it : split_wires_at) { int cursor = 0; for (int next_cursor : it.second) { worker.append_wire(module, it.first, cursor, next_cursor - cursor, format); cursor = next_cursor; } worker.append_wire(module, it.first, cursor, it.first->width - cursor, format); } } else { for (auto &w : module->wires_) { RTLIL::Wire *wire = w.second; if (wire->width > 1 && (wire->port_id == 0 || flag_ports) && design->selected(module, w.second)) worker.splitmap[wire] = std::vector<RTLIL::SigBit>(); } for (auto &it : worker.splitmap) for (int i = 0; i < it.first->width; i++) worker.append_wire(module, it.first, i, 1, format); } module->rewrite_sigspecs(worker); if (flag_ports) { for (auto wire : module->wires()) { if (wire->port_id == 0) continue; SigSpec sig(wire); worker(sig); if (sig == wire) continue; vector<IdString> &new_ports = module_ports_db[module->name][wire->name]; for (SigSpec c : sig.chunks()) new_ports.push_back(c.as_wire()->name); } } pool<RTLIL::Wire*> delete_wires; for (auto &it : worker.splitmap) delete_wires.insert(it.first); module->remove(delete_wires); if (flag_ports) module->fixup_ports(); } if (!module_ports_db.empty()) { for (auto module : design->modules()) for (auto cell : module->cells()) { if (module_ports_db.count(cell->type) == 0) continue; for (auto &it : module_ports_db.at(cell->type)) { IdString port_id = it.first; const auto &new_port_ids = it.second; if (!cell->hasPort(port_id)) continue; int offset = 0; SigSpec sig = cell->getPort(port_id); for (auto nid : new_port_ids) { int nlen = GetSize(design->module(cell->type)->wire(nid)); if (offset + nlen > GetSize(sig)) nlen = GetSize(sig) - offset; if (nlen > 0) cell->setPort(nid, sig.extract(offset, nlen)); offset += nlen; } cell->unsetPort(port_id); } } } } } SplitnetsPass; PRIVATE_NAMESPACE_END
29.440433
102
0.628449
[ "vector" ]
f5a461fe2b440f1df0327354ed044d97237bacf4
34,124
cc
C++
api/app/AppAPI.cc
sinban04/opel-alpha
94e329580e8bc80cc68689c0ba1be845bc58f473
[ "Apache-2.0" ]
null
null
null
api/app/AppAPI.cc
sinban04/opel-alpha
94e329580e8bc80cc68689c0ba1be845bc58f473
[ "Apache-2.0" ]
3
2019-02-26T00:14:16.000Z
2019-02-26T00:14:55.000Z
api/app/AppAPI.cc
SKKU-ESLAB/opel-alpha
94e329580e8bc80cc68689c0ba1be845bc58f473
[ "Apache-2.0" ]
null
null
null
#include <node.h> #include <stdlib.h> #include <string.h> #include <string> #include "AppAPIInternal.h" #include "AppBase.h" #include "OPELdbugLog.h" using namespace v8; #define MAX_NUMBER_OF_ITEMS 20 #define MESSAGE_BUFFER_SIZE 1024 // Utility Functions #define getV8String(isolate, cstr) (String::NewFromOneByte(isolate, \ (const uint8_t*)cstr)) AppBase* gAppBase; void initAppBase(){ printf("initialize AppBase"); gAppBase = new AppBase(); gAppBase->run(); // Send CompleteLaunchingApp command to appcore gAppBase->completeLaunchingApp(); } void makeEventPage(const FunctionCallbackInfo<Value>& args) { Isolate* isolate = Isolate::GetCurrent(); HandleScope scope(isolate); const char* description; v8::String::Utf8Value param1(args[0]->ToString()); std::string inputJsonData = std::string(*param1); description = inputJsonData.c_str(); if (args.Length() == 0) { args.GetReturnValue().Set(getV8String(isolate, "{\"noti\":\"noti\",\"description\":\"\"}")); return; } else if (args.Length() == 1) { char newJsonData[sizeof(char) * strlen(description) + 32]; sprintf(newJsonData, "{\"noti\":\"noti\",\"description\":\"%s\"}", description); args.GetReturnValue().Set(getV8String(isolate, newJsonData)); return; } isolate->ThrowException(Exception::TypeError(getV8String(isolate, "Invalid Use : arguments expected [Null or Description(string)]"))); } void addEventText(const FunctionCallbackInfo<Value>& args) { Isolate* isolate = Isolate::GetCurrent(); HandleScope scope(isolate); int newJsonLength; const char* oldJsonData; const char* textView; if (args.Length() != 2) { isolate->ThrowException(Exception::TypeError(getV8String(isolate, "Invalid Use : 2 arguments expected [Page Name]"))); return; } else if (!args[0]->IsString()) { //IsInteger, IsFunction, etc... isolate->ThrowException(Exception::TypeError(getV8String(isolate, "Wrong arguments"))); return; } else if (!args[1]->IsString()) { //IsInteger, IsFunction, etc... isolate->ThrowException(Exception::TypeError(getV8String(isolate, "Wrong arguments"))); return; } //--------------------- Page Name Check -------------------------// v8::String::Utf8Value param1(args[0]->ToString()); std::string inputJsonData = std::string(*param1); oldJsonData = inputJsonData.c_str(); v8::String::Utf8Value param2(args[1]->ToString()); std::string inputText = std::string(*param2); textView = inputText.c_str(); if (check_page_name(oldJsonData) != 1) { isolate->ThrowException(Exception::TypeError(getV8String(isolate, "addEventItem argument error : " \ "first arg is not the object of event page"))); return; } newJsonLength = strlen(oldJsonData) + strlen(textView) + 20; char newJsonData[sizeof(char) * newJsonLength]; memset(newJsonData, '\0', newJsonLength); char tmpStr[strlen(oldJsonData)]; strncpy(tmpStr, oldJsonData, strlen(oldJsonData)-1 ); tmpStr[strlen(oldJsonData)-1] = '\0'; sprintf(newJsonData, "%s,\"text\":\"%s\"}" , tmpStr, textView); args.GetReturnValue().Set(getV8String(isolate, newJsonData)); } // [MORE] addDescription // TODO: attach image file void addEventImg(const FunctionCallbackInfo<Value>& args) { Isolate* isolate = Isolate::GetCurrent(); HandleScope scope(isolate); int newJsonLength; const char* oldJsonData; const char* imgPath; if (args.Length() != 2) { isolate->ThrowException(Exception::TypeError(getV8String(isolate, "Invalid Use : 2 arguments expected [Page Name]"))); return; } else if (!args[0]->IsString()) { //IsInteger, IsFunction, etc... isolate->ThrowException(Exception::TypeError(getV8String(isolate, "Wrong arguments"))); return; } else if (!args[1]->IsString()) { //IsInteger, IsFunction, etc... isolate->ThrowException(Exception::TypeError(getV8String(isolate, "Wrong arguments"))); return; } //--------------------- Page Name Check -------------------------// v8::String::Utf8Value param1(args[0]->ToString()); std::string inputJsonData = std::string(*param1); oldJsonData = inputJsonData.c_str(); v8::String::Utf8Value param2(args[1]->ToString()); std::string inputText = std::string(*param2); imgPath = inputText.c_str(); if (check_page_name(oldJsonData) != 1) { isolate->ThrowException(Exception::TypeError(getV8String(isolate, "addEventItem argument error : " \ "first arg is not the object of event page"))); return; } newJsonLength = strlen(oldJsonData) + strlen(imgPath)+256 ; char newJsonData[sizeof(char) * newJsonLength]; memset(newJsonData, '\0', newJsonLength); char tmpStr[strlen(oldJsonData)]; strncpy(tmpStr, oldJsonData, strlen(oldJsonData)-1 ); tmpStr[strlen(oldJsonData)-1] = '\0'; sprintf(newJsonData, "%s,\"img\":\"%s\"}" , tmpStr, imgPath); args.GetReturnValue().Set(getV8String(isolate, newJsonData)); } // send CompanionMessage.SendEventPage void sendEventPage(const FunctionCallbackInfo<Value>& args) { Isolate* isolate = Isolate::GetCurrent(); HandleScope scope(isolate); // Arguments const char* jsonData; // Check arguments if ((args.Length() != 1) || !args[0]->IsString() ) { isolate->ThrowException(Exception::TypeError(getV8String(isolate, "Invalid Use : 1 arguments expected [Page obj]"))); return; } // Get argument 0 v8::String::Utf8Value param1(args[0]->ToString()); std::string name_c = std::string(*param1); jsonData = name_c.c_str(); if (check_page_name(jsonData) != 1) { isolate->ThrowException(Exception::TypeError(getV8String(isolate, "sendEventItem argument error : " \ "first arg is not the object of event page"))); return; } // send CompanionMessage.SendEventPage gAppBase->sendEventPageToCompanion(jsonData, false); printf("[NIL] SendEventPage to companion: %s\n", jsonData); return; } // send CompanionMessage.SendEventPage void sendEventPageWithNoti(const FunctionCallbackInfo<Value>& args) { Isolate* isolate = Isolate::GetCurrent(); HandleScope scope(isolate); // Arguments const char* jsonData; // Check arguments if ((args.Length() != 1) || !args[0]->IsString()) { isolate->ThrowException(Exception::TypeError(getV8String(isolate, "Invalid Use : 1 arguments expected [Page obj]"))); return; } // Get argument 0 v8::String::Utf8Value param1(args[0]->ToString()); std::string name_c = std::string(*param1); jsonData = name_c.c_str(); if (check_page_name(jsonData) != 1) { isolate->ThrowException(Exception::TypeError(getV8String(isolate, "sendEventItem argument error : " \ "first arg is not the object of event page"))); return; } // Send CompanionMessage.SendEventPage gAppBase->sendEventPageToCompanion(jsonData, true); printf("[NIL] SendEventPage to companion: %s\n", jsonData); return; } //JSON Warnning : any string shouln't has '"' char //OUTPUT Json format : /* { "conf":"conf", "strTB":"Name[descript/10]", "numTB":"Name[descript/1/10]", "sDialog":"Name[descript/a/b/c/d/e]", "mDialog":"Name[descript/a[a]/b/c/d/e]", "dateDialog":Name[descript/flag]", "timeDialog":Name[descript/flag]" } */ //---------------------- config page -------------------------// void makeConfigPage(const FunctionCallbackInfo<Value>& args) { Isolate* isolate = Isolate::GetCurrent(); HandleScope scope(isolate); args.GetReturnValue().Set(getV8String(isolate, "{\"conf\":\"conf\"}")); } // addStrTextbox(page, name, description, length); // Return new Json string void addStrTextbox(const FunctionCallbackInfo<Value>& args) { Isolate* isolate = Isolate::GetCurrent(); HandleScope scope(isolate); int newJsonLength; const char* oldJsonData; const char* description; const char* name; const char* length; if (args.Length() != 4) { isolate->ThrowException(Exception::TypeError(getV8String(isolate, "Invalid Use : 1st arguments expected " \ "[Page, Name(str), Description(str), length(int)]"))); return; } else if (!args[0]->IsString() || !args[1]->IsString() || !args[2]->IsString() || !args[3]->NumberValue()) { //IsInteger, IsFunction, etc... isolate->ThrowException(Exception::TypeError(getV8String(isolate, "Wrong arguments"))); return; } //--------------------- Page Name Check -------------------------// v8::String::Utf8Value param1(args[0]->ToString()); std::string json = std::string(*param1); oldJsonData = json.c_str(); v8::String::Utf8Value param2(args[1]->ToString()); std::string name_c = std::string(*param2); name = name_c.c_str(); v8::String::Utf8Value param11(args[2]->ToString()); std::string des = std::string(*param11); description= des.c_str(); v8::String::Utf8Value param3(args[3]->ToString()); std::string length_c = std::string(*param3); length = length_c.c_str(); if (check_page_name(oldJsonData) != 2){ isolate->ThrowException(Exception::TypeError(getV8String(isolate, "addConfigItem argument error :" \ "first arg is not the object of config page"))); return; } else if (check_key_overlap(oldJsonData, name) == false){ isolate->ThrowException(Exception::TypeError(getV8String(isolate, "addConfigItem argument error : " \ "the name(key) is already used in this page"))); return; } newJsonLength = strlen(oldJsonData) + strlen(name) + strlen(length) + 32; char newJsonData [sizeof(char) * newJsonLength]; memset(newJsonData, '\0', newJsonLength); char tmpStr[strlen(oldJsonData)]; strncpy(tmpStr, oldJsonData, strlen(oldJsonData)-1 ); tmpStr[strlen(oldJsonData)-1] = '\0'; sprintf(newJsonData, "%s,\"strTB\":\"%s[%s/%s]\"}", tmpStr, name, description,length); args.GetReturnValue().Set(getV8String(isolate, newJsonData)); } // addNumberTextbox(page, name, description, range1, range2); // Return new Json string void addNumberTextbox(const FunctionCallbackInfo<Value>& args) { Isolate* isolate = Isolate::GetCurrent(); HandleScope scope(isolate); const char* oldJsonData; // char* newJsonData; int newJsonLength; const char* name; const char* description; const char* range1; const char* range2; if (args.Length() != 5) { isolate->ThrowException(Exception::TypeError(getV8String(isolate, "addNumberTextbox::Invalid Use : 5 arguments expected " \ "[page,name,description,range1,range2]"))); return; } else if (!args[0]->IsString()) { isolate->ThrowException(Exception::TypeError(getV8String(isolate, "addNumberTextbox::1st argument is wrong [page]"))); return; } else if (!args[1]->IsString() ) { isolate->ThrowException(Exception::TypeError(getV8String(isolate, "addNumberTextbox::2nd argument is wrong [string:Name]"))); return; } else if (!args[2]->IsString() ) { isolate->ThrowException(Exception::TypeError(getV8String(isolate, "addNumberTextbox::3rd argument is wrong [string:description]"))); return; } else if (!args[3]->IsNumber()|| !args[4]->IsNumber() ) { isolate->ThrowException(Exception::TypeError(getV8String(isolate, "addNumberTextbox::4,5th argument is wrong " \ "[int:range1, int:range2]"))); return; } //--------------------- Page Name Check -------------------------// v8::String::Utf8Value param1(args[0]->ToString()); std::string json = std::string(*param1); oldJsonData = json.c_str(); v8::String::Utf8Value param2(args[1]->ToString()); std::string name_c = std::string(*param2); name = name_c.c_str(); v8::String::Utf8Value param11(args[2]->ToString()); std::string des = std::string(*param11); description= des.c_str(); v8::String::Utf8Value param3(args[3]->ToString()); std::string range_1 = std::string(*param3); v8::String::Utf8Value param4(args[4]->ToString()); std::string range_2 = std::string(*param4); if ( atof(range_1.c_str()) < atof(range_2.c_str())){ range1 = range_1.c_str(); range2 = range_2.c_str(); } else { range1 = range_2.c_str(); range2 = range_1.c_str(); } if (check_page_name(oldJsonData) != 2) { isolate->ThrowException(Exception::TypeError(getV8String(isolate, "addConfigItem argument error : " \ "first arg is not the object of config page"))); return; } if (check_key_overlap(oldJsonData, name) == false ) { isolate->ThrowException(Exception::TypeError(getV8String(isolate, "addConfigItem argument error : " \ "the name(key) is already used in this page"))); return; } newJsonLength = strlen(oldJsonData) + strlen(name) + strlen(range1) + strlen(range2) + 32; char newJsonData [sizeof(char) * newJsonLength]; memset(newJsonData, '\0', newJsonLength); char tmpStr[strlen(oldJsonData)]; strncpy(tmpStr, oldJsonData, strlen(oldJsonData)-1 ); tmpStr[strlen(oldJsonData)-1] = '\0'; sprintf(newJsonData, "%s,\"numTB\":\"%s[%s/%s/%s]\"}" , tmpStr, name, description, range1, range2); args.GetReturnValue().Set(getV8String(isolate, newJsonData)); } // addSingleDialog(page, name, description, item1,2,3...); // Return new Json string (+"sDialog":"Name[description/a/b/c/d/e]"), void addSingleDialog(const FunctionCallbackInfo<Value>& args) { Isolate* isolate = Isolate::GetCurrent(); HandleScope scope(isolate); const char* oldJsonData; int newJsonLength; const char* name; char** items; int i; if (!args[0]->IsString()) { isolate->ThrowException(Exception::TypeError(getV8String(isolate, "addSingleDialog::1st argument is wrong [page]"))); return; } else if (!args[1]->IsString() ) { isolate->ThrowException(Exception::TypeError(getV8String(isolate, "addSingleDialog::2nd argument is wrong [string:Name]"))); return; } v8::String::Utf8Value param1(args[0]->ToString()); std::string json = std::string(*param1); oldJsonData = json.c_str(); v8::String::Utf8Value param2(args[1]->ToString()); std::string name_c = std::string(*param2); name = name_c.c_str(); if (check_page_name(oldJsonData) != 2){ isolate->ThrowException(Exception::TypeError(getV8String(isolate, "addSingleDialog argument error : " \ "first arg is not the object of config page"))); return; } else if (check_key_overlap(oldJsonData, name) == false){ isolate->ThrowException(Exception::TypeError(getV8String(isolate, "addConfigItem argument error : " \ "the name(key) is already used in this page"))); return; } // get items items = (char**) malloc(sizeof(char*) * MAX_NUMBER_OF_ITEMS); int itemsTotalLength=0; for (i=2; args[i]->IsString(); i++) { v8::String::Utf8Value param3(args[i]->ToString()); std::string item = std::string(*param3); items[i-2] = (char*) malloc(sizeof(char) * strlen(item.c_str()) ); strcpy(items[i-2], item.c_str()); itemsTotalLength += strlen(item.c_str()); if (i > MAX_NUMBER_OF_ITEMS+1 ) { isolate->ThrowException(Exception::TypeError(getV8String(isolate, "addSingleDialog argument error : " \ "over the maximum number of items"))); return; } } char* itemsString = (char*) malloc( (sizeof(char) * itemsTotalLength) + 4*i ); memset(itemsString, '\0', (sizeof(char) * itemsTotalLength) + 4*i ); for(int j = 0; j < i-2; j++) { if(strchr(items[j], '/') != NULL) { // some items contain '/' character -> cannot use that cuz it's token char isolate->ThrowException(Exception::TypeError(getV8String(isolate, "addSingleDialog::item cannot contain '/' character"))); free(items); free(itemsString); return; } strcat(itemsString, items[j]); if(j == i-3){ strcat(itemsString, "\0"); } else{ strcat(itemsString, "/"); } } newJsonLength = strlen(oldJsonData) + strlen(name) + strlen(itemsString)+ 32; // newJsonData = (char*)malloc(sizeof(char) * newJsonLength); char newJsonData [sizeof(char) * newJsonLength]; memset(newJsonData, '\0', newJsonLength); char tmpStr[strlen(oldJsonData)]; strncpy(tmpStr, oldJsonData, strlen(oldJsonData)-1 ); tmpStr[strlen(oldJsonData)-1] = '\0'; sprintf(newJsonData, "%s,\"sDialog\":\"%s[%s]\"}" , tmpStr, name, itemsString); free(items); free(itemsString); args.GetReturnValue().Set(getV8String(isolate, newJsonData)); } // addMultipleDialog(page, name, description, item1,2,3...); // Return new Json string (+"mDialog":"Name[description/a/b/c/d/e]") void addMultipleDialog(const FunctionCallbackInfo<Value>& args) { Isolate* isolate = Isolate::GetCurrent(); HandleScope scope(isolate); const char* oldJsonData; int newJsonLength; const char* name; char** items; int i; if (!args[0]->IsString()) { isolate->ThrowException(Exception::TypeError(getV8String(isolate, "addMultipleDialog::1st argument is wrong [page]"))); return; } else if (!args[1]->IsString() ) { isolate->ThrowException(Exception::TypeError(getV8String(isolate, "addMultipleDialog::2nd argument is wrong [string:Name]"))); return; } v8::String::Utf8Value param1(args[0]->ToString()); std::string json = std::string(*param1); oldJsonData = json.c_str(); v8::String::Utf8Value param2(args[1]->ToString()); std::string name_c = std::string(*param2); name = name_c.c_str(); if (check_page_name(oldJsonData) != 2) { isolate->ThrowException(Exception::TypeError(getV8String(isolate, "addMultipleDialog argument error : " \ "first arg is not the object of config page"))); return; } else if (check_key_overlap(oldJsonData, name) == false) { isolate->ThrowException(Exception::TypeError(getV8String(isolate, "addConfigItem argument error : " \ "the name(key) is already used in this page"))); return; } // get items items = (char**) malloc(sizeof(char*) * MAX_NUMBER_OF_ITEMS); int itemsTotalLength=0; for(i=2; args[i]->IsString(); i++) { v8::String::Utf8Value param3(args[i]->ToString()); std::string item = std::string(*param3); items[i-2] = (char*) malloc(sizeof(char) * strlen(item.c_str()) ); strcpy(items[i-2], item.c_str()); itemsTotalLength += strlen(item.c_str()); if(i > MAX_NUMBER_OF_ITEMS + 1 ) { isolate->ThrowException(Exception::TypeError(getV8String(isolate, "addSingleDialog argument error : " \ "over the maximum number of items"))); return; } } char* itemsString = (char*) malloc( (sizeof(char) * itemsTotalLength) + 4*i ); memset(itemsString, '\0', (sizeof(char) * itemsTotalLength) + 4*i ); for(int j = 0; j < i-2; j++) { if(strchr(items[j], '/') != NULL) { // some items contain '/' character -> cannot use that cuz it's token char isolate->ThrowException(Exception::TypeError(getV8String(isolate, "addSingleDialog::item cannot contain '/' character"))); free(items); free(itemsString); return; } strcat(itemsString, items[j]); if(j == i-3) { strcat(itemsString, "\0"); } else { strcat(itemsString, "/"); } } newJsonLength = strlen(oldJsonData) + strlen(name) + strlen(itemsString)+ 32; char newJsonData [sizeof(char) * newJsonLength]; memset(newJsonData, '\0', newJsonLength); char tmpStr[strlen(oldJsonData)]; strncpy(tmpStr, oldJsonData, strlen(oldJsonData)-1 ); tmpStr[strlen(oldJsonData)-1] = '\0'; sprintf(newJsonData, "%s,\"mDialog\":\"%s[%s]\"}" , tmpStr, name, itemsString); free(items); free(itemsString); args.GetReturnValue().Set(getV8String(isolate, newJsonData)); } // addMultipleDialog(page, name, description, flag(0||1)); // Return new Json string (+"dateDialog":"Name[flag]") // flag 0 = no constraint , 1 = allow only after current date void addDateDialog(const FunctionCallbackInfo<Value>& args) { Isolate* isolate = Isolate::GetCurrent(); HandleScope scope(isolate); const char* oldJsonData; const char* name; const char* description; const char* flag; if (args.Length() != 4) { isolate->ThrowException(Exception::TypeError(getV8String(isolate, "addDateDialog::Invalid Use : 4 arguments expected " \ "[page,name,description, flag]"))); return; } else if (!args[0]->IsString()) { isolate->ThrowException(Exception::TypeError(getV8String(isolate, "addDateDialog::1st argument is wrong [page]"))); return; } else if (!args[1]->IsString() ) { isolate->ThrowException(Exception::TypeError(getV8String(isolate, "addDateDialog::2nd argument is wrong [string:Name]"))); return; } else if (!args[2]->IsString() ) { isolate->ThrowException(Exception::TypeError(getV8String(isolate, "addDateDialog::3rd argument is wrong [string:description]"))); return; } else if (!args[3]->IsNumber() ) { isolate->ThrowException(Exception::TypeError(getV8String(isolate, "addDateDialog::4th argument is wrong [int 0 or 1]"))); return; } //--------------------- Page Name Check -------------------------// v8::String::Utf8Value param1(args[0]->ToString()); std::string json = std::string(*param1); oldJsonData = json.c_str(); v8::String::Utf8Value param2(args[1]->ToString()); std::string name_c = std::string(*param2); name = name_c.c_str(); v8::String::Utf8Value param11(args[2]->ToString()); std::string des = std::string(*param11); description= des.c_str(); v8::String::Utf8Value param3(args[3]->ToString()); std::string flag_c = std::string(*param3); flag = flag_c.c_str(); if (check_page_name(oldJsonData) != 2) { isolate->ThrowException(Exception::TypeError(getV8String(isolate, "addDateDialog argument error : " \ "first arg is not the object of config page"))); return; } else if (check_key_overlap(oldJsonData, name) == false) { isolate->ThrowException(Exception::TypeError(getV8String(isolate, "addConfigItem argument error : " \ "the name(key) is already used in this page"))); return; } else if (atoi(flag)!=0 && atoi(flag)!=1) { isolate->ThrowException(Exception::TypeError(getV8String(isolate, "addDateDialog::3rd argument is wrong [int 0 or 1]"))); return; } char newJsonData [MESSAGE_BUFFER_SIZE]; memset(newJsonData, '\0', MESSAGE_BUFFER_SIZE); char tmpStr[strlen(oldJsonData)]; strncpy(tmpStr, oldJsonData, strlen(oldJsonData)-1 ); tmpStr[strlen(oldJsonData)-1] = '\0'; sprintf(newJsonData, "%s,\"dateDialog\":\"%s[%s/%s]\"}", tmpStr, name, description, flag); args.GetReturnValue().Set(getV8String(isolate, newJsonData)); } // addTimeDialog(page, name, flag(0||1)); // Return new Json string (+"timeDialog":"Name[flag]") // flag 0 = no constraint , 1 = allow only after current time void addTimeDialog(const FunctionCallbackInfo<Value>& args) { Isolate* isolate = Isolate::GetCurrent(); HandleScope scope(isolate); const char* oldJsonData; const char* name; const char* description; const char* flag; if (args.Length() != 4) { isolate->ThrowException(Exception::TypeError(getV8String(isolate, "addDateDialog::Invalid Use : 4 arguments expected " \ "[page,name,description, flag]"))); return; } else if (!args[0]->IsString()) { isolate->ThrowException(Exception::TypeError(getV8String(isolate, "addDateDialog::1st argument is wrong [page]"))); return; } else if (!args[1]->IsString() ) { isolate->ThrowException(Exception::TypeError(getV8String(isolate, "addDateDialog::2nd argument is wrong [string:Name]"))); return; } else if (!args[2]->IsString() ) { isolate->ThrowException(Exception::TypeError(getV8String(isolate, "addDateDialog::3rd argument is wrong [string:description]"))); return; } else if (!args[3]->IsNumber() ) { isolate->ThrowException(Exception::TypeError(getV8String(isolate, "addDateDialog::4th argument is wrong [int 0 or 1]"))); return; } //--------------------- Page Name Check -------------------------// v8::String::Utf8Value param1(args[0]->ToString()); std::string json = std::string(*param1); oldJsonData = json.c_str(); v8::String::Utf8Value param2(args[1]->ToString()); std::string name_c = std::string(*param2); name = name_c.c_str(); v8::String::Utf8Value param11(args[2]->ToString()); std::string des = std::string(*param11); description= des.c_str(); v8::String::Utf8Value param3(args[3]->ToString()); std::string flag_c = std::string(*param3); flag = flag_c.c_str(); if (check_page_name(oldJsonData) != 2) { isolate->ThrowException(Exception::TypeError(getV8String(isolate, "addDateDialog argument error : " \ "first arg is not the object of config page"))); return; } else if (check_key_overlap(oldJsonData, name) == false) { isolate->ThrowException(Exception::TypeError(getV8String(isolate, "addConfigItem argument error : " \ "the name(key) is already used in this page"))); return; } else if (atoi(flag)!=0 && atoi(flag)!=1) { isolate->ThrowException(Exception::TypeError(getV8String(isolate, "addDateDialog::3rd argument is wrong [int 0 or 1]"))); return; } char newJsonData [MESSAGE_BUFFER_SIZE]; memset(newJsonData, '\0', MESSAGE_BUFFER_SIZE); char tmpStr[strlen(oldJsonData)]; strncpy(tmpStr, oldJsonData, strlen(oldJsonData)-1 ); tmpStr[strlen(oldJsonData)-1] = '\0'; sprintf(newJsonData, "%s,\"timeDialog\":\"%s[%s/%s]\"}", tmpStr, name, description, flag); args.GetReturnValue().Set(getV8String(isolate, newJsonData)); } /*//SEND Format to Android { "conf":"Pid", "rqID":"_rqID", "strTB":"Name[StrTextBoxDialog/10]", "numTB":"Age[NumberTextBoxDialog/0/100]", "sDialog":"Gender[SingleDialog/Male/Female]", "mDialog":"Hobby[MultiDialog/Book/Movie/Tennis/Jogging]", "dateDialog":"Birthday[DateDialog/0]", "timeDialog":"time[TimeDialog/0]" } */ // send CompanionMessage.SendConfigPage void sendConfigPage(const FunctionCallbackInfo<Value>& args) { Isolate* isolate = Isolate::GetCurrent(); HandleScope scope(isolate); // Arguments const char* jsonData; Local<Function> onUpdateAppConfigCallback; // Check arguments if ((args.Length() != 2) || !args[1]->IsFunction() || !args[0]->IsString() ) { isolate->ThrowException(Exception::TypeError(getV8String(isolate, "Invalid Use : 2 arguments expected [ConfigPage, Function]"))); return; } // Get argument 0 v8::String::Utf8Value param1(args[0]->ToString()); std::string json_c = std::string(*param1); jsonData = json_c.c_str(); if (check_page_name(jsonData) != 2){ isolate->ThrowException(Exception::TypeError(getV8String(isolate, "sendConfig argument error : " \ "first arg is not the object of config page"))); return; } // Get argument 1 onUpdateAppConfigCallback = Local<Function>::Cast(args[1]); // Register onUpdateAppConfig callback gAppBase->setOnUpdateAppConfig(isolate, onUpdateAppConfigCallback); // Send CompanionMessage.SendConfigPage command gAppBase->sendConfigPageToCompanion(jsonData); printf("[NIL] SendConfigPage >> %s \n", jsonData); return; } // getData(page[return page], name); // Return name(key)->value [string] void getData(const FunctionCallbackInfo<Value>& args) { Isolate* isolate = Isolate::GetCurrent(); HandleScope scope(isolate); const char* rcvJson; const char* name; if (args.Length() != 2) { isolate->ThrowException(Exception::TypeError(getV8String(isolate, "getData::Invalid Use : 2 arguments expected [configurableData,Key]"))); return; } else if (!args[0]->IsString()) { isolate->ThrowException(Exception::TypeError(getV8String(isolate, "getData::1st argument is wrong [page]"))); return; } else if (!args[1]->IsString()) { isolate->ThrowException(Exception::TypeError(getV8String(isolate, "getData::2nd argument is wrong [string:Name]"))); return; } //--------------------- Page Name Check -------------------------// v8::String::Utf8Value param1(args[0]->ToString()); std::string json = std::string(*param1); rcvJson = json.c_str(); v8::String::Utf8Value param2(args[1]->ToString()); std::string name_c = std::string(*param2); name = name_c.c_str(); int position = 0; char key[512]; char value[512]; memset(key, '\0', 512); memset(value, '\0', 512); for(unsigned int i=0; i<strlen(rcvJson); i++){ if (rcvJson[i] == '{' ) continue; else if (rcvJson[i] == '}' ) { if(!strcmp(key, name)) { args.GetReturnValue().Set(getV8String(isolate, value)); } } else if (rcvJson[i] == ':' ) { if(rcvJson[i+1] == '"') { position++; } else{ char tmp[2]; tmp[1] = '\0'; tmp[0] = rcvJson[i]; if(!(position % 2)) // even num -> key strcat(key, tmp); else // odd num -> value strcat(value, tmp); } } else if (rcvJson[i] == ',' ) { if(rcvJson[i+1] == '"') { position++; if(!strcmp(key, name)) { args.GetReturnValue().Set(getV8String(isolate, value)); } else { memset(key, '\0', 512); memset(value, '\0', 512); } } } else if (rcvJson[i] == '"' ) { continue; } else { char tmp[2]; tmp[1] = '\0'; tmp[0] = rcvJson[i]; if(!(position % 2)) // even num -> key strcat(key, tmp); else // odd num -> value strcat(value, tmp); } } printf("[NIL] There is no value with the key[%s]\n", name); args.GetReturnValue().Set(getV8String(isolate, "N/A")); } // [MORE] return multiple choice -> array // onTermination(function) void onTermination(const FunctionCallbackInfo<Value>& args) { Isolate* isolate = Isolate::GetCurrent(); HandleScope scope(isolate); // Arguments Local<Function> onTerminateCallback; // Check arguments if ((args.Length() != 1) || !args[0]->IsFunction()) { isolate->ThrowException(Exception::TypeError(getV8String(isolate, "Invalid Use : 1 arguments expected [Callback Function]"))); return; } // Get argument 0 onTerminateCallback = Local<Function>::Cast(args[0]); // Register onTerminate callback gAppBase->setOnTerminate(isolate, onTerminateCallback); return; } // send CompanionMessage.UpdateSensorData void sendMsgToSensorViewer(const FunctionCallbackInfo<Value>& args) { Isolate* isolate = Isolate::GetCurrent(); HandleScope scope(isolate); // Arguments const char* jsonData; // Check arguments if ((args.Length() != 1) || !args[0]->IsString() ) { isolate->ThrowException(Exception::TypeError(getV8String(isolate, "Invalid Use : 1 arguments expected [SensorData obj]"))); return; } // Get argument 0 v8::String::Utf8Value param1(args[0]->ToString()); std::string name_c = std::string(*param1); jsonData = name_c.c_str(); // Send CompanionMessage.UpdateSensorData gAppBase->updateSensorDataToCompanion(jsonData); printf("[NIL] sendMsgToSensorViewer to companion: %s\n", jsonData); return; } void init(Handle<Object> exports) { Isolate* isolate = Isolate::GetCurrent(); initAppBase(); //-----------------------EventPage------------------------------------------- exports->Set(getV8String(isolate, "makeEventPage"), FunctionTemplate::New(isolate, makeEventPage)->GetFunction()); exports->Set(getV8String(isolate, "addEventText"), FunctionTemplate::New(isolate, addEventText)->GetFunction()); exports->Set(getV8String(isolate, "addEventImg"), FunctionTemplate::New(isolate, addEventImg)->GetFunction()); exports->Set(getV8String(isolate, "sendEventPageWithNoti"), FunctionTemplate::New(isolate, sendEventPageWithNoti)->GetFunction()); exports->Set(getV8String(isolate, "sendEventPage"), FunctionTemplate::New(isolate, sendEventPage)->GetFunction()); //-----------------------ConfigPage------------------------------------------- exports->Set(getV8String(isolate, "makeConfigPage"), FunctionTemplate::New(isolate, makeConfigPage)->GetFunction()); exports->Set(getV8String(isolate, "addStrTextbox"), FunctionTemplate::New(isolate, addStrTextbox)->GetFunction()); exports->Set(getV8String(isolate, "addNumberTextbox"), FunctionTemplate::New(isolate, addNumberTextbox)->GetFunction()); exports->Set(getV8String(isolate, "addSingleDialog"), FunctionTemplate::New(isolate, addSingleDialog)->GetFunction()); exports->Set(getV8String(isolate, "addMultipleDialog"), FunctionTemplate::New(isolate, addMultipleDialog)->GetFunction()); exports->Set(getV8String(isolate, "addDateDialog"), FunctionTemplate::New(isolate, addDateDialog)->GetFunction()); exports->Set(getV8String(isolate, "addTimeDialog"), FunctionTemplate::New(isolate, addTimeDialog)->GetFunction()); exports->Set(getV8String(isolate, "sendConfigPage"), FunctionTemplate::New(isolate, sendConfigPage)->GetFunction()); exports->Set(getV8String(isolate, "getData"), FunctionTemplate::New(isolate, getData)->GetFunction()); //------------------------termination----------------------------------------- exports->Set(getV8String(isolate, "onTermination"), FunctionTemplate::New(isolate, onTermination)->GetFunction()); //------------------------sensor viewer--------------------------------------- exports->Set(getV8String(isolate, "sendMsgToSensorViewer"), FunctionTemplate::New(isolate, sendMsgToSensorViewer)->GetFunction()); } NODE_MODULE(nil, init)
33.454902
84
0.644708
[ "object" ]
f5a823e105219c2802dc0d2e885b95b3c2fed19b
10,806
hpp
C++
windows/include/boost/accumulators/statistics/tail.hpp
jaredhoberock/gotham
e3551cc355646530574d086d7cc2b82e41e8f798
[ "Apache-2.0" ]
6
2015-12-29T07:21:01.000Z
2020-05-29T10:47:38.000Z
windows/include/boost/accumulators/statistics/tail.hpp
jaredhoberock/gotham
e3551cc355646530574d086d7cc2b82e41e8f798
[ "Apache-2.0" ]
null
null
null
windows/include/boost/accumulators/statistics/tail.hpp
jaredhoberock/gotham
e3551cc355646530574d086d7cc2b82e41e8f798
[ "Apache-2.0" ]
null
null
null
/////////////////////////////////////////////////////////////////////////////// // tail.hpp // // Copyright 2005 Eric Niebler, Michael Gauckler. Distributed under the Boost // Software License, Version 1.0. (See accompanying file // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) #ifndef BOOST_ACCUMULATORS_STATISTICS_TAIL_HPP_EAN_28_10_2005 #define BOOST_ACCUMULATORS_STATISTICS_TAIL_HPP_EAN_28_10_2005 #include <vector> #include <functional> #include <boost/assert.hpp> #include <boost/range.hpp> #include <boost/mpl/if.hpp> #include <boost/mpl/or.hpp> #include <boost/mpl/placeholders.hpp> #include <boost/parameter/keyword.hpp> #include <boost/iterator/reverse_iterator.hpp> #include <boost/iterator/permutation_iterator.hpp> #include <boost/accumulators/framework/accumulator_base.hpp> #include <boost/accumulators/framework/extractor.hpp> #include <boost/accumulators/numeric/functional.hpp> #include <boost/accumulators/framework/parameters/sample.hpp> #include <boost/accumulators/framework/depends_on.hpp> #include <boost/accumulators/statistics_fwd.hpp> namespace boost { namespace accumulators { /////////////////////////////////////////////////////////////////////////////// // cache_size named parameters BOOST_PARAMETER_NESTED_KEYWORD(tag, right_tail_cache_size, cache_size) BOOST_PARAMETER_NESTED_KEYWORD(tag, left_tail_cache_size, cache_size) namespace detail { /////////////////////////////////////////////////////////////////////////////// // tail_range /// INTERNAL ONLY /// template<typename ElementIterator, typename IndexIterator> struct tail_range { typedef boost::iterator_range< boost::reverse_iterator<boost::permutation_iterator<ElementIterator, IndexIterator> > > type; }; /////////////////////////////////////////////////////////////////////////////// // make_tail_range /// INTERNAL ONLY /// template<typename ElementIterator, typename IndexIterator> typename tail_range<ElementIterator, IndexIterator>::type make_tail_range(ElementIterator elem_begin, IndexIterator index_begin, IndexIterator index_end) { return boost::make_iterator_range( boost::make_reverse_iterator( boost::make_permutation_iterator(elem_begin, index_end) ) , boost::make_reverse_iterator( boost::make_permutation_iterator(elem_begin, index_begin) ) ); } /////////////////////////////////////////////////////////////////////////////// // stat_assign_visitor /// INTERNAL ONLY /// template<typename Args> struct stat_assign_visitor { stat_assign_visitor(Args const &args, std::size_t index) : args(args) , index(index) { } template<typename Stat> void operator ()(Stat &stat) const { stat.assign(this->args, this->index); } private: stat_assign_visitor &operator =(stat_assign_visitor const &); Args const &args; std::size_t index; }; /////////////////////////////////////////////////////////////////////////////// // stat_assign /// INTERNAL ONLY /// template<typename Args> inline stat_assign_visitor<Args> const stat_assign(Args const &args, std::size_t index) { return stat_assign_visitor<Args>(args, index); } /////////////////////////////////////////////////////////////////////////////// // is_tail_variate_feature /// INTERNAL ONLY /// template<typename Stat, typename LeftRight> struct is_tail_variate_feature : mpl::false_ { }; /// INTERNAL ONLY /// template<typename VariateType, typename VariateTag, typename LeftRight> struct is_tail_variate_feature<tag::tail_variate<VariateType, VariateTag, LeftRight>, LeftRight> : mpl::true_ { }; /// INTERNAL ONLY /// template<typename LeftRight> struct is_tail_variate_feature<tag::tail_weights<LeftRight>, LeftRight> : mpl::true_ { }; } // namespace detail namespace impl { /////////////////////////////////////////////////////////////////////////////// // tail_impl template<typename Sample, typename LeftRight> struct tail_impl : accumulator_base { // LeftRight must be either right or left BOOST_MPL_ASSERT(( mpl::or_<is_same<LeftRight, right>, is_same<LeftRight, left> > )); typedef typename mpl::if_< is_same<LeftRight, right> , numeric::functional::greater<Sample const, Sample const> , numeric::functional::less<Sample const, Sample const> >::type predicate_type; // for boost::result_of typedef typename detail::tail_range< typename std::vector<Sample>::const_iterator , std::vector<std::size_t>::iterator >::type result_type; template<typename Args> tail_impl(Args const &args) : is_sorted(false) , indices() , samples(args[tag::tail<LeftRight>::cache_size], args[sample | Sample()]) { this->indices.reserve(this->samples.size()); } tail_impl(tail_impl const &that) : is_sorted(that.is_sorted) , indices(that.indices) , samples(that.samples) { this->indices.reserve(this->samples.size()); } // This just stores the heap and the samples. // In operator()() below, if we are adding a new sample // to the sample cache, we force all the // tail_variates to update also. (It's not // good enough to wait for the accumulator_set to do it // for us because then information about whether a sample // was stored and where is lost, and would need to be // queried at runtime, which would be slow.) This is // implemented as a filtered visitation over the stats, // which we can access because args[accumulator] gives us // all the stats. template<typename Args> void operator ()(Args const &args) { if(this->indices.size() < this->samples.size()) { this->indices.push_back(this->indices.size()); this->assign(args, this->indices.back()); } else if(predicate_type()(args[sample], this->samples[this->indices[0]])) { std::pop_heap(this->indices.begin(), this->indices.end(), indirect_cmp(this->samples)); this->assign(args, this->indices.back()); } } result_type result(dont_care) const { if(!this->is_sorted) { // Must use the same predicate here as in push_heap/pop_heap above. std::sort_heap(this->indices.begin(), this->indices.end(), indirect_cmp(this->samples)); // sort_heap puts elements in reverse order. Calling std::reverse // turns the sorted sequence back into a valid heap. std::reverse(this->indices.begin(), this->indices.end()); this->is_sorted = true; } return detail::make_tail_range( this->samples.begin() , this->indices.begin() , this->indices.end() ); } private: struct is_tail_variate { template<typename T> struct apply : detail::is_tail_variate_feature< typename detail::feature_tag<T>::type , LeftRight > {}; }; template<typename Args> void assign(Args const &args, std::size_t index) { BOOST_ASSERT(index < this->samples.size()); this->samples[index] = args[sample]; std::push_heap(this->indices.begin(), this->indices.end(), indirect_cmp(this->samples)); this->is_sorted = false; // Tell the tail variates to store their values also args[accumulator].template visit_if<is_tail_variate>(detail::stat_assign(args, index)); } /////////////////////////////////////////////////////////////////////////////// // struct indirect_cmp : std::binary_function<std::size_t, std::size_t, bool> { indirect_cmp(std::vector<Sample> const &samples) : samples(samples) { } bool operator ()(std::size_t left, std::size_t right) const { return predicate_type()(this->samples[left], this->samples[right]); } private: indirect_cmp &operator =(indirect_cmp const &); std::vector<Sample> const &samples; }; mutable bool is_sorted; mutable std::vector<std::size_t> indices; std::vector<Sample> samples; }; } // namespace impl // TODO The templatized tag::tail below should inherit from the correct named parameter. // The following lines provide a workaround, but there must be a better way of doing this. template<typename T> struct tail_cache_size_named_arg { }; template<> struct tail_cache_size_named_arg<left> : tag::left_tail_cache_size { }; template<> struct tail_cache_size_named_arg<right> : tag::right_tail_cache_size { }; /////////////////////////////////////////////////////////////////////////////// // tag::tail<> // namespace tag { template<typename LeftRight> struct tail : depends_on<> , tail_cache_size_named_arg<LeftRight> { /// INTERNAL ONLY /// typedef accumulators::impl::tail_impl<mpl::_1, LeftRight> impl; #ifdef BOOST_ACCUMULATORS_DOXYGEN_INVOKED /// tag::tail<LeftRight>::cache_size named parameter static boost::parameter::keyword<tail_cache_size_named_arg<LeftRight> > const cache_size; #endif }; struct abstract_tail : depends_on<> { }; } /////////////////////////////////////////////////////////////////////////////// // extract::tail // namespace extract { extractor<tag::abstract_tail> const tail = {}; } using extract::tail; template<typename LeftRight> struct feature_of<tag::tail<LeftRight> > : feature_of<tag::abstract_tail> { }; }} // namespace boost::accumulators #endif
32.45045
105
0.547659
[ "vector" ]
f5aac223df449ca14bc57f82a926ed1ce2bf5203
11,756
hpp
C++
user_mgr.hpp
asmithakarun/phosphor-user-manager
ca039ca36114aaacb059abc7545073ab735c3b25
[ "Apache-2.0" ]
7
2017-12-01T19:36:39.000Z
2020-06-01T08:28:24.000Z
user_mgr.hpp
asmithakarun/phosphor-user-manager
ca039ca36114aaacb059abc7545073ab735c3b25
[ "Apache-2.0" ]
13
2018-06-07T16:32:31.000Z
2022-03-18T22:58:48.000Z
user_mgr.hpp
asmithakarun/phosphor-user-manager
ca039ca36114aaacb059abc7545073ab735c3b25
[ "Apache-2.0" ]
8
2018-10-03T16:30:28.000Z
2022-03-22T06:30:00.000Z
/* // Copyright (c) 2018 Intel Corporation // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. */ #pragma once #include "users.hpp" #include <sdbusplus/bus.hpp> #include <sdbusplus/server/object.hpp> #include <xyz/openbmc_project/User/AccountPolicy/server.hpp> #include <xyz/openbmc_project/User/Manager/server.hpp> #include <unordered_map> #include <variant> namespace phosphor { namespace user { using UserMgrIface = sdbusplus::xyz::openbmc_project::User::server::Manager; using UserSSHLists = std::pair<std::vector<std::string>, std::vector<std::string>>; using AccountPolicyIface = sdbusplus::xyz::openbmc_project::User::server::AccountPolicy; using Ifaces = sdbusplus::server::object::object<UserMgrIface, AccountPolicyIface>; using Privilege = std::string; using GroupList = std::vector<std::string>; using UserEnabled = bool; using PropertyName = std::string; using ServiceEnabled = bool; using UserInfo = std::variant<Privilege, GroupList, UserEnabled>; using UserInfoMap = std::map<PropertyName, UserInfo>; using DbusUserObjPath = sdbusplus::message::object_path; using DbusUserPropVariant = std::variant<Privilege, ServiceEnabled>; using DbusUserObjProperties = std::vector<std::pair<PropertyName, DbusUserPropVariant>>; using Interface = std::string; using DbusUserObjValue = std::map<Interface, DbusUserObjProperties>; using DbusUserObj = std::map<DbusUserObjPath, DbusUserObjValue>; /** @class UserMgr * @brief Responsible for managing user accounts over the D-Bus interface. */ class UserMgr : public Ifaces { public: UserMgr() = delete; ~UserMgr() = default; UserMgr(const UserMgr&) = delete; UserMgr& operator=(const UserMgr&) = delete; UserMgr(UserMgr&&) = delete; UserMgr& operator=(UserMgr&&) = delete; /** @brief Constructs UserMgr object. * * @param[in] bus - sdbusplus handler * @param[in] path - D-Bus path */ UserMgr(sdbusplus::bus::bus& bus, const char* path); /** @brief create user method. * This method creates a new user as requested * * @param[in] userName - Name of the user which has to be created * @param[in] groupNames - Group names list, to which user has to be added. * @param[in] priv - Privilege of the user. * @param[in] enabled - State of the user enabled / disabled. */ void createUser(std::string userName, std::vector<std::string> groupNames, std::string priv, bool enabled) override; /** @brief rename user method. * This method renames the user as requested * * @param[in] userName - current name of the user * @param[in] newUserName - new user name to which it has to be renamed. */ void renameUser(std::string userName, std::string newUserName) override; /** @brief delete user method. * This method deletes the user as requested * * @param[in] userName - Name of the user which has to be deleted */ void deleteUser(std::string userName); /** @brief Update user groups & privilege. * This method updates user groups & privilege * * @param[in] userName - user name, for which update is requested * @param[in] groupName - Group to be updated.. * @param[in] priv - Privilege to be updated. */ void updateGroupsAndPriv(const std::string& userName, const std::vector<std::string>& groups, const std::string& priv); /** @brief Update user enabled state. * This method enables / disables user * * @param[in] userName - user name, for which update is requested * @param[in] enabled - enable / disable the user */ void userEnable(const std::string& userName, bool enabled); /** @brief update minimum password length requirement * * @param[in] val - minimum password length * @return - minimum password length */ uint8_t minPasswordLength(uint8_t val) override; /** @brief update old password history count * * @param[in] val - number of times old passwords has to be avoided * @return - number of times old password has to be avoided */ uint8_t rememberOldPasswordTimes(uint8_t val) override; /** @brief update maximum number of failed login attempt before locked * out. * * @param[in] val - number of allowed attempt * @return - number of allowed attempt */ uint16_t maxLoginAttemptBeforeLockout(uint16_t val) override; /** @brief update timeout to unlock the account * * @param[in] val - value in seconds * @return - value in seconds */ uint32_t accountUnlockTimeout(uint32_t val) override; /** @brief lists user locked state for failed attempt * * @param[in] - user name * @return - true / false indicating user locked / un-locked **/ virtual bool userLockedForFailedAttempt(const std::string& userName); /** @brief lists user locked state for failed attempt * * @param[in]: user name * @param[in]: value - false -unlock user account, true - no action taken **/ bool userLockedForFailedAttempt(const std::string& userName, const bool& value); /** @brief shows if the user's password is expired * * @param[in]: user name * @return - true / false indicating user password expired **/ virtual bool userPasswordExpired(const std::string& userName); /** @brief returns user info * Checks if user is local user, then returns map of properties of user. * like user privilege, list of user groups, user enabled state and user * locked state. If its not local user, then it checks if its a ldap user, * then it gets the privilege mapping of the LDAP group. * * @param[in] - user name * @return - map of user properties **/ UserInfoMap getUserInfo(std::string userName) override; private: /** @brief sdbusplus handler */ sdbusplus::bus::bus& bus; /** @brief object path */ const std::string path; /** @brief privilege manager container */ std::vector<std::string> privMgr = {"priv-admin", "priv-operator", "priv-user", "priv-noaccess"}; /** @brief groups manager container */ std::vector<std::string> groupsMgr = {"web", "redfish", "ipmi", "ssh"}; /** @brief map container to hold users object */ using UserName = std::string; std::unordered_map<UserName, std::unique_ptr<phosphor::user::Users>> usersList; /** @brief get users in group * method to get group user list * * @param[in] groupName - group name * * @return userList - list of users in the group. */ std::vector<std::string> getUsersInGroup(const std::string& groupName); /** @brief get user & SSH users list * method to get the users and ssh users list. * *@return - vector of User & SSH user lists */ UserSSHLists getUserAndSshGrpList(void); /** @brief check for user presence * method to check for user existence * * @param[in] userName - name of the user * @return -true if user exists and false if not. */ bool isUserExist(const std::string& userName); /** @brief check user exists * method to check whether user exist, and throw if not. * * @param[in] userName - name of the user */ void throwForUserDoesNotExist(const std::string& userName); /** @brief check user does not exist * method to check whether does not exist, and throw if exists. * * @param[in] userName - name of the user */ void throwForUserExists(const std::string& userName); /** @brief check user name constraints * method to check user name constraints and throw if failed. * * @param[in] userName - name of the user * @param[in] groupNames - user groups */ void throwForUserNameConstraints(const std::string& userName, const std::vector<std::string>& groupNames); /** @brief check group user count * method to check max group user count, and throw if limit reached * * @param[in] groupNames - group name */ void throwForMaxGrpUserCount(const std::vector<std::string>& groupNames); /** @brief check for valid privielge * method to check valid privilege, and throw if invalid * * @param[in] priv - privilege of the user */ void throwForInvalidPrivilege(const std::string& priv); /** @brief check for valid groups * method to check valid groups, and throw if invalid * * @param[in] groupNames - user groups */ void throwForInvalidGroups(const std::vector<std::string>& groupName); /** @brief get user enabled state * method to get user enabled state. * * @param[in] userName - name of the user * @return - user enabled status (true/false) */ bool isUserEnabled(const std::string& userName); /** @brief initialize the user manager objects * method to initialize the user manager objects accordingly * */ void initUserObjects(void); /** @brief get IPMI user count * method to get IPMI user count * * @return - returns user count */ size_t getIpmiUsersCount(void); /** @brief get pam argument value * method to get argument value from pam configuration * * @param[in] moduleName - name of the module from where arg has to be read * @param[in] argName - argument name * @param[out] argValue - argument value * * @return 0 - success state of the function */ int getPamModuleArgValue(const std::string& moduleName, const std::string& argName, std::string& argValue); /** @brief set pam argument value * method to set argument value in pam configuration * * @param[in] moduleName - name of the module in which argument value has * to be set * @param[in] argName - argument name * @param[out] argValue - argument value * * @return 0 - success state of the function */ int setPamModuleArgValue(const std::string& moduleName, const std::string& argName, const std::string& argValue); /** @brief get service name * method to get dbus service name * * @param[in] path - object path * @param[in] intf - interface * @return - service name */ std::string getServiceName(std::string&& path, std::string&& intf); protected: /** @brief get LDAP group name * method to get LDAP group name for the given LDAP user * * @param[in] - userName * @return - group name */ virtual std::string getLdapGroupName(const std::string& userName); /** @brief get privilege mapper object * method to get dbus privilege mapper object * * @return - map of user object */ virtual DbusUserObj getPrivilegeMapperObject(void); friend class TestUserMgr; }; } // namespace user } // namespace phosphor
33.115493
80
0.642565
[ "object", "vector" ]
f5ad3615be0354a897408d552447609c11d03157
2,201
cpp
C++
src/model.cpp
codemusings/reversing-starmada
c77ae51104d6c3a2ddae42749bda4e8899573050
[ "MIT" ]
null
null
null
src/model.cpp
codemusings/reversing-starmada
c77ae51104d6c3a2ddae42749bda4e8899573050
[ "MIT" ]
null
null
null
src/model.cpp
codemusings/reversing-starmada
c77ae51104d6c3a2ddae42749bda4e8899573050
[ "MIT" ]
null
null
null
#include <stdexcept> #define STB_IMAGE_IMPLEMENTATION #include <stb_image.h> #include "model.hpp" Model::Model(const SODNode *meshNode, const char *textureFilePath) { SODNodeDataMesh *data = meshNode->data.mesh; int stride = 3 + 3 + 2; // coords + color + tex_coords numberOfVertices = 0; for (int i = 0; i < data->ngroups; i++) { SODVertexLightingGroup *group = data->lighting_groups[i]; int group_size = 0; for (int j = 0; j < group->nfaces; j++) { group_size = group->nfaces * 3 * stride; } numberOfVertices += group_size; } vertices = new float[numberOfVertices]; int lgroup_offset = 0; for (int i = 0; i < data->ngroups; i++) { SODVertexLightingGroup *group = data->lighting_groups[i]; for (int j = 0; j < group->nfaces; j++) { // 3 * (3 + 3 + 2) = 24 int face_offset = lgroup_offset + j * 3 * stride; for (int k = 0; k < 3; k++) { SODFaceVertex *vertex = group->faces[j]->face_vertices[k]; uint16_t v = vertex->index_vertices; uint16_t t = vertex->index_texcoords; // coords vertices[face_offset + k * stride + 0] = data->vertices[v]->x; vertices[face_offset + k * stride + 1] = data->vertices[v]->y; vertices[face_offset + k * stride + 2] = data->vertices[v]->z; // color vertices[face_offset + k * stride + 3] = 1.0f; vertices[face_offset + k * stride + 4] = 1.0f; vertices[face_offset + k * stride + 5] = 1.0f; // texture coords vertices[face_offset + k * stride + 6] = data->texcoords[t]->u; vertices[face_offset + k * stride + 7] = data->texcoords[t]->v; } } lgroup_offset += group->nfaces * 3 * stride; } textureData = stbi_load(textureFilePath, &textureWidth, &textureHeight, NULL, 0); if (!textureData) { throw std::runtime_error(std::string("Unable to load texture: ") + textureFilePath); } } Model::~Model() { delete vertices; stbi_image_free(textureData); }
36.683333
92
0.550204
[ "mesh", "model" ]
f5ae43bf29cb8b962cb1eeb41dd474ea72427fd6
259
cpp
C++
src/onnx_model/test/env.cpp
TomFinley/FeatureBroker
481a8f9a1a2e0980eee14d84f712ec3abf40ef0e
[ "MIT" ]
10
2020-03-17T00:35:54.000Z
2021-08-22T12:31:27.000Z
src/onnx_model/test/env.cpp
TomFinley/FeatureBroker
481a8f9a1a2e0980eee14d84f712ec3abf40ef0e
[ "MIT" ]
3
2020-03-17T17:25:15.000Z
2020-03-17T21:10:41.000Z
src/onnx_model/test/env.cpp
TomFinley/FeatureBroker
481a8f9a1a2e0980eee14d84f712ec3abf40ef0e
[ "MIT" ]
6
2020-03-13T15:39:03.000Z
2021-11-10T08:19:06.000Z
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. #include "env.hpp" #include <fstream> #include <iostream> #include <string> #include <vector> namespace onnx_model_test { std::string test_dir_path; } // namespace onnx_model_test
18.5
39
0.749035
[ "vector" ]
f5b17f27425caf318a1bc0e8c74a662878ebc3d3
4,735
cpp
C++
snippets/cpp/VS_Snippets_Winforms/CreateParams/CPP/createparams.cpp
BohdanMosiyuk/samples
59d435ba9e61e0fc19f5176c96b1cdbd53596142
[ "CC-BY-4.0", "MIT" ]
834
2017-06-24T10:40:36.000Z
2022-03-31T19:48:51.000Z
snippets/cpp/VS_Snippets_Winforms/CreateParams/CPP/createparams.cpp
BohdanMosiyuk/samples
59d435ba9e61e0fc19f5176c96b1cdbd53596142
[ "CC-BY-4.0", "MIT" ]
7,042
2017-06-23T22:34:47.000Z
2022-03-31T23:05:23.000Z
snippets/cpp/VS_Snippets_Winforms/CreateParams/CPP/createparams.cpp
BohdanMosiyuk/samples
59d435ba9e61e0fc19f5176c96b1cdbd53596142
[ "CC-BY-4.0", "MIT" ]
1,640
2017-06-23T22:31:39.000Z
2022-03-31T02:45:37.000Z
// <snippet1> #include <windows.h> #using <System.dll> #using <System.Drawing.dll> #using <System.Windows.Forms.dll> using namespace System; using namespace System::Drawing; using namespace System::Windows::Forms; using namespace System::Runtime::InteropServices; using namespace System::Diagnostics; using namespace System::IO; public ref class MyIconButton: public Button { private: Icon^ icon; public: MyIconButton() { // Set the button's FlatStyle property. FlatStyle = ::FlatStyle::System; } MyIconButton( Icon^ ButtonIcon ) { // Set the button's FlatStyle property. FlatStyle = ::FlatStyle::System; // Assign the icon to the private field. this->icon = ButtonIcon; // Size the button to 4 pixels larger than the icon. this->Height = icon->Height + 4; this->Width = icon->Width + 4; } protected: property System::Windows::Forms::CreateParams^ CreateParams { //<snippet3> virtual System::Windows::Forms::CreateParams^ get() override { // Extend the CreateParams property of the Button class. System::Windows::Forms::CreateParams^ cp = __super::CreateParams; // Update the button Style. cp->Style |= 0x00000040; // BS_ICON value return cp; } //</snippet3> } public: property System::Drawing::Icon^ Icon { System::Drawing::Icon^ get() { return icon; } void set(System::Drawing::Icon^ value) { icon = value; UpdateIcon(); this->Height = icon->Height + 4; this->Width = icon->Width + 4; } } protected: virtual void OnHandleCreated( EventArgs^ e ) override { Button::OnHandleCreated( e ); // Update the icon on the button if there is currently an icon assigned to the icon field. if ( icon != nullptr ) { UpdateIcon(); } } private: void UpdateIcon() { IntPtr iconHandle = IntPtr::Zero; // Get the icon's handle. if ( icon != nullptr ) { iconHandle = icon->Handle; } // Send Windows the message to update the button. SendMessage( (HWND)Handle.ToPointer(), 0x00F7, 1, (int)iconHandle ); /*BM_SETIMAGE value*/ /*IMAGE_ICON value*/ } public: [DllImport("user32.dll")] static LRESULT SendMessage(HWND hWnd, int msg, int wParam, int lParam); }; // </snippet1> // <snippet2> public ref class MyApplication: public Form { private: MyIconButton^ myIconButton; Button^ stdButton; OpenFileDialog^ openDlg; public: MyApplication() { try { // Create the button with the default icon. myIconButton = gcnew MyIconButton( gcnew System::Drawing::Icon( String::Concat( Application::StartupPath, "\\Default.ico" ) ) ); } catch ( Exception^ ex ) { // If the default icon does not exist, create the button without an icon. myIconButton = gcnew MyIconButton; #if defined(DEBUG) Debug::WriteLine( ex ); #endif } finally { stdButton = gcnew Button; // Add the Click event handlers. myIconButton->Click += gcnew EventHandler( this, &MyApplication::myIconButton_Click ); stdButton->Click += gcnew EventHandler( this, &MyApplication::stdButton_Click ); // Set the location, text and width of the standard button. stdButton->Location = Point(myIconButton->Location.X,myIconButton->Location.Y + myIconButton->Height + 20); stdButton->Text = "Change Icon"; stdButton->Width = 100; // Add the buttons to the Form. this->Controls->Add( stdButton ); this->Controls->Add( myIconButton ); } } private: void myIconButton_Click( Object^ /*Sender*/, EventArgs^ /*e*/ ) { #undef MessageBox // Make sure MyIconButton works. MessageBox::Show( "MyIconButton was clicked!" ); } void stdButton_Click( Object^ /*Sender*/, EventArgs^ /*e*/ ) { // Use an OpenFileDialog to allow the user to assign a new image to the derived button. openDlg = gcnew OpenFileDialog; openDlg->InitialDirectory = Application::StartupPath; openDlg->Filter = "Icon files (*.ico)|*.ico"; openDlg->Multiselect = false; openDlg->ShowDialog(); if ( !openDlg->FileName->Equals( "" ) ) { myIconButton->Icon = gcnew System::Drawing::Icon( openDlg->FileName ); } } }; int main() { Application::Run( gcnew MyApplication ); } // </snippet2>
23.675
137
0.593875
[ "object" ]
f5b2dc743c68a79aed69845e84026be5666b4a30
5,055
cpp
C++
src/widgets/dialogs/switcher/QuickSwitcherPopup.cpp
pjw20/chatterino2
a52e0eb7f70dbca74f5d2c1945783777de87aeb1
[ "MIT" ]
1
2021-01-25T00:14:46.000Z
2021-01-25T00:14:46.000Z
src/widgets/dialogs/switcher/QuickSwitcherPopup.cpp
pjw20/chatterino2
a52e0eb7f70dbca74f5d2c1945783777de87aeb1
[ "MIT" ]
null
null
null
src/widgets/dialogs/switcher/QuickSwitcherPopup.cpp
pjw20/chatterino2
a52e0eb7f70dbca74f5d2c1945783777de87aeb1
[ "MIT" ]
null
null
null
#include "widgets/dialogs/switcher/QuickSwitcherPopup.hpp" #include "Application.hpp" #include "singletons/Theme.hpp" #include "singletons/WindowManager.hpp" #include "util/LayoutCreator.hpp" #include "widgets/Notebook.hpp" #include "widgets/Window.hpp" #include "widgets/dialogs/switcher/NewTabItem.hpp" #include "widgets/dialogs/switcher/SwitchSplitItem.hpp" #include "widgets/helper/NotebookTab.hpp" #include "widgets/listview/GenericListView.hpp" namespace chatterino { namespace { QSet<SplitContainer *> openPages() { QSet<SplitContainer *> pages; auto &nb = getApp()->windows->getMainWindow().getNotebook(); for (int i = 0; i < nb.getPageCount(); ++i) { pages.insert(static_cast<SplitContainer *>(nb.getPageAt(i))); } return pages; } } // namespace const QSize QuickSwitcherPopup::MINIMUM_SIZE(500, 300); QuickSwitcherPopup::QuickSwitcherPopup(QWidget *parent) : BasePopup(FlagsEnum<BaseWindow::Flags>{BaseWindow::Flags::Frameless, BaseWindow::Flags::TopMost}, parent) , switcherModel_(this) { this->setWindowFlag(Qt::Dialog); this->setActionOnFocusLoss(BaseWindow::ActionOnFocusLoss::Delete); this->setMinimumSize(QuickSwitcherPopup::MINIMUM_SIZE); this->initWidgets(); this->setStayInScreenRect(true); const QRect geom = parent->geometry(); // This places the popup in the middle of the parent widget this->setGeometry(QStyle::alignedRect(Qt::LeftToRight, Qt::AlignCenter, this->size(), geom)); this->themeChangedEvent(); this->installEventFilter(this->ui_.list); } void QuickSwitcherPopup::initWidgets() { LayoutCreator<QWidget> creator(this->BaseWindow::getLayoutContainer()); auto vbox = creator.setLayoutType<QVBoxLayout>(); { auto lineEdit = vbox.emplace<QLineEdit>().assign(&this->ui_.searchEdit); lineEdit->setPlaceholderText("Jump to a channel or open a new one"); QObject::connect(this->ui_.searchEdit, &QLineEdit::textChanged, this, &QuickSwitcherPopup::updateSuggestions); } { auto listView = vbox.emplace<GenericListView>().assign(&this->ui_.list); listView->setModel(&this->switcherModel_); QObject::connect(listView.getElement(), &GenericListView::closeRequested, this, [this] { this->close(); }); this->ui_.searchEdit->installEventFilter(listView.getElement()); } } void QuickSwitcherPopup::updateSuggestions(const QString &text) { this->switcherModel_.clear(); // Add items for navigating to different splits for (auto *sc : openPages()) { const QString &tabTitle = sc->getTab()->getTitle(); const auto splits = sc->getSplits(); // First, check for splits on this page for (auto *split : splits) { if (split->getChannel()->getName().contains(text, Qt::CaseInsensitive)) { auto item = std::make_unique<SwitchSplitItem>(split); this->switcherModel_.addItem(std::move(item)); // We want to continue the outer loop so we need a goto goto nextPage; } } // Then check if tab title matches if (tabTitle.contains(text, Qt::CaseInsensitive)) { auto item = std::make_unique<SwitchSplitItem>(sc); this->switcherModel_.addItem(std::move(item)); continue; } nextPage:; } // Add item for opening a channel in a new tab if (!text.isEmpty()) { auto item = std::make_unique<NewTabItem>(text); this->switcherModel_.addItem(std::move(item)); } const auto &startIdx = this->switcherModel_.index(0); this->ui_.list->setCurrentIndex(startIdx); /* * Timeout interval 0 means the call will be delayed until all window events * have been processed (cf. https://doc.qt.io/qt-5/qtimer.html#interval-prop). */ QTimer::singleShot(0, [this] { this->adjustSize(); }); } void QuickSwitcherPopup::themeChangedEvent() { BasePopup::themeChangedEvent(); const QString textCol = this->theme->window.text.name(); const QString bgCol = this->theme->window.background.name(); const QString selCol = (this->theme->isLightTheme() ? "#68B1FF" // Copied from Theme::splits.input.styleSheet : this->theme->tabs.selected.backgrounds.regular.color().name()); const QString listStyle = QString( "color: %1; background-color: %2; selection-background-color: %3") .arg(textCol) .arg(bgCol) .arg(selCol); this->ui_.searchEdit->setStyleSheet(this->theme->splits.input.styleSheet); this->ui_.list->refreshTheme(*this->theme); } } // namespace chatterino
31.792453
82
0.617409
[ "geometry" ]
f5b5221a40e7afc5bcb033c100d4adaa181de776
10,856
cpp
C++
lib/internal/NodeBlock.cpp
tmkasun/streaming_graph_store
f39548eda3b7819ca8fb0f41b4e12355aed2e3bf
[ "MIT" ]
7
2019-11-06T12:25:52.000Z
2022-03-03T06:44:47.000Z
lib/internal/NodeBlock.cpp
tmkasun/streaming_graph_store
f39548eda3b7819ca8fb0f41b4e12355aed2e3bf
[ "MIT" ]
3
2022-02-14T09:05:44.000Z
2022-02-27T15:13:56.000Z
libs/graphStore/NodeBlock.cpp
tmkasun/streaming_graph_partitioning
fd89bb64d1e3ec53ff80e8e376edd4bfd4d4073a
[ "Apache-2.0" ]
1
2022-01-13T09:55:39.000Z
2022-01-13T09:55:39.000Z
/** Copyright 2020 JasmineGraph Team Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. **/ #include "NodeBlock.h" #include <sstream> #include <vector> #include "../../util/logger/Logger.h" #include "RelationBlock.h" Logger node_block_logger; NodeBlock::NodeBlock(std::string id, unsigned int address, unsigned int propRef, unsigned int edgeRef, char _label[], bool usage) : id(id), addr(address), propRef(propRef), edgeRef(edgeRef), usage(usage) { strcpy(label, _label); }; bool NodeBlock::isInUse() { return this->usage == '\1'; } std::string NodeBlock::getLabel() { return std::string(this->label); } void NodeBlock::save() { char _label[PropertyLink::MAX_VALUE_SIZE] = {0}; std::strcpy(_label, id.c_str()); bool isSmallLabel = id.length() <= sizeof(label); if (isSmallLabel) { std::strcpy(this->label, this->id.c_str()); } NodeBlock::nodesDB->seekp(this->addr); NodeBlock::nodesDB->put(this->usage); NodeBlock::nodesDB->write(reinterpret_cast<char*>(&(this->edgeRef)), sizeof(this->edgeRef)); NodeBlock::nodesDB->write(reinterpret_cast<char*>(&(this->propRef)), sizeof(this->propRef)); NodeBlock::nodesDB->write(this->label, sizeof(this->label)); NodeBlock::nodesDB->flush(); // Sync the file with in-memory stream if (!isSmallLabel) { this->addProperty("label", _label); } } void NodeBlock::addProperty(std::string name, char* value) { if (this->propRef == 0) { PropertyLink* newLink = PropertyLink::create(name, value); if (newLink) { this->propRef = newLink->blockAddress; // If it was an empty prop link before inserting, Then update the property reference of this node // block NodeBlock::nodesDB->seekp(this->addr + 1 + sizeof(this->edgeRef)); NodeBlock::nodesDB->write(reinterpret_cast<char*>(&(this->propRef)), sizeof(this->propRef)); NodeBlock::nodesDB->flush(); } else { throw "Error occurred while adding a new property link to " + std::to_string(this->addr) + " node block"; } } else { this->propRef = this->getPropertyHead()->insert(name, value); } } bool NodeBlock::updateRelation(RelationBlock* newRelation, bool relocateHead) { unsigned int edgeReferenceAddress = newRelation->addr; unsigned int thisAddress = this->addr; RelationBlock* currentHead = this->getRelationHead(); if (relocateHead) { // Insert new relation link to the head of the link list if (currentHead) { if (thisAddress == currentHead->source.address) { currentHead->setPreviousSource(newRelation->addr); } else if (thisAddress == currentHead->destination.address) { currentHead->setPreviousDestination(newRelation->addr); } else { throw std::to_string(thisAddress) + " relation head does not contain current node in its source or destination"; } if (thisAddress == newRelation->source.address) { newRelation->setNextSource(currentHead->addr); } else if (thisAddress == newRelation->destination.address) { newRelation->setNextDestination(currentHead->addr); } else { throw std::to_string(thisAddress) + " new relation does not contain current node in its source or destination"; } } return this->setRelationHead(*newRelation); } else { RelationBlock* currentRelation = currentHead; while (currentRelation != NULL) { if (currentRelation->source.address == this->addr) { if (currentRelation->source.nextRelationId == 0) { return currentRelation->setNextSource(edgeReferenceAddress); } else { currentRelation = currentRelation->nextSource(); } } else if (!this->isDirected && currentRelation->destination.address == this->addr) { if (currentRelation->destination.nextRelationId == 0) { return currentRelation->setNextDestination(edgeReferenceAddress); } else { currentRelation = currentRelation->nextDestination(); } } else { node_block_logger.warn("Invalid relation block" + std::to_string(currentRelation->addr)); } } return false; } return false; } RelationBlock* NodeBlock::getRelationHead() { RelationBlock* relationsHead = NULL; if (this->edgeRef != 0) { relationsHead = RelationBlock::get(this->edgeRef); } return relationsHead; }; bool NodeBlock::setRelationHead(RelationBlock newRelation) { unsigned int edgeReferenceAddress = newRelation.addr; int edgeReferenceOffset = sizeof(this->usage); NodeBlock::nodesDB->seekp(this->addr + edgeReferenceOffset); if (!NodeBlock::nodesDB->write(reinterpret_cast<char*>(&(edgeReferenceAddress)), sizeof(unsigned int))) { node_block_logger.error("ERROR: Error while updating edge reference address of " + std::to_string(edgeReferenceAddress) + " for node " + std::to_string(this->addr)); return false; } NodeBlock::nodesDB->flush(); // Sync the file with in-memory stream this->edgeRef = edgeReferenceAddress; return true; } /** * Return a pointer to matching relation block with the given node if found, Else return NULL * **/ RelationBlock* NodeBlock::searchRelation(NodeBlock withNode) { RelationBlock* found = NULL; RelationBlock* currentRelation = this->getRelationHead(); while (currentRelation) { if (currentRelation->source.address == this->addr) { if (currentRelation->destination.address == withNode.addr) { found = currentRelation; break; } else { currentRelation = currentRelation->nextSource(); } } else if (!this->isDirected && (currentRelation->destination.address == this->addr)) { if (currentRelation->source.address == withNode.addr) { found = currentRelation; break; } else { currentRelation = currentRelation->nextDestination(); } } else { throw "Exception: Unrelated relation block for " + std::to_string(this->addr) + " found in relation block " + std::to_string(currentRelation->addr); } } return found; } std::list<NodeBlock> NodeBlock::getEdges() { std::list<NodeBlock> edges; RelationBlock* currentRelation = this->getRelationHead(); while (currentRelation != NULL) { NodeBlock* node = NULL; if (currentRelation->source.address == this->addr) { node = NodeBlock::get(currentRelation->destination.address); currentRelation = currentRelation->nextSource(); } else if (currentRelation->destination.address == this->addr) { node = NodeBlock::get(currentRelation->source.address); currentRelation = currentRelation->nextDestination(); } else { throw "Error: Unrecognized relation for " + std::to_string(this->addr) + " in relation block " + std::to_string(currentRelation->addr); } if (!node) { throw "Error creating node in the relation"; } edges.push_back(*node); } return edges; } std::map<std::string, char*> NodeBlock::getAllProperties() { std::map<std::string, char*> allProperties; PropertyLink* current = this->getPropertyHead(); while (current) { allProperties.insert({current->name, current->value}); PropertyLink* temp = current->next(); delete current; // To prevent memory leaks current = temp; } delete current; return allProperties; } NodeBlock* NodeBlock::get(unsigned int blockAddress) { NodeBlock* nodeBlockPointer = NULL; NodeBlock::nodesDB->seekg(blockAddress); unsigned int edgeRef; unsigned int propRef; char usageBlock; char label[NodeBlock::LABEL_SIZE]; std::string id; if (!NodeBlock::nodesDB->get(usageBlock)) { node_block_logger.error("Error while reading usage data from block " + std::to_string(blockAddress)); } if (!NodeBlock::nodesDB->read(reinterpret_cast<char*>(&edgeRef), sizeof(unsigned int))) { node_block_logger.error("Error while reading edge reference data from block " + std::to_string(blockAddress)); } if (!NodeBlock::nodesDB->read(reinterpret_cast<char*>(&propRef), sizeof(unsigned int))) { node_block_logger.error("Error while reading prop reference data from block " + std::to_string(blockAddress)); } if (!NodeBlock::nodesDB->read(&label[0], NodeBlock::LABEL_SIZE)) { node_block_logger.error("Error while reading label data from block " + std::to_string(blockAddress)); } bool usage = usageBlock == '\1'; node_block_logger.debug("Label = " + std::string(label)); node_block_logger.debug("Label = " + std::string(label)); node_block_logger.debug("Length of label = " + std::to_string(strlen(label))); node_block_logger.debug("edgeRef = " + std::to_string(edgeRef)); if (strlen(label) != 0) { id = std::string(label); } nodeBlockPointer = new NodeBlock(id, blockAddress, propRef, edgeRef, label, usage); if (nodeBlockPointer->id.length() == 0) { // if label not found in node block look in the properties std::map<std::string, char*> props = nodeBlockPointer->getAllProperties(); if (props["label"]) { nodeBlockPointer->id = props["label"]; } else { throw "Could not find node ID/Label for node with block address = " + std::to_string(nodeBlockPointer->addr); } } node_block_logger.debug("Edge ref = " + std::to_string(nodeBlockPointer->edgeRef)); if (nodeBlockPointer->edgeRef % RelationBlock::BLOCK_SIZE != 0) { throw "Exception: Invalid edge reference address = " + nodeBlockPointer->edgeRef; } return nodeBlockPointer; } PropertyLink* NodeBlock::getPropertyHead() { return PropertyLink::get(this->propRef); } std::fstream* NodeBlock::nodesDB = NULL;
42.241245
118
0.636791
[ "vector" ]
f5ba4d2899dfc0defea7e1609e0da883628d45c0
9,590
cpp
C++
Alien Engine/Alien Engine/ResourcePrefab.cpp
VictorSegura99/GameEngine_CITM
195295bc86e9623895ac07774c3d2489e2d1c4f6
[ "MIT" ]
11
2019-10-14T00:37:28.000Z
2020-05-10T23:13:30.000Z
Alien Engine/Alien Engine/ResourcePrefab.cpp
VictorSegura99/GameEngine_CITM
195295bc86e9623895ac07774c3d2489e2d1c4f6
[ "MIT" ]
null
null
null
Alien Engine/Alien Engine/ResourcePrefab.cpp
VictorSegura99/GameEngine_CITM
195295bc86e9623895ac07774c3d2489e2d1c4f6
[ "MIT" ]
5
2019-10-12T17:59:37.000Z
2020-03-17T10:13:57.000Z
#include "ResourcePrefab.h" #include "Application.h" #include "ModuleObjects.h" #include "ComponentLight.h" #include "ComponentTransform.h" #include "PanelHierarchy.h" ResourcePrefab::ResourcePrefab() : Resource() { type = ResourceType::RESOURCE_PREFAB; } ResourcePrefab::~ResourcePrefab() { prefab_references.clear(); } bool ResourcePrefab::CreateMetaData(GameObject* object, const char* folder, u64 force_id) { std::vector<std::string> files; std::vector<std::string> dir; if (folder == nullptr) { path = std::string(ASSETS_PREFAB_FOLDER + std::string(object->GetName()) + ".alienPrefab"); App->file_system->DiscoverFiles(ASSETS_PREFAB_FOLDER, files, dir); } else { path = std::string(std::string(folder) + std::string(object->GetName()) + ".alienPrefab"); App->file_system->DiscoverFiles(folder, files, dir); } if (force_id != 0) { ID = force_id; } else { ID = App->resources->GetRandomID(); } if (!files.empty()) { uint num_file = 0; for (uint i = 0; i < files.size(); ++i) { if (App->StringCmp(files[i].data(), App->file_system->GetBaseFileNameWithExtension(path.data()).data())) { ++num_file; if (folder == nullptr) { path = std::string(ASSETS_PREFAB_FOLDER + std::string(object->GetName()) + " (" + std::to_string(num_file) + ")" + ".alienPrefab"); } else { path = std::string(std::string(folder) + std::string(object->GetName()) + " (" + std::to_string(num_file) + ")" + ".alienPrefab"); } i = -1; } } } JSON_Value* value = json_value_init_object(); JSON_Object* json_object = json_value_get_object(value); json_serialize_to_file_pretty(value, path.data()); if (value != nullptr && json_object != nullptr) { // save ID in assets JSONfilepack* prefab_scene = new JSONfilepack(path.data(), json_object, value); prefab_scene->StartSave(); SetName(App->file_system->GetBaseFileName(path.data()).data()); // save prefab in library meta_data_path = path; object->SetPrefab(ID); JSONArraypack* game_objects = prefab_scene->InitNewArray("Prefab.GameObjects"); game_objects->SetAnotherNode(); App->objects->SaveGameObject(object, game_objects, 1); prefab_scene->FinishSave(); delete prefab_scene; App->resources->AddResource(this); std::string meta_path = App->file_system->GetPathWithoutExtension(path) + "_meta.alien"; JSON_Value* meta_value = json_value_init_object(); JSON_Object* meta_object = json_value_get_object(meta_value); json_serialize_to_file_pretty(meta_value, meta_path.data()); if (meta_value != nullptr && meta_object != nullptr) { JSONfilepack* meta = new JSONfilepack(meta_path.data(), meta_object, meta_value); meta->StartSave(); meta->SetString("Meta.ID", std::to_string(ID)); meta->FinishSave(); delete meta; meta_data_path = LIBRARY_PREFABS_FOLDER + std::to_string(ID) + ".alienPrefab"; App->file_system->Copy(path.data(), meta_data_path.data()); } } else { LOG_ENGINE("Could not load scene, fail when creating the file"); } return true; } bool ResourcePrefab::ReadBaseInfo(const char* assets_file_path) { path = std::string(assets_file_path); // TODO: change when loading game ID = App->resources->GetIDFromAlienPath(std::string(App->file_system->GetPathWithoutExtension(path) + "_meta.alien").data()); if (ID != 0) { meta_data_path = LIBRARY_PREFABS_FOLDER + std::to_string(ID) + ".alienPrefab"; if (!App->file_system->Exists(meta_data_path.data())) { App->file_system->Copy(path.data(), meta_data_path.data()); } else { // TODO: look what to do when game mode struct stat meta_file; struct stat assets_file; stat(path.data(), &assets_file); stat(meta_data_path.data(), &meta_file); if (assets_file.st_mtime != meta_file.st_mtime) { remove(meta_data_path.data()); App->file_system->Copy(path.data(), meta_data_path.data()); } } SetName(App->file_system->GetBaseFileName(path.data()).data()); App->resources->AddResource(this); } return true; } void ResourcePrefab::ReadLibrary(const char* meta_data) { meta_data_path = std::string(meta_data); ID = std::stoull(App->file_system->GetBaseFileName(meta_data_path.data())); App->resources->AddResource(this); } bool ResourcePrefab::DeleteMetaData() { if (App->objects->prefab_scene && App->objects->prefab_opened == this) { App->objects->LoadScene("Library/save_prefab_scene.alienScene", false); App->objects->prefab_opened = nullptr; App->objects->prefab_scene = false; App->objects->enable_instancies = true; App->objects->SwapReturnZ(true, true); } remove(meta_data_path.data()); App->objects->GetRoot(true)->UnpackAllPrefabsOf(ID); return true; } void ResourcePrefab::Save(GameObject* prefab_root) { remove(meta_data_path.data()); remove(path.data()); JSON_Value* prefab_value = json_value_init_object(); JSON_Object* prefab_object = json_value_get_object(prefab_value); json_serialize_to_file_pretty(prefab_value, path.data()); prefab_root->SetPrefab(ID); if (prefab_value != nullptr && prefab_object != nullptr) { JSONfilepack* prefab = new JSONfilepack(path.data(), prefab_object, prefab_value); prefab->StartSave(); JSONArraypack* game_objects = prefab->InitNewArray("Prefab.GameObjects"); game_objects->SetAnotherNode(); App->objects->SaveGameObject(prefab_root, game_objects, 1); prefab->FinishSave(); App->file_system->Copy(path.data(), meta_data_path.data()); delete prefab; } if (App->objects->prefab_scene) { App->objects->prefab_opened = nullptr; App->objects->prefab_scene = false; App->objects->SwapReturnZ(true, true); App->objects->LoadScene("Library/save_prefab_scene.alienScene", false); App->objects->enable_instancies = true; remove("Library/save_prefab_scene.alienScene"); } App->objects->ignore_cntrlZ = true; App->objects->in_cntrl_Z = true; std::vector<GameObject*> objs; App->objects->GetRoot(true)->GetObjectWithPrefabID(ID, &objs); if (!objs.empty()) { std::vector<GameObject*>::iterator item = objs.begin(); for (; item != objs.end(); ++item) { if (*item != nullptr && !(*item)->prefab_locked && (*item) != prefab_root) { GameObject* parent = (*item)->parent; std::vector<GameObject*>::iterator iter = parent->children.begin(); for (; iter != parent->children.end(); ++iter) { if (*iter == (*item)) { (*item)->ToDelete(); float3 pos = static_cast<ComponentTransform*>((*item)->GetComponent(ComponentType::TRANSFORM))->GetLocalPosition(); ConvertToGameObjects(parent, iter - parent->children.begin(), pos, false); break; } } } } } App->objects->in_cntrl_Z = false; App->objects->ignore_cntrlZ = false; } void ResourcePrefab::OpenPrefabScene() { if (Time::IsInGameState()) { App->ui->panel_hierarchy->popup_no_open_prefab = true; return; } if (App->objects->prefab_scene) { return; } App->objects->prefab_opened = this; App->objects->enable_instancies = false; App->objects->SwapReturnZ(false, false); App->objects->prefab_scene = true; App->objects->SaveScene(nullptr, "Library/save_prefab_scene.alienScene"); App->objects->DeselectObjects(); App->objects->CreateRoot(); ConvertToGameObjects(App->objects->GetRoot(true)); } void ResourcePrefab::ConvertToGameObjects(GameObject* parent, int list_num, float3 pos, bool set_selected) { JSON_Value* value = json_parse_file(meta_data_path.data()); JSON_Object* object = json_value_get_object(value); if (value != nullptr && object != nullptr) { JSONfilepack* prefab = new JSONfilepack(meta_data_path.data(), object, value); JSONArraypack* game_objects = prefab->GetArray("Prefab.GameObjects"); // first is family number, second parentID, third is array index in the json file std::vector<std::tuple<uint, u64, uint>> objects_to_create; for (uint i = 0; i < game_objects->GetArraySize(); ++i) { uint family_number = game_objects->GetNumber("FamilyNumber"); u64 parentID = std::stoull(game_objects->GetString("ParentID")); objects_to_create.push_back({ family_number,parentID, i }); game_objects->GetAnotherNode(); } std::sort(objects_to_create.begin(), objects_to_create.end(), ModuleObjects::SortByFamilyNumber); game_objects->GetFirstNode(); std::vector<GameObject*> objects_created; std::vector<std::tuple<uint, u64, uint>>::iterator item = objects_to_create.begin(); for (; item != objects_to_create.end(); ++item) { game_objects->GetNode(std::get<2>(*item)); GameObject* obj = new GameObject(); if (std::get<0>(*item) == 1) { obj->LoadObject(game_objects, parent, !set_selected); } else { // search parent std::vector<GameObject*>::iterator objects = objects_created.begin(); for (; objects != objects_created.end(); ++objects) { if ((*objects)->ID == std::get<1>(*item)) { obj->LoadObject(game_objects, *objects, !set_selected); break; } } } objects_created.push_back(obj); } GameObject* obj = parent->children.back(); if (list_num != -1) { parent->children.pop_back(); parent->children.insert(parent->children.begin() + list_num, obj); } obj->ResetIDs(); obj->SetPrefab(ID); ComponentTransform* transform = (ComponentTransform*)(obj)->GetComponent(ComponentType::TRANSFORM); transform->SetLocalPosition(pos.x, pos.y, pos.z); if (set_selected) { App->objects->SetNewSelectedObject(obj); App->camera->fake_camera->Look(parent->children.back()->GetBB().CenterPoint()); App->camera->reference = parent->children.back()->GetBB().CenterPoint(); } delete prefab; } else { LOG_ENGINE("Error loading prefab %s", path.data()); } }
32.508475
136
0.699166
[ "object", "vector", "transform" ]
f5bd26a46fd3731d70dcbd1e894dc51df0320363
2,504
cpp
C++
eth_udp/src/main_eth_udp.cpp
nvitya/vihaltests
ee6e0be1208bed91971d3525a521213af57c4296
[ "BSD-2-Clause" ]
null
null
null
eth_udp/src/main_eth_udp.cpp
nvitya/vihaltests
ee6e0be1208bed91971d3525a521213af57c4296
[ "BSD-2-Clause" ]
null
null
null
eth_udp/src/main_eth_udp.cpp
nvitya/vihaltests
ee6e0be1208bed91971d3525a521213af57c4296
[ "BSD-2-Clause" ]
2
2022-01-05T01:53:54.000Z
2022-03-14T19:58:29.000Z
/* * file: main_eth_raw.cpp * brief: Raw Ethernet example for VIHAL * created: 2022-03-14 * authors: nvitya * * description: * */ #include "platform.h" #include "hwpins.h" #include "hwclk.h" #include "hwuart.h" #include "cppinit.h" #include "clockcnt.h" #include "hwusbctrl.h" #include "board_pins.h" #include "udp_test.h" #include "traces.h" volatile unsigned hbcounter = 0; extern "C" __attribute__((noreturn)) void _start(unsigned self_flashing) // self_flashing = 1: self-flashing required for RAM-loaded applications { // after ram setup and region copy the cpu jumps here, with probably RC oscillator // Set the interrupt vector table offset, so that the interrupts and exceptions work mcu_init_vector_table(); // run the C/C++ initialization (variable initializations, constructors) cppinit(); #if defined(MCU_FIXED_SPEED) SystemCoreClock = MCU_FIXED_SPEED; #else #if 0 SystemCoreClock = MCU_INTERNAL_RC_SPEED; #else //if (!hwclk_init(0, MCU_CLOCK_SPEED)) // if the EXTERNAL_XTAL_HZ == 0, then the internal RC oscillator will be used //if (!hwclk_init(EXTERNAL_XTAL_HZ, 72000000)) // special for STM32F3, STM32F1 if (!hwclk_init(EXTERNAL_XTAL_HZ, MCU_CLOCK_SPEED)) // if the EXTERNAL_XTAL_HZ == 0, then the internal RC oscillator will be used { while (1) { // error } } #endif #endif mcu_enable_fpu(); // enable coprocessor if present mcu_enable_icache(); // enable instruction cache if present clockcnt_init(); // go on with the hardware initializations board_pins_init(); traces_init(); //tracebuf.waitsend = false; // force to buffered mode (default) //tracebuf.waitsend = true; // better for basic debugging TRACE("\r\n--------------------------------------\r\n"); TRACE("VIHAL UDP Network Stack Test\r\n"); TRACE("Board: %s\r\n", BOARD_NAME); TRACE("SystemCoreClock: %u\r\n", SystemCoreClock); TRACE_FLUSH(); mcu_interrupts_enable(); udp_test_init(); TRACE("\r\nStarting main cycle...\r\n"); unsigned hbclocks = SystemCoreClock / 2; unsigned t0, t1; t0 = CLOCKCNT; // Infinite loop while (1) { t1 = CLOCKCNT; udp_test_run(); tracebuf.Run(); if (t1-t0 > hbclocks) { ++hbcounter; for (unsigned n = 0; n < pin_led_count; ++n) { pin_led[n].SetTo((hbcounter >> n) & 1); } t0 = t1; } } } // ----------------------------------------------------------------------------
22.558559
146
0.63139
[ "vector" ]
f5bd5035e096b9ecdab34d918e5e0bc16845f5af
19,972
cpp
C++
Engine/Source/ThirdParty/Oculus/LibOVRMobile/LibOVRMobile_050/VRLib/jni/VrApi/Sensors/OVR_SensorFusion.cpp
PopCap/GameIdea
201e1df50b2bc99afc079ce326aa0a44b178a391
[ "BSD-2-Clause" ]
null
null
null
Engine/Source/ThirdParty/Oculus/LibOVRMobile/LibOVRMobile_050/VRLib/jni/VrApi/Sensors/OVR_SensorFusion.cpp
PopCap/GameIdea
201e1df50b2bc99afc079ce326aa0a44b178a391
[ "BSD-2-Clause" ]
2
2015-06-21T17:38:11.000Z
2015-06-22T20:54:42.000Z
Engine/Source/ThirdParty/Oculus/LibOVRMobile/LibOVRMobile_050/VRLib/jni/VrApi/Sensors/OVR_SensorFusion.cpp
PopCap/GameIdea
201e1df50b2bc99afc079ce326aa0a44b178a391
[ "BSD-2-Clause" ]
null
null
null
/************************************************************************************ Filename : OVR_SensorFusion.cpp Content : Methods that determine head orientation from sensor data over time Created : October 9, 2012 Authors : Michael Antonov, Steve LaValle, Dov Katz, Max Katsev, Dan Gierl Copyright : Copyright 2014 Oculus VR, LLC. All Rights reserved. *************************************************************************************/ #include "OVR_SensorFusion.h" #include "Kernel/OVR_Log.h" #include "Kernel/OVR_System.h" #include "Kernel/OVR_JSON.h" //#define YAW_LOGGING namespace OVR { //------------------------------------------------------------------------------------- // ***** Sensor Fusion SensorFusion::SensorFusion(SensorDevice* sensor) : ApplyDrift(false), FAccelHeadset(1000), FAngV(20), MotionTrackingEnabled(true), EnableGravity(true), EnableYawCorrection(true), FocusDirection(Vector3f(0, 0, 0)), FocusFOV(0.0), RecenterTransform() { OVR_DEBUG_LOG(("SensorFusion::SensorFusion")); pHandler = new BodyFrameHandler(this); if (sensor) { AttachToSensor(sensor); } Reset(); } SensorFusion::~SensorFusion() { delete pHandler; } bool SensorFusion::AttachToSensor(SensorDevice* sensor) { if (sensor != NULL) { MessageHandler* pCurrentHandler = sensor->GetMessageHandler(); if (pCurrentHandler == pHandler) { Reset(); return true; } if (pCurrentHandler != NULL) { OVR_DEBUG_LOG( ("SensorFusion::AttachToSensor failed - sensor %p already has handler", sensor)); return false; } } if (pHandler->IsHandlerInstalled()) { pHandler->RemoveHandlerFromDevices(); } if (sensor != NULL) { sensor->SetMessageHandler(pHandler); } Reset(); return true; } void SensorFusion::Reset() { Lock::Locker lockScope(pHandler->GetHandlerLock()); UpdatedState.SetState(StateForPrediction()); State = PoseStatef(); Stage = 0; MagRefs.Clear(); MagRefIdx = -1; MagCorrectionIntegralTerm = 0.0f; MagLatencyCompBufferIndex = 0; MagLatencyCompFillCount = 0; YawCorrectionTimer = 0.0f; FAccelHeadset.Clear(); FAngV.Clear(); } float SensorFusion::GetYaw() { // get the current state const StateForPrediction state = UpdatedState.GetState(); // get the yaw in the current state float yaw, pitch, roll; state.State.Transform.Orientation.GetEulerAngles< Axis_Y, Axis_X, Axis_Z >( &yaw, &pitch, &roll ); return yaw; } void SensorFusion::SetYaw( float newYaw ) { // get the current state const StateForPrediction state = UpdatedState.GetState(); // get the yaw in the current state float yaw, pitch, roll; state.State.Transform.Orientation.GetEulerAngles< Axis_Y, Axis_X, Axis_Z >( &yaw, &pitch, &roll ); // get the pose that adjusts the yaw Posef yawAdjustment( Quatf( Axis_Y, newYaw - yaw ), Vector3f( 0.0f ) ); // To allow SetYaw() to be called from multiple threads we need a mutex // because LocklessUpdater is only safe for single producer cases. RecenterMutex.DoLock(); RecenterTransform.SetState( yawAdjustment ); RecenterMutex.Unlock(); } void SensorFusion::RecenterYaw() { // get the current state const StateForPrediction state = UpdatedState.GetState(); // get the yaw in the current state float yaw, pitch, roll; state.State.Transform.Orientation.GetEulerAngles< Axis_Y, Axis_X, Axis_Z >( &yaw, &pitch, &roll ); // get the pose that adjusts the yaw Posef yawAdjustment( Quatf( Axis_Y, -yaw ), Vector3f( 0.0f ) ); // To allow RecenterYaw() to be called from multiple threads we need a mutex // because LocklessUpdater is only safe for single producer cases. RecenterMutex.DoLock(); RecenterTransform.SetState( yawAdjustment ); RecenterMutex.Unlock(); } void SensorFusion::handleMessage(const MessageBodyFrame& msg) { if (msg.Type != Message_BodyFrame || !IsMotionTrackingEnabled()) return; if (msg.Acceleration == Vector3f::ZERO) return; // Put the sensor readings into convenient local variables Vector3f gyro(msg.RotationRate); Vector3f accel(msg.Acceleration); Vector3f mag(msg.MagneticField); Vector3f magBias(msg.MagneticBias); float DeltaT = msg.TimeDelta; // Keep track of time State.TimeInSeconds = msg.AbsoluteTimeSeconds; Stage++; // Insert current sensor data into filter history FAngV.PushBack(gyro); FAccelHeadset.Update(accel, DeltaT, Quatf(gyro, gyro.Length() * DeltaT)); // Process raw inputs State.AngularVelocity = gyro; State.LinearAcceleration = State.Transform.Orientation.Rotate(accel) - Vector3f(0, 9.8f, 0); // Update headset orientation float angle = gyro.Length() * DeltaT; if (angle > 0) State.Transform.Orientation = State.Transform.Orientation * Quatf(gyro, angle); // Tilt correction based on accelerometer if (EnableGravity) applyTiltCorrection(DeltaT); // Yaw correction based on magnetometer if (EnableYawCorrection && HasMagCalibration()) applyMagYawCorrection(mag, magBias, gyro, DeltaT); /* // Focus Correction if ((FocusDirection.x != 0.0f || FocusDirection.z != 0.0f) && FocusFOV < Mathf::Pi) applyFocusCorrection(DeltaT); */ // The quaternion magnitude may slowly drift due to numerical error, // so it is periodically normalized. if ((Stage & 0xFF) == 0) State.Transform.Orientation.Normalize(); // Update headset position { EnableGravity = true; EnableYawCorrection = true; // TBD apply neck model here State.LinearVelocity.x = State.LinearVelocity.y = State.LinearVelocity.z = 0.0f; State.Transform.Position.x = State.Transform.Position.y = State.Transform.Position.z = 0.0f; } // Compute the angular acceleration State.AngularAcceleration = (FAngV.GetSize() >= 12 && DeltaT > 0) ? (FAngV.SavitzkyGolayDerivative12() / DeltaT) : Vector3f(); // Store the lockless state. StateForPrediction state; state.State = State; state.Temperature = msg.Temperature; UpdatedState.SetState(state); } // These two functions need to be moved into Quat class // Compute a rotation required to Pose "from" into "to". Quatf vectorAlignmentRotation(const Vector3f &from, const Vector3f &to) { Vector3f axis = from.Cross(to); if (axis.LengthSq() == 0) // this handles both collinear and zero-length input cases return Quatf(); float angle = from.Angle(to); return Quatf(axis, angle); } bool SensorFusion::getBufferedOrientation(Quatf* orientation, const Vector3f& gyro, float gyroThreshold, float deltaT) { MagLatencyCompBuffer[MagLatencyCompBufferIndex].Orientation = State.Transform.Orientation; MagLatencyCompBuffer[MagLatencyCompBufferIndex].GyroMagnitude = gyro.Length(); MagLatencyCompBufferIndex++; if (MagLatencyCompBufferIndex >= MagLatencyBufferSizeMax) { MagLatencyCompBufferIndex = 0; } // Determine how far to look back in buffer. int backDist = (int) ((float) MagLatencyCompensationMilliseconds / (1000.0f * deltaT)); backDist = Alg::Min(backDist, MagLatencyBufferSizeMax-1); if (MagLatencyCompFillCount < MagLatencyBufferSizeMax) { MagLatencyCompFillCount++; } if (MagLatencyCompFillCount <= backDist) { // Haven't buffered enough yet. #ifdef YAW_LOGGING LogText("YAW - Not buffered enough orientation values.\n"); #endif return false; } int readIndex = MagLatencyCompBufferIndex - backDist; if (readIndex < 0) { readIndex += MagLatencyBufferSizeMax; } *orientation = MagLatencyCompBuffer[readIndex].Orientation; // Check to see if the angular velocity was too high. float gyroMagnitude = MagLatencyCompBuffer[readIndex].GyroMagnitude; if (gyroMagnitude > gyroThreshold) { #ifdef YAW_LOGGING LogText("YAW - Angular velocity too high.\n"); #endif return false; } return true; } void SensorFusion::applyMagYawCorrection(const Vector3f& magUncalibrated, const Vector3f& magBias, const Vector3f& gyro, float deltaT) { const float minMagLengthSq = Mathd::Tolerance; // need to use a real value to discard very weak fields const float maxAngleRefDist = 5.0f * Mathf::DegreeToRadFactor; const float maxTiltError = 0.05f; const float correctionDegreesPerSecMax = 0.07f; const float correctionRadPerSecMax = correctionDegreesPerSecMax * Mathf::DegreeToRadFactor; const float proportionalGain = correctionDegreesPerSecMax / 5.0f; // When we had the integral term we used a proportional gain value of 0.01. // When the integral term was removed and the max correction clipped, the // gain was altered to provided the clipped amount at 5 degrees of error. const float tiltStabilizeTimeSeconds = 5.0f; const int maxRefPointScore = 5000; // If angular velocity is above this then we don't perform mag yaw correction. This is because error grows // due to our approximate latency compensation and because of latency due to the mag sample rate being 100Hz // rather than 1kHz for other sensors. 100Hz => 10mS latency @ 200 deg/s = 2 degrees error. const float gyroThreshold = 200.0f * Mathf::DegreeToRadFactor; if (magBias == Vector3f::ZERO) { // Assume Android calibration has not yet occurred. #ifdef YAW_LOGGING LogText("YAW - Android calibration not occurred.\n"); #endif return; } // Buffer orientation since mag latency is higher than HMT sensor latency. Quatf orientation; if (!getBufferedOrientation(&orientation, gyro, gyroThreshold, deltaT)) { return; } // Wait a while for tilt to stabilize. YawCorrectionTimer += deltaT; if (YawCorrectionTimer < tiltStabilizeTimeSeconds) { #ifdef YAW_LOGGING LogText("YAW - Waiting for tilt to stabilize.\n"); #endif return; } Vector3f magCalibrated = magUncalibrated - magBias; Vector3f magInWorldFrame = orientation.Rotate(magCalibrated); // Verify that the horizontal component is sufficient. if (magInWorldFrame.x * magInWorldFrame.x + magInWorldFrame.z * magInWorldFrame.z < minMagLengthSq) { #ifdef YAW_LOGGING LogText("YAW - Field horizontal component too small.\n"); #endif return; } magInWorldFrame.Normalize(); // Delete a bad point if (MagRefIdx >= 0 && MagRefs[MagRefIdx].Score < 0) { #ifdef YAW_LOGGING LogText("YAW - Deleted ref point %d\n", MagRefIdx); #endif MagRefs.RemoveAtUnordered(MagRefIdx); MagRefIdx = -1; } // Update the reference point if needed if (MagRefIdx < 0 || orientation.Angle(MagRefs[MagRefIdx].WorldFromImu) > maxAngleRefDist) { // Find a new one MagRefIdx = -1; float bestDist = maxAngleRefDist; for (UPInt i = 0; i < MagRefs.GetSize(); ++i) { float dist = orientation.Angle(MagRefs[i].WorldFromImu); if (bestDist > dist) { bestDist = dist; MagRefIdx = i; } } #ifdef YAW_LOGGING if (MagRefIdx != -1) { LogText("YAW - Switched to ref point %d\n", MagRefIdx); } #endif // Create one if needed if (MagRefIdx < 0 && MagRefs.GetSize() < MagMaxReferences) { MagRefs.PushBack(MagReferencePoint(magUncalibrated, orientation, 1000)); #ifdef YAW_LOGGING LogText("YAW - Created ref point [%d] %f %f %f\n", MagRefs.GetSize()-1, magUncalibrated.x, magUncalibrated.y, magUncalibrated.z); #endif } } if (MagRefIdx >= 0) { Vector3f magRefInWorldFrame = MagRefs[MagRefIdx].WorldFromImu.Rotate(MagRefs[MagRefIdx].MagUncalibratedInImuFrame-magBias); // Verify that the horizontal component is sufficient when using current bias. if (magRefInWorldFrame.x * magRefInWorldFrame.x + magRefInWorldFrame.z * magRefInWorldFrame.z < minMagLengthSq) { #ifdef YAW_LOGGING LogText("YAW - Calibrated ref point field horizontal component too small.\n"); #endif return; } magRefInWorldFrame.Normalize(); // If the vertical angle is wrong, decrease the score and do nothing. if (Alg::Abs(magRefInWorldFrame.y - magInWorldFrame.y) > maxTiltError) { MagRefs[MagRefIdx].Score -= 1; #ifdef YAW_LOGGING LogText("YAW - Decrement ref point score %d\n", MagRefs[MagRefIdx].Score); #endif return; } if (MagRefs[MagRefIdx].Score < maxRefPointScore) { MagRefs[MagRefIdx].Score += 2; } // Correction is computed in the horizontal plane magInWorldFrame.y = magRefInWorldFrame.y = 0; // Don't need to check for zero vectors since we already validated horizontal components above. float yawError = magInWorldFrame.Angle(magRefInWorldFrame); if (magInWorldFrame.Cross(magRefInWorldFrame).y < 0.0f) { yawError *= -1.0f; } float propCorrectionRadPerSec = yawError * proportionalGain; float totalCorrectionRadPerSec = propCorrectionRadPerSec; // Limit correction. totalCorrectionRadPerSec = Alg::Min(totalCorrectionRadPerSec, correctionRadPerSecMax); totalCorrectionRadPerSec = Alg::Max(totalCorrectionRadPerSec, -correctionRadPerSecMax); Quatf correction(Vector3f(0.0f, 1.0f, 0.0f), totalCorrectionRadPerSec * deltaT); State.Transform.Orientation = correction * State.Transform.Orientation; #ifdef YAW_LOGGING static int logCount = 0; static int lastLogCount = 0; logCount++; if (logCount - lastLogCount > 1000) { lastLogCount = logCount; float yaw, pitch, roll; orientation.GetEulerAngles<Axis_Y, Axis_X, Axis_Z>(&yaw, &pitch, &roll); yaw *= Mathf::RadToDegreeFactor; pitch *= Mathf::RadToDegreeFactor; roll *= Mathf::RadToDegreeFactor; float pyaw, ppitch, proll; MagRefs[MagRefIdx].WorldFromImu.GetEulerAngles<Axis_Y, Axis_X, Axis_Z>(&pyaw, &ppitch, &proll); pyaw *= Mathf::RadToDegreeFactor; ppitch *= Mathf::RadToDegreeFactor; proll *= Mathf::RadToDegreeFactor; LogText("YAW %5.2f::: [%d:%d] ypr=%.1f,%.1f,%.1f ref_ypr=%.1f,%.1f,%.1f magUncalib=%.3f %.3f %.3f magBias=%.3f %.3f %.3f error=%.3f prop=%.6f correction=%.6f\n", (float) logCount/1000.0f, MagRefIdx, MagRefs.GetSize(), yaw, pitch, roll, pyaw, ppitch, proll, magUncalibrated.x, magUncalibrated.y, magUncalibrated.z, magBias.x, magBias.y, magBias.z, yawError * Mathf::RadToDegreeFactor, propCorrectionRadPerSec * Mathf::RadToDegreeFactor, totalCorrectionRadPerSec * Mathf::RadToDegreeFactor); } #endif } } void SensorFusion::applyTiltCorrection(float deltaT) { const float gain = 0.25; const float snapThreshold = 0.1; const Vector3f up(0, 1, 0); Vector3f accelLocalFiltered(FAccelHeadset.GetFilteredValue()); Vector3f accelW = State.Transform.Orientation.Rotate(accelLocalFiltered); Quatf error = vectorAlignmentRotation(accelW, up); Quatf correction; if (FAccelHeadset.GetSize() == 1 || ((Alg::Abs(error.w) < cos(snapThreshold / 2) && FAccelHeadset.Confidence() > 0.75))) { // full correction for start-up // or large error with high confidence correction = error; } else if (FAccelHeadset.Confidence() > 0.5) { correction = error.Nlerp(Quatf(), gain * deltaT); } else { // accelerometer is unreliable due to movement return; } State.Transform.Orientation = correction * State.Transform.Orientation; } void SensorFusion::applyFocusCorrection(float deltaT) { Vector3f up = Vector3f(0, 1, 0); float gain = 0.01; Vector3f currentDir = State.Transform.Orientation.Rotate(Vector3f(0, 0, 1)); Vector3f focusYawComponent = FocusDirection.ProjectToPlane(up); Vector3f currentYawComponent = currentDir.ProjectToPlane(up); float angle = focusYawComponent.Angle(currentYawComponent); if( angle > FocusFOV ) { Quatf yawError; if ( FocusFOV != 0.0f) { Vector3f lFocus = Quatf(up, -FocusFOV).Rotate(focusYawComponent); Vector3f rFocus = Quatf(up, FocusFOV).Rotate(focusYawComponent); float lAngle = lFocus.Angle(currentYawComponent); float rAngle = rFocus.Angle(currentYawComponent); if(lAngle < rAngle) { yawError = vectorAlignmentRotation(currentDir, lFocus); } else { yawError = vectorAlignmentRotation(currentDir, rFocus); } } else { yawError = vectorAlignmentRotation(currentYawComponent, focusYawComponent); Vector3f axis; float angle; yawError.GetAxisAngle(&axis, &angle); } Quatf correction = yawError.Nlerp(Quatf(), gain * deltaT); State.Transform.Orientation = correction * State.Transform.Orientation; } } void SensorFusion::SetFocusDirection() { SetFocusDirection(Vector3f(State.Transform.Orientation.Rotate(Vector3f(0.0, 0.0, 1.0)))); } void SensorFusion::SetFocusDirection(Vector3f direction) { FocusDirection = direction; } void SensorFusion::SetFocusFOV(float fov) { OVR_ASSERT(fov >= 0.0); FocusFOV = fov; } void SensorFusion::ClearFocus() { FocusDirection = Vector3f(0.0, 0.0, 0.0); FocusFOV = 0.0f; } // This is a "perceptually tuned predictive filter", which means that it is optimized // for improvements in the VR experience, rather than pure error. In particular, // jitter is more perceptible at lower speeds whereas latency is more perceptable // after a high-speed motion. Therefore, the prediction interval is dynamically // adjusted based on speed. Significant more research is needed to further improve // this family of filters. Posef calcPredictedPose(const PoseStatef& poseState, float predictionDt ) { Posef pose = poseState.Transform; const float linearCoef = 1.0; Vector3f angularVelocity = poseState.AngularVelocity; float angularSpeed = angularVelocity.Length(); // This could be tuned so that linear and angular are combined with different coefficients float speed = angularSpeed + linearCoef * poseState.LinearVelocity.Length(); const float slope = 0.2; // The rate at which the dynamic prediction interval varies float candidateDt = slope * speed; // TODO: Replace with smoothstep function float dynamicDt = predictionDt; // Choose the candidate if it is shorter, to improve stability if (candidateDt < predictionDt) dynamicDt = candidateDt; if (angularSpeed > 0.001) pose.Orientation = pose.Orientation * Quatf(angularVelocity, angularSpeed * dynamicDt); pose.Position += poseState.LinearVelocity * dynamicDt; return pose; } // A predictive filter based on extrapolating the smoothed, current angular velocity SensorState SensorFusion::GetPredictionForTime( const double absoluteTimeSeconds ) const { SensorState sstate; sstate.Status = Status_OrientationTracked | Status_HmdConnected; // lockless state fetch const StateForPrediction state = UpdatedState.GetState(); // Delta time from the last processed message const float pdt = absoluteTimeSeconds - state.State.TimeInSeconds; sstate.Recorded = state.State; sstate.Temperature = state.Temperature; const Posef recenter = RecenterTransform.GetState(); // Do prediction logic sstate.Predicted = sstate.Recorded; sstate.Predicted.TimeInSeconds = absoluteTimeSeconds; sstate.Predicted.Transform = recenter * calcPredictedPose(state.State, pdt); return sstate; } SensorFusion::BodyFrameHandler::~BodyFrameHandler() { RemoveHandlerFromDevices(); } void SensorFusion::BodyFrameHandler::OnMessage(const Message& msg) { if (msg.Type == Message_BodyFrame) { pFusion->handleMessage(static_cast<const MessageBodyFrame&>(msg)); } } bool SensorFusion::BodyFrameHandler::SupportsMessageType(MessageType type) const { return (type == Message_BodyFrame); } } // namespace OVR
30.398782
164
0.687462
[ "model", "transform" ]
f5bdd4e5802ff017a67234370030084b9711370b
12,924
cpp
C++
sw/src/pairhmm.cpp
lvandam/pairhmm_posit_hdl_arrow
428e935d1f3cb78d881ec590cfcc1f85806c4589
[ "Apache-2.0" ]
1
2019-07-01T10:25:43.000Z
2019-07-01T10:25:43.000Z
sw/src/pairhmm.cpp
lvandam/pairhmm_posit_hdl_arrow
428e935d1f3cb78d881ec590cfcc1f85806c4589
[ "Apache-2.0" ]
null
null
null
sw/src/pairhmm.cpp
lvandam/pairhmm_posit_hdl_arrow
428e935d1f3cb78d881ec590cfcc1f85806c4589
[ "Apache-2.0" ]
2
2019-07-01T10:42:31.000Z
2021-02-05T09:10:13.000Z
// Copyright 2018 Delft University of Technology // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <cstdint> #include <memory> #include <vector> #include <string> #include <numeric> #include <iostream> #include <iomanip> #include <fstream> #include <omp.h> // Apache Arrow #include <arrow/api.h> // Fletcher #include <fletcher/fletcher.h> // Pair-HMM FPGA UserCore #include "scheme.hpp" #include "PairHMMUserCore.h" #include "pairhmm.hpp" #include "debug_values.hpp" #include "utils.hpp" #include "batch.hpp" #ifndef PLATFORM #define PLATFORM 2 #endif /* Burst step length in bytes */ #define BURST_LENGTH 4096 using namespace std; /* Structure to easily convert from 64-bit addresses to 2x32-bit registers */ typedef struct _lohi { uint32_t lo; uint32_t hi; } lohi; typedef union _addr_lohi { uint64_t full; lohi half; } addr_lohi; /** * Main function for pair HMM accelerator */ int main(int argc, char ** argv) { // Times double start, stop; double t_fill_batch, t_fill_table, t_prepare_column, t_create_core, t_fpga, t_sw, t_float, t_dec = 0.0; srand(0); flush(cout); t_workload *workload; std::vector<t_batch> batches; int rc = 0; float f_hw = 125e6; float max_cups = f_hw * (float)16; unsigned long pairs, x, y = 0; int initial_constant_power = 1; bool calculate_sw = true; bool show_results = false; bool show_table = false; DEBUG_PRINT("Parsing input arguments...\n"); if (argc > 4) { pairs = strtoul(argv[1], NULL, 0); x = strtoul(argv[2], NULL, 0); y = strtoul(argv[3], NULL, 0); initial_constant_power = strtoul(argv[4], NULL, 0); workload = gen_workload(pairs, x, y); BENCH_PRINT("M, "); BENCH_PRINT("%8d, %8d, %8d, ", workload->pairs, x, y); } else { fprintf(stderr, "ERROR: Correct usage is: %s <pairs> <X> <Y> <initial constant power>\n", "pairhmm"); return (EXIT_FAILURE); } batches = std::vector<t_batch>(workload->batches); start = omp_get_wtime(); // Generate random basepair strings for reads and haplotypes std::string x_string = randomBasepairs(workload->batches * (px(x, y) + x - 1)); std::string y_string = randomBasepairs(workload->batches * (py(y) + y - 1)); for (int q = 0; q < workload->batches; q++) { fill_batch(batches[q], x_string, y_string, q, workload->bx[q], workload->by[q], powf(2.0, initial_constant_power)); // HW unit starts with last batch } stop = omp_get_wtime(); t_fill_batch = stop - start; PairHMMPosit pairhmm_posit(workload, show_results, show_table); PairHMMFloat<float> pairhmm_float(workload, show_results, show_table); PairHMMFloat<cpp_dec_float_100> pairhmm_dec50(workload, show_results, show_table); if (calculate_sw) { DEBUG_PRINT("Calculating on host...\n"); start = omp_get_wtime(); pairhmm_posit.calculate(batches); stop = omp_get_wtime(); t_sw = stop - start; start = omp_get_wtime(); pairhmm_float.calculate(batches); stop = omp_get_wtime(); t_float = stop - start; start = omp_get_wtime(); pairhmm_dec50.calculate(batches); stop = omp_get_wtime(); t_dec = stop - start; } DEBUG_PRINT("Creating Arrow table...\n"); start = omp_get_wtime(); // Make a table with haplotypes shared_ptr<arrow::Table> table_hapl = create_table_hapl(batches); // Create the read and probabilities columns shared_ptr<arrow::Table> table_reads_reads = create_table_reads_reads(batches); shared_ptr<arrow::Table> table_reads_probs = create_table_reads_probs(batches); stop = omp_get_wtime(); t_fill_table = stop - start; // Calculate on FPGA // Create a platform shared_ptr<fletcher::SNAPPlatform> platform(new fletcher::SNAPPlatform()); DEBUG_PRINT("Preparing column buffers...\n"); // Prepare the colummn buffers start = omp_get_wtime(); std::vector<std::shared_ptr<arrow::Column> > columns; columns.push_back(table_hapl->column(0)); columns.push_back(table_reads_reads->column(0)); columns.push_back(table_reads_probs->column(0)); platform->prepare_column_chunks(columns); // This requires a modification in Fletcher (to accept vectors) stop = omp_get_wtime(); t_prepare_column = stop - start; DEBUG_PRINT("Creating UserCore instance...\n"); start = omp_get_wtime(); // Create a UserCore PairHMMUserCore uc(static_pointer_cast<fletcher::FPGAPlatform>(platform)); // Reset UserCore uc.reset(); // Initial values for each core std::vector<t_inits> inits(roundToMultiple(CORES, 2)); // Number of batches for each core std::vector<uint32_t> batch_length(roundToMultiple(CORES, 2)); // X & Y length for each core std::vector<uint32_t> x_len(roundToMultiple(CORES, 2)); std::vector<uint32_t> y_len(roundToMultiple(CORES, 2)); int batch_length_total = 0; // Balance total batches over multiple cores int avg_batches_per_core = floor((float)workload->batches / CORES); for(int i = 0; i < roundToMultiple(CORES, 2); i++) { // For now, duplicate batch information across all core MMIO registers batch_length[i] = (i == 0 && workload->batches % avg_batches_per_core > 0) ? avg_batches_per_core + 1 : avg_batches_per_core; // Remainder of batches is done by first core inits[i] = (i > CORES - 1) ? batches[0].init : batches[i].init; x_len[i] = (i > CORES - 1) ? 0 : workload->bx[i]; y_len[i] = (i > CORES - 1) ? 0 : workload->by[i]; } // Write result buffer addresses // Create arrays for results to be written to (per SA core) std::vector<uint32_t *> result_hw(roundToMultiple(CORES, 2)); for(int i = 0; i < roundToMultiple(CORES, 2); i++) { rc = posix_memalign((void * * ) &(result_hw[i]), BURST_LENGTH, sizeof(uint32_t) * roundToMultiple(batch_length[i], 2) * PIPE_DEPTH); // clear values buffer for (uint32_t j = 0; j < roundToMultiple(batch_length[i], 2) * PIPE_DEPTH; j++) { result_hw[i][j] = 0xDEADBEEF; } addr_lohi val; val.full = (uint64_t) result_hw[i]; platform->write_mmio(REG_RESULT_DATA_OFFSET + i, val.full); } stop = omp_get_wtime(); t_create_core = stop - start; // Configure the pair HMM SA cores uc.set_batch_init(batch_length, inits, x_len, y_len); std::vector<uint32_t> batch_offsets; batch_offsets.resize(roundToMultiple(CORES, 2)); int batch_counter = 0; for(int i = 0; i < roundToMultiple(CORES, 2); i++) { batch_offsets[i] = batch_counter; batch_counter = batch_counter + batch_length[i]; } uc.set_batch_offsets(batch_offsets); // Run DEBUG_PRINT("Starting accelerator computation...\n"); start = omp_get_wtime(); uc.start(); uc.wait_for_finish(); // Wait for last result of last SA core do { // for(int i = 0; i < CORES; i++) { // cout << "==================================" << endl; // cout << "== CORE " << i << endl; // cout << "==================================" << endl; // for(int j = 0; j < batch_length[i] * PIPE_DEPTH; j++) { // cout << dec << j <<": " << hex << result_hw[i][j] << dec <<endl; // } // cout << "==================================" << endl; // cout << endl; // } usleep(1); } while ((result_hw[CORES - 1][batch_length[CORES - 1] * PIPE_DEPTH - 1] == 0xDEADBEEF)); stop = omp_get_wtime(); t_fpga = stop - start; for(int i = 0; i < CORES; i++) { cout << "==================================" << endl; cout << "== CORE " << i << endl; cout << "==================================" << endl; for(int j = 0; j < batch_length[i] * PIPE_DEPTH; j++) { cout << dec << j <<": " << hex << result_hw[i][j] << dec <<endl; } cout << "==================================" << endl; cout << endl; } // Check for errors with SW calculation if (calculate_sw) { DebugValues<posit<NBITS, ES> > hw_debug_values; for (int c = 0; c < CORES; c++) { for (int i = 0; i < batch_length[c]; i++) { for(int j = 0; j < PIPE_DEPTH; j++) { // Store HW posit result for decimal accuracy calculation posit<NBITS, ES> res_hw; res_hw.set_raw_bits(result_hw[c][i * PIPE_DEPTH + j]); hw_debug_values.debugValue(res_hw, "result[%d][%d]", batch_offsets[c] + (batch_length[c] - i - 1), j); } } } cout << "Writing benchmark file..." << endl; writeBenchmark(pairhmm_dec50, pairhmm_float, pairhmm_posit, hw_debug_values, "pairhmm_es" + std::to_string(ES) + "_" + std::to_string(CORES) + "core_" + std::to_string(pairs) + "_" + std::to_string(x) + "_" + std::to_string(y) + "_" + std::to_string(initial_constant_power) + ".txt", false, true); DEBUG_PRINT("Checking errors...\n"); int errs_posit = 0; errs_posit = pairhmm_posit.count_errors(batch_offsets, batch_length, result_hw); DEBUG_PRINT("Posit errors: %d\n", errs_posit); } cout << "Resetting user core..." << endl; // Reset UserCore uc.reset(); float p_fpga = ((double)workload->cups / (double)t_fpga) / 1000000; // in MCUPS float p_sw = ((double)workload->cups / (double)t_sw) / 1000000; // in MCUPS float p_float = ((double)workload->cups / (double)t_float) / 1000000; // in MCUPS float p_dec = ((double)workload->cups / (double)t_dec) / 1000000; // in MCUPS float utilization = ((double)workload->cups / (double)t_fpga) / max_cups; float speedup = t_sw / t_fpga; cout << "Adding timing data..." << endl; time_t t = chrono::system_clock::to_time_t(chrono::system_clock::now()); ofstream outfile("pairhmm_es" + std::to_string(ES) + "_" + std::to_string(CORES) + "core_" + std::to_string(pairs) + "_" + std::to_string(x) + "_" + std::to_string(y) + "_" + std::to_string(initial_constant_power) + ".txt", ios::out | ios::app); outfile << endl << "===================" << endl; outfile << ctime(&t) << endl; outfile << "Pairs = " << pairs << endl; outfile << "X = " << x << endl; outfile << "Y = " << y << endl; outfile << "Initial Constant = " << initial_constant_power << endl; outfile << "cups,t_fill_batch,t_fill_table,t_prepare_column,t_create_core,t_fpga,p_fpga,t_sw,p_sw,t_float,p_float,t_dec,p_dec,utilization,speedup" << endl; outfile << setprecision(20) << fixed << workload->cups <<","<< t_fill_batch <<","<< t_fill_table <<","<< t_prepare_column <<","<< t_create_core <<","<< t_fpga <<","<< p_fpga <<","<< t_sw <<","<< p_sw <<","<< t_float <<","<< p_float <<","<< t_dec <<","<< p_dec <<","<< utilization <<","<< speedup << endl; outfile.close(); return 0; }
41.290735
312
0.54333
[ "vector" ]
f5c01abb28eb66a0ba916ea594f04d7a0173dac8
4,933
cpp
C++
cme/src/v20191029/model/ModifyTeamMemberRequest.cpp
suluner/tencentcloud-sdk-cpp
a56c73cc3f488c4d1e10755704107bb15c5e000d
[ "Apache-2.0" ]
43
2019-08-14T08:14:12.000Z
2022-03-30T12:35:09.000Z
cme/src/v20191029/model/ModifyTeamMemberRequest.cpp
suluner/tencentcloud-sdk-cpp
a56c73cc3f488c4d1e10755704107bb15c5e000d
[ "Apache-2.0" ]
12
2019-07-15T10:44:59.000Z
2021-11-02T12:35:00.000Z
cme/src/v20191029/model/ModifyTeamMemberRequest.cpp
suluner/tencentcloud-sdk-cpp
a56c73cc3f488c4d1e10755704107bb15c5e000d
[ "Apache-2.0" ]
28
2019-07-12T09:06:22.000Z
2022-03-30T08:04:18.000Z
/* * Copyright (c) 2017-2019 THL A29 Limited, a Tencent company. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <tencentcloud/cme/v20191029/model/ModifyTeamMemberRequest.h> #include <tencentcloud/core/utils/rapidjson/document.h> #include <tencentcloud/core/utils/rapidjson/writer.h> #include <tencentcloud/core/utils/rapidjson/stringbuffer.h> using namespace TencentCloud::Cme::V20191029::Model; using namespace std; ModifyTeamMemberRequest::ModifyTeamMemberRequest() : m_platformHasBeenSet(false), m_teamIdHasBeenSet(false), m_memberIdHasBeenSet(false), m_remarkHasBeenSet(false), m_roleHasBeenSet(false), m_operatorHasBeenSet(false) { } string ModifyTeamMemberRequest::ToJsonString() const { rapidjson::Document d; d.SetObject(); rapidjson::Document::AllocatorType& allocator = d.GetAllocator(); if (m_platformHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "Platform"; iKey.SetString(key.c_str(), allocator); d.AddMember(iKey, rapidjson::Value(m_platform.c_str(), allocator).Move(), allocator); } if (m_teamIdHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "TeamId"; iKey.SetString(key.c_str(), allocator); d.AddMember(iKey, rapidjson::Value(m_teamId.c_str(), allocator).Move(), allocator); } if (m_memberIdHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "MemberId"; iKey.SetString(key.c_str(), allocator); d.AddMember(iKey, rapidjson::Value(m_memberId.c_str(), allocator).Move(), allocator); } if (m_remarkHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "Remark"; iKey.SetString(key.c_str(), allocator); d.AddMember(iKey, rapidjson::Value(m_remark.c_str(), allocator).Move(), allocator); } if (m_roleHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "Role"; iKey.SetString(key.c_str(), allocator); d.AddMember(iKey, rapidjson::Value(m_role.c_str(), allocator).Move(), allocator); } if (m_operatorHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "Operator"; iKey.SetString(key.c_str(), allocator); d.AddMember(iKey, rapidjson::Value(m_operator.c_str(), allocator).Move(), allocator); } rapidjson::StringBuffer buffer; rapidjson::Writer<rapidjson::StringBuffer> writer(buffer); d.Accept(writer); return buffer.GetString(); } string ModifyTeamMemberRequest::GetPlatform() const { return m_platform; } void ModifyTeamMemberRequest::SetPlatform(const string& _platform) { m_platform = _platform; m_platformHasBeenSet = true; } bool ModifyTeamMemberRequest::PlatformHasBeenSet() const { return m_platformHasBeenSet; } string ModifyTeamMemberRequest::GetTeamId() const { return m_teamId; } void ModifyTeamMemberRequest::SetTeamId(const string& _teamId) { m_teamId = _teamId; m_teamIdHasBeenSet = true; } bool ModifyTeamMemberRequest::TeamIdHasBeenSet() const { return m_teamIdHasBeenSet; } string ModifyTeamMemberRequest::GetMemberId() const { return m_memberId; } void ModifyTeamMemberRequest::SetMemberId(const string& _memberId) { m_memberId = _memberId; m_memberIdHasBeenSet = true; } bool ModifyTeamMemberRequest::MemberIdHasBeenSet() const { return m_memberIdHasBeenSet; } string ModifyTeamMemberRequest::GetRemark() const { return m_remark; } void ModifyTeamMemberRequest::SetRemark(const string& _remark) { m_remark = _remark; m_remarkHasBeenSet = true; } bool ModifyTeamMemberRequest::RemarkHasBeenSet() const { return m_remarkHasBeenSet; } string ModifyTeamMemberRequest::GetRole() const { return m_role; } void ModifyTeamMemberRequest::SetRole(const string& _role) { m_role = _role; m_roleHasBeenSet = true; } bool ModifyTeamMemberRequest::RoleHasBeenSet() const { return m_roleHasBeenSet; } string ModifyTeamMemberRequest::GetOperator() const { return m_operator; } void ModifyTeamMemberRequest::SetOperator(const string& _operator) { m_operator = _operator; m_operatorHasBeenSet = true; } bool ModifyTeamMemberRequest::OperatorHasBeenSet() const { return m_operatorHasBeenSet; }
25.297436
93
0.714778
[ "model" ]
f5c1919e3c21eb581aa13b91524766ec3b20a84f
1,477
cpp
C++
Modules/IOExt/Internal/mitkObjFileReaderService.cpp
zhaomengxiao/MITK
a09fd849a4328276806008bfa92487f83a9e2437
[ "BSD-3-Clause" ]
1
2022-03-03T12:03:32.000Z
2022-03-03T12:03:32.000Z
Modules/IOExt/Internal/mitkObjFileReaderService.cpp
zhaomengxiao/MITK
a09fd849a4328276806008bfa92487f83a9e2437
[ "BSD-3-Clause" ]
1
2021-12-22T10:19:02.000Z
2021-12-22T10:19:02.000Z
Modules/IOExt/Internal/mitkObjFileReaderService.cpp
zhaomengxiao/MITK_lancet
a09fd849a4328276806008bfa92487f83a9e2437
[ "BSD-3-Clause" ]
1
2020-11-27T09:41:18.000Z
2020-11-27T09:41:18.000Z
/*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ // MITK #include "mitkObjFileReaderService.h" #include <mitkCustomMimeType.h> #include <mitkIOMimeTypes.h> #include <mitkSurface.h> // VTK #include <vtkOBJReader.h> #include <vtkSmartPointer.h> mitk::ObjFileReaderService::ObjFileReaderService() : AbstractFileReader(CustomMimeType(IOMimeTypes::WAVEFRONT_OBJ_MIMETYPE()), "Wavefront OBJ Reader") { this->RegisterService(); } mitk::ObjFileReaderService::~ObjFileReaderService() { } std::vector<itk::SmartPointer<mitk::BaseData>> mitk::ObjFileReaderService::DoRead() { std::vector<itk::SmartPointer<BaseData>> result; vtkSmartPointer<vtkOBJReader> reader = vtkSmartPointer<vtkOBJReader>::New(); reader->SetFileName(GetInputLocation().c_str()); reader->Update(); if (reader->GetOutput() != nullptr) { mitk::Surface::Pointer surface = mitk::Surface::New(); surface->SetVtkPolyData(reader->GetOutput()); result.push_back(dynamic_cast<mitk::BaseData *>(surface.GetPointer())); } return result; } mitk::ObjFileReaderService *mitk::ObjFileReaderService::Clone() const { return new ObjFileReaderService(*this); }
27.351852
101
0.670278
[ "vector" ]
f5c5e0091749524af1e07c196d758243afe6b070
3,692
cpp
C++
src/common/transformations/src/transformations/smart_reshape/mimic_set_batch_size.cpp
kurylo/openvino
4da0941cd2e8f9829875e60df73d3cd01f820b9c
[ "Apache-2.0" ]
1,127
2018-10-15T14:36:58.000Z
2020-04-20T09:29:44.000Z
src/common/transformations/src/transformations/smart_reshape/mimic_set_batch_size.cpp
kurylo/openvino
4da0941cd2e8f9829875e60df73d3cd01f820b9c
[ "Apache-2.0" ]
439
2018-10-20T04:40:35.000Z
2020-04-19T05:56:25.000Z
src/common/transformations/src/transformations/smart_reshape/mimic_set_batch_size.cpp
kurylo/openvino
4da0941cd2e8f9829875e60df73d3cd01f820b9c
[ "Apache-2.0" ]
414
2018-10-17T05:53:46.000Z
2020-04-16T17:29:53.000Z
// Copyright (C) 2018-2022 Intel Corporation // SPDX-License-Identifier: Apache-2.0 // #include <ngraph/opsets/opset5.hpp> #include <ngraph/pass/constant_folding.hpp> #include <ngraph/pass/manager.hpp> #include <transformations/smart_reshape/mimic_set_batch_size.hpp> #include "itt.hpp" bool ngraph::pass::MimicSetBatchSize::run_on_model(const std::shared_ptr<ngraph::Function>& f) { // TODO: enable conditional compile // RUN_ON_FUNCTION_SCOPE(MimicSetBatchSize); // extracting ratio of out to in 0-index dimension value from the folded function auto specialized_function = ngraph::clone_function(*f); ngraph::pass::Manager manager; manager.register_pass<ngraph::pass::ConstantFolding>(); manager.run_passes(specialized_function); std::map<std::string, float> scale; for (const auto& node : specialized_function->get_ops()) { if (const auto& reshape = std::dynamic_pointer_cast<opset5::Reshape>(node)) { const auto in_pshape = reshape->get_input_partial_shape(0), out_pshape = reshape->get_output_partial_shape(0); if (in_pshape.rank().is_dynamic() || in_pshape.rank().get_length() <= 1 || in_pshape[0].is_dynamic() || out_pshape.rank().is_dynamic() || out_pshape.rank().get_length() <= 1 || out_pshape[0].is_dynamic()) continue; const auto& pattern = std::dynamic_pointer_cast<opset5::Constant>(reshape->get_input_node_shared_ptr(1)); if (pattern && pattern->cast_vector<int64_t>()[0] > 0) { scale[reshape->get_friendly_name()] = static_cast<float>(out_pshape[0].get_length()) / static_cast<float>(in_pshape[0].get_length()); } } } // apply transformation to original function bool transformed = false; for (auto& reshape : f->get_ops()) { if (!is_type<opset5::Reshape>(reshape) || !scale.count(reshape->get_friendly_name()) || reshape->get_output_partial_shape(0).rank().is_dynamic()) continue; const auto& shape_of = std::make_shared<opset5::ShapeOf>(reshape->get_input_source_output(0), reshape->get_input_element_type(1)); const auto& new_input_batch = std::make_shared<ngraph::opset5::Gather>( shape_of, ngraph::opset5::Constant::create(ngraph::element::i64, {1}, std::vector<int64_t>{0}), ngraph::opset5::Constant::create(ngraph::element::i64, {}, std::vector<int64_t>{0})); const std::shared_ptr<Node>& new_output_batch = std::make_shared<opset5::Convert>( std::make_shared<opset5::Ceiling>(std::make_shared<opset5::Multiply>( std::make_shared<opset5::Convert>(new_input_batch, element::f32), opset5::Constant::create(element::f32, {1}, {scale[reshape->get_friendly_name()]}))), reshape->get_input_element_type(1)); std::vector<int64_t> non_batch_dims(reshape->get_output_partial_shape(0).rank().get_length() - 1); std::iota(non_batch_dims.begin(), non_batch_dims.end(), 1); const auto& non_batch_dims_node = std::make_shared<ngraph::opset5::Gather>( reshape->input_value(1), ngraph::opset5::Constant::create(ngraph::element::i64, {non_batch_dims.size()}, non_batch_dims), ngraph::opset5::Constant::create(ngraph::element::i64, {}, std::vector<int64_t>{0})); auto new_reshape_pattern = std::make_shared<opset5::Concat>(OutputVector{new_output_batch, non_batch_dims_node}, 0); reshape->input(1).replace_source_output(new_reshape_pattern->output(0)); transformed = true; } return transformed; }
53.507246
119
0.660618
[ "vector" ]
f5c8688ea2988eb2e4f3a0636b8f82ad816b09e0
4,753
hpp
C++
grabcut/grabcut.hpp
irllabs/grabcut
d8d9e89a6c00419bc14aba4dac0f61b16bbe96fc
[ "MIT" ]
18
2018-06-11T07:50:17.000Z
2021-11-24T02:02:20.000Z
grabcut/grabcut.hpp
Pandinosaurus/grabcut
d8d9e89a6c00419bc14aba4dac0f61b16bbe96fc
[ "MIT" ]
null
null
null
grabcut/grabcut.hpp
Pandinosaurus/grabcut
d8d9e89a6c00419bc14aba4dac0f61b16bbe96fc
[ "MIT" ]
6
2018-07-06T19:36:17.000Z
2021-01-05T05:38:32.000Z
/* * grabcut.h * HandDetectionDemo * * Created by Kris Kitani on 3/21/13. * Copyright 2013 __MyCompanyName__. All rights reserved. * */ #include <opencv2/opencv.hpp> using namespace std; using namespace cv; static void wevents( int e, int x, int y, int flags, void* ptr ); class GrabCut { public: GrabCut(); void run(Mat img, Mat &msk); void show(); Mat getFG(); Mat getBinMask(); void events( int e, int x, int y, int flags); Mat _gcut; int _mode; Mat _src; Mat _bin; Mat _tmp; Mat _mask; Mat _fgd; Mat _bgd; Mat _dsp; Point _pt; Point lstart; Point rstart; bool ldrag; bool rdrag; //int lab; string _name; }; GrabCut::GrabCut() { _mode=GC_FGD; } void GrabCut::run(Mat img, Mat &msk) { cout << "run grabcut" << endl; _src = img; _mask = Mat::ones(_src.size(),CV_8UC1)*GC_PR_BGD; _bin = Mat::zeros(_src.size(),CV_8UC1); cout << "GC_BGD " << GC_BGD <<endl; // 0 cout << "GC_FGD " << GC_FGD <<endl; // 1 cout << "GC_PR_BGD " << GC_PR_BGD <<endl; // 2 cout << "GC_PR_FGD " << GC_PR_FGD <<endl; // 3 _name = "graphcut"; namedWindow(_name); setMouseCallback(_name, wevents,this); Rect roi(0,0,_src.cols,_src.rows); _dsp = Mat::zeros(_src.rows*2,_src.cols*2,CV_8UC3); _src.copyTo(_dsp(roi)); //_dsp(roi) = _src.clone(); cout << "loop" << endl; while(1) { imshow(_name,_dsp); char c = waitKey(1); // if(c=='d') // done { msk = _bin*1.0; // output break; } else if(c=='f') _mode = GC_FGD; // forground mode else if(c=='b') _mode = GC_BGD; // background mode else if(c=='r') // reset { _src.copyTo(_dsp(roi)); // _mask = GC_PR_BGD; _gcut = GC_PR_BGD; show(); } } destroyWindow(_name); } void GrabCut::show() { Scalar fg_color(255,0,0); Scalar bg_color(0,255,0); cv::Mat scribbled_src = _src.clone(); const float alpha = 0.7f; for(int y=0; y < _gcut.rows; y++){ for(int x=0; x < _gcut.cols; x++){ if(_gcut.at<uchar>(y, x) == cv::GC_FGD) { cv::circle(scribbled_src, cv::Point(x, y), 2, fg_color, -1); } else if(_gcut.at<uchar>(y, x) == cv::GC_BGD) { cv::circle(scribbled_src, cv::Point(x, y), 2, bg_color, -1); } else if(_gcut.at<uchar>(y, x) == cv::GC_PR_BGD) { cv::Vec3b& pix = scribbled_src.at<cv::Vec3b>(y, x); pix[0] = (uchar)(pix[0] * alpha + bg_color[0] * (1-alpha)); pix[1] = (uchar)(pix[1] * alpha + bg_color[1] * (1-alpha)); pix[2] = (uchar)(pix[2] * alpha + bg_color[2] * (1-alpha)); } else if(_gcut.at<uchar>(y, x) == cv::GC_PR_FGD) { cv::Vec3b& pix = scribbled_src.at<cv::Vec3b>(y, x); pix[0] = (uchar)(pix[0] * alpha + fg_color[0] * (1-alpha)); pix[1] = (uchar)(pix[1] * alpha + fg_color[1] * (1-alpha)); pix[2] = (uchar)(pix[2] * alpha + fg_color[2] * (1-alpha)); } } } Rect roi; Mat scrb; roi = Rect(_src.cols,0,_src.cols,_src.rows); scribbled_src.copyTo(_dsp(roi)); Mat fg = getFG(); roi = Rect(_src.cols,_src.rows,_src.cols,_src.rows); fg.copyTo(_dsp(roi)); Mat msk = getBinMask(); cvtColor(msk,msk,COLOR_GRAY2BGR); roi = Rect(0,_src.rows,_src.cols,_src.rows); msk.copyTo(_dsp(roi)); imshow(_name,_dsp); waitKey(1); } Mat GrabCut::getFG() { Mat fg = cv::Mat::zeros(_src.size(), _src.type()); Mat mask = getBinMask(); _src.copyTo(fg, mask); return fg; } Mat GrabCut::getBinMask() { Mat binmask(_gcut.size(), CV_8U); binmask = _gcut & GC_FGD; binmask = binmask * 255; Mat tmp; binmask.copyTo(tmp); vector<vector<Point> > co; vector<Vec4i> hi; binmask *= 0; findContours(tmp,co,hi,RETR_EXTERNAL,CHAIN_APPROX_NONE); for(int i=0;i<co.size();i++){ if(contourArea(Mat(co[i])) < 50) continue; drawContours(binmask, co,i, CV_RGB(255,255,255), CV_FILLED, CV_AA); } binmask.copyTo(_bin); return binmask; } void GrabCut::events( int e, int x, int y, int flags) { _pt = Point(x,y); int c; switch(e) { case EVENT_LBUTTONDOWN: ldrag = true; lstart = _pt; break; case EVENT_LBUTTONUP: ldrag = false; _tmp = _mask & GC_FGD; c = countNonZero(_tmp); if(c>0) { _mask.copyTo(_gcut); cv::grabCut(_src,_gcut,Rect(), _bgd, _fgd, 1, cv::GC_INIT_WITH_MASK); show(); } break; case EVENT_MOUSEMOVE: if(ldrag) { line(_mask,lstart, _pt, Scalar(_mode), 1); if(_mode==GC_FGD) line(_dsp,lstart, _pt,CV_RGB(255,0,0), 1); else if(_mode==GC_BGD) line(_dsp,lstart, _pt,CV_RGB(0,255,0), 1); lstart = _pt; //cout << _pt << endl; } break; default: break; }; //cout << "eventout" << endl; } static void wevents( int e, int x, int y, int flags, void* ptr ) { GrabCut *mptr = (GrabCut*)ptr; if(mptr != NULL) mptr->events(e,x,y,flags); }
19.088353
73
0.594151
[ "vector" ]
f5c8d98fbfa56002cca40404ae2916a94198cfc6
3,877
cc
C++
components/viz/service/display_embedder/software_output_device_ozone_unittest.cc
sarang-apps/darshan_browser
173649bb8a7c656dc60784d19e7bb73e07c20daa
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
575
2015-06-18T23:58:20.000Z
2022-03-23T09:32:39.000Z
components/viz/service/display_embedder/software_output_device_ozone_unittest.cc
sarang-apps/darshan_browser
173649bb8a7c656dc60784d19e7bb73e07c20daa
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
113
2015-05-04T09:58:14.000Z
2022-01-31T19:35:03.000Z
components/viz/service/display_embedder/software_output_device_ozone_unittest.cc
sarang-apps/darshan_browser
173649bb8a7c656dc60784d19e7bb73e07c20daa
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
52
2015-07-14T10:40:50.000Z
2022-03-15T01:11:49.000Z
// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "components/viz/service/display_embedder/software_output_device_ozone.h" #include <memory> #include "base/threading/thread_task_runner_handle.h" #include "base/time/time.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" #include "third_party/skia/include/core/SkCanvas.h" #include "ui/compositor/compositor.h" #include "ui/compositor/test/test_context_factories.h" #include "ui/gfx/geometry/size.h" #include "ui/gfx/skia_util.h" #include "ui/gfx/vsync_provider.h" #include "ui/gl/gl_implementation.h" #include "ui/ozone/public/ozone_platform.h" #include "ui/ozone/public/platform_window_surface.h" #include "ui/ozone/public/surface_factory_ozone.h" #include "ui/ozone/public/surface_ozone_canvas.h" #include "ui/platform_window/platform_window.h" #include "ui/platform_window/platform_window_delegate.h" #include "ui/platform_window/platform_window_init_properties.h" namespace viz { namespace { class TestSurfaceOzoneCanvas : public ui::SurfaceOzoneCanvas { public: TestSurfaceOzoneCanvas() = default; ~TestSurfaceOzoneCanvas() override = default; // ui::SurfaceOzoneCanvas override: SkCanvas* GetCanvas() override { return surface_->getCanvas(); } void ResizeCanvas(const gfx::Size& viewport_size) override { surface_ = SkSurface::MakeRaster(SkImageInfo::MakeN32Premul( viewport_size.width(), viewport_size.height())); } std::unique_ptr<gfx::VSyncProvider> CreateVSyncProvider() override { return nullptr; } MOCK_METHOD1(PresentCanvas, void(const gfx::Rect& damage)); private: sk_sp<SkSurface> surface_; }; } // namespace class SoftwareOutputDeviceOzoneTest : public testing::Test { public: SoftwareOutputDeviceOzoneTest(); ~SoftwareOutputDeviceOzoneTest() override; SoftwareOutputDeviceOzoneTest(const SoftwareOutputDeviceOzoneTest&) = delete; SoftwareOutputDeviceOzoneTest& operator=( const SoftwareOutputDeviceOzoneTest&) = delete; void SetUp() override; void TearDown() override; protected: std::unique_ptr<SoftwareOutputDeviceOzone> output_device_; bool enable_pixel_output_ = false; TestSurfaceOzoneCanvas* surface_ozone_ = nullptr; }; SoftwareOutputDeviceOzoneTest::SoftwareOutputDeviceOzoneTest() = default; SoftwareOutputDeviceOzoneTest::~SoftwareOutputDeviceOzoneTest() = default; void SoftwareOutputDeviceOzoneTest::SetUp() { std::unique_ptr<TestSurfaceOzoneCanvas> surface_ozone = std::make_unique<TestSurfaceOzoneCanvas>(); surface_ozone_ = surface_ozone.get(); output_device_ = std::make_unique<SoftwareOutputDeviceOzone>( nullptr, std::move(surface_ozone)); } void SoftwareOutputDeviceOzoneTest::TearDown() { output_device_.reset(); } TEST_F(SoftwareOutputDeviceOzoneTest, CheckCorrectResizeBehavior) { constexpr gfx::Size size(200, 100); // Reduce size. output_device_->Resize(size, 1.f); constexpr gfx::Rect damage1(0, 0, 100, 100); SkCanvas* canvas = output_device_->BeginPaint(damage1); ASSERT_TRUE(canvas); gfx::Size canvas_size(canvas->getBaseLayerSize().width(), canvas->getBaseLayerSize().height()); EXPECT_EQ(size, canvas_size); EXPECT_CALL(*surface_ozone_, PresentCanvas(damage1)).Times(1); output_device_->EndPaint(); constexpr gfx::Size size2(1000, 500); // Increase size. output_device_->Resize(size2, 1.f); constexpr gfx::Rect damage2(0, 0, 50, 60); canvas = output_device_->BeginPaint(damage2); canvas_size.SetSize(canvas->getBaseLayerSize().width(), canvas->getBaseLayerSize().height()); EXPECT_EQ(size2, canvas_size); EXPECT_CALL(*surface_ozone_, PresentCanvas(damage2)).Times(1); output_device_->EndPaint(); } } // namespace viz
33.422414
81
0.761929
[ "geometry" ]
f5ca56d88ab5bf79a3b345cbf82765363329b237
5,560
hpp
C++
kernel/src/simulationTools/TimeSteppingCombinedProjection.hpp
ljktest/siconos
85b60e62beca46e6bf06bfbd65670089e86607c7
[ "Apache-2.0" ]
null
null
null
kernel/src/simulationTools/TimeSteppingCombinedProjection.hpp
ljktest/siconos
85b60e62beca46e6bf06bfbd65670089e86607c7
[ "Apache-2.0" ]
null
null
null
kernel/src/simulationTools/TimeSteppingCombinedProjection.hpp
ljktest/siconos
85b60e62beca46e6bf06bfbd65670089e86607c7
[ "Apache-2.0" ]
1
2015-10-07T19:35:16.000Z
2015-10-07T19:35:16.000Z
/* Siconos is a program dedicated to modeling, simulation and control * of non smooth dynamical systems. * * Copyright 2018 INRIA. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /*! \file Time-Stepping simulation with projections on constraints */ #ifndef TIMESTEPPINGCOMBINEDPROJECTION_H #define TIMESTEPPINGCOMBINEDPROJECTION_H #include "TimeStepping.hpp" /** Time-Stepping scheme * */ class TimeSteppingCombinedProjection : public TimeStepping { protected: /** serialization hooks */ ACCEPT_SERIALIZATION(TimeSteppingCombinedProjection); /** level of IndexSet on which we project * (default =2 (subset of activated constraint with positive reactions)) */ unsigned int _indexSetLevelForProjection; /** Cumulated Number of steps performed is the Newton Loop */ unsigned int _cumulatedNewtonNbIterations; /** Number of iteration of projection */ unsigned int _nbProjectionIteration; /** Number of cumulated iteration of projection */ unsigned int _nbCumulatedProjectionIteration; /** Number of iteration for stabilizating indexsets */ unsigned int _nbIndexSetsIteration; /** tolerance for the violation of the equality * constraints at the position level. */ double _constraintTol; /** tolerance for the violation of the unilateral * constraints at the position level. */ double _constraintTolUnilateral; /** maximum violation for the violation of the unilateral * constraints at the position level. */ double _maxViolationUnilateral; /** maximum violation for the violation of the equality * constraints at the position level. */ double _maxViolationEquality; /** Default maximum number of projection iteration*/ unsigned int _projectionMaxIteration; /** Default maximum number of index set activation iteration*/ unsigned int _kIndexSetMax; /** disabled or enabled projection (Debug Projection) */ bool _doCombinedProj; /** disabled or enabled projection On Equality (or Unilateral) for unilateral constraints */ bool _doCombinedProjOnEquality; /** Boolean to check if the index sets are stabilized in the Combined Projection Algorithm */ bool _isIndexSetsStable; /** update indexSets[i] of the topology, using current y and lambda values of Interactions. * \param level unsigned int: the level of the set to be updated */ void updateIndexSet(unsigned int level); struct _SimulationEffectOnOSNSP; friend struct _SimulationEffectOnOSNSP; public: virtual void initOSNS(); /** Constructor with the time-discretisation. * \param nsds the nsds that we want to simulate * \param td a pointer to a timeDiscretisation (linked to the model * that owns this simulation) * \param osi a one step integrator * \param osnspb_velo a one step non smooth problem for the velocity formulation * \param osnspb_pos a one step non smooth problem for the position formulation * \param _level */ TimeSteppingCombinedProjection( SP::NonSmoothDynamicalSystem nsds, SP::TimeDiscretisation td, SP::OneStepIntegrator osi, SP::OneStepNSProblem osnspb_velo, SP::OneStepNSProblem osnspb_pos, unsigned int _level = 2); /** default constructor */ TimeSteppingCombinedProjection() {}; virtual ~TimeSteppingCombinedProjection(); virtual void updateWorldFromDS() { ; } /** get the Number of iteration of projection * \return unsigned int nbProjectionIteration */ inline unsigned int nbProjectionIteration() { return _nbProjectionIteration; } /** get the Number of cumulated iteration of projection * \return unsigned int */ inline unsigned int nbCumulatedProjectionIteration() { return _nbCumulatedProjectionIteration; } /** get the Cumulated Number of steps performed in the Newton Loop * \return unsigned int */ inline unsigned int cumulatedNewtonNbIterations() { return _cumulatedNewtonNbIterations; } /** get the Number of iteration for stabilizating indexsets * \return unsigned int */ inline unsigned int nbIndexSetsIteration() { return _nbIndexSetsIteration; } inline void setConstraintTol(double v) { _constraintTol = v; } inline void setConstraintTolUnilateral(double v) { _constraintTolUnilateral = v; } inline double maxViolationUnilateral() { return _maxViolationUnilateral; } inline double maxViolationEquality() { return _maxViolationEquality; } inline void setProjectionMaxIteration(unsigned int v) { _projectionMaxIteration = v; } inline void setDoCombinedProj(unsigned int v) { _doCombinedProj = v; } inline bool doCombinedProjOnEquality() { return _doCombinedProjOnEquality; } /** */ void advanceToEvent(); /** */ void advanceToEventOLD(); /* */ void computeCriteria(bool * runningProjection); /** visitors hook */ ACCEPT_STD_VISITORS(); }; DEFINE_SPTR(TimeSteppingCombinedProjection) #endif // TIMESTEPPINGCOMBINEDPROJECTION_H
23.559322
95
0.730576
[ "model" ]
f5ccf542d918b2cd20343a10049cde48b757f326
7,664
hpp
C++
src/vlGraphics/SceneManager.hpp
Christophe-ABEL/VisualizationLibrary
936fe9e5047970b23d97ff0088725e9016b470ee
[ "BSD-2-Clause" ]
281
2016-04-16T14:11:04.000Z
2022-03-24T14:48:52.000Z
src/vlGraphics/SceneManager.hpp
Christophe-ABEL/VisualizationLibrary
936fe9e5047970b23d97ff0088725e9016b470ee
[ "BSD-2-Clause" ]
91
2016-04-20T19:55:45.000Z
2022-01-04T02:59:33.000Z
src/vlGraphics/SceneManager.hpp
Christophe-ABEL/VisualizationLibrary
936fe9e5047970b23d97ff0088725e9016b470ee
[ "BSD-2-Clause" ]
83
2016-04-26T01:28:40.000Z
2022-03-21T13:23:55.000Z
/**************************************************************************************/ /* */ /* Visualization Library */ /* http://visualizationlibrary.org */ /* */ /* Copyright (c) 2005-2020, Michele Bosi */ /* All rights reserved. */ /* */ /* Redistribution and use in source and binary forms, with or without modification, */ /* are permitted provided that the following conditions are met: */ /* */ /* - Redistributions of source code must retain the above copyright notice, this */ /* list of conditions and the following disclaimer. */ /* */ /* - Redistributions in binary form must reproduce the above copyright notice, this */ /* list of conditions and the following disclaimer in the documentation and/or */ /* other materials provided with the distribution. */ /* */ /* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND */ /* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED */ /* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE */ /* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR */ /* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES */ /* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; */ /* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON */ /* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT */ /* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS */ /* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /* */ /**************************************************************************************/ #ifndef SceneManager_INCLUDE_ONCE #define SceneManager_INCLUDE_ONCE #include <vlGraphics/link_config.hpp> #include <vlCore/Object.hpp> #include <vlCore/Sphere.hpp> namespace vl { class Actor; class ActorCollection; class Camera; //------------------------------------------------------------------------------------------------------------------------------------------- // SceneManager //------------------------------------------------------------------------------------------------------------------------------------------- /** * The SceneManager class is the base class for all the scene managers. * * A SceneManager implements an algorithm used to quickly identify which objects are visible and which ones are not. * The algorithm can be a space partitioning scheme like a BSP, Kd-Tree, Octree etc. or a visibility based scheme like * sector/portals, precomputed PVS etc. or a mix of them. The set of SceneManager[s] attached to a Rendering * defines the scene. In fact, if an Actor does not belong to any SceneManager it will not have any chance of being rendered. * * Visualization Library allows you to bind and use multiple SceneManagers at the same time within the same Rendering. * Note that an Actor should belong to one and only one SceneManager otherwise you might end up rendering twice the same Actor * thus wasting computational resources. * * In order to implement your own scene manager you will have to dirive from the SceneManager class and provide an appropriate * implementation for the following methods: extractVisibleActors(), extractActors(). * * \sa * - ActorKdTree * - ActorTree * - SceneManager * - SceneManagerActorKdTree * - SceneManagerActorTree * - SceneManagerPortals * - Actor */ class VLGRAPHICS_EXPORT SceneManager: public Object { VL_INSTRUMENT_ABSTRACT_CLASS(vl::SceneManager, Object) public: //! Constructor. SceneManager(); //! Appends all the Actors contained in the scene manager without performing frustum culling or checking enable masks. virtual void extractActors(ActorCollection& list) = 0; //! Extracts all the enabled and visible Actors contained in the ActorTree hierarchy and appends them to the given ActorCollection. //! \see SceneManager::enableMask(), Actor::enableMask(), Actor::isEnabled(), ActorTreeAbstract::isEnabled() virtual void extractVisibleActors(ActorCollection& list, const Camera* camera) = 0; //! Computes the bounding box and bounding sphere of the scene manager and of all the Actors contained in the SceneManager. virtual void computeBounds(); //! Explicitly set the scene manager's bounding sphere. See also computeBounds(). void setBoundingSphere(const Sphere& sphere) { mSphere = sphere; } //! Returns the scene manager's bounding sphere. const Sphere& boundingSphere() const { return mSphere; } //! Explicitly set the scene manager's bounding sphere. See also computeBounds(). void setBoundingBox(const AABB& bbox) { mAABB = bbox; } //! Returns the scene manager's bounding box. const AABB& boundingBox() const { return mAABB; } //! Flags a scene manager's bounding box and bounding sphere as dirty. The bounds will be recomputed using computeBounds() at the next rendering frame. void setBoundsDirty(bool dirty) { mBoundsDirty = dirty; } //! Returns true if the scene manager's bounds should be recomputed at the next rendering frame. bool boundsDirty() const { return mBoundsDirty; } //! Used to enable or disable frustum culling or whichever culling system the scene manager implements. void setCullingEnabled(bool enable) { mCullingEnabled = enable; } //! Used to enable or disable frustum culling or whichever culling system the scene manager implements. bool cullingEnabled() const { return mCullingEnabled; } //! The enable mask to be used by extractVisibleActors() //! \see \see Actor::enableMask(), Actor::isEnabled(), ActorTreeAbstract::isEnabled(), SceneManager::enableMask(), Rendering::enableMask(), Rendering::effectOverrideMask(), Renderer::enableMask(), Renderer::shaderOverrideMask(). void setEnableMask(unsigned int enabled) { mEnableMask = enabled; } //! The enable mask to be used by extractVisibleActors() //! \see \see Actor::enableMask(), Actor::isEnabled(), ActorTreeAbstract::isEnabled(), SceneManager::enableMask(), Rendering::enableMask(), Rendering::effectOverrideMask(), Renderer::enableMask(), Renderer::shaderOverrideMask(). unsigned int enableMask() const { return mEnableMask; } //! Returns \p true if \p "a->enableMask() & enableMask()) != 0" bool isEnabled(Actor*a) const; protected: Sphere mSphere; AABB mAABB; unsigned int mEnableMask; bool mBoundsDirty; bool mCullingEnabled; }; } #endif
58.953846
233
0.582855
[ "object" ]
f5cd7fb74e0265518145505448a83ad93a286354
12,720
cpp
C++
tests/test_RTspace.cpp
pratyuksh/NumHypSys
29e03f9cc0572178701525210561b152d89999d4
[ "MIT" ]
null
null
null
tests/test_RTspace.cpp
pratyuksh/NumHypSys
29e03f9cc0572178701525210561b152d89999d4
[ "MIT" ]
null
null
null
tests/test_RTspace.cpp
pratyuksh/NumHypSys
29e03f9cc0572178701525210561b152d89999d4
[ "MIT" ]
null
null
null
#include <gtest/gtest.h> #include "mfem.hpp" using namespace mfem; #include <iostream> #include <fstream> #include <random> #include <Eigen/Core> #include <Eigen/Dense> #include "../include/core/config.hpp" void eval_vshape_RT0_refEl(const double x, const double y, DenseMatrix& vshape) { int ndofs = 3; vshape.SetSize(ndofs, 2); vshape(0,0) = x ; vshape(0,1) = y-1; vshape(1,0) = x ; vshape(1,1) = y ; vshape(2,0) = x-1; vshape(2,1) = y; } void eval_gradvshape_RT0_refEl(const double, const double, DenseTensor& gradvshape) { int ndofs = 3; gradvshape.SetSize(2,2,ndofs); gradvshape = 0; gradvshape(0,0,0) = gradvshape(1,1,0) = 1; gradvshape(0,0,1) = gradvshape(1,1,1) = 1; gradvshape(0,0,2) = gradvshape(1,1,2) = 1; } class RT1_refEl { public: RT1_refEl () { double c = 1./3.; Vector xi(2); xi(0) = (1-1./sqrt(3))/2; xi(1) = (1+1./sqrt(3))/2; nodes.SetSize(8,2); T.SetSize(8, 8); // set nodes nodes(0,0) = xi(0); nodes(0,1) = 0; nodes(1,0) = xi(1); nodes(1,1) = 0; nodes(2,0) = xi(1); nodes(2,1) = xi(0); nodes(3,0) = xi(0); nodes(3,1) = xi(1); nodes(4,0) = 0; nodes(4,1) = xi(1); nodes(5,0) = 0; nodes(5,1) = xi(0); nodes(6,0) = c; nodes(6,1) = c; nodes(7,0) = c; nodes(7,1) = c; // set matrix T T = 0.0; // dofs 0 and 1 for (int i=0; i<=1; i++) { T(1,i) = -(2*(1 - nodes(i,0) - nodes(i,1))-1); T(3,i) = -(2*nodes(i,0)-1); T(5,i) = -(2*nodes(i,1)-1); T(6,i) = -(2*nodes(i,1)-1)*(nodes(i,1) - c); T(7,i) = -(2*nodes(i,0)-1)*(nodes(i,1) - c); } // dofs 2 and 3 for (int i=2; i<=3; i++) { T(0,i) = T(1,i) = (2*(1 - nodes(i,0) - nodes(i,1))-1); T(2,i) = T(3,i) = (2*nodes(i,0)-1); T(4,i) = T(5,i) = (2*nodes(i,1)-1); T(6,i) = (2*nodes(i,1)-1)*(nodes(i,0) + nodes(i,1) - 2*c); T(7,i) = (2*nodes(i,0)-1)*(nodes(i,0) + nodes(i,1) - 2*c); } // dofs 4 and 5 for (int i=4; i<=5; i++) { T(0,i) = -(2*(1 - nodes(i,0) - nodes(i,1))-1); T(2,i) = -(2*nodes(i,0)-1); T(4,i) = -(2*nodes(i,1)-1); T(6,i) = -(2*nodes(i,1)-1)*(nodes(i,0) - c); T(7,i) = -(2*nodes(i,0)-1)*(nodes(i,0) - c); } // dofs 6 and 7 int i=6; { T(1,i) = -(2*(1 - nodes(i,0) - nodes(i,1))-1); T(3,i) = -(2*nodes(i,0)-1); T(5,i) = -(2*nodes(i,1)-1); T(6,i) = -(2*nodes(i,1)-1)*(nodes(i,1) - c); T(7,i) = -(2*nodes(i,0)-1)*(nodes(i,1) - c); i++; T(0,i) = -(2*(1 - nodes(i,0) - nodes(i,1))-1); T(2,i) = -(2*nodes(i,0)-1); T(4,i) = -(2*nodes(i,1)-1); T(6,i) = -(2*nodes(i,1)-1)*(nodes(i,0) - c); T(7,i) = -(2*nodes(i,0)-1)*(nodes(i,0) - c); } /*for (int k=0; k<T.NumRows(); k++) { for (int l=0; l<T.NumCols(); l++) std::cout << T(k,l) << " "; std::cout << "\n"; }*/ Ti.Factor(T); /*DenseMatrix invT; Ti.GetInverseMatrix(invT); for (int k=0; k<T.NumRows(); k++) { for (int l=0; l<T.NumCols(); l++) std::cout << invT(k,l) << " "; std::cout << "\n"; }*/ } void eval_vshape(const double x, const double y, DenseMatrix &vshape) { double c = 1./3.; int ndofs = 8; DenseMatrix vshape_buf(ndofs, 2); vshape_buf = 0.0; vshape_buf(0,0) = (2*(1-x-y)-1); vshape_buf(1,1) = (2*(1-x-y)-1); vshape_buf(2,0) = (2*x-1); vshape_buf(3,1) = (2*x-1); vshape_buf(4,0) = (2*y-1); vshape_buf(5,1) = (2*y-1); vshape_buf(6,0) = (2*y-1)*(x - c); vshape_buf(6,1) = (2*y-1)*(y - c); vshape_buf(7,0) = (2*x-1)*(x - c); vshape_buf(7,1) = (2*x-1)*(y - c); Ti.Mult(vshape_buf, vshape); } private: DenseMatrix nodes; DenseMatrix T; DenseMatrixInverse Ti; }; TEST(RTspace, vshape_deg0_test1) { std::string input_dir = "../input/"; const std::string mesh_file = input_dir+"tri_elem1"; Mesh mesh(mesh_file.c_str()); assert(mesh.GetNE() == 1); FiniteElementCollection *hdiv_coll = new RT_FECollection(0, mesh.Dimension()); FiniteElementSpace *R_space = new FiniteElementSpace(&mesh, hdiv_coll); int j=0; // only 1 element in the mesh { const FiniteElement *fe = R_space->GetFE(j); ElementTransformation *trans = R_space->GetElementTransformation(j); const IntegrationRule *ir = &IntRules.Get(fe->GetGeomType(), 2); DenseMatrix vshape(3,2); DenseMatrix true_vshape(3,2); auto vshape_fn = [](Vector &x) { DenseMatrix vshape(3,2); vshape(0,0) = x(0)-2; vshape(0,1) = x(1); vshape(1,0) = x(0)-2; vshape(1,1) = x(1)-1; vshape(2,0) = x(0); vshape(2,1) = x(1); vshape *= 0.5; return vshape; }; for (int i = 0; i < ir->GetNPoints(); i++) { const IntegrationPoint &ip = ir->IntPoint(i); trans->SetIntPoint(&ip); fe->CalcVShape(*trans, true_vshape); Vector eip; trans->Transform(ip, eip); vshape = vshape_fn(eip); /*std::cout << "\n\nvshape:" << std::endl; for (int k=0; k<vshape.NumRows(); k++) { for (int l=0; l<vshape.NumCols(); l++) std::cout << vshape(k,l) << " "; std::cout << "\n"; } std::cout << "\n\nTrue vshape:" << std::endl; for (int k=0; k<vshape.NumRows(); k++) { for (int l=0; l<vshape.NumCols(); l++) std::cout << true_vshape(k,l) << " "; std::cout << "\n"; }*/ double TOL = 1E-10; true_vshape -= vshape; ASSERT_LE(true_vshape.FNorm(), TOL); } } delete hdiv_coll; delete R_space; } TEST(RTspace, gradvshape_deg0) { std::string input_dir = "../input/"; const std::string mesh_file = input_dir+"tri_elem1"; Mesh mesh(mesh_file.c_str()); assert(mesh.GetNE() == 1); FiniteElementCollection *hdiv_coll = new RT_FECollection(0, mesh.Dimension()); FiniteElementSpace *R_space = new FiniteElementSpace(&mesh, hdiv_coll); int ndofs = 3; auto gradvshape_fn = [](Vector &) { DenseTensor gradvshape(2,2,3); gradvshape = 0.0; gradvshape(0,0,0) = 0.5; gradvshape(1,1,0) = 0.5; gradvshape(0,0,1) = 0.5; gradvshape(1,1,1) = 0.5; gradvshape(0,0,2) = 0.5; gradvshape(1,1,2) = 0.5; return gradvshape; }; int j=0; { const FiniteElement *fe = R_space->GetFE(j); ElementTransformation *trans = R_space->GetElementTransformation(j); const IntegrationRule *ir = &IntRules.Get(fe->GetGeomType(), 2); DenseTensor true_gradvshape(2,2,3); for (int i = 0; i < ir->GetNPoints(); i++) { const IntegrationPoint &ip = ir->IntPoint(i); trans->SetIntPoint(&ip); fe->CalcGradVShape(*trans, true_gradvshape); Vector eip; trans->Transform(ip, eip); auto gradvshape = gradvshape_fn(eip); for (int m=0; m < ndofs; m++) { /*std::cout << "\n\ngradvshape:" << std::endl; for (int k=0; k<gradvshape(m).NumRows(); k++) { for (int l=0; l<gradvshape(m).NumCols(); l++) std::cout << gradvshape(k,l,m) << " "; std::cout << "\n"; } std::cout << "\n\ntrue_gradvshape:" << std::endl; for (int k=0; k<gradvshape(m).NumRows(); k++) { for (int l=0; l<gradvshape(m).NumCols(); l++) std::cout << true_gradvshape(k,l,m) << " "; std::cout << "\n"; }*/ true_gradvshape(m) -= gradvshape(m); double TOL = 1E-10; ASSERT_LE(true_gradvshape(m).FNorm(), TOL); } } } delete hdiv_coll; delete R_space; } TEST(RTspace, vshape_deg1) { std::string input_dir = "../input/"; const std::string mesh_file = input_dir+"tri_elem2"; Mesh mesh(mesh_file.c_str()); FiniteElementCollection *hdiv_coll = new RT_FECollection(1, mesh.Dimension()); FiniteElementSpace *R_space = new FiniteElementSpace(&mesh, hdiv_coll); for (int j=0; j<1; j++) { const FiniteElement *fe = R_space->GetFE(j); ElementTransformation *trans = R_space->GetElementTransformation(j); const IntegrationRule *ir = &IntRules.Get(fe->GetGeomType(), 2); DenseMatrix vshape(8,2); DenseMatrix true_vshape(8,2); RT1_refEl rt1_refEl; for (int i = 0; i < ir->GetNPoints(); i++) { const IntegrationPoint &ip = ir->IntPoint(i); trans->SetIntPoint(&ip); //fe->CalcVShape(trans->GetIntPoint(), true_vshape); fe->CalcVShape(*trans, true_vshape); DenseMatrix vshape_buf; rt1_refEl.eval_vshape(ip.x, ip.y, vshape_buf); MultABt(vshape_buf, trans->Jacobian(), vshape); vshape *= (1./trans->Weight()); /*std::cout << "\n\nvshape:" << std::endl; for (int k=0; k<vshape.NumRows(); k++) { for (int l=0; l<vshape.NumCols(); l++) std::cout << vshape(k,l) << " "; std::cout << "\n"; } std::cout << "\n\nTrue vshape:" << std::endl; for (int k=0; k<vshape.NumRows(); k++) { for (int l=0; l<vshape.NumCols(); l++) std::cout << true_vshape(k,l) << " "; std::cout << "\n"; }*/ double TOL = 1E-10; true_vshape -= vshape; ASSERT_LE(true_vshape.FNorm(), TOL); //std::cout << "\nError: " << true_vshape.FNorm() << std::endl; } } delete hdiv_coll; delete R_space; } /*TEST(RTspace, gradvshape_deg0) { std::string input_dir = "../input/"; const std::string mesh_file = input_dir+"tri_elem2"; Mesh mesh(mesh_file.c_str()); FiniteElementCollection *hdiv_coll = new RT_FECollection(0, mesh.Dimension()); FiniteElementSpace *R_space = new FiniteElementSpace(&mesh, hdiv_coll); int ndofs = 3; int dim = 2; auto gradvshape_fn = [](Vector &x) { DenseTensor gradvshape(3,2,2); gradvshape = 0.0; gradvshape(0,0,0) = 0.5; gradvshape(0,1,1) = 0.5; gradvshape(1,0,0) = 0.5; gradvshape(1,1,1) = 0.5; gradvshape(2,0,0) = 0.5; gradvshape(2,1,1) = 0.5; return gradvshape; }; for (int j=0; j<1; j++) { const FiniteElement *fe = R_space->GetFE(j); ElementTransformation *trans = R_space->GetElementTransformation(j); const IntegrationRule *ir = &IntRules.Get(fe->GetGeomType(), 2); //DenseTensor gradvshape(2,2,3); DenseTensor true_gradvshape(2,2,3); for (int i = 0; i < ir->GetNPoints(); i++) { const IntegrationPoint &ip = ir->IntPoint(i); trans->SetIntPoint(&ip); fe->CalcGradVShape(*trans, true_gradvshape); DenseMatrix J, Jinv; DenseTensor gradvshape_buf; J = trans->Jacobian(); Jinv = trans->InverseJacobian(); eval_gradvshape_RT0_refEl(ip.x, ip.y, gradvshape_buf); for (int m=0; m < ndofs; m++) { // apply Piola transformation // gradvshape = |J|^{-1}*J * gradvshape_buf * invJ DenseMatrix tempMat(dim, dim); Mult(J, gradvshape_buf(m), tempMat); Mult(tempMat, Jinv, gradvshape(m)); gradvshape(m) *= (1.0 / trans->Weight()); true_gradvshape(m) -= gradvshape(m); double TOL = 1E-10; ASSERT_LE(true_gradvshape(m).FNorm(), TOL); } } } delete hdiv_coll; delete R_space; }*/
29.107551
75
0.47445
[ "mesh", "vector", "transform" ]
f5d2a253de73ebebf380747605a44196f50a84b7
6,494
cpp
C++
test/capi/capiLinearGradient.cpp
patrykka/thorvg
dc7bb0deed9d930cf96041a343788a8ae620aca7
[ "MIT" ]
null
null
null
test/capi/capiLinearGradient.cpp
patrykka/thorvg
dc7bb0deed9d930cf96041a343788a8ae620aca7
[ "MIT" ]
null
null
null
test/capi/capiLinearGradient.cpp
patrykka/thorvg
dc7bb0deed9d930cf96041a343788a8ae620aca7
[ "MIT" ]
null
null
null
/* * Copyright (c) 2021 Samsung Electronics Co., Ltd. All rights reserved. * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ #include <thorvg_capi.h> #include "../catch.hpp" TEST_CASE("Linear Gradient Basic Create", "[capiLinearGradient]") { Tvg_Gradient *gradient = tvg_linear_gradient_new(); REQUIRE(gradient); REQUIRE(tvg_gradient_del(gradient) == TVG_RESULT_SUCCESS); } TEST_CASE("Linear Gradient start and end position", "[capiLinearGradient]") { Tvg_Gradient *gradient = tvg_linear_gradient_new(); REQUIRE(gradient); REQUIRE(tvg_linear_gradient_set(gradient, 10.0, 20.0, 50.0, 40.0) == TVG_RESULT_SUCCESS); float x1, y1, x2, y2; REQUIRE(tvg_linear_gradient_get(gradient, &x1, &y1, &x2, &y2) == TVG_RESULT_SUCCESS); REQUIRE(x1 == 10.0); REQUIRE(y1 == 20.0); REQUIRE(x2 == 50.0); REQUIRE(y2 == 40.0); REQUIRE(tvg_gradient_del(gradient) == TVG_RESULT_SUCCESS); } TEST_CASE("Linear Gradient in shape", "[capiLinearGradient]") { REQUIRE(tvg_shape_set_linear_gradient(NULL, NULL) == TVG_RESULT_INVALID_ARGUMENT); Tvg_Gradient *gradient = tvg_linear_gradient_new(); REQUIRE(gradient); REQUIRE(tvg_shape_set_linear_gradient(NULL, gradient) == TVG_RESULT_INVALID_ARGUMENT); Tvg_Paint *shape = tvg_shape_new(); REQUIRE(shape); REQUIRE(tvg_shape_set_linear_gradient(shape, gradient) == TVG_RESULT_SUCCESS); Tvg_Gradient *gradient_ret = NULL; REQUIRE(tvg_shape_get_gradient(shape, &gradient_ret) == TVG_RESULT_SUCCESS); REQUIRE(gradient_ret); REQUIRE(tvg_shape_set_linear_gradient(shape, NULL) == TVG_RESULT_MEMORY_CORRUPTION); REQUIRE(tvg_paint_del(shape) == TVG_RESULT_SUCCESS); } TEST_CASE("Linear Gradient color stops", "[capiLinearGradient]") { Tvg_Paint *shape = tvg_shape_new(); REQUIRE(shape); Tvg_Gradient *gradient = tvg_linear_gradient_new(); REQUIRE(gradient); Tvg_Color_Stop color_stops[2] = { {.offset=0.0, .r=0, .g=0, .b=0, .a=255}, {.offset=1, .r=0, .g=255, .b=0, .a=255}, }; const Tvg_Color_Stop *color_stops_ret; uint32_t color_stops_count_ret; REQUIRE(tvg_gradient_set_color_stops(gradient, color_stops, 2) == TVG_RESULT_SUCCESS); REQUIRE(tvg_gradient_get_color_stops(gradient, &color_stops_ret, &color_stops_count_ret) == TVG_RESULT_SUCCESS); REQUIRE(color_stops_count_ret == 2); REQUIRE(color_stops_ret[0].a == 255); REQUIRE(color_stops_ret[1].g == 255); REQUIRE(tvg_gradient_del(gradient) == TVG_RESULT_SUCCESS); REQUIRE(tvg_paint_del(shape) == TVG_RESULT_SUCCESS); } TEST_CASE("Linear Gradient clear data", "[capiLinearGradient]") { Tvg_Paint *shape = tvg_shape_new(); REQUIRE(shape); Tvg_Gradient *gradient = tvg_linear_gradient_new(); REQUIRE(gradient); Tvg_Color_Stop color_stops[2] = { {.offset=0.0, .r=0, .g=0, .b=0, .a=255}, {.offset=1, .r=0, .g=255, .b=0, .a=255}, }; const Tvg_Color_Stop *color_stops_ret = NULL; uint32_t color_stops_count_ret = 0; REQUIRE(tvg_gradient_set_color_stops(gradient, color_stops, 2) == TVG_RESULT_SUCCESS); REQUIRE(tvg_gradient_get_color_stops(gradient, &color_stops_ret, &color_stops_count_ret) == TVG_RESULT_SUCCESS); REQUIRE(color_stops_ret); REQUIRE(color_stops_count_ret == 2); REQUIRE(tvg_gradient_set_color_stops(gradient, NULL, 0) == TVG_RESULT_SUCCESS); REQUIRE(tvg_gradient_get_color_stops(gradient, &color_stops_ret, &color_stops_count_ret) == TVG_RESULT_SUCCESS); REQUIRE(color_stops_ret == NULL); REQUIRE(color_stops_count_ret == 0); REQUIRE(tvg_gradient_del(gradient) == TVG_RESULT_SUCCESS); REQUIRE(tvg_paint_del(shape) == TVG_RESULT_SUCCESS); } TEST_CASE("Linear Gradient spread", "[capiLinearGradient]") { Tvg_Gradient *gradient = tvg_linear_gradient_new(); REQUIRE(gradient); Tvg_Stroke_Fill spread; REQUIRE(tvg_gradient_set_spread(gradient, TVG_STROKE_FILL_PAD) == TVG_RESULT_SUCCESS); REQUIRE(tvg_gradient_get_spread(gradient, &spread) == TVG_RESULT_SUCCESS); REQUIRE(spread == TVG_STROKE_FILL_PAD); REQUIRE(tvg_gradient_del(gradient) == TVG_RESULT_SUCCESS); REQUIRE(tvg_gradient_del(NULL) == TVG_RESULT_INVALID_ARGUMENT); } TEST_CASE("Stroke Linear Gradient", "[capiLinearGradient]") { Tvg_Paint *shape = tvg_shape_new(); REQUIRE(shape); Tvg_Gradient *gradient = tvg_linear_gradient_new(); REQUIRE(gradient); Tvg_Color_Stop color_stops[2] = { {.offset=0.0, .r=0, .g=0, .b=0, .a=255}, {.offset=1, .r=0, .g=255, .b=0, .a=255}, }; Tvg_Gradient *gradient_ret = NULL; const Tvg_Color_Stop *color_stops_ret = NULL; uint32_t color_stops_count_ret = 0; REQUIRE(tvg_gradient_set_color_stops(gradient, color_stops, 2) == TVG_RESULT_SUCCESS); REQUIRE(tvg_shape_set_stroke_linear_gradient(NULL, NULL) == TVG_RESULT_INVALID_ARGUMENT); REQUIRE(tvg_shape_set_stroke_linear_gradient(NULL, gradient) == TVG_RESULT_INVALID_ARGUMENT); REQUIRE(tvg_shape_set_stroke_linear_gradient(shape, gradient) == TVG_RESULT_SUCCESS); REQUIRE(tvg_shape_get_stroke_gradient(shape, &gradient_ret) == TVG_RESULT_SUCCESS); REQUIRE(gradient_ret); REQUIRE(tvg_gradient_get_color_stops(gradient_ret, &color_stops_ret, &color_stops_count_ret) == TVG_RESULT_SUCCESS); REQUIRE(color_stops_ret); REQUIRE(color_stops_count_ret == 2); REQUIRE(tvg_paint_del(shape) == TVG_RESULT_SUCCESS); }
36.897727
121
0.729751
[ "shape" ]
f5d374a5c1fb7ce9d775e202337a9bdae2c0cd93
7,379
cpp
C++
OpenSim/External_Functions/Pendulum_8dofs/Pendulum_8dofs.cpp
MaartenAfschrift/OpenSim_SourceAD
e063021c44e15744cfc5438b5fe5250d02018098
[ "Apache-2.0" ]
2
2020-10-30T09:08:44.000Z
2020-12-08T07:15:54.000Z
OpenSim/External_Functions/Pendulum_8dofs/Pendulum_8dofs.cpp
MaartenAfschrift/OpenSim_SourceAD
e063021c44e15744cfc5438b5fe5250d02018098
[ "Apache-2.0" ]
null
null
null
OpenSim/External_Functions/Pendulum_8dofs/Pendulum_8dofs.cpp
MaartenAfschrift/OpenSim_SourceAD
e063021c44e15744cfc5438b5fe5250d02018098
[ "Apache-2.0" ]
null
null
null
/* This code describes the OpenSim model and the skeleton dynamics Author: Gil Serrancoli Contributor: Joris Gillis, Antoine Falisse, Chris Dembia */ #include <OpenSim/Simulation/Model/Model.h> #include <OpenSim/Simulation/SimbodyEngine/PinJoint.h> #include <OpenSim/Simulation/SimbodyEngine/Body.h> #include "SimTKcommon/internal/recorder.h" #include <iostream> #include <iterator> #include <random> #include <cassert> #include <algorithm> #include <vector> #include <fstream> using namespace SimTK; using namespace OpenSim; /* The function F describes the OpenSim model and, implicitly, the skeleton dynamics. F takes as inputs joint positions and velocities (states x), joint accelerations (controls u), a platform perturbation value (p), and returns the joint torques. F is templatized using type T. F(x,u,p)->(r). */ // Inputs/outputs of function F /// number of vectors in inputs/outputs of function F constexpr int n_in = 3; constexpr int n_out = 1; /// number of elements in input/output vectors of function F constexpr int ndof = 8; // # degrees of freedom constexpr int NX = ndof*2; // # states constexpr int NU = ndof; // # controls constexpr int NP = 1; // # perturbation values constexpr int NR = ndof; // # residual torques // Helper function value template<typename T> T value(const Recorder& e) { return e; } template<> double value(const Recorder& e) { return e.getValue(); } // Function F template<typename T> int F_generic(const T** arg, T** res) { // OpenSim model: create components /// Model Model* model; /// Bodies OpenSim::Body* bodyInfo1; OpenSim::Body* bodyInfo2; OpenSim::Body* bodyInfo3; OpenSim::Body* bodyInfo4; OpenSim::Body* bodyInfo5; OpenSim::Body* bodyInfo6; OpenSim::Body* bodyInfo7; OpenSim::Body* bodyInfo8; /// Joints OpenSim::PinJoint* pendulum1; OpenSim::PinJoint* pendulum2; OpenSim::PinJoint* pendulum3; OpenSim::PinJoint* pendulum4; OpenSim::PinJoint* pendulum5; OpenSim::PinJoint* pendulum6; OpenSim::PinJoint* pendulum7; OpenSim::PinJoint* pendulum8; // OpenSim model: initialize components /// Model model = new OpenSim::Model(); /// Body specifications bodyInfo1 = new OpenSim::Body("body1", 26, Vec3(0, 0.55, 0), Inertia(1.4)); bodyInfo2 = new OpenSim::Body("body2", 46, Vec3(0, 0.365, 0), Inertia(2.9)); bodyInfo3 = new OpenSim::Body("body3", 30, Vec3(0, 0.5, 0), Inertia(3.0)); bodyInfo4 = new OpenSim::Body("body4", 30, Vec3(0, 0.5, 0), Inertia(3.0)); bodyInfo5 = new OpenSim::Body("body5", 30, Vec3(0, 0.5, 0), Inertia(3.0)); bodyInfo6 = new OpenSim::Body("body6", 30, Vec3(0, 0.5, 0), Inertia(3.0)); bodyInfo7 = new OpenSim::Body("body7", 30, Vec3(0, 0.5, 0), Inertia(3.0)); bodyInfo8 = new OpenSim::Body("body8", 30, Vec3(0, 0.5, 0), Inertia(3.0)); /// Joint specifications pendulum1 = new PinJoint("pendulum1", model->getGround(), Vec3(0), Vec3(0), *bodyInfo1, Vec3(0), Vec3(0)); pendulum2 = new PinJoint("pendulum2", *bodyInfo1, Vec3(0, 0.853, 0), Vec3(0), *bodyInfo2, Vec3(0), Vec3(0)); pendulum3 = new PinJoint("pendulum3", *bodyInfo2, Vec3(0, 0.6, 0), Vec3(0), *bodyInfo3, Vec3(0), Vec3(0)); pendulum4 = new PinJoint("pendulum4", *bodyInfo3, Vec3(0, 1.0, 0), Vec3(0), *bodyInfo4, Vec3(0), Vec3(0)); pendulum5 = new PinJoint("pendulum5", *bodyInfo4, Vec3(0, 1.0, 0), Vec3(0), *bodyInfo5, Vec3(0), Vec3(0)); pendulum6 = new PinJoint("pendulum6", *bodyInfo5, Vec3(0, 1.0, 0), Vec3(0), *bodyInfo6, Vec3(0), Vec3(0)); pendulum7 = new PinJoint("pendulum7", *bodyInfo6, Vec3(0, 1.0, 0), Vec3(0), *bodyInfo7, Vec3(0), Vec3(0)); pendulum8 = new PinJoint("pendulum8", *bodyInfo7, Vec3(0, 1.0, 0), Vec3(0), *bodyInfo8, Vec3(0), Vec3(0)); /// Add bodies and joints to model model->addBody(bodyInfo1); model->addBody(bodyInfo2); model->addBody(bodyInfo3); model->addBody(bodyInfo4); model->addBody(bodyInfo5); model->addBody(bodyInfo6); model->addBody(bodyInfo7); model->addBody(bodyInfo8); model->addJoint(pendulum1); model->addJoint(pendulum2); model->addJoint(pendulum3); model->addJoint(pendulum4); model->addJoint(pendulum5); model->addJoint(pendulum6); model->addJoint(pendulum7); model->addJoint(pendulum8); // Initialize system and state State* state; state = new State(model->initSystem()); // Read inputs std::vector<T> x(arg[0], arg[0] + NX); std::vector<T> u(arg[1], arg[1] + NU); std::vector<T> p(arg[2], arg[2] + NP); Vector QsUs(NX); /// joint positions (Qs) and velocities (Us) - states T ua[NU]; /// joint accelerations (Qdotdots) - controls T pert[NP]; /// platform perturbation // Assign inputs to model variables /// States for (int i = 0; i < NX; ++i) QsUs[i] = x[i]; /// Controls for (int i = 0; i < NU; ++i) ua[i] = u[i]; /// Platform perturbation pert[0] = p[0]; // Set state variables and realize model->setStateVariableValues(*state, QsUs); model->realizeVelocity(*state); // Compute residual forces /// appliedMobilityForces (# mobilities) Vector appliedMobilityForces(ndof); appliedMobilityForces.setToZero(); /// appliedBodyForces (# bodies + ground) Vector_<SpatialVec> appliedBodyForces; int nbodies = model->getBodySet().getSize() + 1; appliedBodyForces.resize(nbodies); appliedBodyForces.setToZero(); /// Set gravity Vec3 gravity(0); gravity[1] = -9.81; /// Set platform perturbation Vec3 pertVec_gravity = Vec3(pert[0] * gravity[1], gravity[1], 0); /// Add to model for (int i = 0; i < model->getBodySet().getSize(); ++i) { model->getMatterSubsystem().addInStationForce(*state, model->getBodySet().get(i).getMobilizedBodyIndex(), model->getBodySet().get(i).getMassCenter(), pertVec_gravity*model->getBodySet().get(i).getMass(), appliedBodyForces); } /// knownUdot Vector knownUdot(ndof); knownUdot.setToZero(); for (int i = 0; i < ndof; ++i) knownUdot[i] = ua[i]; /// Calculate residual forces Vector residualMobilityForces(ndof); residualMobilityForces.setToZero(); model->getMatterSubsystem().calcResidualForceIgnoringConstraints(*state, appliedMobilityForces, appliedBodyForces, knownUdot, residualMobilityForces); // Extract results /// Residual forces for (int i = 0; i < NR; ++i) res[0][i] = value<T>(residualMobilityForces[i]); return 0; } /* In main(), the Recorder is used to save the expression graph of function F. This expression graph is saved as a MATLAB function named foo.m. From this function, a c-code can be generated via CasADi and then compiled as a dll. This dll is then imported in MATLAB as an external function. With this workflow, CasADi can use algorithmic differentiation to differentiate the function F. */ int main() { Recorder x[NX]; Recorder u[NU]; Recorder p[NP]; Recorder tau[NR]; for (int i = 0; i < NX; ++i) x[i] <<= 0; for (int i = 0; i < NU; ++i) u[i] <<= 0; for (int i = 0; i < NP; ++i) p[i] <<= 0; const Recorder* Recorder_arg[n_in] = { x,u, p }; Recorder* Recorder_res[n_out] = { tau }; F_generic<Recorder>(Recorder_arg, Recorder_res); double res[NR]; for (int i = 0; i < NR; ++i) Recorder_res[0][i] >>= res[i]; Recorder::stop_recording(); return 0; }
33.238739
79
0.66242
[ "vector", "model" ]
f5d5f4a6cc21d8e2e9a01dde071dcc920b880731
7,659
cpp
C++
src/Generic/actors/ActorEditDistance.cpp
BBN-E/serif
1e2662d82fb1c377ec3c79355a5a9b0644606cb4
[ "Apache-2.0" ]
1
2022-03-24T19:57:00.000Z
2022-03-24T19:57:00.000Z
src/Generic/actors/ActorEditDistance.cpp
BBN-E/serif
1e2662d82fb1c377ec3c79355a5a9b0644606cb4
[ "Apache-2.0" ]
null
null
null
src/Generic/actors/ActorEditDistance.cpp
BBN-E/serif
1e2662d82fb1c377ec3c79355a5a9b0644606cb4
[ "Apache-2.0" ]
null
null
null
// Copyright 2013 by BBN Technologies Corp. // All Rights Reserved. #include "Generic/common/leak_detection.h" #include "Generic/common/ParamReader.h" #include "Generic/common/UTF8InputStream.h" #include "Generic/common/Sexp.h" #include "Generic/actors/AWAKEDB.h" #include "Generic/actors/ActorEditDistance.h" #include "Generic/theories/Mention.h" #include "Generic/theories/SynNode.h" #include "Generic/theories/DocTheory.h" #include <iostream> #include <boost/foreach.hpp> #include <boost/scoped_ptr.hpp> namespace { // Symbol constants used by _getVowelessEntries: Symbol GPE(L"GPE"); Symbol PER(L"PER"); Symbol LOC(L"LOC"); Symbol FAC(L"FAC"); Symbol ORG(L"ORG"); } ActorEditDistance::ActorEditDistance(ActorInfo_ptr actorInfo) { if (ParamReader::isParamTrue("limited_actor_match")) return; BOOST_FOREACH(ActorPattern *ap, actorInfo->getPatterns()) { // Don't allow edit distance on patterns that require context if (ap->acronym || ap->requires_context) continue; if (ap->entityTypeSymbol == PER) _perActors.push_back(ap); if (ap->entityTypeSymbol == ORG) _orgActors.push_back(ap); if (ap->entityTypeSymbol == GPE) _gpeActors.push_back(ap); if (ap->entityTypeSymbol == LOC) _locActors.push_back(ap); if (ap->entityTypeSymbol == FAC) _facActors.push_back(ap); } // Nicknames boost::scoped_ptr<UTF8InputStream> stream_scoped_ptr(UTF8InputStream::build()); UTF8InputStream& stream(*stream_scoped_ptr); std::string nicknamesFile = ParamReader::getRequiredParam("nicknames_file"); stream.open(nicknamesFile.c_str()); std::string exceptionString = std::string("Malformed nicknames file: ") + nicknamesFile + " referred to by parameter nicknames_file"; while (!stream.eof()) { Sexp *line = _new Sexp(stream, false, true); if (line->isVoid()) break; std::set<std::wstring> nicknameSet; if (line->getNumChildren() != 2) throw UnexpectedInputException("ActorEditDistance::ActorEditDistance", exceptionString.c_str()); std::wstring name = line->getFirstChild()->getValue().to_string(); std::transform(name.begin(), name.end(), name.begin(), towlower); Sexp *nicknamesSexp = line->getSecondChild(); if (!nicknamesSexp->isList()) throw UnexpectedInputException("ActorEditDistance::ActorEditDistance", exceptionString.c_str()); for (int i = 0; i < nicknamesSexp->getNumChildren(); i++) { Sexp *nicknameSexp = nicknamesSexp->getNthChild(i); std::wstring nickname = L""; if (!nicknameSexp->isList()) throw UnexpectedInputException("ActorEditDistance::ActorEditDistance", exceptionString.c_str()); for (int j = 0; j < nicknameSexp->getNumChildren(); j++) { if (nickname.length() > 0) nickname += L" "; nickname += nicknameSexp->getNthChild(j)->getValue().to_string(); } std::transform(nickname.begin(), nickname.end(), nickname.begin(), towlower); nicknameSet.insert(nickname); //std::cout << "adding: " << UnicodeUtil::toUTF8StdString(nickname) << "\n"; } //std::cout << "New entry: " << UnicodeUtil::toUTF8StdString(name) << "\n"; _nicknames[name] = nicknameSet; delete line; // Add the reverse for each nickname as well BOOST_FOREACH(std::wstring nickname, nicknameSet) { _nicknames[nickname].insert(name); } } stream.close(); } ActorEditDistance::~ActorEditDistance() { //_debugStream.close(); } ActorEditDistance::ActorEditDistanceMap ActorEditDistance::findCloseActors(const Mention *mention, double threshold, const SentenceTheory *st, const DocTheory *dt) { ActorEditDistanceMap closeActors; const SynNode *head = mention->getHead(); CharOffset start_offset = st->getTokenSequence()->getToken(head->getStartToken())->getStartCharOffset(); CharOffset end_offset = st->getTokenSequence()->getToken(head->getEndToken())->getEndCharOffset(); LocatedString *originalName = dt->getDocument()->getOriginalText()->substring(start_offset.value(), end_offset.value() + 1); while (originalName->indexOf(L"\r\n") != -1) originalName->replace(L"\r\n", L" "); while (originalName->indexOf(L"\n") != -1) originalName->replace(L"\n", L" "); while (originalName->indexOf(L" ") != -1) originalName->replace(L" ", L" "); std::wstring name = std::wstring(originalName->toWString()); delete originalName; std::transform(name.begin(), name.end(), name.begin(), towlower); size_t name_len = name.length(); // std::cout << "##############################################\n"; // std::cout << "Checking " << UnicodeUtil::toUTF8StdString(name) << "\n"; // std::cout << "###############################################\n"; //_debugStream << L"-------" << name << L"-------\n"; std::vector<ActorPattern *> *actorPatterns = 0; if (mention->getEntityType().matchesGPE()) actorPatterns = &_gpeActors; else if (mention->getEntityType().matchesPER()) actorPatterns = &_perActors; else if (mention->getEntityType().matchesORG()) actorPatterns = &_orgActors; else if (mention->getEntityType().matchesLOC()) actorPatterns = &_locActors; else if (mention->getEntityType().matchesFAC()) actorPatterns = &_facActors; else return closeActors; std::wstringstream wss; wss << name << L"_" << mention->getEntityType().getName().to_string() << L"_" << threshold; std::wstring cacheKey = wss.str(); if (_cache.find(cacheKey) != _cache.end()) return _cache[cacheKey]; EntityType et = mention->getEntityType(); std::set<std::wstring> equivalentNameSet; equivalentNameSet.insert(name); expandNameToEquivalentSet(name, et, equivalentNameSet); for (size_t i = 0; i < actorPatterns->size(); i++) { std::wstring actorPattern = (*actorPatterns)[i]->lcString; ActorId actor_id = (*actorPatterns)[i]->actor_id; // Check for exact match between equivalent name set (including original name) and pattern std::set<std::wstring>::iterator it1; for (it1 = equivalentNameSet.begin(); it1 != equivalentNameSet.end(); ++it1) { std::wstring n = *it1; if (n == actorPattern) { float similarity = (float)0.98; if (closeActors.find(actor_id) == closeActors.end() || similarity > closeActors[actor_id]) closeActors[actor_id] = similarity; break; } } // Edit distance between name and pattern size_t pat_len = actorPattern.length(); if ((float)name_len / pat_len < threshold || (float)pat_len / name_len < threshold) continue; float similarity = _editDistance.similarity(name, actorPattern); if (similarity < threshold) continue; if (closeActors.find(actor_id) == closeActors.end() || similarity > closeActors[actor_id]) closeActors[actor_id] = similarity; } if (_cache.size() > AED_MAX_ENTRIES) _cache.clear(); _cache[cacheKey] = closeActors; return closeActors; } void ActorEditDistance::expandNameToEquivalentSet(std::wstring name, EntityType entityType, std::set<std::wstring> & eqNames) { if (!entityType.matchesPER()) return; size_t pos = name.find_first_of(L" "); if (pos != std::wstring::npos) { std::wstring firstName = name.substr(0, pos); if (_nicknames.find(firstName) != _nicknames.end()) { std::wstring restOfName = name.substr(pos + 1); std::set<std::wstring> nicknameSet = _nicknames[firstName]; BOOST_FOREACH(std::wstring nickname, nicknameSet) { std::wstring newName = nickname + L" " + restOfName; //std::cout << "Expanded: " << UnicodeUtil::toUTF8StdString(name) << " to " << UnicodeUtil::toUTF8StdString(newName) << "\n"; eqNames.insert(newName); } } } }
36.645933
166
0.673848
[ "vector", "transform" ]
f5d65946b164a3f8f35e0b74f1c2c4f26444d71c
25,599
cpp
C++
SCA/ode-0.12/ode/src/util.cpp
JooseRajamaeki/TVCG18
ddc73f422c267b1c38ede3ba20046efff46a6d74
[ "MIT" ]
6
2019-09-23T09:00:32.000Z
2022-01-09T11:10:49.000Z
SCA/ode-0.12/ode/src/util.cpp
JooseRajamaeki/TVCG18
ddc73f422c267b1c38ede3ba20046efff46a6d74
[ "MIT" ]
null
null
null
SCA/ode-0.12/ode/src/util.cpp
JooseRajamaeki/TVCG18
ddc73f422c267b1c38ede3ba20046efff46a6d74
[ "MIT" ]
1
2022-03-26T17:00:08.000Z
2022-03-26T17:00:08.000Z
/************************************************************************* * * * Open Dynamics Engine, Copyright (C) 2001,2002 Russell L. Smith. * * All rights reserved. Email: russ@q12.org Web: www.q12.org * * * * This library is free software; you can redistribute it and/or * * modify it under the terms of EITHER: * * (1) The GNU Lesser General Public License as published by the Free * * Software Foundation; either version 2.1 of the License, or (at * * your option) any later version. The text of the GNU Lesser * * General Public License is included with this library in the * * file LICENSE.TXT. * * (2) The BSD-style license that is included with this library in * * the file LICENSE-BSD.TXT. * * * * This library is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the files * * LICENSE.TXT and LICENSE-BSD.TXT for more details. * * * *************************************************************************/ #include <ode/ode.h> #include "config.h" #include "objects.h" #include "joints/joint.h" #include "util.h" //**************************************************************************** // Malloc based world stepping memory manager /*extern */dxWorldProcessMemoryManager g_WorldProcessMallocMemoryManager(dAlloc, dRealloc, dFree); /*extern */dxWorldProcessMemoryReserveInfo g_WorldProcessDefaultReserveInfo(dWORLDSTEP_RESERVEFACTOR_DEFAULT, dWORLDSTEP_RESERVESIZE_DEFAULT); //**************************************************************************** // dxWorldProcessContext dxWorldProcessContext::dxWorldProcessContext(): m_pmaIslandsArena(NULL), m_pmaStepperArena(NULL) { // Do nothing } dxWorldProcessContext::~dxWorldProcessContext() { if (m_pmaIslandsArena) { dxWorldProcessMemArena::FreeMemArena(m_pmaIslandsArena); } if (m_pmaStepperArena) { dxWorldProcessMemArena::FreeMemArena(m_pmaStepperArena); } } bool dxWorldProcessContext::IsStructureValid() const { return (!m_pmaIslandsArena || m_pmaIslandsArena->IsStructureValid()) && (!m_pmaStepperArena || m_pmaStepperArena->IsStructureValid()); } void dxWorldProcessContext::CleanupContext() { if (m_pmaIslandsArena) { m_pmaIslandsArena->ResetState(); } if (m_pmaStepperArena) { m_pmaStepperArena->ResetState(); } } dxWorldProcessMemArena *dxWorldProcessContext::ReallocateIslandsMemArena(size_t nMemoryRequirement, const dxWorldProcessMemoryManager *pmmMemortManager, float fReserveFactor, unsigned uiReserveMinimum) { dxWorldProcessMemArena *pmaExistingArena = GetIslandsMemArena(); dxWorldProcessMemArena *pmaNewMemArena = dxWorldProcessMemArena::ReallocateMemArena(pmaExistingArena, nMemoryRequirement, pmmMemortManager, fReserveFactor, uiReserveMinimum); SetIslandsMemArena(pmaNewMemArena); return pmaNewMemArena; } dxWorldProcessMemArena *dxWorldProcessContext::ReallocateStepperMemArena(size_t nMemoryRequirement, const dxWorldProcessMemoryManager *pmmMemortManager, float fReserveFactor, unsigned uiReserveMinimum) { dxWorldProcessMemArena *pmaExistingArena = GetStepperMemArena(); dxWorldProcessMemArena *pmaNewMemArena = dxWorldProcessMemArena::ReallocateMemArena(pmaExistingArena, nMemoryRequirement, pmmMemortManager, fReserveFactor, uiReserveMinimum); SetStepperMemArena(pmaNewMemArena); return pmaNewMemArena; } //**************************************************************************** // Auto disabling void dInternalHandleAutoDisabling (dxWorld *world, dReal stepsize) { dxBody *bb; for ( bb=world->firstbody; bb; bb=(dxBody*)bb->next ) { // don't freeze objects mid-air (patch 1586738) if ( bb->firstjoint == NULL ) continue; // nothing to do unless this body is currently enabled and has // the auto-disable flag set if ( (bb->flags & (dxBodyAutoDisable|dxBodyDisabled)) != dxBodyAutoDisable ) continue; // if sampling / threshold testing is disabled, we can never sleep. if ( bb->adis.average_samples == 0 ) continue; // // see if the body is idle // #ifndef dNODEBUG // sanity check if ( bb->average_counter >= bb->adis.average_samples ) { dUASSERT( bb->average_counter < bb->adis.average_samples, "buffer overflow" ); // something is going wrong, reset the average-calculations bb->average_ready = 0; // not ready for average calculation bb->average_counter = 0; // reset the buffer index } #endif // dNODEBUG // sample the linear and angular velocity bb->average_lvel_buffer[bb->average_counter][0] = bb->lvel[0]; bb->average_lvel_buffer[bb->average_counter][1] = bb->lvel[1]; bb->average_lvel_buffer[bb->average_counter][2] = bb->lvel[2]; bb->average_avel_buffer[bb->average_counter][0] = bb->avel[0]; bb->average_avel_buffer[bb->average_counter][1] = bb->avel[1]; bb->average_avel_buffer[bb->average_counter][2] = bb->avel[2]; bb->average_counter++; // buffer ready test if ( bb->average_counter >= bb->adis.average_samples ) { bb->average_counter = 0; // fill the buffer from the beginning bb->average_ready = 1; // this body is ready now for average calculation } int idle = 0; // Assume it's in motion unless we have samples to disprove it. // enough samples? if ( bb->average_ready ) { idle = 1; // Initial assumption: IDLE // the sample buffers are filled and ready for calculation dVector3 average_lvel, average_avel; // Store first velocity samples average_lvel[0] = bb->average_lvel_buffer[0][0]; average_avel[0] = bb->average_avel_buffer[0][0]; average_lvel[1] = bb->average_lvel_buffer[0][1]; average_avel[1] = bb->average_avel_buffer[0][1]; average_lvel[2] = bb->average_lvel_buffer[0][2]; average_avel[2] = bb->average_avel_buffer[0][2]; // If we're not in "instantaneous mode" if ( bb->adis.average_samples > 1 ) { // add remaining velocities together for ( unsigned int i = 1; i < bb->adis.average_samples; ++i ) { average_lvel[0] += bb->average_lvel_buffer[i][0]; average_avel[0] += bb->average_avel_buffer[i][0]; average_lvel[1] += bb->average_lvel_buffer[i][1]; average_avel[1] += bb->average_avel_buffer[i][1]; average_lvel[2] += bb->average_lvel_buffer[i][2]; average_avel[2] += bb->average_avel_buffer[i][2]; } // make average dReal r1 = dReal( 1.0 ) / dReal( bb->adis.average_samples ); average_lvel[0] *= r1; average_avel[0] *= r1; average_lvel[1] *= r1; average_avel[1] *= r1; average_lvel[2] *= r1; average_avel[2] *= r1; } // threshold test dReal av_lspeed, av_aspeed; av_lspeed = dCalcVectorDot3( average_lvel, average_lvel ); if ( av_lspeed > bb->adis.linear_average_threshold ) { idle = 0; // average linear velocity is too high for idle } else { av_aspeed = dCalcVectorDot3( average_avel, average_avel ); if ( av_aspeed > bb->adis.angular_average_threshold ) { idle = 0; // average angular velocity is too high for idle } } } // if it's idle, accumulate steps and time. // these counters won't overflow because this code doesn't run for disabled bodies. if (idle) { bb->adis_stepsleft--; bb->adis_timeleft -= stepsize; } else { // Reset countdowns bb->adis_stepsleft = bb->adis.idle_steps; bb->adis_timeleft = bb->adis.idle_time; } // disable the body if it's idle for a long enough time if ( bb->adis_stepsleft <= 0 && bb->adis_timeleft <= 0 ) { bb->flags |= dxBodyDisabled; // set the disable flag // disabling bodies should also include resetting the velocity // should prevent jittering in big "islands" bb->lvel[0] = 0; bb->lvel[1] = 0; bb->lvel[2] = 0; bb->avel[0] = 0; bb->avel[1] = 0; bb->avel[2] = 0; } } } //**************************************************************************** // body rotation // return sin(x)/x. this has a singularity at 0 so special handling is needed // for small arguments. static inline dReal sinc (dReal x) { // if |x| < 1e-4 then use a taylor series expansion. this two term expansion // is actually accurate to one LS bit within this range if double precision // is being used - so don't worry! if (dFabs(x) < 1.0e-4) return REAL(1.0) - x*x*REAL(0.166666666666666666667); else return dSin(x)/x; } // given a body b, apply its linear and angular rotation over the time // interval h, thereby adjusting its position and orientation. void dxStepBody (dxBody *b, dReal h) { // cap the angular velocity if (b->flags & dxBodyMaxAngularSpeed) { const dReal max_ang_speed = b->max_angular_speed; const dReal aspeed = dCalcVectorDot3( b->avel, b->avel ); if (aspeed > max_ang_speed*max_ang_speed) { const dReal coef = max_ang_speed/dSqrt(aspeed); dScaleVector3(b->avel, coef); } } // end of angular velocity cap // handle linear velocity for (unsigned int j=0; j<3; j++) b->posr.pos[j] += h * b->lvel[j]; if (b->flags & dxBodyFlagFiniteRotation) { dVector3 irv; // infitesimal rotation vector dQuaternion q; // quaternion for finite rotation if (b->flags & dxBodyFlagFiniteRotationAxis) { // split the angular velocity vector into a component along the finite // rotation axis, and a component orthogonal to it. dVector3 frv; // finite rotation vector dReal k = dCalcVectorDot3 (b->finite_rot_axis,b->avel); frv[0] = b->finite_rot_axis[0] * k; frv[1] = b->finite_rot_axis[1] * k; frv[2] = b->finite_rot_axis[2] * k; irv[0] = b->avel[0] - frv[0]; irv[1] = b->avel[1] - frv[1]; irv[2] = b->avel[2] - frv[2]; // make a rotation quaternion q that corresponds to frv * h. // compare this with the full-finite-rotation case below. h *= REAL(0.5); dReal theta = k * h; q[0] = dCos(theta); dReal s = sinc(theta) * h; q[1] = frv[0] * s; q[2] = frv[1] * s; q[3] = frv[2] * s; } else { // make a rotation quaternion q that corresponds to w * h dReal wlen = dSqrt (b->avel[0]*b->avel[0] + b->avel[1]*b->avel[1] + b->avel[2]*b->avel[2]); h *= REAL(0.5); dReal theta = wlen * h; q[0] = dCos(theta); dReal s = sinc(theta) * h; q[1] = b->avel[0] * s; q[2] = b->avel[1] * s; q[3] = b->avel[2] * s; } // do the finite rotation dQuaternion q2; dQMultiply0 (q2,q,b->q); for (unsigned int j=0; j<4; j++) b->q[j] = q2[j]; // do the infitesimal rotation if required if (b->flags & dxBodyFlagFiniteRotationAxis) { dReal dq[4]; dWtoDQ (irv,b->q,dq); for (unsigned int j=0; j<4; j++) b->q[j] += h * dq[j]; } } else { // the normal way - do an infitesimal rotation dReal dq[4]; dWtoDQ (b->avel,b->q,dq); for (unsigned int j=0; j<4; j++) b->q[j] += h * dq[j]; } // normalize the quaternion and convert it to a rotation matrix dNormalize4 (b->q); dQtoR (b->q,b->posr.R); // notify all attached geoms that this body has moved for (dxGeom *geom = b->geom; geom; geom = dGeomGetBodyNext (geom)) dGeomMoved (geom); // notify the user if (b->moved_callback) b->moved_callback(b); // damping if (b->flags & dxBodyLinearDamping) { const dReal lin_threshold = b->dampingp.linear_threshold; const dReal lin_speed = dCalcVectorDot3( b->lvel, b->lvel ); if ( lin_speed > lin_threshold) { const dReal k = 1 - b->dampingp.linear_scale; dScaleVector3(b->lvel, k); } } if (b->flags & dxBodyAngularDamping) { const dReal ang_threshold = b->dampingp.angular_threshold; const dReal ang_speed = dCalcVectorDot3( b->avel, b->avel ); if ( ang_speed > ang_threshold) { const dReal k = 1 - b->dampingp.angular_scale; dScaleVector3(b->avel, k); } } } //**************************************************************************** // island processing // This estimates dynamic memory requirements for dxProcessIslands static size_t EstimateIslandsProcessingMemoryRequirements(dxWorld *world) { size_t res = 0; size_t islandcounts = dEFFICIENT_SIZE((size_t)(unsigned)world->nb * 2 * sizeof(int)); res += islandcounts; size_t bodiessize = dEFFICIENT_SIZE((size_t)(unsigned)world->nb * sizeof(dxBody*)); size_t jointssize = dEFFICIENT_SIZE((size_t)(unsigned)world->nj * sizeof(dxJoint*)); res += bodiessize + jointssize; size_t sesize = (bodiessize < jointssize) ? bodiessize : jointssize; res += sesize; return res; } static size_t BuildIslandsAndEstimateStepperMemoryRequirements( dxWorldProcessIslandsInfo &islandsinfo, dxWorldProcessMemArena *memarena, dxWorld *world, dReal stepsize, dmemestimate_fn_t stepperestimate) { const unsigned int sizeelements = 2; size_t maxreq = 0; // handle auto-disabling of bodies dInternalHandleAutoDisabling (world,stepsize); unsigned int nb = world->nb, nj = world->nj; // Make array for island body/joint counts unsigned int *islandsizes = memarena->AllocateArray<unsigned int>(2 * (size_t)nb); unsigned int *sizescurr; // make arrays for body and joint lists (for a single island) to go into dxBody **body = memarena->AllocateArray<dxBody *>(nb); dxJoint **joint = memarena->AllocateArray<dxJoint *>(nj); BEGIN_STATE_SAVE(memarena, stackstate) { // allocate a stack of unvisited bodies in the island. the maximum size of // the stack can be the lesser of the number of bodies or joints, because // new bodies are only ever added to the stack by going through untagged // joints. all the bodies in the stack must be tagged! unsigned int stackalloc = (nj < nb) ? nj : nb; dxBody **stack = memarena->AllocateArray<dxBody *>(stackalloc); { // set all body/joint tags to 0 for (dxBody *b=world->firstbody; b; b=(dxBody*)b->next) b->tag = 0; for (dxJoint *j=world->firstjoint; j; j=(dxJoint*)j->next) j->tag = 0; } sizescurr = islandsizes; dxBody **bodystart = body; dxJoint **jointstart = joint; for (dxBody *bb=world->firstbody; bb; bb=(dxBody*)bb->next) { // get bb = the next enabled, untagged body, and tag it if (!bb->tag) { if (!(bb->flags & dxBodyDisabled)) { bb->tag = 1; dxBody **bodycurr = bodystart; dxJoint **jointcurr = jointstart; // tag all bodies and joints starting from bb. *bodycurr++ = bb; unsigned int stacksize = 0; dxBody *b = bb; while (true) { // traverse and tag all body's joints, add untagged connected bodies // to stack for (dxJointNode *n=b->firstjoint; n; n=n->next) { dxJoint *njoint = n->joint; if (!njoint->tag) { if (njoint->isEnabled()) { njoint->tag = 1; *jointcurr++ = njoint; dxBody *nbody = n->body; // Body disabled flag is not checked here. This is how auto-enable works. if (nbody && nbody->tag <= 0) { nbody->tag = 1; // Make sure all bodies are in the enabled state. nbody->flags &= ~dxBodyDisabled; stack[stacksize++] = nbody; } } else { njoint->tag = -1; // Used in Step to prevent search over disabled joints (not needed for QuickStep so far) } } } dIASSERT(stacksize <= (unsigned int)world->nb); dIASSERT(stacksize <= (unsigned int)world->nj); if (stacksize == 0) { break; } b = stack[--stacksize]; // pop body off stack *bodycurr++ = b; // put body on body list } unsigned int bcount = (unsigned int)(bodycurr - bodystart); unsigned int jcount = (unsigned int)(jointcurr - jointstart); dIASSERT((size_t)(bodycurr - bodystart) <= (size_t)UINT_MAX); dIASSERT((size_t)(jointcurr - jointstart) <= (size_t)UINT_MAX); sizescurr[0] = bcount; sizescurr[1] = jcount; sizescurr += sizeelements; size_t islandreq = stepperestimate(bodystart, bcount, jointstart, jcount); maxreq = (maxreq > islandreq) ? maxreq : islandreq; bodystart = bodycurr; jointstart = jointcurr; } else { bb->tag = -1; // Not used so far (assigned to retain consistency with joints) } } } } END_STATE_SAVE(memarena, stackstate); # ifndef dNODEBUG // if debugging, check that all objects (except for disabled bodies, // unconnected joints, and joints that are connected to disabled bodies) // were tagged. { for (dxBody *b=world->firstbody; b; b=(dxBody*)b->next) { if (b->flags & dxBodyDisabled) { if (b->tag > 0) dDebug (0,"disabled body tagged"); } else { if (b->tag <= 0) dDebug (0,"enabled body not tagged"); } } for (dxJoint *j=world->firstjoint; j; j=(dxJoint*)j->next) { if ( (( j->node[0].body && (j->node[0].body->flags & dxBodyDisabled)==0 ) || (j->node[1].body && (j->node[1].body->flags & dxBodyDisabled)==0) ) && j->isEnabled() ) { if (j->tag <= 0) dDebug (0,"attached enabled joint not tagged"); } else { if (j->tag > 0) dDebug (0,"unattached or disabled joint tagged"); } } } # endif size_t islandcount = ((size_t)(sizescurr - islandsizes) / sizeelements); islandsinfo.AssignInfo(islandcount, islandsizes, body, joint); return maxreq; } // this groups all joints and bodies in a world into islands. all objects // in an island are reachable by going through connected bodies and joints. // each island can be simulated separately. // note that joints that are not attached to anything will not be included // in any island, an so they do not affect the simulation. // // this function starts new island from unvisited bodies. however, it will // never start a new islands from a disabled body. thus islands of disabled // bodies will not be included in the simulation. disabled bodies are // re-enabled if they are found to be part of an active island. void dxProcessIslands (dxWorld *world, const dxWorldProcessIslandsInfo &islandsinfo, dReal stepsize, dstepper_fn_t stepper) { const unsigned int sizeelements = 2; dxStepWorkingMemory *wmem = world->wmem; dIASSERT(wmem != NULL); dxWorldProcessContext *context = wmem->GetWorldProcessingContext(); dIASSERT(context != NULL); size_t islandcount = islandsinfo.GetIslandsCount(); unsigned int const *islandsizes = islandsinfo.GetIslandSizes(); dxBody *const *body = islandsinfo.GetBodiesArray(); dxJoint *const *joint = islandsinfo.GetJointsArray(); dxWorldProcessMemArena *stepperarena = context->GetStepperMemArena(); dxBody *const *bodystart = body; dxJoint *const *jointstart = joint; unsigned int const *const sizesend = islandsizes + islandcount * sizeelements; for (unsigned int const *sizescurr = islandsizes; sizescurr != sizesend; sizescurr += sizeelements) { unsigned int bcount = sizescurr[0]; unsigned int jcount = sizescurr[1]; BEGIN_STATE_SAVE(stepperarena, stepperstate) { // now do something with body and joint lists stepper (stepperarena,world,bodystart,bcount,jointstart,jcount,stepsize); } END_STATE_SAVE(stepperarena, stepperstate); bodystart += bcount; jointstart += jcount; } } //**************************************************************************** // World processing context management dxWorldProcessMemArena *dxWorldProcessMemArena::ReallocateMemArena ( dxWorldProcessMemArena *oldarena, size_t memreq, const dxWorldProcessMemoryManager *memmgr, float rsrvfactor, unsigned rsrvminimum) { dxWorldProcessMemArena *arena = oldarena; bool allocsuccess = false; size_t nOldArenaSize; void *pOldArenaBuffer; do { size_t oldmemsize = oldarena ? oldarena->GetMemorySize() : 0; if (oldarena == NULL || oldmemsize < memreq) { nOldArenaSize = oldarena ? dxWorldProcessMemArena::MakeArenaSize(oldmemsize) : 0; pOldArenaBuffer = oldarena ? oldarena->m_pArenaBegin : NULL; if (!dxWorldProcessMemArena::IsArenaPossible(memreq)) { break; } size_t arenareq = dxWorldProcessMemArena::MakeArenaSize(memreq); size_t arenareq_with_reserve = AdjustArenaSizeForReserveRequirements(arenareq, rsrvfactor, rsrvminimum); size_t memreq_with_reserve = memreq + (arenareq_with_reserve - arenareq); if (oldarena != NULL) { oldarena->m_pArenaMemMgr->m_fnFree(pOldArenaBuffer, nOldArenaSize); oldarena = NULL; // Zero variables to avoid another freeing on exit pOldArenaBuffer = NULL; nOldArenaSize = 0; } // Allocate new arena void *pNewArenaBuffer = memmgr->m_fnAlloc(arenareq_with_reserve); if (pNewArenaBuffer == NULL) { break; } arena = (dxWorldProcessMemArena *)dEFFICIENT_PTR(pNewArenaBuffer); void *blockbegin = dEFFICIENT_PTR(arena + 1); void *blockend = dOFFSET_EFFICIENTLY(blockbegin, memreq_with_reserve); arena->m_pAllocBegin = blockbegin; arena->m_pAllocEnd = blockend; arena->m_pArenaBegin = pNewArenaBuffer; arena->m_pAllocCurrent = blockbegin; arena->m_pArenaMemMgr = memmgr; } allocsuccess = true; } while (false); if (!allocsuccess) { if (pOldArenaBuffer != NULL) { dIASSERT(oldarena != NULL); oldarena->m_pArenaMemMgr->m_fnFree(pOldArenaBuffer, nOldArenaSize); } arena = NULL; } return arena; } void dxWorldProcessMemArena::FreeMemArena (dxWorldProcessMemArena *arena) { size_t memsize = arena->GetMemorySize(); size_t arenasize = dxWorldProcessMemArena::MakeArenaSize(memsize); void *pArenaBegin = arena->m_pArenaBegin; arena->m_pArenaMemMgr->m_fnFree(pArenaBegin, arenasize); } size_t dxWorldProcessMemArena::AdjustArenaSizeForReserveRequirements(size_t arenareq, float rsrvfactor, unsigned rsrvminimum) { float scaledarena = arenareq * rsrvfactor; size_t adjustedarena = (scaledarena < SIZE_MAX) ? (size_t)scaledarena : SIZE_MAX; size_t boundedarena = (adjustedarena > rsrvminimum) ? adjustedarena : (size_t)rsrvminimum; return dEFFICIENT_SIZE(boundedarena); } bool dxReallocateWorldProcessContext (dxWorld *world, dxWorldProcessIslandsInfo &islandsinfo, dReal stepsize, dmemestimate_fn_t stepperestimate) { dxStepWorkingMemory *wmem = AllocateOnDemand(world->wmem); if (wmem == NULL) return false; dxWorldProcessContext *context = wmem->SureGetWorldProcessingContext(); if (context == NULL) return false; dIASSERT (context->IsStructureValid()); const dxWorldProcessMemoryReserveInfo *reserveinfo = wmem->SureGetMemoryReserveInfo(); const dxWorldProcessMemoryManager *memmgr = wmem->SureGetMemoryManager(); size_t islandsreq = EstimateIslandsProcessingMemoryRequirements(world); dIASSERT(islandsreq == dEFFICIENT_SIZE(islandsreq)); dxWorldProcessMemArena *stepperarena = NULL; dxWorldProcessMemArena *islandsarena = context->ReallocateIslandsMemArena(islandsreq, memmgr, 1.0f, reserveinfo->m_uiReserveMinimum); if (islandsarena != NULL) { size_t stepperreq = BuildIslandsAndEstimateStepperMemoryRequirements(islandsinfo, islandsarena, world, stepsize, stepperestimate); dIASSERT(stepperreq == dEFFICIENT_SIZE(stepperreq)); stepperarena = context->ReallocateStepperMemArena(stepperreq, memmgr, reserveinfo->m_fReserveFactor, reserveinfo->m_uiReserveMinimum); } return stepperarena != NULL; } void dxCleanupWorldProcessContext (dxWorld *world) { dxStepWorkingMemory *wmem = world->wmem; if (wmem != NULL) { dxWorldProcessContext *context = wmem->GetWorldProcessingContext(); if (context != NULL) { context->CleanupContext(); dIASSERT(context->IsStructureValid()); } } } dxWorldProcessMemArena *dxAllocateTemporaryWorldProcessMemArena( size_t memreq, const dxWorldProcessMemoryManager *memmgr/*=NULL*/, const dxWorldProcessMemoryReserveInfo *reserveinfo/*=NULL*/) { const dxWorldProcessMemoryManager *surememmgr = memmgr ? memmgr : &g_WorldProcessMallocMemoryManager; const dxWorldProcessMemoryReserveInfo *surereserveinfo = reserveinfo ? reserveinfo : &g_WorldProcessDefaultReserveInfo; dxWorldProcessMemArena *arena = dxWorldProcessMemArena::ReallocateMemArena(NULL, memreq, surememmgr, surereserveinfo->m_fReserveFactor, surereserveinfo->m_uiReserveMinimum); return arena; } void dxFreeTemporaryWorldProcessMemArena(dxWorldProcessMemArena *arena) { dxWorldProcessMemArena::FreeMemArena(arena); }
35.802797
176
0.640377
[ "vector" ]
f5d803ba22fd9c0027100e0905d285641989eedd
8,685
cpp
C++
hashing/double_hash_hash_table.cpp
icbdubey/C-Plus-Plus
d51947a9d5a96695ea52db4394db6518d777bddf
[ "MIT" ]
20,295
2016-07-17T06:29:04.000Z
2022-03-31T23:32:16.000Z
hashing/double_hash_hash_table.cpp
icbdubey/C-Plus-Plus
d51947a9d5a96695ea52db4394db6518d777bddf
[ "MIT" ]
1,399
2017-06-02T05:59:45.000Z
2022-03-31T00:55:00.000Z
hashing/double_hash_hash_table.cpp
icbdubey/C-Plus-Plus
d51947a9d5a96695ea52db4394db6518d777bddf
[ "MIT" ]
5,775
2016-10-14T08:10:18.000Z
2022-03-31T18:26:39.000Z
/** * @file double_hash_hash_table.cpp * @author [achance6](https://github.com/achance6) * @author [Krishna Vedala](https://github.com/kvedala) * @brief Storage mechanism using [double-hashed * keys](https://en.wikipedia.org/wiki/Double_hashing). * @note The implementation can be optimized by using OOP style. */ #include <iostream> #include <memory> #include <vector> /** * @addtogroup open_addressing Open Addressing * @{ * @namespace double_hashing * @brief An implementation of hash table using [double * hashing](https://en.wikipedia.org/wiki/Double_hashing) algorithm. */ namespace double_hashing { // fwd declarations using Entry = struct Entry; bool putProber(const Entry& entry, int key); bool searchingProber(const Entry& entry, int key); void add(int key); // Undocumented globals int notPresent; std::vector<Entry> table; int totalSize; int tomb = -1; int size; bool rehashing; /** Node object that holds key */ struct Entry { explicit Entry(int key = notPresent) : key(key) {} ///< constructor int key; ///< key value }; /** * @brief Hash a key. Uses the STL library's `std::hash()` function. * * @param key value to hash * @return hash value of the key */ size_t hashFxn(int key) { std::hash<int> hash; return hash(key); } /** * @brief Used for second hash function * * @param key key value to hash * @return hash value of the key */ size_t otherHashFxn(int key) { std::hash<int> hash; return 1 + (7 - (hash(key) % 7)); } /** * @brief Performs double hashing to resolve collisions * * @param key key value to apply double-hash on * @param searching `true` to check for conflicts * @return Index of key when found * @return new hash if no conflicts present */ int doubleHash(int key, bool searching) { int hash = static_cast<int>(hashFxn(key)); int i = 0; Entry entry; do { int index = static_cast<int>(hash + (i * otherHashFxn(key))) % totalSize; entry = table[index]; if (searching) { if (entry.key == notPresent) { return notPresent; } if (searchingProber(entry, key)) { std::cout << "Found key!" << std::endl; return index; } std::cout << "Found tombstone or equal hash, checking next" << std::endl; i++; } else { if (putProber(entry, key)) { if (!rehashing) { std::cout << "Spot found!" << std::endl; } return index; } if (!rehashing) { std::cout << "Spot taken, looking at next (next index:" << " " << static_cast<int>(hash + (i * otherHashFxn(key))) % totalSize << ")" << std::endl; } i++; } if (i == totalSize * 100) { std::cout << "DoubleHash probe failed" << std::endl; return notPresent; } } while (entry.key != notPresent); return notPresent; } /** Finds empty spot in a vector * @param entry vector to search in * @param key key to search for * @returns `true` if key is not present or is a `toumb` * @returns `false` is already occupied */ bool putProber(const Entry& entry, int key) { if (entry.key == notPresent || entry.key == tomb) { return true; } return false; } /** Looks for a matching key * @param entry vector to search in * @param key key value to search * @returns `true` if found * @returns `false` if not found */ bool searchingProber(const Entry& entry, int key) { if (entry.key == key) { return true; } return false; } /** Displays the table * @returns None */ void display() { for (int i = 0; i < totalSize; i++) { if (table[i].key == notPresent) { std::cout << " Empty "; } else if (table[i].key == tomb) { std::cout << " Tomb "; } else { std::cout << " "; std::cout << table[i].key; std::cout << " "; } } std::cout << std::endl; } /** Rehashes the table into a bigger table * @returns None */ void rehash() { // Necessary so wall of add info isn't printed all at once rehashing = true; int oldSize = totalSize; std::vector<Entry> oldTable(table); // Really this should use the next prime number greater than totalSize * 2 table = std::vector<Entry>(totalSize * 2); totalSize *= 2; for (int i = 0; i < oldSize; i++) { if (oldTable[i].key != -1 && oldTable[i].key != notPresent) { size--; // Size stays the same (add increments size) add(oldTable[i].key); } } // delete[] oldTable; // oldTable.reset(); rehashing = false; std::cout << "Table was rehashed, new size is: " << totalSize << std::endl; } /** Checks for load factor here * @param key key value to add to the table */ void add(int key) { // auto* entry = new Entry(); // entry->key = key; int index = doubleHash(key, false); table[index].key = key; // Load factor greater than 0.5 causes resizing if (++size / static_cast<double>(totalSize) >= 0.5) { rehash(); } } /** Removes key. Leaves tombstone upon removal. * @param key key value to remove */ void remove(int key) { int index = doubleHash(key, true); if (index == notPresent) { std::cout << "key not found" << std::endl; } table[index].key = tomb; std::cout << "Removal successful, leaving tombstone" << std::endl; size--; } /** Information about the adding process * @param key key value to add to table */ void addInfo(int key) { std::cout << "Initial table: "; display(); std::cout << std::endl; std::cout << "hash of " << key << " is " << hashFxn(key) << " % " << totalSize << " == " << hashFxn(key) % totalSize; std::cout << std::endl; add(key); std::cout << "New table: "; display(); } /** Information about removal process * @param key key value to remove from table */ void removalInfo(int key) { std::cout << "Initial table: "; display(); std::cout << std::endl; std::cout << "hash of " << key << " is " << hashFxn(key) << " % " << totalSize << " == " << hashFxn(key) % totalSize; std::cout << std::endl; remove(key); std::cout << "New table: "; display(); } } // namespace double_hashing /** * @} */ using double_hashing::Entry; using double_hashing::table; using double_hashing::totalSize; /** Main program * @returns 0 on success */ int main() { int cmd = 0, hash = 0, key = 0; std::cout << "Enter the initial size of Hash Table. = "; std::cin >> totalSize; table = std::vector<Entry>(totalSize); bool loop = true; while (loop) { std::cout << std::endl; std::cout << "PLEASE CHOOSE -" << std::endl; std::cout << "1. Add key. (Numeric only)" << std::endl; std::cout << "2. Remove key." << std::endl; std::cout << "3. Find key." << std::endl; std::cout << "4. Generate Hash. (Numeric only)" << std::endl; std::cout << "5. Display Hash table." << std::endl; std::cout << "6. Exit." << std::endl; std::cin >> cmd; switch (cmd) { case 1: std::cout << "Enter key to add = "; std::cin >> key; double_hashing::addInfo(key); break; case 2: std::cout << "Enter key to remove = "; std::cin >> key; double_hashing::removalInfo(key); break; case 3: { std::cout << "Enter key to search = "; std::cin >> key; Entry entry = table[double_hashing::doubleHash(key, true)]; if (entry.key == double_hashing::notPresent) { std::cout << "Key not present"; } break; } case 4: std::cout << "Enter element to generate hash = "; std::cin >> key; std::cout << "Hash of " << key << " is = " << double_hashing::hashFxn(key); break; case 5: double_hashing::display(); break; default: loop = false; break; // delete[] table; } std::cout << std::endl; } return 0; }
28.569079
79
0.529073
[ "object", "vector" ]
f5d93afd544eba713914116e1163c5bedcabfb16
2,950
cpp
C++
test/module/irohad/consensus/yac/yac_proposal_storage_test.cpp
coderintherye/iroha
68509282851130c9818f21acef1ef28e53622315
[ "Apache-2.0" ]
null
null
null
test/module/irohad/consensus/yac/yac_proposal_storage_test.cpp
coderintherye/iroha
68509282851130c9818f21acef1ef28e53622315
[ "Apache-2.0" ]
null
null
null
test/module/irohad/consensus/yac/yac_proposal_storage_test.cpp
coderintherye/iroha
68509282851130c9818f21acef1ef28e53622315
[ "Apache-2.0" ]
null
null
null
/** * Copyright Soramitsu Co., Ltd. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0 */ #include "consensus/yac/storage/yac_proposal_storage.hpp" #include <gtest/gtest.h> #include "consensus/yac/storage/yac_common.hpp" #include "logger/logger.hpp" #include "module/irohad/consensus/yac/yac_mocks.hpp" using namespace iroha::consensus::yac; static logger::Logger log_ = logger::testLog("YacProposalStorage"); class YacProposalStorageTest : public ::testing::Test { public: YacHash hash; PeersNumberType number_of_peers; YacProposalStorage storage = YacProposalStorage(iroha::consensus::Round{1, 1}, 4); std::vector<VoteMessage> valid_votes; void SetUp() override { hash = YacHash(iroha::consensus::Round{1, 1}, "proposal", "commit"); number_of_peers = 7; storage = YacProposalStorage(iroha::consensus::Round{1, 1}, number_of_peers); valid_votes = [this]() { std::vector<VoteMessage> votes; for (auto i = 0u; i < number_of_peers; ++i) { votes.push_back(create_vote(hash, std::to_string(i))); } return votes; }(); } }; TEST_F(YacProposalStorageTest, YacProposalStorageWhenCommitCase) { log_->info( "Init storage => insert unique votes => " "expected commit"); for (auto i = 0u; i < 4; ++i) { ASSERT_EQ(boost::none, storage.insert(valid_votes.at(i))); } for (auto i = 4u; i < 7; ++i) { auto commit = storage.insert(valid_votes.at(i)); log_->info("Commit: {}", logger::opt_to_string(commit, [](auto answer) { return "value"; })); ASSERT_NE(boost::none, commit); ASSERT_EQ(i + 1, boost::get<CommitMessage>(*commit).votes.size()); } } TEST_F(YacProposalStorageTest, YacProposalStorageWhenInsertNotUnique) { log_->info( "Init storage => insert not-unique votes => " "expected absence of commit"); for (auto i = 0; i < 7; ++i) { auto fixed_index = 0; ASSERT_EQ(boost::none, storage.insert(valid_votes.at(fixed_index))); } } TEST_F(YacProposalStorageTest, YacProposalStorageWhenRejectCase) { log_->info( "Init storage => insert votes for reject case => " "expected absence of commit"); // insert 3 vote for hash 1 for (auto i = 0; i < 3; ++i) { ASSERT_EQ(boost::none, storage.insert(valid_votes.at(i))); } // insert 2 for other hash auto other_hash = YacHash(iroha::consensus::Round{1, 1}, hash.vote_hashes.proposal_hash, "other_commit"); for (auto i = 0; i < 2; ++i) { auto answer = storage.insert( create_vote(other_hash, std::to_string(valid_votes.size() + 1 + i))); ASSERT_EQ(boost::none, answer); } // insert more one for other hash auto answer = storage.insert( create_vote(other_hash, std::to_string(2 * valid_votes.size() + 1))); ASSERT_NE(boost::none, answer); ASSERT_EQ(6, boost::get<RejectMessage>(*answer).votes.size()); }
30.729167
77
0.647458
[ "vector" ]
f5dae9ad7e8e29a549aac242a2d5f63cb14b7d9e
9,072
cc
C++
content/browser/accessibility/accessibility_tree_formatter_base.cc
sarang-apps/darshan_browser
173649bb8a7c656dc60784d19e7bb73e07c20daa
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
content/browser/accessibility/accessibility_tree_formatter_base.cc
sarang-apps/darshan_browser
173649bb8a7c656dc60784d19e7bb73e07c20daa
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
content/browser/accessibility/accessibility_tree_formatter_base.cc
sarang-apps/darshan_browser
173649bb8a7c656dc60784d19e7bb73e07c20daa
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
// Copyright 2019 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "content/browser/accessibility/accessibility_tree_formatter_base.h" #include <stddef.h> #include <memory> #include <utility> #include "base/logging.h" #include "base/strings/pattern.h" #include "base/strings/string_number_conversions.h" #include "base/strings/string_util.h" #include "base/strings/stringprintf.h" #include "base/strings/utf_string_conversions.h" #include "content/browser/accessibility/accessibility_tree_formatter_blink.h" #include "content/browser/accessibility/browser_accessibility_manager.h" #include "content/browser/renderer_host/render_widget_host_view_base.h" #include "content/browser/web_contents/web_contents_impl.h" #include "content/public/browser/web_contents.h" namespace content { namespace { const char kIndentSymbol = '+'; const int kIndentSymbolCount = 2; const char kSkipString[] = "@NO_DUMP"; const char kSkipChildren[] = "@NO_CHILDREN_DUMP"; } // namespace AccessibilityTreeFormatter::TestPass AccessibilityTreeFormatter::GetTestPass( size_t index) { std::vector<content::AccessibilityTreeFormatter::TestPass> passes = content::AccessibilityTreeFormatter::GetTestPasses(); CHECK_LT(index, passes.size()); return passes[index]; } // static base::string16 AccessibilityTreeFormatterBase::DumpAccessibilityTreeFromManager( BrowserAccessibilityManager* ax_mgr, bool internal, std::vector<PropertyFilter> property_filters) { std::unique_ptr<AccessibilityTreeFormatter> formatter; if (internal) formatter = std::make_unique<AccessibilityTreeFormatterBlink>(); else formatter = Create(); base::string16 accessibility_contents_utf16; formatter->SetPropertyFilters(property_filters); std::unique_ptr<base::DictionaryValue> dict = static_cast<AccessibilityTreeFormatterBase*>(formatter.get()) ->BuildAccessibilityTree(ax_mgr->GetRoot()); formatter->FormatAccessibilityTree(*dict, &accessibility_contents_utf16); return accessibility_contents_utf16; } bool AccessibilityTreeFormatter::MatchesPropertyFilters( const std::vector<PropertyFilter>& property_filters, const base::string16& text, bool default_result) { bool allow = default_result; for (const auto& filter : property_filters) { if (base::MatchPattern(text, filter.match_str)) { switch (filter.type) { case PropertyFilter::ALLOW_EMPTY: allow = true; break; case PropertyFilter::ALLOW: allow = (!base::MatchPattern(text, base::UTF8ToUTF16("*=''"))); break; case PropertyFilter::DENY: allow = false; break; } } } return allow; } bool AccessibilityTreeFormatter::MatchesNodeFilters( const std::vector<NodeFilter>& node_filters, const base::DictionaryValue& dict) { for (const auto& filter : node_filters) { base::string16 value; if (!dict.GetString(filter.property, &value)) { continue; } if (base::MatchPattern(value, filter.pattern)) { return true; } } return false; } AccessibilityTreeFormatterBase::AccessibilityTreeFormatterBase() = default; AccessibilityTreeFormatterBase::~AccessibilityTreeFormatterBase() = default; void AccessibilityTreeFormatterBase::FormatAccessibilityTree( const base::DictionaryValue& dict, base::string16* contents) { RecursiveFormatAccessibilityTree(dict, contents); } void AccessibilityTreeFormatterBase::FormatAccessibilityTreeForTesting( ui::AXPlatformNodeDelegate* root, base::string16* contents) { auto* node_internal = BrowserAccessibility::FromAXPlatformNodeDelegate(root); DCHECK(node_internal); FormatAccessibilityTree(*BuildAccessibilityTree(node_internal), contents); } std::unique_ptr<base::DictionaryValue> AccessibilityTreeFormatterBase::FilterAccessibilityTree( const base::DictionaryValue& dict) { auto filtered_dict = std::make_unique<base::DictionaryValue>(); ProcessTreeForOutput(dict, filtered_dict.get()); const base::ListValue* children; if (dict.GetList(kChildrenDictAttr, &children) && !children->empty()) { const base::DictionaryValue* child_dict; auto filtered_children = std::make_unique<base::ListValue>(); for (size_t i = 0; i < children->GetSize(); i++) { children->GetDictionary(i, &child_dict); auto filtered_child = FilterAccessibilityTree(*child_dict); filtered_children->Append(std::move(filtered_child)); } filtered_dict->Set(kChildrenDictAttr, std::move(filtered_children)); } return filtered_dict; } void AccessibilityTreeFormatterBase::RecursiveFormatAccessibilityTree( const base::DictionaryValue& dict, base::string16* contents, int depth) { // Check dictionary against node filters, may require us to skip this node // and its children. if (MatchesNodeFilters(dict)) return; base::string16 indent = base::string16(depth * kIndentSymbolCount, kIndentSymbol); base::string16 line = indent + ProcessTreeForOutput(dict); if (line.find(base::ASCIIToUTF16(kSkipString)) != base::string16::npos) return; // Normalize any Windows-style line endings by removing \r. base::RemoveChars(line, base::ASCIIToUTF16("\r"), &line); // Replace literal newlines with "<newline>" base::ReplaceChars(line, base::ASCIIToUTF16("\n"), base::ASCIIToUTF16("<newline>"), &line); *contents += line + base::ASCIIToUTF16("\n"); if (line.find(base::ASCIIToUTF16(kSkipChildren)) != base::string16::npos) return; const base::ListValue* children; if (!dict.GetList(kChildrenDictAttr, &children)) return; const base::DictionaryValue* child_dict; for (size_t i = 0; i < children->GetSize(); i++) { children->GetDictionary(i, &child_dict); RecursiveFormatAccessibilityTree(*child_dict, contents, depth + 1); } } void AccessibilityTreeFormatterBase::SetPropertyFilters( const std::vector<PropertyFilter>& property_filters) { property_filters_ = property_filters; } void AccessibilityTreeFormatterBase::SetNodeFilters( const std::vector<NodeFilter>& node_filters) { node_filters_ = node_filters; } void AccessibilityTreeFormatterBase::set_show_ids(bool show_ids) { show_ids_ = show_ids; } base::FilePath::StringType AccessibilityTreeFormatterBase::GetVersionSpecificExpectedFileSuffix() { return FILE_PATH_LITERAL(""); } bool AccessibilityTreeFormatterBase::MatchesPropertyFilters( const base::string16& text, bool default_result) const { return AccessibilityTreeFormatter::MatchesPropertyFilters( property_filters_, text, default_result); } bool AccessibilityTreeFormatterBase::MatchesNodeFilters( const base::DictionaryValue& dict) const { return AccessibilityTreeFormatter::MatchesNodeFilters(node_filters_, dict); } base::string16 AccessibilityTreeFormatterBase::FormatCoordinates( const base::DictionaryValue& value, const std::string& name, const std::string& x_name, const std::string& y_name) { int x, y; value.GetInteger(x_name, &x); value.GetInteger(y_name, &y); std::string xy_str(base::StringPrintf("%s=(%d, %d)", name.c_str(), x, y)); return base::UTF8ToUTF16(xy_str); } base::string16 AccessibilityTreeFormatterBase::FormatRectangle( const base::DictionaryValue& value, const std::string& name, const std::string& left_name, const std::string& top_name, const std::string& width_name, const std::string& height_name) { int left, top, width, height; value.GetInteger(left_name, &left); value.GetInteger(top_name, &top); value.GetInteger(width_name, &width); value.GetInteger(height_name, &height); std::string rect_str(base::StringPrintf("%s=(%d, %d, %d, %d)", name.c_str(), left, top, width, height)); return base::UTF8ToUTF16(rect_str); } bool AccessibilityTreeFormatterBase::WriteAttribute(bool include_by_default, const std::string& attr, base::string16* line) { return WriteAttribute(include_by_default, base::UTF8ToUTF16(attr), line); } bool AccessibilityTreeFormatterBase::WriteAttribute(bool include_by_default, const base::string16& attr, base::string16* line) { if (attr.empty()) return false; if (!MatchesPropertyFilters(attr, include_by_default)) return false; if (!line->empty()) *line += base::ASCIIToUTF16(" "); *line += attr; return true; } void AccessibilityTreeFormatterBase::AddPropertyFilter( std::vector<PropertyFilter>* property_filters, std::string filter, PropertyFilter::Type type) { property_filters->push_back(PropertyFilter(base::ASCIIToUTF16(filter), type)); } void AccessibilityTreeFormatterBase::AddDefaultFilters( std::vector<PropertyFilter>* property_filters) {} } // namespace content
34.363636
80
0.720569
[ "vector" ]
f5de18c84c9276476f2b1e35a437ade4b5177e47
4,504
cpp
C++
vstgui/lib/cgraphicspath.cpp
Kingston1/vstgui
e448091ba9a13139f2e6bed6d55053348bd8fc56
[ "BSD-3-Clause" ]
11
2019-05-02T18:43:51.000Z
2022-03-19T02:48:51.000Z
vstgui/lib/cgraphicspath.cpp
Kingston1/vstgui
e448091ba9a13139f2e6bed6d55053348bd8fc56
[ "BSD-3-Clause" ]
11
2019-02-09T16:15:34.000Z
2021-03-24T06:28:56.000Z
vstgui/lib/cgraphicspath.cpp
Kingston1/vstgui
e448091ba9a13139f2e6bed6d55053348bd8fc56
[ "BSD-3-Clause" ]
8
2019-02-09T07:30:04.000Z
2021-04-25T09:49:34.000Z
// This file is part of VSTGUI. It is subject to the license terms // in the LICENSE file found in the top-level directory of this // distribution and at http://github.com/steinbergmedia/vstgui/LICENSE #include "cgraphicspath.h" #include "cdrawcontext.h" #include "cgraphicstransform.h" namespace VSTGUI { //----------------------------------------------------------------------------- void CGraphicsPath::addRoundRect (const CRect& size, CCoord radius) { if (radius == 0.) { addRect (size); return; } CRect rect2 (size); rect2.normalize (); const CCoord left = rect2.left; const CCoord right = rect2.right; const CCoord top = rect2.top; const CCoord bottom = rect2.bottom; beginSubpath (CPoint (right-radius, top)); addArc (CRect (right - 2.0 * radius, top, right, top + 2.0 * radius), 270., 360., true); addArc (CRect (right - 2.0 * radius, bottom - 2.0 *radius, right, bottom), 0., 90., true); addArc (CRect (left, bottom - 2.0 * radius, left + 2.0 * radius, bottom), 90., 180., true); addArc (CRect (left, top, left + 2.0 * radius, top + 2.0 * radius), 180., 270., true); closeSubpath (); } //----------------------------------------------------------------------------- void CGraphicsPath::addPath (const CGraphicsPath& path, CGraphicsTransform* transformation) { for (auto e : path.elements) { if (transformation) { switch (e.type) { case Element::kArc: { transformation->transform (e.instruction.arc.rect.left, e.instruction.arc.rect.right, e.instruction.arc.rect.top, e.instruction.arc.rect.bottom); break; } case Element::kEllipse: case Element::kRect: { transformation->transform (e.instruction.rect.left, e.instruction.rect.right, e.instruction.rect.top, e.instruction.rect.bottom); break; } case Element::kBeginSubpath: case Element::kLine: { transformation->transform (e.instruction.point.x, e.instruction.point.y); break; } case Element::kBezierCurve: { transformation->transform (e.instruction.curve.control1.x, e.instruction.curve.control1.y); transformation->transform (e.instruction.curve.control2.x, e.instruction.curve.control2.y); transformation->transform (e.instruction.curve.end.x, e.instruction.curve.end.y); break; } case Element::kCloseSubpath: { break; } } } elements.emplace_back (e); } dirty (); } //----------------------------------------------------------------------------- void CGraphicsPath::addArc (const CRect& rect, double startAngle, double endAngle, bool clockwise) { Element e; e.type = Element::kArc; CRect2Rect (rect, e.instruction.arc.rect); e.instruction.arc.startAngle = startAngle; e.instruction.arc.endAngle = endAngle; e.instruction.arc.clockwise = clockwise; elements.emplace_back (e); dirty (); } //----------------------------------------------------------------------------- void CGraphicsPath::addEllipse (const CRect& rect) { Element e; e.type = Element::kEllipse; CRect2Rect (rect, e.instruction.rect); elements.emplace_back (e); dirty (); } //----------------------------------------------------------------------------- void CGraphicsPath::addRect (const CRect& rect) { Element e; e.type = Element::kRect; CRect2Rect (rect, e.instruction.rect); elements.emplace_back (e); dirty (); } //----------------------------------------------------------------------------- void CGraphicsPath::addLine (const CPoint& to) { Element e; e.type = Element::kLine; CPoint2Point (to, e.instruction.point); elements.emplace_back (e); dirty (); } //----------------------------------------------------------------------------- void CGraphicsPath::addBezierCurve (const CPoint& control1, const CPoint& control2, const CPoint& end) { Element e; e.type = Element::kBezierCurve; CPoint2Point (control1, e.instruction.curve.control1); CPoint2Point (control2, e.instruction.curve.control2); CPoint2Point (end, e.instruction.curve.end); elements.emplace_back (e); dirty (); } //----------------------------------------------------------------------------- void CGraphicsPath::beginSubpath (const CPoint& start) { Element e; e.type = Element::kBeginSubpath; CPoint2Point (start, e.instruction.point); elements.emplace_back (e); dirty (); } //----------------------------------------------------------------------------- void CGraphicsPath::closeSubpath () { Element e; e.type = Element::kCloseSubpath; elements.emplace_back (e); dirty (); } } // namespace
29.437908
150
0.58659
[ "transform" ]
f5e0a40f0c184879a1c6943f0b331e8c35f62f81
2,541
cpp
C++
Game/Platform.cpp
DanielCordell/What-do-you-want-GMTKJam2017
74d47a89e6eba92b2a811fb4fb7ce730ec4a3617
[ "CC-BY-3.0" ]
null
null
null
Game/Platform.cpp
DanielCordell/What-do-you-want-GMTKJam2017
74d47a89e6eba92b2a811fb4fb7ce730ec4a3617
[ "CC-BY-3.0" ]
null
null
null
Game/Platform.cpp
DanielCordell/What-do-you-want-GMTKJam2017
74d47a89e6eba92b2a811fb4fb7ce730ec4a3617
[ "CC-BY-3.0" ]
null
null
null
#include <SFML/Graphics/RenderTarget.hpp> #include <SFML/Graphics/Font.hpp> #include <sstream> #include "Platform.h" sf::Font Platform::font; sf::Color Platform::colors[] = { sf::Color(255,168,168), sf::Color(166,202,169), sf::Color(160,149,238), sf::Color(123,167,255), sf::Color(163,254,186), sf::Color(255,213,134), sf::Color(200,200,149), sf::Color(200,200,200) }; void Platform::Reset(std::string string, Position pos) { transitionSpeed = 0; text.setString(""); this->doesExist = true; int randColor = rand() % 8; platform.setFillColor(colors[randColor]); sf::Vector2f platPos; platPos.y = rand() % 400 + 130; platPos.x = rand() % 226 + 426 * pos; platform.setPosition(platPos); //Adding newlines to string std::string buf; // Have a buffer string std::stringstream ss(string); // Insert the string into a stream std::vector<std::string> tokens; // Create vector to hold our words float spaceWidth = sf::Text(" ", font, 20).getGlobalBounds().width; while (ss >> buf) tokens.push_back(buf); float currentWidth = 0; for (auto word : tokens) { auto wordWidth = sf::Text(word, font, 20).getGlobalBounds().width; if (currentWidth + wordWidth + spaceWidth >= 200) { text.setString(text.getString().toAnsiString() += "\n" + word + " "); currentWidth = wordWidth + spaceWidth; } else { text.setString(text.getString().toAnsiString() += word + " "); currentWidth += wordWidth + spaceWidth; } } text.setString(text.getString().substring(0, text.getString().getSize() - 1)); // Remove trailing space text.setPosition(platform.getPosition().x + (200 - text.getGlobalBounds().width) / 2.f, platform.getPosition().y - text.getLocalBounds().height - 20); } void Platform::Reset() { this->doesExist = false; } void Platform::draw(sf::RenderTarget & target, sf::RenderStates states) const { target.draw(text, states); target.draw(platform, states); } std::optional<float> Platform::GetCollision(sf::FloatRect player) const { auto bounds = platform.getGlobalBounds(); if (player.intersects(sf::FloatRect(bounds.left, bounds.top, bounds.width, 1))) return std::make_optional(bounds.top); return {}; } void Platform::Transition() { transitionSpeed+= 1; platform.move(0, transitionSpeed); text.move(0, transitionSpeed); } Platform::Platform() { doesExist = false; platform.setOutlineColor(sf::Color::Black); platform.setSize({ 200, 15 }); font.loadFromFile("Resources/font.ttf"); text.setFillColor(sf::Color(0, 0, 0)); text.setCharacterSize(20); text.setFont(font); }
29.206897
151
0.692641
[ "vector" ]
f5e1dcba2a12f33a841fef168def7811bec0c2cc
3,710
cpp
C++
Sources/Graphics/GUILib/Qt5Example/WebRequest.cpp
wurui1994/test
027cef75f98dbb252b322113dacd4a9a6997d84f
[ "MIT" ]
27
2017-12-19T09:15:36.000Z
2021-07-30T13:02:00.000Z
Sources/Graphics/GUILib/Qt5Example/WebRequest.cpp
wurui1994/test
027cef75f98dbb252b322113dacd4a9a6997d84f
[ "MIT" ]
null
null
null
Sources/Graphics/GUILib/Qt5Example/WebRequest.cpp
wurui1994/test
027cef75f98dbb252b322113dacd4a9a6997d84f
[ "MIT" ]
29
2018-04-10T13:25:54.000Z
2021-12-24T01:51:03.000Z
#include <QCoreApplication> #include <QtNetwork/QtNetwork> #include <QDebug> QByteArray WebRequest(QString url, int& status_code, QString method="get", QByteArray postData="", QList<QNetworkReply::RawHeaderPair>* reply_pairs=nullptr, int time_out=0) { QNetworkAccessManager networkManager; QNetworkRequest request; QSslConfiguration config; request.setUrl(QUrl(url)); QNetworkReply* reply; if (method == "get") { reply = networkManager.get(request); } else if (method == "post") { request.setHeader(QNetworkRequest::ContentTypeHeader, "application/x-www-form-urlencoded"); reply = networkManager.post(request, postData); } else { qDebug() << "method not support."; return QByteArray(""); } QTimer timer; timer.setSingleShot(true); QEventLoop loop; QObject::connect(&timer, SIGNAL(timeout()), &loop, SLOT(quit())); QObject::connect(reply, SIGNAL(finished()), &loop, SLOT(quit())); if (time_out <= 0) { time_out = 3000; } timer.start(time_out); // 3 secs. timeout loop.exec(); if (timer.isActive()) { timer.stop(); if (reply->error() > 0) { qDebug() << "error";// handle error return QByteArray(""); } else { status_code = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt(); if (status_code >= 200 && status_code < 300) { // Success if (reply_pairs) { *reply_pairs = reply->rawHeaderPairs(); } return reply->readAll(); } } } else { // timeout QObject::disconnect(reply, SIGNAL(finished()), &loop, SLOT(quit())); reply->abort(); return QByteArray(""); } } int main(int argc, char *argv[]) { QCoreApplication a(argc, argv); QString identifier = "10016"; QString usersig = "eJxlz0FPwjAUwPH7PkXTq0a6dWPDWxkLDpkBR4J4aWbXQWdsSymLw-jdxalxxnf9-V9e3psDAICreX5VMKaO0lLbag7BNYAIXv6i1qKkhaXYlP*Qv2phOC0qy02HbhAEHkL9RpRcWlGJnwIhd9jjQ-lMuxtf6p*XcYj-JmLbYZZs4nQ5aX2mLxJWVywanxY4jwf50zAZTdcmrPVsk0drdb-PHoOZJOmO3AnBJ-VSqXR7moaczJtdPX44VvtWxqS5KWxmLUm8we1q1DtpxQv-fsjFkY-8sK8NNwehZBd46Jx4GH0OdN6dDzo7XFY_"; QString login = QString("https://webim.tim.qq.com/v4/openim/login?identifier=%1&usersig=%2&contenttype=json&sdkappid=1400037316").arg(identifier).arg(usersig); int statusCode; QString jsonString = WebRequest(login, statusCode); qDebug() << jsonString; QJsonDocument jsonResponse = QJsonDocument::fromJson(jsonString.toUtf8()); QJsonObject jsonObject = jsonResponse.object(); //qDebug() << jsonObject.contains("A2Key"); qDebug() << jsonObject["A2Key"]; qDebug() << jsonObject["TinyId"]; QString authKey = QString("https://webim.tim.qq.com/v4/openim/authkey?tinyid=%1&a2=%2&contenttype=json&sdkappid=1400037316").arg(jsonObject["TinyId"].toString()).arg(jsonObject["A2Key"].toString()); qDebug() << authKey; jsonString = WebRequest(authKey, statusCode); qDebug() << jsonString; jsonResponse = QJsonDocument::fromJson(jsonString.toUtf8()); jsonObject = jsonResponse.object(); qDebug() << jsonObject.contains("AuthKey"); qDebug() << jsonObject["AuthKey"]; // QString fileid = "3051020100044a30480201000405313030303502037a1afd02041a16a3b402045a546fe2042531363437303036313830313838393130303233385fb3b6f685f9ad44cdc6cb8eb05a10912f0201000201000400"; QString filename = "%E6%8D%95%E8%8E%B7.PNG"; QString file = QString("http://180.163.22.25/asn.com/stddownload_common_file?authkey=%1&bid=10001&subbid=1400037316&fileid=%2&filetype=2107&openid=10005&ver=0&filename=%3").arg(jsonObject["AuthKey"].toString()).arg(fileid).arg(filename); qDebug() << file; QByteArray data = WebRequest(file, statusCode); qDebug() << data.size(); //return a.exec(); }
33.423423
339
0.708625
[ "object" ]
f5e7f8575d942bfd1ad4528087c48943113bd8a5
23,189
cpp
C++
external/openglcts/modules/gl/gl4cIndirectParametersTests.cpp
aosp-caf-upstream/platform_external_deqp
c76160521ae25619f7e0f698673654faed55e057
[ "Apache-2.0" ]
1
2018-05-02T22:43:33.000Z
2018-05-02T22:43:33.000Z
external/openglcts/modules/gl/gl4cIndirectParametersTests.cpp
aosp-caf-upstream/platform_external_deqp
c76160521ae25619f7e0f698673654faed55e057
[ "Apache-2.0" ]
3
2017-10-17T22:38:53.000Z
2018-02-17T02:09:03.000Z
external/openglcts/modules/gl/gl4cIndirectParametersTests.cpp
aosp-caf-upstream/platform_external_deqp
c76160521ae25619f7e0f698673654faed55e057
[ "Apache-2.0" ]
2
2017-10-17T10:00:25.000Z
2022-02-28T07:43:27.000Z
/*------------------------------------------------------------------------- * OpenGL Conformance Test Suite * ----------------------------- * * Copyright (c) 2017 The Khronos Group Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ /*! * \file * \brief */ /*-------------------------------------------------------------------*/ /** */ /*! * \file gl4cIndirectParametersTests.cpp * \brief Conformance tests for the GL_ARB_indirect_parameters functionality. */ /*-------------------------------------------------------------------*/ #include "gl4cIndirectParametersTests.hpp" #include "gluContextInfo.hpp" #include "gluDefs.hpp" #include "gluDrawUtil.hpp" #include "gluShaderProgram.hpp" #include "glwEnums.hpp" #include "glwFunctions.hpp" #include "tcuRenderTarget.hpp" #include "tcuTestLog.hpp" using namespace glw; using namespace glu; namespace gl4cts { static const char* c_vertShader = "#version 430\n" "\n" "in vec3 vertex;\n" "\n" "void main()\n" "{\n" " gl_Position = vec4(vertex, 1);\n" "}\n"; static const char* c_fragShader = "#version 430\n" "\n" "out vec4 fragColor;\n" "\n" "void main()\n" "{\n" " fragColor = vec4(1, 1, 1, 0.5);\n" "}\n"; /** Constructor. * * @param context Rendering context */ ParameterBufferOperationsCase::ParameterBufferOperationsCase(deqp::Context& context) : TestCase(context, "ParameterBufferOperations", "Verifies if operations on new buffer object PARAMETER_BUFFER_ARB works as expected.") { /* Left blank intentionally */ } /** Stub init method */ void ParameterBufferOperationsCase::init() { } /** Executes test iteration. * * @return Returns STOP when test has finished executing, CONTINUE if more iterations are needed. */ tcu::TestNode::IterateResult ParameterBufferOperationsCase::iterate() { glu::ContextType contextType = m_context.getRenderContext().getType(); if (!glu::contextSupports(contextType, glu::ApiType::core(4, 6)) && !m_context.getContextInfo().isExtensionSupported("GL_ARB_indirect_parameters")) { m_testCtx.setTestResult(QP_TEST_RESULT_NOT_SUPPORTED, "Not Supported"); return STOP; } const Functions& gl = m_context.getRenderContext().getFunctions(); GLuint paramBuffer; GLint data[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }; GLint subData[] = { 10, 11, 12, 13, 14 }; GLint expData[] = { 0, 1, 10, 11, 12, 13, 14, 7, 8, 9 }; bool result = true; // Test buffer generating and binding gl.genBuffers(1, &paramBuffer); GLU_EXPECT_NO_ERROR(gl.getError(), "glGenBuffers"); gl.bindBuffer(GL_PARAMETER_BUFFER_ARB, paramBuffer); GLU_EXPECT_NO_ERROR(gl.getError(), "glBindBuffer"); GLint paramBinding; gl.getIntegerv(GL_PARAMETER_BUFFER_BINDING_ARB, &paramBinding); GLU_EXPECT_NO_ERROR(gl.getError(), "glGetIntegerv"); if ((GLuint)paramBinding != paramBuffer) { result = false; m_testCtx.getLog() << tcu::TestLog::Message << "Buffer binding mismatch" << tcu::TestLog::EndMessage; } else { // Test filling buffer with data gl.bufferData(GL_PARAMETER_BUFFER_ARB, 10 * sizeof(GLint), data, GL_DYNAMIC_DRAW); GLU_EXPECT_NO_ERROR(gl.getError(), "glBufferData"); gl.bufferSubData(GL_PARAMETER_BUFFER_ARB, 2 * sizeof(GLint), 5 * sizeof(GLint), subData); GLU_EXPECT_NO_ERROR(gl.getError(), "glBufferData"); // Test buffer mapping GLvoid* buffer = gl.mapBuffer(GL_PARAMETER_BUFFER_ARB, GL_READ_ONLY); GLU_EXPECT_NO_ERROR(gl.getError(), "glMapBuffer"); if (memcmp(buffer, expData, 10 * sizeof(GLint)) != 0) { result = false; m_testCtx.getLog() << tcu::TestLog::Message << "Buffer data mismatch" << tcu::TestLog::EndMessage; } else { GLvoid* bufferPointer; gl.getBufferPointerv(GL_PARAMETER_BUFFER_ARB, GL_BUFFER_MAP_POINTER, &bufferPointer); GLU_EXPECT_NO_ERROR(gl.getError(), "glGetBufferPointerv"); if (buffer != bufferPointer) { result = false; m_testCtx.getLog() << tcu::TestLog::Message << "Buffer pointer mismatch" << tcu::TestLog::EndMessage; } else { GLint bufferSize; GLint bufferUsage; gl.getBufferParameteriv(GL_PARAMETER_BUFFER_ARB, GL_BUFFER_SIZE, &bufferSize); GLU_EXPECT_NO_ERROR(gl.getError(), "glGetBufferParameteriv"); gl.getBufferParameteriv(GL_PARAMETER_BUFFER_ARB, GL_BUFFER_USAGE, &bufferUsage); GLU_EXPECT_NO_ERROR(gl.getError(), "glGetBufferParameteriv"); if (bufferSize != 10 * sizeof(GLint)) { result = false; m_testCtx.getLog() << tcu::TestLog::Message << "Buffer size mismatch" << tcu::TestLog::EndMessage; } else if (bufferUsage != GL_DYNAMIC_DRAW) { result = false; m_testCtx.getLog() << tcu::TestLog::Message << "Buffer usage mismatch" << tcu::TestLog::EndMessage; } } } gl.unmapBuffer(GL_PARAMETER_BUFFER_ARB); GLU_EXPECT_NO_ERROR(gl.getError(), "glUnmapBuffer"); // Test buffer ranged mapping buffer = gl.mapBufferRange(GL_PARAMETER_BUFFER_ARB, 0, sizeof(GLint), GL_MAP_WRITE_BIT | GL_MAP_FLUSH_EXPLICIT_BIT); GLU_EXPECT_NO_ERROR(gl.getError(), "glMapBufferRange"); // Test buffer flushing GLint* bufferInt = (GLint*)buffer; bufferInt[0] = 100; gl.flushMappedBufferRange(GL_PARAMETER_BUFFER_ARB, 0, sizeof(GLint)); GLU_EXPECT_NO_ERROR(gl.getError(), "glFlushMappedBufferRange"); gl.unmapBuffer(GL_PARAMETER_BUFFER_ARB); GLU_EXPECT_NO_ERROR(gl.getError(), "glUnmapBuffer"); // Test buffers data copying GLuint arrayBuffer; gl.genBuffers(1, &arrayBuffer); GLU_EXPECT_NO_ERROR(gl.getError(), "glGenBuffers"); gl.bindBuffer(GL_ARRAY_BUFFER, arrayBuffer); GLU_EXPECT_NO_ERROR(gl.getError(), "glBindBuffer"); gl.bufferData(GL_ARRAY_BUFFER, 10 * sizeof(GLint), data, GL_DYNAMIC_DRAW); GLU_EXPECT_NO_ERROR(gl.getError(), "glBufferData"); gl.copyBufferSubData(GL_PARAMETER_BUFFER_ARB, GL_ARRAY_BUFFER, 0, 0, sizeof(GLint)); GLU_EXPECT_NO_ERROR(gl.getError(), "glCopyBufferSubData"); gl.mapBufferRange(GL_ARRAY_BUFFER, 0, 1, GL_MAP_READ_BIT); GLU_EXPECT_NO_ERROR(gl.getError(), "glMapBufferRange"); bufferInt = (GLint*)buffer; if (bufferInt[0] != 100) { result = false; m_testCtx.getLog() << tcu::TestLog::Message << "Buffer copy operation failed" << tcu::TestLog::EndMessage; } gl.unmapBuffer(GL_ARRAY_BUFFER); GLU_EXPECT_NO_ERROR(gl.getError(), "glUnmapBuffer"); // Release array buffer gl.deleteBuffers(1, &arrayBuffer); GLU_EXPECT_NO_ERROR(gl.getError(), "glDeleteBuffers"); } // Release parameter buffer gl.deleteBuffers(1, &paramBuffer); GLU_EXPECT_NO_ERROR(gl.getError(), "glDeleteBuffers"); if (result) m_testCtx.setTestResult(QP_TEST_RESULT_PASS, "Pass"); else m_testCtx.setTestResult(QP_TEST_RESULT_FAIL, "Fail"); return STOP; } /** Constructor. * * @param context Rendering context */ VertexArrayIndirectDrawingBaseCase::VertexArrayIndirectDrawingBaseCase(deqp::Context& context, const char* name, const char* description) : TestCase(context, name, description) { /* Left blank intentionally */ } /** Executes test iteration. * * @return Returns STOP when test has finished executing, CONTINUE if more iterations are needed. */ tcu::TestNode::IterateResult VertexArrayIndirectDrawingBaseCase::iterate() { glu::ContextType contextType = m_context.getRenderContext().getType(); if (!glu::contextSupports(contextType, glu::ApiType::core(4, 6)) && !m_context.getContextInfo().isExtensionSupported("GL_ARB_indirect_parameters")) { m_testCtx.setTestResult(QP_TEST_RESULT_NOT_SUPPORTED, "Not Supported"); return STOP; } if (draw() && verify()) m_testCtx.setTestResult(QP_TEST_RESULT_PASS, "Pass"); else m_testCtx.setTestResult(QP_TEST_RESULT_FAIL, "Fail"); return STOP; } /** This method verifies if drawn quads are as expected. * * @return Returns true if quads are drawn properly, false otherwise. */ bool VertexArrayIndirectDrawingBaseCase::verify() { const Functions& gl = m_context.getRenderContext().getFunctions(); const tcu::RenderTarget& rt = m_context.getRenderContext().getRenderTarget(); const int width = rt.getWidth(); const int height = rt.getHeight(); std::vector<GLubyte> pixels; pixels.resize(width * height); gl.pixelStorei(GL_PACK_ALIGNMENT, 1); gl.readPixels(0, 0, width, height, GL_RED, GL_UNSIGNED_BYTE, pixels.data()); gl.pixelStorei(GL_PACK_ALIGNMENT, 4); //Verify first quad for (int y = 2; y < height - 2; ++y) { for (int x = 2; x < width / 2 - 2; ++x) { GLubyte value = pixels[x + y * width]; if (value < 190 || value > 194) { m_testCtx.getLog() << tcu::TestLog::Message << "First quad verification failed. " << "Wrong value read from framebuffer at " << x << "/" << y << " value: " << value << ", expected: <190-194>" << tcu::TestLog::EndMessage; return false; } } } //Verify second quad for (int y = 2; y < height - 2; ++y) { for (int x = width / 2 + 2; x < width - 2; ++x) { GLubyte value = pixels[x + y * width]; if (value < 126 || value > 130) { m_testCtx.getLog() << tcu::TestLog::Message << "Second quad verification failed. " << "Wrong value read from framebuffer at " << x << "/" << y << " value: " << value << ", expected: <126-130>" << tcu::TestLog::EndMessage; return false; } } } return verifyErrors(); } /** Constructor. * * @param context Rendering context */ MultiDrawArraysIndirectCountCase::MultiDrawArraysIndirectCountCase(deqp::Context& context) : VertexArrayIndirectDrawingBaseCase(context, "MultiDrawArraysIndirectCount", "Test verifies if MultiDrawArraysIndirectCountARB function works as expected.") , m_vao(0) , m_arrayBuffer(0) , m_drawIndirectBuffer(0) , m_parameterBuffer(0) { /* Left blank intentionally */ } /** Stub init method */ void MultiDrawArraysIndirectCountCase::init() { glu::ContextType contextType = m_context.getRenderContext().getType(); if (!glu::contextSupports(contextType, glu::ApiType::core(4, 6)) && !m_context.getContextInfo().isExtensionSupported("GL_ARB_indirect_parameters")) return; const Functions& gl = m_context.getRenderContext().getFunctions(); const GLfloat vertices[] = { -1.0f, -1.0f, 0.0f, -1.0f, 1.0f, 0.0f, 0.0f, -1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 1.0f, -1.0f, 0.0f, 1.0f, 1.0f, 0.0f }; const DrawArraysIndirectCommand indirect[] = { { 4, 2, 0, 0 }, //4 vertices, 2 instanceCount, 0 first, 0 baseInstance { 4, 1, 2, 0 } //4 vertices, 1 instanceCount, 2 first, 0 baseInstance }; const GLushort parameters[] = { 2, 1 }; // Generate vertex array object gl.genVertexArrays(1, &m_vao); GLU_EXPECT_NO_ERROR(gl.getError(), "glGenVertexArrays"); gl.bindVertexArray(m_vao); GLU_EXPECT_NO_ERROR(gl.getError(), "glBindVertexArray"); // Setup vertex array buffer gl.genBuffers(1, &m_arrayBuffer); GLU_EXPECT_NO_ERROR(gl.getError(), "glGenBuffers"); gl.bindBuffer(GL_ARRAY_BUFFER, m_arrayBuffer); GLU_EXPECT_NO_ERROR(gl.getError(), "glBindBuffer"); gl.bufferData(GL_ARRAY_BUFFER, 24 * sizeof(GLfloat), vertices, GL_STATIC_DRAW); GLU_EXPECT_NO_ERROR(gl.getError(), "glBufferData"); // Setup indirect command buffer gl.genBuffers(1, &m_drawIndirectBuffer); GLU_EXPECT_NO_ERROR(gl.getError(), "glGenBuffers"); gl.bindBuffer(GL_DRAW_INDIRECT_BUFFER, m_drawIndirectBuffer); GLU_EXPECT_NO_ERROR(gl.getError(), "glBindBuffer"); gl.bufferData(GL_DRAW_INDIRECT_BUFFER, 2 * sizeof(DrawArraysIndirectCommand), indirect, GL_STATIC_DRAW); GLU_EXPECT_NO_ERROR(gl.getError(), "glBufferData"); // Setup parameter buffer gl.genBuffers(1, &m_parameterBuffer); GLU_EXPECT_NO_ERROR(gl.getError(), "glGenBuffers"); gl.bindBuffer(GL_PARAMETER_BUFFER_ARB, m_parameterBuffer); GLU_EXPECT_NO_ERROR(gl.getError(), "glBindBuffer"); gl.bufferData(GL_PARAMETER_BUFFER_ARB, 100 * sizeof(GLushort), parameters, GL_STATIC_DRAW); GLU_EXPECT_NO_ERROR(gl.getError(), "glBufferData"); } /** Stub deinit method */ void MultiDrawArraysIndirectCountCase::deinit() { const Functions& gl = m_context.getRenderContext().getFunctions(); if (m_vao) gl.deleteVertexArrays(1, &m_vao); if (m_arrayBuffer) gl.deleteBuffers(1, &m_arrayBuffer); if (m_drawIndirectBuffer) gl.deleteBuffers(1, &m_drawIndirectBuffer); if (m_parameterBuffer) gl.deleteBuffers(1, &m_parameterBuffer); } /** Drawing quads method using drawArrays. */ bool MultiDrawArraysIndirectCountCase::draw() { const Functions& gl = m_context.getRenderContext().getFunctions(); ProgramSources sources = makeVtxFragSources(c_vertShader, c_fragShader); ShaderProgram program(gl, sources); if (!program.isOk()) { m_testCtx.getLog() << tcu::TestLog::Message << "Shader build failed.\n" << "Vertex: " << program.getShaderInfo(SHADERTYPE_VERTEX).infoLog << "\n" << "Fragment: " << program.getShaderInfo(SHADERTYPE_FRAGMENT).infoLog << "\n" << "Program: " << program.getProgramInfo().infoLog << tcu::TestLog::EndMessage; return false; } gl.useProgram(program.getProgram()); GLU_EXPECT_NO_ERROR(gl.getError(), "glUseProgram"); gl.clearColor(0.0f, 0.0f, 0.0f, 1.0f); gl.clear(GL_COLOR_BUFFER_BIT); gl.enable(GL_BLEND); gl.blendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); gl.enableVertexAttribArray(0); GLU_EXPECT_NO_ERROR(gl.getError(), "glEnableVertexAttribArray"); gl.vertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, NULL); GLU_EXPECT_NO_ERROR(gl.getError(), "glVertexAttribPointer"); gl.multiDrawArraysIndirectCount(GL_TRIANGLE_STRIP, 0, 0, 2, 0); GLU_EXPECT_NO_ERROR(gl.getError(), "glMultiDrawArraysIndirectCountARB"); gl.disableVertexAttribArray(0); GLU_EXPECT_NO_ERROR(gl.getError(), "glDisableVertexAttribArray"); gl.disable(GL_BLEND); return true; } /** Verify MultiDrawArrayIndirectCountARB errors */ bool MultiDrawArraysIndirectCountCase::verifyErrors() { const Functions& gl = m_context.getRenderContext().getFunctions(); GLint errorCode; bool result = true; // INVALID_VALUE - drawcount offset not multiple of 4 gl.multiDrawArraysIndirectCount(GL_TRIANGLE_STRIP, 0, 2, 1, 0); errorCode = gl.getError(); if (errorCode != GL_INVALID_VALUE) { m_testCtx.getLog() << tcu::TestLog::Message << "MultiDrawArraysIndirectCount error verifying failed (1). Expected code: " << GL_INVALID_VALUE << ", current code: " << errorCode << tcu::TestLog::EndMessage; result = false; } // INVALID_OPERATION - maxdrawcount greater then parameter buffer size gl.multiDrawArraysIndirectCount(GL_TRIANGLE_STRIP, 0, 0, 4, 0); errorCode = gl.getError(); if (errorCode != GL_INVALID_OPERATION) { m_testCtx.getLog() << tcu::TestLog::Message << "MultiDrawArraysIndirectCount error verifying failed (2). Expected code: " << GL_INVALID_OPERATION << ", current code: " << errorCode << tcu::TestLog::EndMessage; result = false; } gl.bindBuffer(GL_PARAMETER_BUFFER_ARB, 0); GLU_EXPECT_NO_ERROR(gl.getError(), "glBindBuffer"); // INVALID_OPERATION - GL_PARAMETER_BUFFER_ARB not bound gl.multiDrawArraysIndirectCount(GL_TRIANGLE_STRIP, 0, 0, 2, 0); errorCode = gl.getError(); if (errorCode != GL_INVALID_OPERATION) { m_testCtx.getLog() << tcu::TestLog::Message << "MultiDrawArraysIndirectCount error verifying failed (3). Expected code: " << GL_INVALID_OPERATION << ", current code: " << errorCode << tcu::TestLog::EndMessage; result = false; } return result; } /** Constructor. * * @param context Rendering context */ MultiDrawElementsIndirectCountCase::MultiDrawElementsIndirectCountCase(deqp::Context& context) : VertexArrayIndirectDrawingBaseCase( context, "MultiDrawElementsIndirectCount", "Test verifies if MultiDrawElementsIndirectCountARB function works as expected.") , m_vao(0) , m_arrayBuffer(0) , m_drawIndirectBuffer(0) , m_parameterBuffer(0) { /* Left blank intentionally */ } /** Stub init method */ void MultiDrawElementsIndirectCountCase::init() { glu::ContextType contextType = m_context.getRenderContext().getType(); if (!glu::contextSupports(contextType, glu::ApiType::core(4, 6)) && !m_context.getContextInfo().isExtensionSupported("GL_ARB_indirect_parameters")) return; const Functions& gl = m_context.getRenderContext().getFunctions(); const GLfloat vertices[] = { -1.0f, -1.0f, 0.0f, -1.0f, 1.0f, 0.0f, 0.0f, -1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 1.0f, -1.0f, 0.0f, 1.0f, 1.0f, 0.0f }; const GLushort elements[] = { 0, 1, 2, 3, 4, 5 }; const DrawElementsIndirectCommand indirect[] = { { 4, 2, 0, 0, 0 }, //4 indices, 2 instanceCount, 0 firstIndex, 0 baseVertex, 0 baseInstance { 4, 1, 2, 0, 0 } //4 indices, 1 instanceCount, 2 firstIndex, 0 baseVertex, 0 baseInstance }; const GLushort parameters[] = { 2, 1 }; // Generate vertex array object gl.genVertexArrays(1, &m_vao); GLU_EXPECT_NO_ERROR(gl.getError(), "glGenVertexArrays"); gl.bindVertexArray(m_vao); GLU_EXPECT_NO_ERROR(gl.getError(), "glBindVertexArray"); // Setup vertex array buffer gl.genBuffers(1, &m_arrayBuffer); GLU_EXPECT_NO_ERROR(gl.getError(), "glGenBuffers"); gl.bindBuffer(GL_ARRAY_BUFFER, m_arrayBuffer); GLU_EXPECT_NO_ERROR(gl.getError(), "glBindBuffer"); gl.bufferData(GL_ARRAY_BUFFER, 24 * sizeof(GLfloat), vertices, GL_STATIC_DRAW); GLU_EXPECT_NO_ERROR(gl.getError(), "glBufferData"); // Setup element array buffer gl.genBuffers(1, &m_elementBuffer); GLU_EXPECT_NO_ERROR(gl.getError(), "glGenBuffers"); gl.bindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_elementBuffer); GLU_EXPECT_NO_ERROR(gl.getError(), "glBindBuffer"); gl.bufferData(GL_ELEMENT_ARRAY_BUFFER, 6 * sizeof(GLushort), elements, GL_STATIC_DRAW); GLU_EXPECT_NO_ERROR(gl.getError(), "glBufferData"); // Setup indirect command buffer gl.genBuffers(1, &m_drawIndirectBuffer); GLU_EXPECT_NO_ERROR(gl.getError(), "glGenBuffers"); gl.bindBuffer(GL_DRAW_INDIRECT_BUFFER, m_drawIndirectBuffer); GLU_EXPECT_NO_ERROR(gl.getError(), "glBindBuffer"); gl.bufferData(GL_DRAW_INDIRECT_BUFFER, 3 * sizeof(DrawElementsIndirectCommand), indirect, GL_STATIC_DRAW); GLU_EXPECT_NO_ERROR(gl.getError(), "glBufferData"); // Setup parameters Re: buffer gl.genBuffers(1, &m_parameterBuffer); GLU_EXPECT_NO_ERROR(gl.getError(), "glGenBuffers"); gl.bindBuffer(GL_PARAMETER_BUFFER_ARB, m_parameterBuffer); GLU_EXPECT_NO_ERROR(gl.getError(), "glBindBuffer"); gl.bufferData(GL_PARAMETER_BUFFER_ARB, 2 * sizeof(GLushort), parameters, GL_STATIC_DRAW); GLU_EXPECT_NO_ERROR(gl.getError(), "glBufferData"); } /** Stub deinit method */ void MultiDrawElementsIndirectCountCase::deinit() { const Functions& gl = m_context.getRenderContext().getFunctions(); if (m_vao) gl.deleteVertexArrays(1, &m_vao); if (m_arrayBuffer) gl.deleteBuffers(1, &m_arrayBuffer); if (m_elementBuffer) gl.deleteBuffers(1, &m_elementBuffer); if (m_drawIndirectBuffer) gl.deleteBuffers(1, &m_drawIndirectBuffer); if (m_parameterBuffer) gl.deleteBuffers(1, &m_parameterBuffer); } /** Drawing quads method using drawArrays. */ bool MultiDrawElementsIndirectCountCase::draw() { const Functions& gl = m_context.getRenderContext().getFunctions(); ProgramSources sources = makeVtxFragSources(c_vertShader, c_fragShader); ShaderProgram program(gl, sources); if (!program.isOk()) { m_testCtx.getLog() << tcu::TestLog::Message << "Shader build failed.\n" << "Vertex: " << program.getShaderInfo(SHADERTYPE_VERTEX).infoLog << "\n" << "Fragment: " << program.getShaderInfo(SHADERTYPE_FRAGMENT).infoLog << "\n" << "Program: " << program.getProgramInfo().infoLog << tcu::TestLog::EndMessage; return false; } gl.useProgram(program.getProgram()); GLU_EXPECT_NO_ERROR(gl.getError(), "glUseProgram"); gl.clearColor(0.0f, 0.0f, 0.0f, 1.0f); gl.clear(GL_COLOR_BUFFER_BIT); gl.enable(GL_BLEND); gl.blendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); gl.enableVertexAttribArray(0); GLU_EXPECT_NO_ERROR(gl.getError(), "glEnableVertexAttribArray"); gl.vertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, NULL); GLU_EXPECT_NO_ERROR(gl.getError(), "glVertexAttribPointer"); gl.multiDrawElementsIndirectCount(GL_TRIANGLE_STRIP, GL_UNSIGNED_SHORT, 0, 0, 2, 0); GLU_EXPECT_NO_ERROR(gl.getError(), "glMultiDrawElementsIndirectCountARB"); gl.disableVertexAttribArray(0); GLU_EXPECT_NO_ERROR(gl.getError(), "glDisableVertexAttribArray"); gl.disable(GL_BLEND); return true; } /** Verify MultiDrawElementsIndirectCountARB errors */ bool MultiDrawElementsIndirectCountCase::verifyErrors() { const Functions& gl = m_context.getRenderContext().getFunctions(); GLint errorCode; bool result = true; // INVALID_VALUE - drawcount offset not multiple of 4 gl.multiDrawElementsIndirectCount(GL_TRIANGLE_STRIP, GL_UNSIGNED_BYTE, 0, 2, 1, 0); errorCode = gl.getError(); if (errorCode != GL_INVALID_VALUE) { m_testCtx.getLog() << tcu::TestLog::Message << "MultiDrawElementIndirectCount error verifying failed (1). Expected code: " << GL_INVALID_VALUE << ", current code: " << errorCode << tcu::TestLog::EndMessage; result = false; } // INVALID_OPERATION - maxdrawcount greater then parameter buffer size gl.multiDrawElementsIndirectCount(GL_TRIANGLE_STRIP, GL_UNSIGNED_BYTE, 0, 0, 4, 0); errorCode = gl.getError(); if (errorCode != GL_INVALID_OPERATION) { m_testCtx.getLog() << tcu::TestLog::Message << "MultiDrawElementIndirectCount error verifying failed (2). Expected code: " << GL_INVALID_OPERATION << ", current code: " << errorCode << tcu::TestLog::EndMessage; result = false; } gl.bindBuffer(GL_PARAMETER_BUFFER_ARB, 0); GLU_EXPECT_NO_ERROR(gl.getError(), "glBindBuffer"); // INVALID_OPERATION - GL_PARAMETER_BUFFER_ARB not bound gl.multiDrawElementsIndirectCount(GL_TRIANGLE_STRIP, GL_UNSIGNED_BYTE, 0, 0, 3, 0); errorCode = gl.getError(); if (errorCode != GL_INVALID_OPERATION) { m_testCtx.getLog() << tcu::TestLog::Message << "MultiDrawElementIndirectCount error verifying failed (3). Expected code: " << GL_INVALID_OPERATION << ", current code: " << errorCode << tcu::TestLog::EndMessage; result = false; } return result; } /** Constructor. * * @param context Rendering context. */ IndirectParametersTests::IndirectParametersTests(deqp::Context& context) : TestCaseGroup(context, "indirect_parameters_tests", "Verify conformance of CTS_ARB_indirect_parameters implementation") { } /** Initializes the test group contents. */ void IndirectParametersTests::init() { addChild(new ParameterBufferOperationsCase(m_context)); addChild(new MultiDrawArraysIndirectCountCase(m_context)); addChild(new MultiDrawElementsIndirectCountCase(m_context)); } } /* gl4cts namespace */
32.477591
112
0.712277
[ "object", "vector" ]
f5e8ecd950f0cb7d08398ed78be2dfece95dcede
396,257
cpp
C++
tests/hot/single-threaded-test/src/hot/singlethreaded/HOTSingleThreadedTest.cpp
yishayahu/hot
579e225ba5f9b1e5cda0cd282121f4202406f245
[ "0BSD" ]
99
2018-03-23T11:08:48.000Z
2022-03-03T10:03:35.000Z
tests/hot/single-threaded-test/src/hot/singlethreaded/HOTSingleThreadedTest.cpp
SheldonZhong/hot
ec29331ecb4b0d5381b90d5b45ce2319b7cfeff0
[ "ISC" ]
3
2018-12-18T19:00:04.000Z
2021-09-07T13:05:36.000Z
tests/hot/single-threaded-test/src/hot/singlethreaded/HOTSingleThreadedTest.cpp
SheldonZhong/hot
ec29331ecb4b0d5381b90d5b45ce2319b7cfeff0
[ "ISC" ]
29
2018-06-03T07:56:35.000Z
2022-03-04T07:31:50.000Z
// // Created by Robert Binna on 23.12.14. // // #include <bitset> #include <set> #include <vector> #include <boost/test/unit_test.hpp> #include <hot/singlethreaded/HOTSingleThreaded.hpp> #include <hot/testhelpers/PartialKeyMappingTestHelper.hpp> #include <hot/testhelpers/SampleTriples.hpp> #include <idx/contenthelpers/IdentityKeyExtractor.hpp> #include <idx/contenthelpers/PairPointerKeyExtractor.hpp> #include <idx/contenthelpers/KeyComparator.hpp> #include <idx/contenthelpers/OptionalValue.hpp> #include "idx/utils/8ByteDatFileIO.hpp" #include <idx/utils/RandomRangeGenerator.hpp> namespace hot { namespace singlethreaded { using HOTSingleThreadedUint64 = hot::singlethreaded::HOTSingleThreaded<uint64_t, idx::contenthelpers::IdentityKeyExtractor>; using CStringTrieType = hot::singlethreaded::HOTSingleThreaded<const char*, idx::contenthelpers::IdentityKeyExtractor>; inline bool isPartitionCorrect(HOTSingleThreadedChildPointer const * childPointer) { return childPointer->executeForSpecificNodeType(false, [&](const auto & node) { return node.isPartitionCorrect(); }); } template<typename ValueType, template <typename> typename KeyExtractor> inline bool isSubTreeValid(HOTSingleThreadedChildPointer const * currentSubtreeRoot) { if(currentSubtreeRoot->isLeaf() || currentSubtreeRoot->getNode() == nullptr) { return true; } KeyExtractor<ValueType> extractKey; using KeyType = decltype(extractKey(std::declval<ValueType>())); std::array<HOTSingleThreadedChildPointer const *, 60> nodeStack; std::array<unsigned int, 60> entryIndexStack; int stackIndex = 0; nodeStack[0] = currentSubtreeRoot; entryIndexStack[0] = 0; bool isValid = true; while(isValid && stackIndex >= 0) { if(nodeStack[stackIndex]->isLeaf()) { KeyType const & key = extractKey(idx::contenthelpers::tidToValue<ValueType>(nodeStack[stackIndex]->getTid())); auto const & fixedSizedKey = idx::contenthelpers::toFixSizedKey(idx::contenthelpers::toBigEndianByteOrder(key)); uint8_t const * rawValue = idx::contenthelpers::interpretAsByteArray(fixedSizedKey); for(int i=0; i < stackIndex; ++i) { bool isNodeEntryValid = (*nodeStack[i+1] == (*nodeStack[i]->search(rawValue))); if(!isNodeEntryValid) { std::cout << "node entry is invalid for path ["; for(int j = 0; j <= i; ++j) { if(j > 0) { std::cout << ", "; } std::cout << entryIndexStack[j]; } std::cout << "]" << std::endl; isValid = false; } } --stackIndex; } else { isValid &= isPartitionCorrect(nodeStack[stackIndex]); HOTSingleThreadedChildPointer nodePointer = *nodeStack[stackIndex]; HOTSingleThreadedNodeBase* node = nodePointer.getNode(); unsigned int indexInNode = entryIndexStack[stackIndex]++; if(indexInNode < node->getNumberEntries()) { HOTSingleThreadedChildPointer* childPointer = node->getPointers() + indexInNode; nodeStack[++stackIndex] = childPointer; if(!childPointer->isLeaf()) { uint16_t leastSignificantBitIndexForEntry = nodePointer.executeForSpecificNodeType(false, [&](const auto & node) { return node.getLeastSignificantDiscriminativeBitForEntry(indexInNode); }); uint16_t mostSignificantBitIndexForChildNode = childPointer->executeForSpecificNodeType(false, [&](const auto & node) { return node.mDiscriminativeBitsRepresentation.mMostSignificantDiscriminativeBitIndex; }); bool isLeastSignificantBitIndexInParentEntryStrictlySmallerThanMostSignificantBitIndexInChild = leastSignificantBitIndexForEntry < mostSignificantBitIndexForChildNode; if(!isLeastSignificantBitIndexInParentEntryStrictlySmallerThanMostSignificantBitIndexInChild) { //uint anotherLeastSignifcantBitIndexForEntry = nodePointer.getLeastSignificantDiscriminativeBitForEntry(indexInNode); std::cout << "node entry has larger bit index for least significant bit than the index of the most significan bit in the chlid node ["; for(int j = 0; j < stackIndex; ++j) { if(j > 0) { std::cout << ", "; } std::cout << (entryIndexStack[j] - 1); } std::cout << "]" << std::endl; std::cout << "leastSignificantBitIndexForEntry :: " << leastSignificantBitIndexForEntry << " vs. mostSignificantBitIndexForChildNode :: " << mostSignificantBitIndexForChildNode << std::endl; isValid = false; } } entryIndexStack[stackIndex] = 0; } else { --stackIndex; } } } return isValid; } template<typename ValueType> std::shared_ptr<hot::singlethreaded::HOTSingleThreaded<ValueType, idx::contenthelpers::IdentityKeyExtractor>> insertWithoutCheck(std::vector<ValueType> const &valuesToInsert) { std::shared_ptr<hot::singlethreaded::HOTSingleThreaded<ValueType, idx::contenthelpers::IdentityKeyExtractor>> hotSingleThreaded = std::make_shared<hot::singlethreaded::HOTSingleThreaded<ValueType, idx::contenthelpers::IdentityKeyExtractor>>(); for (size_t i = 0u; i < valuesToInsert.size(); ++i) { hotSingleThreaded->insert(valuesToInsert[i]); } return hotSingleThreaded; } template<typename ValueType> std::shared_ptr<hot::singlethreaded::HOTSingleThreaded<ValueType, idx::contenthelpers::IdentityKeyExtractor>> testValues(std::vector<ValueType> const &valuesToInsert, int expectedLevel=-1) { std::shared_ptr<hot::singlethreaded::HOTSingleThreaded<ValueType, idx::contenthelpers::IdentityKeyExtractor>> hotSingleThreaded = std::make_shared<hot::singlethreaded::HOTSingleThreaded<ValueType, idx::contenthelpers::IdentityKeyExtractor>>(); using KeyType = typename hot::singlethreaded::HOTSingleThreaded<ValueType, idx::contenthelpers::IdentityKeyExtractor>::KeyType; for (size_t i = 0u; i < valuesToInsert.size(); ++i) { KeyType key = valuesToInsert[i]; if(i == (valuesToInsert.size() - 1)) { BOOST_REQUIRE_MESSAGE(hotSingleThreaded->find(key) == hotSingleThreaded->end(), "element has not been inserted yet, hence it must no be contained in the trie"); } hotSingleThreaded->insert(valuesToInsert[i]); } bool found = true; //works only because key == value std::set<ValueType, typename idx::contenthelpers::KeyComparator<ValueType>::type> temporarySet(valuesToInsert.begin(), valuesToInsert.end()); std::vector<ValueType> sortedValues(temporarySet.begin(), temporarySet.end()); BOOST_REQUIRE_EQUAL(valuesToInsert.size(), sortedValues.size()); size_t numberValues = sortedValues.size(); for (size_t j = 0u; j < numberValues; ++j) { idx::contenthelpers::OptionalValue<ValueType> result = hotSingleThreaded->lookup(sortedValues[j]); found = found && result.mIsValid && (result.mValue == sortedValues[j]); if (!found) { std::cout << "j :: " << j << " => " << found << std::endl; } } if(numberValues < 1000) { for (size_t j = 0u; j < numberValues; ++j) { KeyType rawSearchValue = sortedValues[j]; BOOST_REQUIRE_EQUAL_COLLECTIONS(hotSingleThreaded->find(rawSearchValue), hotSingleThreaded->end(), sortedValues.begin() + j, sortedValues.end()); BOOST_REQUIRE_EQUAL_COLLECTIONS(hotSingleThreaded->lower_bound(rawSearchValue), hotSingleThreaded->end(), sortedValues.begin() + j, sortedValues.end()); BOOST_REQUIRE_EQUAL_COLLECTIONS(hotSingleThreaded->upper_bound(rawSearchValue), hotSingleThreaded->end(), sortedValues.begin() + j + 1, sortedValues.end()); BOOST_REQUIRE(hotSingleThreaded->scan(rawSearchValue, numberValues - j - 1).compliesWith({ true, *sortedValues.rbegin() })); } } else { for (size_t j = 0u; j < numberValues; j+=(numberValues/100)) { KeyType rawSearchValue = sortedValues[j]; BOOST_REQUIRE_EQUAL_COLLECTIONS(hotSingleThreaded->find(rawSearchValue), hotSingleThreaded->end(), sortedValues.begin() + j, sortedValues.end()); BOOST_REQUIRE_EQUAL_COLLECTIONS(hotSingleThreaded->lower_bound(rawSearchValue), hotSingleThreaded->end(), sortedValues.begin() + j, sortedValues.end()); BOOST_REQUIRE_EQUAL_COLLECTIONS(hotSingleThreaded->upper_bound(rawSearchValue), hotSingleThreaded->end(), sortedValues.begin() + j + 1, sortedValues.end()); BOOST_REQUIRE(hotSingleThreaded->scan(rawSearchValue, numberValues - j - 1).compliesWith({ true, *sortedValues.rbegin() })); } } BOOST_REQUIRE_EQUAL_COLLECTIONS(hotSingleThreaded->begin(), hotSingleThreaded->end(), sortedValues.begin(), sortedValues.end()); bool subtreeValid = isSubTreeValid<ValueType, idx::contenthelpers::IdentityKeyExtractor>(&(hotSingleThreaded->mRoot)); BOOST_REQUIRE(subtreeValid); BOOST_REQUIRE(found); if(expectedLevel != -1) { BOOST_REQUIRE_EQUAL(hotSingleThreaded->mRoot.getHeight(), expectedLevel); } size_t currentHeight = hotSingleThreaded->getHeight(); size_t previousHeight = currentHeight; for (size_t i = 0u; i < valuesToInsert.size(); ++i) { KeyType key = valuesToInsert[i]; if(i == 24682) { //std::cout << "critical path" << std::endl; bool removed = hotSingleThreaded->remove(key); BOOST_REQUIRE(removed); } else { BOOST_REQUIRE(hotSingleThreaded->remove(key)); } currentHeight = hotSingleThreaded->getHeight(); temporarySet.erase(key); size_t remainingValues = valuesToInsert.size() - i; ///|| remainingValues < 100 if( (currentHeight != previousHeight) || i == UINT64_MAX || remainingValues <= 10 || (i%(remainingValues/10))==0 ) { std::shared_ptr<hot::singlethreaded::HOTSingleThreaded<ValueType, idx::contenthelpers::IdentityKeyExtractor>> hotSingleThreaded2 = std::make_shared<hot::singlethreaded::HOTSingleThreaded<ValueType, idx::contenthelpers::IdentityKeyExtractor>>(); for (size_t j = 0; j <= i; ++j) { BOOST_REQUIRE(!hotSingleThreaded->lookup(valuesToInsert[j]).mIsValid); } for (size_t j = i + 1; j < valuesToInsert.size(); ++j) { hotSingleThreaded2->insert(valuesToInsert[j]); BOOST_REQUIRE(hotSingleThreaded->lookup(valuesToInsert[j]).mIsValid); } BOOST_REQUIRE_EQUAL(hotSingleThreaded2->getHeight(), hotSingleThreaded->getHeight()); BOOST_REQUIRE_EQUAL_COLLECTIONS(hotSingleThreaded->begin(), hotSingleThreaded->end(), temporarySet.begin(), temporarySet.end()); bool subtreeValid = isSubTreeValid<ValueType, idx::contenthelpers::IdentityKeyExtractor>( &(hotSingleThreaded->mRoot)); BOOST_REQUIRE(subtreeValid); } if(currentHeight != previousHeight) { //std::cout << "Checking height change from " << previousHeight << " to " << currentHeight << std::endl; std::shared_ptr<hot::singlethreaded::HOTSingleThreaded<ValueType, idx::contenthelpers::IdentityKeyExtractor>> hotSingleThreaded2 = std::make_shared<hot::singlethreaded::HOTSingleThreaded<ValueType, idx::contenthelpers::IdentityKeyExtractor>>(); for (size_t j = i; j < valuesToInsert.size(); ++j) { hotSingleThreaded2->insert(valuesToInsert[j]); } BOOST_REQUIRE_EQUAL(hotSingleThreaded2->getHeight(), previousHeight); } previousHeight = currentHeight; } std::shared_ptr<hot::singlethreaded::HOTSingleThreaded<ValueType, idx::contenthelpers::IdentityKeyExtractor>> finalTrie = std::make_shared<hot::singlethreaded::HOTSingleThreaded<ValueType, idx::contenthelpers::IdentityKeyExtractor>>(); for (size_t i = 0; i < valuesToInsert.size(); ++i) { finalTrie->insert(valuesToInsert[i]); } return finalTrie; //std::cout << "Checked Integrity" << std::endl; } BOOST_AUTO_TEST_SUITE(HOTSingleThreadedTest) BOOST_AUTO_TEST_CASE(testSequentialValuesWithSplitTwoLevel) { std::vector<uint64_t> valuesToInsert; int numberEntries = 32 * 32; for (int i = 0; i < numberEntries; ++i) { valuesToInsert.push_back(i); } std::shared_ptr<HOTSingleThreadedUint64> trie = testValues(valuesToInsert, 2); } BOOST_AUTO_TEST_CASE(testSequentialValuesWithSplitThreeLevel) { std::vector<uint64_t> valuesToInsert; int numberEntries = 32 * 32 * 32; for (int i = 0; i < numberEntries; ++i) { valuesToInsert.push_back(i); } testValues(valuesToInsert, 3); } BOOST_AUTO_TEST_CASE(testSequentialValuesWithSplitThreeLevelsReverse) { std::vector<uint64_t> valuesToInsert; int numberEntries = 32 * 32 * 32; for (int i = numberEntries - 1; i >= 0; --i) { valuesToInsert.push_back(i); } testValues(valuesToInsert, 3); } BOOST_AUTO_TEST_CASE(testRandomValues) { std::vector<uint64_t> valuesToInsert; idx::utils::RandomRangeGenerator<uint64_t> rnd{12344567, 0, INT64_MAX}; //uint numberValues = 10000; //uint numberValues = 16000; unsigned int numberValues = 100000; for (size_t i = 0u; i < numberValues; ++i) { valuesToInsert.push_back(rnd()); } testValues(valuesToInsert); } BOOST_AUTO_TEST_CASE(testBoundsInteger) { std::set<uint64_t> sortedValues; idx::utils::RandomRangeGenerator<uint64_t> rnd{12344567, 0, INT64_MAX}; unsigned int numberValues = 100000; for (size_t i = 0u; i < numberValues; ++i) { sortedValues.insert(rnd()); } std::vector<uint64_t> valuesToInsert; std::vector<uint64_t> valuesToLeaveOut; uint64_t valueBeforeAll; uint64_t valueAfterAll; size_t index = 0; for(auto value : sortedValues) { if(index == 0) { valueBeforeAll = value; } else if(index == (sortedValues.size() - 1)) { valueAfterAll = value; } else if((index%2) == 1) { valuesToInsert.push_back(value); } else { valuesToLeaveOut.push_back(value); } ++index; } std::shared_ptr<HOTSingleThreadedUint64> trie = testValues(valuesToInsert); std::set<uint64_t> redBlackTree(valuesToInsert.begin(), valuesToInsert.end()); const typename HOTSingleThreadedUint64::const_iterator &lowerBound = trie->lower_bound(valueAfterAll); BOOST_REQUIRE_MESSAGE(lowerBound == trie->end(), "Lower bound for value which is after all values is the end"); BOOST_REQUIRE_MESSAGE(trie->upper_bound(valueAfterAll) == trie->end(), "Upper bound for a value which is after all values is the end"); BOOST_REQUIRE_MESSAGE(*trie->lower_bound(valueBeforeAll) == valuesToInsert[0], "Lower bound for value which is before all values is the first value"); BOOST_REQUIRE_MESSAGE(*trie->upper_bound(valueBeforeAll) == valuesToInsert[0], "Upper bound for a value which is before all values is the first value"); BOOST_REQUIRE_EQUAL(*trie->lower_bound(valueBeforeAll), *redBlackTree.lower_bound(valueBeforeAll)); BOOST_REQUIRE_MESSAGE(redBlackTree.lower_bound(valueAfterAll) == redBlackTree.end(), "Defined behavior for lower bound if value after all is searched"); BOOST_REQUIRE_EQUAL(*trie->upper_bound(valueBeforeAll), *redBlackTree.upper_bound(valueBeforeAll)); BOOST_REQUIRE_MESSAGE(redBlackTree.upper_bound(valueAfterAll) == redBlackTree.end(), "Defined behavior for upper bound if value after all is searched"); for(size_t i=2; i < (valuesToLeaveOut.size() - 2); ++i) { BOOST_REQUIRE_EQUAL(*trie->lower_bound(valuesToLeaveOut[i]), *redBlackTree.lower_bound(valuesToLeaveOut[i])); BOOST_REQUIRE_EQUAL(*trie->upper_bound(valuesToLeaveOut[i]), *redBlackTree.upper_bound(valuesToLeaveOut[i])); } BOOST_REQUIRE_EQUAL_COLLECTIONS( trie->lower_bound(valuesToLeaveOut[4]), trie->upper_bound(valuesToLeaveOut[valuesToLeaveOut.size() - 2]), redBlackTree.lower_bound(valuesToLeaveOut[4]), redBlackTree.upper_bound(valuesToLeaveOut[valuesToLeaveOut.size() - 2]) ); } BOOST_AUTO_TEST_CASE(testTriples) { std::vector<uint64_t> const & valuesToInsert = hot::testhelpers::getSampleTriples(); testValues(valuesToInsert); } std::vector<std::string> getLongStrings() { std::vector<std::string> strings; strings.push_back("<http://www.mpii.de/yago/resource/isKnownFor>"); strings.push_back("<http://www.w3.org/2000/01/rdf-schema#domain>"); strings.push_back("<http://www.w3.org/2000/01/rdf-schema#range>"); strings.push_back("<http://www.mpii.de/yago/resource/worksAt>"); strings.push_back("<http://www.mpii.de/yago/resource/hasGivenName>"); strings.push_back("<http://www.mpii.de/yago/resource/hasRevenue>"); strings.push_back("<http://www.mpii.de/yago/resource/happenedIn>"); strings.push_back("<http://www.mpii.de/yago/resource/produced>"); strings.push_back("<http://www.mpii.de/yago/resource/hasPreferredMeaning>"); strings.push_back("<http://www.mpii.de/yago/resource/hasCapital>"); strings.push_back("<http://www.mpii.de/yago/resource/graduatedFrom>"); strings.push_back("<http://www.mpii.de/yago/resource/hasTLD>"); strings.push_back("<http://www.mpii.de/yago/resource/playsFor>"); strings.push_back("<http://www.mpii.de/yago/resource/created>"); strings.push_back("<http://www.mpii.de/yago/resource/directed>"); strings.push_back("<http://www.mpii.de/yago/resource/holdsPoliticalPosition>"); strings.push_back("<http://www.mpii.de/yago/resource/hasMusicalRole>"); strings.push_back("<http://www.mpii.de/yago/resource/dealsWith>"); strings.push_back("<http://www.mpii.de/yago/resource/isAffiliatedTo>"); strings.push_back("<http://www.mpii.de/yago/resource/hasNumberOfPeople>"); strings.push_back("<http://www.mpii.de/yago/resource/diedIn>"); strings.push_back("<http://www.w3.org/2000/01/rdf-schema#label>"); strings.push_back("<http://www.mpii.de/yago/resource/isInterestedIn>"); strings.push_back("<http://www.mpii.de/yago/resource/hasICD10>"); strings.push_back("<http://www.mpii.de/yago/resource/hasWebsite>"); strings.push_back("<http://www.mpii.de/yago/resource/hasMotto>"); strings.push_back("<http://www.mpii.de/yago/resource/isCitizenOf>"); strings.push_back("<http://www.mpii.de/yago/resource/imports>"); strings.push_back("<http://www.mpii.de/yago/resource/hasBudget>"); strings.push_back("<http://www.mpii.de/yago/resource/hasWeight>"); strings.push_back("<http://www.mpii.de/yago/resource/hasChild>"); strings.push_back("<http://www.mpii.de/yago/resource/hasWikipediaArticleLength>"); strings.push_back("<http://www.mpii.de/yago/resource/isMarriedTo>"); strings.push_back("<http://www.mpii.de/yago/resource/hasExport>"); strings.push_back("<http://www.w3.org/2000/01/rdf-schema#subPropertyOf>"); strings.push_back("<http://www.mpii.de/yago/resource/hasPreferredName>"); strings.push_back("<http://www.mpii.de/yago/resource/hasWonPrize>"); strings.push_back("<http://www.mpii.de/yago/resource/endedOnDate>"); strings.push_back("<http://www.mpii.de/yago/resource/hasGDP>"); strings.push_back("<http://www.mpii.de/yago/resource/hasDuration>"); strings.push_back("<http://www.mpii.de/yago/resource/hasImport>"); strings.push_back("<http://www.mpii.de/yago/resource/hasHDI>"); strings.push_back("<http://www.mpii.de/yago/resource/hasGeonamesId>"); strings.push_back("<http://www.mpii.de/yago/resource/hasPoverty>"); strings.push_back("<http://www.mpii.de/yago/resource/isPoliticianOf>"); strings.push_back("<http://www.mpii.de/yago/resource/hasUnemployment>"); strings.push_back("<http://www.mpii.de/yago/resource/hasWikipediaCategory>"); strings.push_back("<http://www.mpii.de/yago/resource/livesIn>"); strings.push_back("<http://www.mpii.de/yago/resource/hasThreeLetterLanguageCode>"); strings.push_back("<http://www.mpii.de/yago/resource/hasExpenses>"); strings.push_back("<http://www.mpii.de/yago/resource/hasCurrency>"); strings.push_back("<http://www.mpii.de/yago/resource/happenedOnDate>"); strings.push_back("<http://www.mpii.de/yago/resource/wasBornOnDate>"); strings.push_back("<http://www.mpii.de/yago/resource/participatedIn>"); strings.push_back("<http://www.mpii.de/yago/resource/hasPages>"); strings.push_back("<http://www.mpii.de/yago/resource/hasImdb>"); strings.push_back("<http://www.mpii.de/yago/resource/influences>"); strings.push_back("<http://www.mpii.de/yago/resource/diedOnDate>"); strings.push_back("<http://www.w3.org/2000/01/rdf-schema#subClassOf>"); strings.push_back("<http://www.mpii.de/yago/resource/hasNumberOfWikipediaLinks>"); strings.push_back("<http://www.mpii.de/yago/resource/hasISBN>"); strings.push_back("<http://www.mpii.de/yago/resource/hasWikipediaAnchorText>"); strings.push_back("<http://www.mpii.de/yago/resource/actedIn>"); strings.push_back("<http://www.mpii.de/yago/resource/exports>"); strings.push_back("<http://www.mpii.de/yago/resource/hasPopulationDensity>"); strings.push_back("<http://www.mpii.de/yago/resource/hasAcademicAdvisor>"); strings.push_back("<http://www.mpii.de/yago/resource/hasArea>"); strings.push_back("<http://www.mpii.de/yago/resource/hasUTCOffset>"); strings.push_back("<http://www.mpii.de/yago/resource/hasGini>"); strings.push_back("<http://www.mpii.de/yago/resource/hasGender>"); strings.push_back("<http://www.mpii.de/yago/resource/hasPopulation>"); strings.push_back("<http://www.w3.org/1999/02/22-rdf-syntax-ns#type>"); strings.push_back("<http://www.mpii.de/yago/resource/hasCitationTitle>"); strings.push_back("<http://www.mpii.de/yago/resource/wasCreatedOnDate>"); strings.push_back("<http://www.mpii.de/yago/resource/isLocatedIn>"); strings.push_back("<http://www.mpii.de/yago/resource/startedOnDate>"); strings.push_back("<http://www.mpii.de/yago/resource/hasOfficialLanguage>"); strings.push_back("<http://www.mpii.de/yago/resource/wasBornIn>"); strings.push_back("<http://www.mpii.de/yago/resource/isLeaderOf>"); strings.push_back("<http://www.mpii.de/yago/resource/wasDestroyedOnDate>"); strings.push_back("<http://www.mpii.de/yago/resource/hasGloss>"); strings.push_back("<http://www.mpii.de/yago/resource/hasEconomicGrowth>"); strings.push_back("<http://www.mpii.de/yago/resource/hasSynsetId>"); strings.push_back("<http://www.mpii.de/yago/resource/hasFamilyName>"); strings.push_back("<http://www.mpii.de/yago/resource/hasWikipediaUrl>"); strings.push_back("<http://www.mpii.de/yago/resource/hasInflation>"); strings.push_back("<http://www.mpii.de/yago/resource/hasExternalWikipediaLinkTo>"); strings.push_back("<http://www.mpii.de/yago/resource/hasHeight>"); strings.push_back("<http://www.mpii.de/yago/resource/hasLanguageCode>"); strings.push_back("<http://www.mpii.de/yago/resource/isCalled>"); strings.push_back("<http://www.mpii.de/yago/resource/hasInternalWikipediaLinkTo>"); strings.push_back("<http://www.mpii.de/yago/resource/Allan_Dwan>"); strings.push_back("<http://www.mpii.de/yago/resource/Los_Angeles>"); strings.push_back("<http://www.mpii.de/yago/resource/Aldous_Huxley>"); strings.push_back("<http://www.mpii.de/yago/resource/Abraham_Lincoln>"); strings.push_back("<http://www.mpii.de/yago/resource/Washington,_D.C.>"); strings.push_back("<http://www.mpii.de/yago/resource/Alfred_Nobel>"); strings.push_back("<http://www.mpii.de/yago/resource/Sanremo>"); strings.push_back("<http://www.mpii.de/yago/resource/Alfons_Maria_Jakob>"); strings.push_back("<http://www.mpii.de/yago/resource/Hamburg>"); strings.push_back("<http://www.mpii.de/yago/resource/Andy_Warhol>"); strings.push_back("<http://www.mpii.de/yago/resource/New_York_City>"); strings.push_back("<http://www.mpii.de/yago/resource/Alexander_the_Great>"); strings.push_back("<http://www.mpii.de/yago/resource/Babylon>"); strings.push_back("<http://www.mpii.de/yago/resource/Allen_Ginsberg>"); strings.push_back("<http://www.mpii.de/yago/resource/Ashoka>"); strings.push_back("<http://www.mpii.de/yago/resource/Pataliputra>"); strings.push_back("<http://www.mpii.de/yago/resource/Andr%C3%A9-Marie_Amp%C3%A8re>"); strings.push_back("<http://www.mpii.de/yago/resource/Marseille>"); strings.push_back("<http://www.mpii.de/yago/resource/Amos_Bronson_Alcott>"); strings.push_back("<http://www.mpii.de/yago/resource/Boston>"); strings.push_back("<http://www.mpii.de/yago/resource/Arthur_Aikin>"); strings.push_back("<http://www.mpii.de/yago/resource/London>"); strings.push_back("<http://www.mpii.de/yago/resource/Agrippina_the_Elder>"); strings.push_back("<http://www.mpii.de/yago/resource/Ventotene>"); strings.push_back("<http://www.mpii.de/yago/resource/Albertus_Magnus>"); strings.push_back("<http://www.mpii.de/yago/resource/Cologne>"); strings.push_back("<http://www.mpii.de/yago/resource/Alaric_I>"); strings.push_back("<http://www.mpii.de/yago/resource/Cosenza>"); strings.push_back("<http://www.mpii.de/yago/resource/Ahmad_Shah_Durrani>"); strings.push_back("<http://www.mpii.de/yago/resource/Kandahar>"); strings.push_back("<http://www.mpii.de/yago/resource/Alexander_Jagiellon>"); strings.push_back("<http://www.mpii.de/yago/resource/Vilnius>"); strings.push_back("<http://www.mpii.de/yago/resource/Alexander_I_of_Scotland>"); strings.push_back("<http://www.mpii.de/yago/resource/Stirling>"); strings.push_back("<http://www.mpii.de/yago/resource/Alexander_Severus>"); strings.push_back("<http://www.mpii.de/yago/resource/Mainz>"); strings.push_back("<http://www.mpii.de/yago/resource/Ealdred_(archbishop_of_York)>"); strings.push_back("<http://www.mpii.de/yago/resource/York>"); strings.push_back("<http://www.mpii.de/yago/resource/Alboin>"); strings.push_back("<http://www.mpii.de/yago/resource/Verona>"); strings.push_back("<http://www.mpii.de/yago/resource/Afonso_IV_of_Portugal>"); strings.push_back("<http://www.mpii.de/yago/resource/Lisbon>"); strings.push_back("<http://www.mpii.de/yago/resource/Afonso_V_of_Portugal>"); strings.push_back("<http://www.mpii.de/yago/resource/Afonso_I_of_Portugal>"); strings.push_back("<http://www.mpii.de/yago/resource/Coimbra>"); strings.push_back("<http://www.mpii.de/yago/resource/Alfonso_XIII_of_Spain>"); strings.push_back("<http://www.mpii.de/yago/resource/Rome>"); strings.push_back("<http://www.mpii.de/yago/resource/Andrew_Johnson>"); strings.push_back("<http://www.mpii.de/yago/resource/Elizabethton,_Tennessee>"); strings.push_back("<http://www.mpii.de/yago/resource/Augustus>"); strings.push_back("<http://www.mpii.de/yago/resource/Nola>"); strings.push_back("<http://www.mpii.de/yago/resource/Andrew_Jackson>"); strings.push_back("<http://www.mpii.de/yago/resource/Nashville,_Tennessee>"); strings.push_back("<http://www.mpii.de/yago/resource/Adolph_Wilhelm_Hermann_Kolbe>"); strings.push_back("<http://www.mpii.de/yago/resource/Leipzig>"); strings.push_back("<http://www.mpii.de/yago/resource/Alfred_Jarry>"); strings.push_back("<http://www.mpii.de/yago/resource/Paris>"); strings.push_back("<http://www.mpii.de/yago/resource/Absalon>"); strings.push_back("<http://www.mpii.de/yago/resource/Sor%C3%B8>"); strings.push_back("<http://www.mpii.de/yago/resource/Abu_Bakr>"); strings.push_back("<http://www.mpii.de/yago/resource/Medina>"); strings.push_back("<http://www.mpii.de/yago/resource/Adam_Smith>"); strings.push_back("<http://www.mpii.de/yago/resource/Edinburgh>"); strings.push_back("<http://www.mpii.de/yago/resource/Alessandro_Volta>"); strings.push_back("<http://www.mpii.de/yago/resource/Como>"); strings.push_back("<http://www.mpii.de/yago/resource/Alvar_Aalto>"); strings.push_back("<http://www.mpii.de/yago/resource/Helsinki>"); strings.push_back("<http://www.mpii.de/yago/resource/Amerigo_Vespucci>"); strings.push_back("<http://www.mpii.de/yago/resource/Seville>"); strings.push_back("<http://www.mpii.de/yago/resource/Aage_Bohr>"); strings.push_back("<http://www.mpii.de/yago/resource/Copenhagen>"); strings.push_back("<http://www.mpii.de/yago/resource/Antoni_Gaud%C3%AD>"); strings.push_back("<http://www.mpii.de/yago/resource/Barcelona>"); strings.push_back("<http://www.mpii.de/yago/resource/Arthur_Stanley_Eddington>"); strings.push_back("<http://www.mpii.de/yago/resource/Cambridge>"); strings.push_back("<http://www.mpii.de/yago/resource/Albert_Pike>"); strings.push_back("<http://www.mpii.de/yago/resource/Alois_Alzheimer>"); strings.push_back("<http://www.mpii.de/yago/resource/Wroc%C5%82aw>"); strings.push_back("<http://www.mpii.de/yago/resource/Alberto_Giacometti>"); strings.push_back("<http://www.mpii.de/yago/resource/Chur>"); strings.push_back("<http://www.mpii.de/yago/resource/Ambrosius_Bosschaert>"); strings.push_back("<http://www.mpii.de/yago/resource/The_Hague>"); strings.push_back("<http://www.mpii.de/yago/resource/Aurangzeb>"); strings.push_back("<http://www.mpii.de/yago/resource/Ahmednagar>"); strings.push_back("<http://www.mpii.de/yago/resource/Alexander_Kerensky>"); strings.push_back("<http://www.mpii.de/yago/resource/Arthur_Phillip>"); strings.push_back("<http://www.mpii.de/yago/resource/Bath,_Somerset>"); strings.push_back("<http://www.mpii.de/yago/resource/Abbas_II_of_Egypt>"); strings.push_back("<http://www.mpii.de/yago/resource/Geneva>"); strings.push_back("<http://www.mpii.de/yago/resource/Andr%C3%A9_the_Giant>"); strings.push_back("<http://www.mpii.de/yago/resource/Arthur_St._Clair>"); strings.push_back("<http://www.mpii.de/yago/resource/Greensburg,_Pennsylvania>"); strings.push_back("<http://www.mpii.de/yago/resource/Andrei_Sakharov>"); strings.push_back("<http://www.mpii.de/yago/resource/Moscow>"); strings.push_back("<http://www.mpii.de/yago/resource/Augustine_of_Canterbury>"); strings.push_back("<http://www.mpii.de/yago/resource/Canterbury>"); strings.push_back("<http://www.mpii.de/yago/resource/Adolphe_Sax>"); strings.push_back("<http://www.mpii.de/yago/resource/A._E._Housman>"); strings.push_back("<http://www.mpii.de/yago/resource/Anthony_of_Saxony>"); strings.push_back("<http://www.mpii.de/yago/resource/Dresden>"); strings.push_back("<http://www.mpii.de/yago/resource/Albert_III,_Duke_of_Saxony>"); strings.push_back("<http://www.mpii.de/yago/resource/Emden>"); strings.push_back("<http://www.mpii.de/yago/resource/Athanasius_of_Alexandria>"); strings.push_back("<http://www.mpii.de/yago/resource/Alexandria>"); strings.push_back("<http://www.mpii.de/yago/resource/Gautama_Buddha>"); strings.push_back("<http://www.mpii.de/yago/resource/Kushinagar>"); strings.push_back("<http://www.mpii.de/yago/resource/Baruch_Spinoza>"); strings.push_back("<http://www.mpii.de/yago/resource/Bram_Stoker>"); strings.push_back("<http://www.mpii.de/yago/resource/Blaise_Pascal>"); strings.push_back("<http://www.mpii.de/yago/resource/Berthe_Morisot>"); strings.push_back("<http://www.mpii.de/yago/resource/Benjamin_Franklin>"); strings.push_back("<http://www.mpii.de/yago/resource/Philadelphia>"); strings.push_back("<http://www.mpii.de/yago/resource/Babrak_Karmal>"); strings.push_back("<http://www.mpii.de/yago/resource/Babur>"); strings.push_back("<http://www.mpii.de/yago/resource/Agra>"); strings.push_back("<http://www.mpii.de/yago/resource/Barnabas>"); strings.push_back("<http://www.mpii.de/yago/resource/Salamis,_Cyprus>"); strings.push_back("<http://www.mpii.de/yago/resource/Benjamin_Tucker>"); strings.push_back("<http://www.mpii.de/yago/resource/Monaco>"); strings.push_back("<http://www.mpii.de/yago/resource/B._F._Skinner>"); strings.push_back("<http://www.mpii.de/yago/resource/Cambridge,_Massachusetts>"); strings.push_back("<http://www.mpii.de/yago/resource/Bohdan_Khmelnytsky>"); strings.push_back("<http://www.mpii.de/yago/resource/Chyhyryn>"); strings.push_back("<http://www.mpii.de/yago/resource/Brigham_Young>"); strings.push_back("<http://www.mpii.de/yago/resource/Salt_Lake_City>"); strings.push_back("<http://www.mpii.de/yago/resource/Charlie_Chaplin>"); strings.push_back("<http://www.mpii.de/yago/resource/Vevey>"); strings.push_back("<http://www.mpii.de/yago/resource/Charlemagne>"); strings.push_back("<http://www.mpii.de/yago/resource/Aachen>"); strings.push_back("<http://www.mpii.de/yago/resource/C._Northcote_Parkinson>"); strings.push_back("<http://www.mpii.de/yago/resource/Claude_Shannon>"); strings.push_back("<http://www.mpii.de/yago/resource/Medford,_Massachusetts>"); strings.push_back("<http://www.mpii.de/yago/resource/C._S._Forester>"); strings.push_back("<http://www.mpii.de/yago/resource/Fullerton,_California>"); strings.push_back("<http://www.mpii.de/yago/resource/Carlo_Goldoni>"); strings.push_back("<http://www.mpii.de/yago/resource/C._S._Lewis>"); strings.push_back("<http://www.mpii.de/yago/resource/Oxford>"); strings.push_back("<http://www.mpii.de/yago/resource/Clark_Ashton_Smith>"); strings.push_back("<http://www.mpii.de/yago/resource/Pacific_Grove,_California>"); strings.push_back("<http://www.mpii.de/yago/resource/Calvin_Coolidge>"); strings.push_back("<http://www.mpii.de/yago/resource/Northampton,_Massachusetts>"); strings.push_back("<http://www.mpii.de/yago/resource/Czes%C5%82aw_Mi%C5%82osz>"); strings.push_back("<http://www.mpii.de/yago/resource/Krak%C3%B3w>"); strings.push_back("<http://www.mpii.de/yago/resource/Clyde_Tombaugh>"); strings.push_back("<http://www.mpii.de/yago/resource/Las_Cruces,_New_Mexico>"); strings.push_back("<http://www.mpii.de/yago/resource/Constantine_Kanaris>"); strings.push_back("<http://www.mpii.de/yago/resource/Athens>"); strings.push_back("<http://www.mpii.de/yago/resource/Cecilia_Beaux>"); strings.push_back("<http://www.mpii.de/yago/resource/Gloucester,_Massachusetts>"); strings.push_back("<http://www.mpii.de/yago/resource/Carl_Sagan>"); strings.push_back("<http://www.mpii.de/yago/resource/Seattle>"); strings.push_back("<http://www.mpii.de/yago/resource/Colette>"); strings.push_back("<http://www.mpii.de/yago/resource/Cimabue>"); strings.push_back("<http://www.mpii.de/yago/resource/Pisa>"); strings.push_back("<http://www.mpii.de/yago/resource/Christiaan_Barnard>"); strings.push_back("<http://www.mpii.de/yago/resource/Paphos>"); strings.push_back("<http://www.mpii.de/yago/resource/Christian_Doppler>"); strings.push_back("<http://www.mpii.de/yago/resource/Venice>"); strings.push_back("<http://www.mpii.de/yago/resource/Caravaggio>"); strings.push_back("<http://www.mpii.de/yago/resource/Monte_Argentario>"); strings.push_back("<http://www.mpii.de/yago/resource/Casimir_III_the_Great>"); strings.push_back("<http://www.mpii.de/yago/resource/Cyril_of_Jerusalem>"); strings.push_back("<http://www.mpii.de/yago/resource/Jerusalem>"); strings.push_back("<http://www.mpii.de/yago/resource/Carl_Barks>"); strings.push_back("<http://www.mpii.de/yago/resource/Grants_Pass,_Oregon>"); strings.push_back("<http://www.mpii.de/yago/resource/Camille_Pissarro>"); strings.push_back("<http://www.mpii.de/yago/resource/Catherine_of_Siena>"); strings.push_back("<http://www.mpii.de/yago/resource/Carl_Rogers>"); strings.push_back("<http://www.mpii.de/yago/resource/San_Diego>"); strings.push_back("<http://www.mpii.de/yago/resource/Clarence_Brown>"); strings.push_back("<http://www.mpii.de/yago/resource/Santa_Monica,_California>"); strings.push_back("<http://www.mpii.de/yago/resource/Camilla_Hall>"); strings.push_back("<http://www.mpii.de/yago/resource/Colin_Maclaurin>"); strings.push_back("<http://www.mpii.de/yago/resource/The_Amazing_Criswell>"); strings.push_back("<http://www.mpii.de/yago/resource/Burbank,_California>"); strings.push_back("<http://www.mpii.de/yago/resource/Dale_Earnhardt>"); strings.push_back("<http://www.mpii.de/yago/resource/Daytona_Beach,_Florida>"); strings.push_back("<http://www.mpii.de/yago/resource/Constantine_I>"); strings.push_back("<http://www.mpii.de/yago/resource/Nicomedia>"); strings.push_back("<http://www.mpii.de/yago/resource/Dalton_Trumbo>"); strings.push_back("<http://www.mpii.de/yago/resource/Douglas_Adams>"); strings.push_back("<http://www.mpii.de/yago/resource/Santa_Barbara,_California>"); strings.push_back("<http://www.mpii.de/yago/resource/Dante_Alighieri>"); strings.push_back("<http://www.mpii.de/yago/resource/Ravenna>"); strings.push_back("<http://www.mpii.de/yago/resource/David_Janssen>"); strings.push_back("<http://www.mpii.de/yago/resource/Malibu,_California>"); strings.push_back("<http://www.mpii.de/yago/resource/Dwight_D._Eisenhower>"); strings.push_back("<http://www.mpii.de/yago/resource/David>"); strings.push_back("<http://www.mpii.de/yago/resource/Daniel_Gabriel_Fahrenheit>"); strings.push_back("<http://www.mpii.de/yago/resource/David_Rice_Atchison>"); strings.push_back("<http://www.mpii.de/yago/resource/Gower,_Missouri>"); strings.push_back("<http://www.mpii.de/yago/resource/Desi_Arnaz>"); strings.push_back("<http://www.mpii.de/yago/resource/Del_Mar,_California>"); strings.push_back("<http://www.mpii.de/yago/resource/Dorothy_Parker>"); strings.push_back("<http://www.mpii.de/yago/resource/Donald_Dewar>"); strings.push_back("<http://www.mpii.de/yago/resource/Donald_A._Wollheim>"); strings.push_back("<http://www.mpii.de/yago/resource/David_Beatty,_1st_Earl_Beatty>"); strings.push_back("<http://www.mpii.de/yago/resource/Dunstan>"); strings.push_back("<http://www.mpii.de/yago/resource/Dave_Thomas_(American_businessman)>"); strings.push_back("<http://www.mpii.de/yago/resource/Fort_Lauderdale,_Florida>"); strings.push_back("<http://www.mpii.de/yago/resource/Damon_Runyon>"); strings.push_back("<http://www.mpii.de/yago/resource/Edward_Sapir>"); strings.push_back("<http://www.mpii.de/yago/resource/New_Haven,_Connecticut>"); strings.push_back("<http://www.mpii.de/yago/resource/Ethan_Allen>"); strings.push_back("<http://www.mpii.de/yago/resource/Burlington,_Vermont>"); strings.push_back("<http://www.mpii.de/yago/resource/Elias_Canetti>"); strings.push_back("<http://www.mpii.de/yago/resource/Z%C3%BCrich>"); strings.push_back("<http://www.mpii.de/yago/resource/Ernest_Hemingway>"); strings.push_back("<http://www.mpii.de/yago/resource/Ketchum,_Idaho>"); strings.push_back("<http://www.mpii.de/yago/resource/Edgar_Allan_Poe>"); strings.push_back("<http://www.mpii.de/yago/resource/Baltimore>"); strings.push_back("<http://www.mpii.de/yago/resource/Ernest_Rutherford>"); strings.push_back("<http://www.mpii.de/yago/resource/Ernest_Thayer>"); strings.push_back("<http://www.mpii.de/yago/resource/%C3%89variste_Galois>"); strings.push_back("<http://www.mpii.de/yago/resource/Edvard_Munch>"); strings.push_back("<http://www.mpii.de/yago/resource/Oslo>"); strings.push_back("<http://www.mpii.de/yago/resource/E._E._Smith>"); strings.push_back("<http://www.mpii.de/yago/resource/Seaside,_Oregon>"); strings.push_back("<http://www.mpii.de/yago/resource/Erik_Satie>"); strings.push_back("<http://www.mpii.de/yago/resource/Emperor_Sh%C5%8Dmu>"); strings.push_back("<http://www.mpii.de/yago/resource/Nara,_Nara>"); strings.push_back("<http://www.mpii.de/yago/resource/E._T._A._Hoffmann>"); strings.push_back("<http://www.mpii.de/yago/resource/Berlin>"); strings.push_back("<http://www.mpii.de/yago/resource/Elihu_Yale>"); strings.push_back("<http://www.mpii.de/yago/resource/Desiderius_Erasmus>"); strings.push_back("<http://www.mpii.de/yago/resource/Basel>"); strings.push_back("<http://www.mpii.de/yago/resource/Elbridge_Gerry>"); strings.push_back("<http://www.mpii.de/yago/resource/Edward_Gibbon>"); strings.push_back("<http://www.mpii.de/yago/resource/Ephrem_the_Syrian>"); strings.push_back("<http://www.mpii.de/yago/resource/Edessa,_Mesopotamia>"); strings.push_back("<http://www.mpii.de/yago/resource/Edward_Lear>"); strings.push_back("<http://www.mpii.de/yago/resource/Empress_Gensh%C5%8D>"); strings.push_back("<http://www.mpii.de/yago/resource/Epictetus>"); strings.push_back("<http://www.mpii.de/yago/resource/Nicopolis>"); strings.push_back("<http://www.mpii.de/yago/resource/Edwin_Hubble>"); strings.push_back("<http://www.mpii.de/yago/resource/San_Marino,_California>"); strings.push_back("<http://www.mpii.de/yago/resource/Frank_Herbert>"); strings.push_back("<http://www.mpii.de/yago/resource/Madison,_Wisconsin>"); strings.push_back("<http://www.mpii.de/yago/resource/Frank_Lloyd_Wright>"); strings.push_back("<http://www.mpii.de/yago/resource/Phoenix,_Arizona>"); strings.push_back("<http://www.mpii.de/yago/resource/Felix_Bloch>"); strings.push_back("<http://www.mpii.de/yago/resource/Francis_Scott_Key>"); strings.push_back("<http://www.mpii.de/yago/resource/Felix_Hausdorff>"); strings.push_back("<http://www.mpii.de/yago/resource/Bonn>"); strings.push_back("<http://www.mpii.de/yago/resource/Francis_Hopkinson>"); strings.push_back("<http://www.mpii.de/yago/resource/Frederick_Douglass>"); strings.push_back("<http://www.mpii.de/yago/resource/Francesco_Borromini>"); strings.push_back("<http://www.mpii.de/yago/resource/Francisco_I._Madero>"); strings.push_back("<http://www.mpii.de/yago/resource/Mexico_City>"); strings.push_back("<http://www.mpii.de/yago/resource/Frans_Eemil_Sillanp%C3%A4%C3%A4>"); strings.push_back("<http://www.mpii.de/yago/resource/Felix_Wankel>"); strings.push_back("<http://www.mpii.de/yago/resource/Heidelberg>"); strings.push_back("<http://www.mpii.de/yago/resource/Frank_Capra>"); strings.push_back("<http://www.mpii.de/yago/resource/La_Quinta,_California>"); strings.push_back("<http://www.mpii.de/yago/resource/Fernando_Pessoa>"); strings.push_back("<http://www.mpii.de/yago/resource/Friedrich_August_Kekul%C3%A9_von_Stradonitz>"); strings.push_back("<http://www.mpii.de/yago/resource/Frederick_III,_Holy_Roman_Emperor>"); strings.push_back("<http://www.mpii.de/yago/resource/Linz>"); strings.push_back("<http://www.mpii.de/yago/resource/Fra_Angelico>"); strings.push_back("<http://www.mpii.de/yago/resource/Firmin_Abauzit>"); strings.push_back("<http://www.mpii.de/yago/resource/Franklin_D._Roosevelt>"); strings.push_back("<http://www.mpii.de/yago/resource/Warm_Springs,_Georgia>"); strings.push_back("<http://www.mpii.de/yago/resource/Fritz_Lang>"); strings.push_back("<http://www.mpii.de/yago/resource/Beverly_Hills,_California>"); strings.push_back("<http://www.mpii.de/yago/resource/Fyodor_Dostoyevsky>"); strings.push_back("<http://www.mpii.de/yago/resource/Saint_Petersburg>"); strings.push_back("<http://www.mpii.de/yago/resource/Francis_Crick>"); strings.push_back("<http://www.mpii.de/yago/resource/Franklin_J._Schaffner>"); strings.push_back("<http://www.mpii.de/yago/resource/Frederick_William_I_of_Prussia>"); strings.push_back("<http://www.mpii.de/yago/resource/Filippo_Tommaso_Marinetti>"); strings.push_back("<http://www.mpii.de/yago/resource/Bellagio>"); strings.push_back("<http://www.mpii.de/yago/resource/Francesco_Cossiga>"); strings.push_back("<http://www.mpii.de/yago/resource/Federico_Fellini>"); strings.push_back("<http://www.mpii.de/yago/resource/George_Berkeley>"); strings.push_back("<http://www.mpii.de/yago/resource/Johann_Gottlieb_Fichte>"); strings.push_back("<http://www.mpii.de/yago/resource/Guglielmo_Marconi>"); strings.push_back("<http://www.mpii.de/yago/resource/Gary_Coleman>"); strings.push_back("<http://www.mpii.de/yago/resource/Provo,_Utah>"); strings.push_back("<http://www.mpii.de/yago/resource/Gene_Kelly>"); strings.push_back("<http://www.mpii.de/yago/resource/Georges_Braque>"); strings.push_back("<http://www.mpii.de/yago/resource/Gustav_Kirchhoff>"); strings.push_back("<http://www.mpii.de/yago/resource/Georg_Cantor>"); strings.push_back("<http://www.mpii.de/yago/resource/Halle,_Saxony-Anhalt>"); strings.push_back("<http://www.mpii.de/yago/resource/Germanicus>"); strings.push_back("<http://www.mpii.de/yago/resource/Antioch>"); strings.push_back("<http://www.mpii.de/yago/resource/Gottfried_Leibniz>"); strings.push_back("<http://www.mpii.de/yago/resource/Hanover>"); strings.push_back("<http://www.mpii.de/yago/resource/Garnet_Bailey>"); strings.push_back("<http://www.mpii.de/yago/resource/Gregor_Mendel>"); strings.push_back("<http://www.mpii.de/yago/resource/Brno>"); strings.push_back("<http://www.mpii.de/yago/resource/Gerrit_Rietveld>"); strings.push_back("<http://www.mpii.de/yago/resource/Utrecht_(city)>"); strings.push_back("<http://www.mpii.de/yago/resource/Gian_Lorenzo_Bernini>"); strings.push_back("<http://www.mpii.de/yago/resource/Gary_Kildall>"); strings.push_back("<http://www.mpii.de/yago/resource/Monterey,_California>"); strings.push_back("<http://www.mpii.de/yago/resource/Gia_Carangi>"); strings.push_back("<http://www.mpii.de/yago/resource/Gustav_Radbruch>"); strings.push_back("<http://www.mpii.de/yago/resource/Georg_Wilhelm_Friedrich_Hegel>"); strings.push_back("<http://www.mpii.de/yago/resource/Grigori_Rasputin>"); strings.push_back("<http://www.mpii.de/yago/resource/Gary_Gygax>"); strings.push_back("<http://www.mpii.de/yago/resource/Lake_Geneva,_Wisconsin>"); strings.push_back("<http://www.mpii.de/yago/resource/Giovanni_Boccaccio>"); strings.push_back("<http://www.mpii.de/yago/resource/Certaldo>"); strings.push_back("<http://www.mpii.de/yago/resource/Gavrilo_Princip>"); strings.push_back("<http://www.mpii.de/yago/resource/Terez%C3%ADn>"); strings.push_back("<http://www.mpii.de/yago/resource/Giordano_Bruno>"); strings.push_back("<http://www.mpii.de/yago/resource/George_Washington_Carver>"); strings.push_back("<http://www.mpii.de/yago/resource/Tuskegee,_Alabama>"); strings.push_back("<http://www.mpii.de/yago/resource/Gerolamo_Cardano>"); strings.push_back("<http://www.mpii.de/yago/resource/Glenn_T._Seaborg>"); strings.push_back("<http://www.mpii.de/yago/resource/Lafayette,_California>"); strings.push_back("<http://www.mpii.de/yago/resource/George,_Duke_of_Saxony>"); strings.push_back("<http://www.mpii.de/yago/resource/Howard_Hawks>"); strings.push_back("<http://www.mpii.de/yago/resource/Palm_Springs,_California>"); strings.push_back("<http://www.mpii.de/yago/resource/George_Fox>"); strings.push_back("<http://www.mpii.de/yago/resource/Hans_Gerhard_Creutzfeldt>"); strings.push_back("<http://www.mpii.de/yago/resource/Munich>"); strings.push_back("<http://www.mpii.de/yago/resource/Hans_Selye>"); strings.push_back("<http://www.mpii.de/yago/resource/Montreal>"); strings.push_back("<http://www.mpii.de/yago/resource/Henry_Fielding>"); strings.push_back("<http://www.mpii.de/yago/resource/Hans_Christian_Andersen>"); strings.push_back("<http://www.mpii.de/yago/resource/Heinrich_Schliemann>"); strings.push_back("<http://www.mpii.de/yago/resource/Naples>"); strings.push_back("<http://www.mpii.de/yago/resource/Hermann_Ebbinghaus>"); strings.push_back("<http://www.mpii.de/yago/resource/H._P._Lovecraft>"); strings.push_back("<http://www.mpii.de/yago/resource/Providence,_Rhode_Island>"); strings.push_back("<http://www.mpii.de/yago/resource/Robert_Koch>"); strings.push_back("<http://www.mpii.de/yago/resource/Baden-Baden>"); strings.push_back("<http://www.mpii.de/yago/resource/Herman_Hollerith>"); strings.push_back("<http://www.mpii.de/yago/resource/Hannibal_Hamlin>"); strings.push_back("<http://www.mpii.de/yago/resource/Bangor,_Maine>"); strings.push_back("<http://www.mpii.de/yago/resource/Hans-Georg_Gadamer>"); strings.push_back("<http://www.mpii.de/yago/resource/Helen_Gandy>"); strings.push_back("<http://www.mpii.de/yago/resource/DeLand,_Florida>"); strings.push_back("<http://www.mpii.de/yago/resource/Humayun>"); strings.push_back("<http://www.mpii.de/yago/resource/Delhi>"); strings.push_back("<http://www.mpii.de/yago/resource/Hannibal>"); strings.push_back("<http://www.mpii.de/yago/resource/Gebze>"); strings.push_back("<http://www.mpii.de/yago/resource/Henry_Bruce,_1st_Baron_Aberdare>"); strings.push_back("<http://www.mpii.de/yago/resource/Herbert_Simon>"); strings.push_back("<http://www.mpii.de/yago/resource/Pittsburgh>"); strings.push_back("<http://www.mpii.de/yago/resource/Henrik_Ibsen>"); strings.push_back("<http://www.mpii.de/yago/resource/Henry_Middleton>"); strings.push_back("<http://www.mpii.de/yago/resource/Charleston,_South_Carolina>"); strings.push_back("<http://www.mpii.de/yago/resource/Henry_Laurens>"); strings.push_back("<http://www.mpii.de/yago/resource/Humphry_Davy>"); strings.push_back("<http://www.mpii.de/yago/resource/Hedwig_of_Andechs>"); strings.push_back("<http://www.mpii.de/yago/resource/Trzebnica>"); strings.push_back("<http://www.mpii.de/yago/resource/Harold_Eugene_Edgerton>"); strings.push_back("<http://www.mpii.de/yago/resource/Indira_Gandhi>"); strings.push_back("<http://www.mpii.de/yago/resource/New_Delhi>"); strings.push_back("<http://www.mpii.de/yago/resource/Ignatius_of_Antioch>"); strings.push_back("<http://www.mpii.de/yago/resource/John_Grierson>"); strings.push_back("<http://www.mpii.de/yago/resource/John_Bardeen>"); strings.push_back("<http://www.mpii.de/yago/resource/Johannes_Rau>"); strings.push_back("<http://www.mpii.de/yago/resource/Johannes_Gutenberg>"); strings.push_back("<http://www.mpii.de/yago/resource/John_Quincy_Adams>"); strings.push_back("<http://www.mpii.de/yago/resource/Jack_Lemmon>"); strings.push_back("<http://www.mpii.de/yago/resource/Jorge_Luis_Borges>"); strings.push_back("<http://www.mpii.de/yago/resource/James_Branch_Cabell>"); strings.push_back("<http://www.mpii.de/yago/resource/Richmond,_Virginia>"); strings.push_back("<http://www.mpii.de/yago/resource/Jack_Kerouac>"); strings.push_back("<http://www.mpii.de/yago/resource/St._Petersburg,_Florida>"); strings.push_back("<http://www.mpii.de/yago/resource/Jack_L._Chalker>"); strings.push_back("<http://www.mpii.de/yago/resource/John_von_Neumann>"); strings.push_back("<http://www.mpii.de/yago/resource/John_Calvin>"); strings.push_back("<http://www.mpii.de/yago/resource/Justus_von_Liebig>"); strings.push_back("<http://www.mpii.de/yago/resource/Jerome>"); strings.push_back("<http://www.mpii.de/yago/resource/Bethlehem>"); strings.push_back("<http://www.mpii.de/yago/resource/James_K._Polk>"); strings.push_back("<http://www.mpii.de/yago/resource/Jan_Hus>"); strings.push_back("<http://www.mpii.de/yago/resource/Konstanz>"); strings.push_back("<http://www.mpii.de/yago/resource/Johann_Elert_Bode>"); strings.push_back("<http://www.mpii.de/yago/resource/John_James_Richard_Macleod>"); strings.push_back("<http://www.mpii.de/yago/resource/Aberdeen>"); strings.push_back("<http://www.mpii.de/yago/resource/Joseph_Gurney_Cannon>"); strings.push_back("<http://www.mpii.de/yago/resource/Danville,_Illinois>"); strings.push_back("<http://www.mpii.de/yago/resource/Jeffrey_Dahmer>"); strings.push_back("<http://www.mpii.de/yago/resource/Portage,_Wisconsin>"); strings.push_back("<http://www.mpii.de/yago/resource/James_G._Blaine>"); strings.push_back("<http://www.mpii.de/yago/resource/Jawaharlal_Nehru>"); strings.push_back("<http://www.mpii.de/yago/resource/John_Paul_Jones>"); strings.push_back("<http://www.mpii.de/yago/resource/Jadwiga_of_Poland>"); strings.push_back("<http://www.mpii.de/yago/resource/Justin_Martyr>"); strings.push_back("<http://www.mpii.de/yago/resource/J.E.B._Stuart>"); strings.push_back("<http://www.mpii.de/yago/resource/John_Pople>"); strings.push_back("<http://www.mpii.de/yago/resource/Chicago>"); strings.push_back("<http://www.mpii.de/yago/resource/Johannes_Nicolaus_Br%C3%B8nsted>"); strings.push_back("<http://www.mpii.de/yago/resource/Jerry_Falwell>"); strings.push_back("<http://www.mpii.de/yago/resource/Lynchburg,_Virginia>"); strings.push_back("<http://www.mpii.de/yago/resource/Jacob_Grimm>"); strings.push_back("<http://www.mpii.de/yago/resource/Jacques_Dupuis_(priest)>"); strings.push_back("<http://www.mpii.de/yago/resource/Jack_Kirby>"); strings.push_back("<http://www.mpii.de/yago/resource/Thousand_Oaks,_California>"); strings.push_back("<http://www.mpii.de/yago/resource/Karl_Marx>"); strings.push_back("<http://www.mpii.de/yago/resource/Kiyoshi_Atsumi>"); strings.push_back("<http://www.mpii.de/yago/resource/Tokyo>"); strings.push_back("<http://www.mpii.de/yago/resource/Karel_Hynek_M%C3%A1cha>"); strings.push_back("<http://www.mpii.de/yago/resource/Litom%C4%9B%C5%99ice>"); strings.push_back("<http://www.mpii.de/yago/resource/Kim_Philby>"); strings.push_back("<http://www.mpii.de/yago/resource/Konstantin_Tsiolkovsky>"); strings.push_back("<http://www.mpii.de/yago/resource/Kaluga>"); strings.push_back("<http://www.mpii.de/yago/resource/Kwame_Nkrumah>"); strings.push_back("<http://www.mpii.de/yago/resource/Bucharest>"); strings.push_back("<http://www.mpii.de/yago/resource/Knud_Rasmussen>"); strings.push_back("<http://www.mpii.de/yago/resource/Konstantin_Chernenko>"); strings.push_back("<http://www.mpii.de/yago/resource/Kliment_Voroshilov>"); strings.push_back("<http://www.mpii.de/yago/resource/Klaus_Fuchs>"); strings.push_back("<http://www.mpii.de/yago/resource/Khwaja_Ahmad_Abbas>"); strings.push_back("<http://www.mpii.de/yago/resource/Mumbai>"); strings.push_back("<http://www.mpii.de/yago/resource/Klement_Gottwald>"); strings.push_back("<http://www.mpii.de/yago/resource/Prague>"); strings.push_back("<http://www.mpii.de/yago/resource/Constantin_Stanislavski>"); strings.push_back("<http://www.mpii.de/yago/resource/Fumimaro_Konoe>"); strings.push_back("<http://www.mpii.de/yago/resource/Ludovico_Ariosto>"); strings.push_back("<http://www.mpii.de/yago/resource/Ferrara>"); strings.push_back("<http://www.mpii.de/yago/resource/Ludwig_Wittgenstein>"); strings.push_back("<http://www.mpii.de/yago/resource/Edward_Plunkett,_18th_Baron_of_Dunsany>"); strings.push_back("<http://www.mpii.de/yago/resource/Dublin>"); strings.push_back("<http://www.mpii.de/yago/resource/Louisa_May_Alcott>"); strings.push_back("<http://www.mpii.de/yago/resource/Louis_Leakey>"); strings.push_back("<http://www.mpii.de/yago/resource/Louis_Agassiz>"); strings.push_back("<http://www.mpii.de/yago/resource/Leon_Battista_Alberti>"); strings.push_back("<http://www.mpii.de/yago/resource/Leonard_Bloomfield>"); strings.push_back("<http://www.mpii.de/yago/resource/Lise_Meitner>"); strings.push_back("<http://www.mpii.de/yago/resource/L._L._Zamenhof>"); strings.push_back("<http://www.mpii.de/yago/resource/Warsaw>"); strings.push_back("<http://www.mpii.de/yago/resource/Lev_Kuleshov>"); strings.push_back("<http://www.mpii.de/yago/resource/Lee_Marvin>"); strings.push_back("<http://www.mpii.de/yago/resource/Tucson,_Arizona>"); strings.push_back("<http://www.mpii.de/yago/resource/Lavrentiy_Beria>"); strings.push_back("<http://www.mpii.de/yago/resource/L%C3%A9on_Theremin>"); strings.push_back("<http://www.mpii.de/yago/resource/Louis_IX_of_France>"); strings.push_back("<http://www.mpii.de/yago/resource/Tunis>"); strings.push_back("<http://www.mpii.de/yago/resource/Lucrezia_Borgia>"); strings.push_back("<http://www.mpii.de/yago/resource/Luigi_Pirandello>"); strings.push_back("<http://www.mpii.de/yago/resource/Masaki_Kobayashi>"); strings.push_back("<http://www.mpii.de/yago/resource/Max_Weber>"); strings.push_back("<http://www.mpii.de/yago/resource/Mohandas_Karamchand_Gandhi>"); strings.push_back("<http://www.mpii.de/yago/resource/Margaret_Mead>"); strings.push_back("<http://www.mpii.de/yago/resource/Maciej_P%C5%82a%C5%BCy%C5%84ski>"); strings.push_back("<http://www.mpii.de/yago/resource/Smolensk>"); strings.push_back("<http://www.mpii.de/yago/resource/Mark_Antony>"); strings.push_back("<http://www.mpii.de/yago/resource/Marino_Marini_(sculptor)>"); strings.push_back("<http://www.mpii.de/yago/resource/Viareggio>"); strings.push_back("<http://www.mpii.de/yago/resource/Murray_Rothbard>"); strings.push_back("<http://www.mpii.de/yago/resource/Mary_Cassatt>"); strings.push_back("<http://www.mpii.de/yago/resource/Martin_Luther_King,_Jr.>"); strings.push_back("<http://www.mpii.de/yago/resource/Memphis,_Tennessee>"); strings.push_back("<http://www.mpii.de/yago/resource/Michael_Bentine>"); strings.push_back("<http://www.mpii.de/yago/resource/Mieszko_II_Lambert>"); strings.push_back("<http://www.mpii.de/yago/resource/Pozna%C5%84>"); strings.push_back("<http://www.mpii.de/yago/resource/Macrinus>"); strings.push_back("<http://www.mpii.de/yago/resource/Cappadocia>"); strings.push_back("<http://www.mpii.de/yago/resource/Saint_Matthew>"); strings.push_back("<http://www.mpii.de/yago/resource/Hierapolis>"); strings.push_back("<http://www.mpii.de/yago/resource/Mieszko_I_of_Poland>"); strings.push_back("<http://www.mpii.de/yago/resource/Mordecai_Kaplan>"); strings.push_back("<http://www.mpii.de/yago/resource/Moctezuma_II>"); strings.push_back("<http://www.mpii.de/yago/resource/Tenochtitlan>"); strings.push_back("<http://www.mpii.de/yago/resource/Mary_Magdalene>"); strings.push_back("<http://www.mpii.de/yago/resource/Ephesus>"); strings.push_back("<http://www.mpii.de/yago/resource/Michael_Crichton>"); strings.push_back("<http://www.mpii.de/yago/resource/Malcolm_X>"); strings.push_back("<http://www.mpii.de/yago/resource/Michelangelo>"); strings.push_back("<http://www.mpii.de/yago/resource/Niels_Bohr>"); strings.push_back("<http://www.mpii.de/yago/resource/Nero>"); strings.push_back("<http://www.mpii.de/yago/resource/Ninon_de_l'Enclos>"); strings.push_back("<http://www.mpii.de/yago/resource/Norman_Hackerman>"); strings.push_back("<http://www.mpii.de/yago/resource/Temple,_Texas>"); strings.push_back("<http://www.mpii.de/yago/resource/Nikolay_Gerasimovich_Kuznetsov>"); strings.push_back("<http://www.mpii.de/yago/resource/Nikolai_Bukharin>"); strings.push_back("<http://www.mpii.de/yago/resource/Nicholas_II_of_Russia>"); strings.push_back("<http://www.mpii.de/yago/resource/Yekaterinburg>"); strings.push_back("<http://www.mpii.de/yago/resource/Ouida>"); strings.push_back("<http://www.mpii.de/yago/resource/Ole_R%C3%B8mer>"); strings.push_back("<http://www.mpii.de/yago/resource/Origen>"); strings.push_back("<http://www.mpii.de/yago/resource/Caesarea_Maritima>"); strings.push_back("<http://www.mpii.de/yago/resource/Olga_of_Kiev>"); strings.push_back("<http://www.mpii.de/yago/resource/Kiev>"); strings.push_back("<http://www.mpii.de/yago/resource/Philip_K._Dick>"); strings.push_back("<http://www.mpii.de/yago/resource/Santa_Ana,_California>"); strings.push_back("<http://www.mpii.de/yago/resource/Poul_Anderson>"); strings.push_back("<http://www.mpii.de/yago/resource/Orinda,_California>"); strings.push_back("<http://www.mpii.de/yago/resource/Petrarch>"); strings.push_back("<http://www.mpii.de/yago/resource/Arqu%C3%A0_Petrarca>"); strings.push_back("<http://www.mpii.de/yago/resource/Pope_Linus>"); strings.push_back("<http://www.mpii.de/yago/resource/Pope_Alexander_IV>"); strings.push_back("<http://www.mpii.de/yago/resource/Viterbo>"); strings.push_back("<http://www.mpii.de/yago/resource/Pope_Alexander_VIII>"); strings.push_back("<http://www.mpii.de/yago/resource/Pope_Alexander_II>"); strings.push_back("<http://www.mpii.de/yago/resource/Pope_Alexander_I>"); strings.push_back("<http://www.mpii.de/yago/resource/Pope_Alexander_VII>"); strings.push_back("<http://www.mpii.de/yago/resource/Pope_Agatho>"); strings.push_back("<http://www.mpii.de/yago/resource/Pope_Stephen_II>"); strings.push_back("<http://www.mpii.de/yago/resource/Pope_Adrian_III>"); strings.push_back("<http://www.mpii.de/yago/resource/Modena>"); strings.push_back("<http://www.mpii.de/yago/resource/Pope_Agapetus_II>"); strings.push_back("<http://www.mpii.de/yago/resource/Pope_Adrian_V>"); strings.push_back("<http://www.mpii.de/yago/resource/Pope_John_XXIII>"); strings.push_back("<http://www.mpii.de/yago/resource/Vatican_City>"); strings.push_back("<http://www.mpii.de/yago/resource/Pope_Adrian_IV>"); strings.push_back("<http://www.mpii.de/yago/resource/Anagni>"); strings.push_back("<http://www.mpii.de/yago/resource/Pope_John_XXI>"); strings.push_back("<http://www.mpii.de/yago/resource/Pope_Anastasius_III>"); strings.push_back("<http://www.mpii.de/yago/resource/Pope_Anastasius_IV>"); strings.push_back("<http://www.mpii.de/yago/resource/Pope_Anastasius_II>"); strings.push_back("<http://www.mpii.de/yago/resource/Pope_Adrian_VI>"); strings.push_back("<http://www.mpii.de/yago/resource/Pope_Alexander_VI>"); strings.push_back("<http://www.mpii.de/yago/resource/Pope_Honorius_II>"); strings.push_back("<http://www.mpii.de/yago/resource/Pope_Damasus_I>"); strings.push_back("<http://www.mpii.de/yago/resource/Pope_Honorius_III>"); strings.push_back("<http://www.mpii.de/yago/resource/Pope_Honorius_IV>"); strings.push_back("<http://www.mpii.de/yago/resource/Pope_Martin_V>"); strings.push_back("<http://www.mpii.de/yago/resource/Pope_Marinus_II>"); strings.push_back("<http://www.mpii.de/yago/resource/Pope_Miltiades>"); strings.push_back("<http://www.mpii.de/yago/resource/Pope_Marcellus_I>"); strings.push_back("<http://www.mpii.de/yago/resource/Pope_Marcellus_II>"); strings.push_back("<http://www.mpii.de/yago/resource/Pope_Benedict_I>"); strings.push_back("<http://www.mpii.de/yago/resource/Pope_Benedict_II>"); strings.push_back("<http://www.mpii.de/yago/resource/Pope_Benedict_V>"); strings.push_back("<http://www.mpii.de/yago/resource/Ptolemy>"); strings.push_back("<http://www.mpii.de/yago/resource/Pope_Benedict_VI>"); strings.push_back("<http://www.mpii.de/yago/resource/Pope_Benedict_VII>"); strings.push_back("<http://www.mpii.de/yago/resource/Pope_Benedict_VIII>"); strings.push_back("<http://www.mpii.de/yago/resource/Pope_Benedict_IX>"); strings.push_back("<http://www.mpii.de/yago/resource/Grottaferrata>"); strings.push_back("<http://www.mpii.de/yago/resource/Pope_Benedict_XIV>"); strings.push_back("<http://www.mpii.de/yago/resource/Pope_Benedict_XIII>"); strings.push_back("<http://www.mpii.de/yago/resource/Pope_Boniface_III>"); strings.push_back("<http://www.mpii.de/yago/resource/Pope_Boniface_IV>"); strings.push_back("<http://www.mpii.de/yago/resource/Pope_Boniface_IX>"); strings.push_back("<http://www.mpii.de/yago/resource/Pope_Pius_I>"); strings.push_back("<http://www.mpii.de/yago/resource/Pope_Pius_IV>"); strings.push_back("<http://www.mpii.de/yago/resource/Pope_Pius_III>"); strings.push_back("<http://www.mpii.de/yago/resource/Pope_Boniface_VIII>"); strings.push_back("<http://www.mpii.de/yago/resource/Pope_Pius_V>"); strings.push_back("<http://www.mpii.de/yago/resource/Pope_Pius_II>"); strings.push_back("<http://www.mpii.de/yago/resource/Ancona>"); strings.push_back("<http://www.mpii.de/yago/resource/Pope_Clement_III>"); strings.push_back("<http://www.mpii.de/yago/resource/Pope_Clement_IV>"); strings.push_back("<http://www.mpii.de/yago/resource/Pope_Clement_VIII>"); strings.push_back("<http://www.mpii.de/yago/resource/Pope_Clement_VII>"); strings.push_back("<http://www.mpii.de/yago/resource/Pope_Clement_IX>"); strings.push_back("<http://www.mpii.de/yago/resource/Pope_Clement_XI>"); strings.push_back("<http://www.mpii.de/yago/resource/Pope_Clement_X>"); strings.push_back("<http://www.mpii.de/yago/resource/Pope_Clement_XII>"); strings.push_back("<http://www.mpii.de/yago/resource/Pope_Clement_XIII>"); strings.push_back("<http://www.mpii.de/yago/resource/Pope_Celestine_II>"); strings.push_back("<http://www.mpii.de/yago/resource/Pope_Clement_XIV>"); strings.push_back("<http://www.mpii.de/yago/resource/Pope_Celestine_III>"); strings.push_back("<http://www.mpii.de/yago/resource/Pope_Celestine_IV>"); strings.push_back("<http://www.mpii.de/yago/resource/Pope_Celestine_V>"); strings.push_back("<http://www.mpii.de/yago/resource/Ferentino>"); strings.push_back("<http://www.mpii.de/yago/resource/Pope_Gregory_II>"); strings.push_back("<http://www.mpii.de/yago/resource/Pope_Gregory_V>"); strings.push_back("<http://www.mpii.de/yago/resource/Pope_Gregory_VIII>"); strings.push_back("<http://www.mpii.de/yago/resource/Pope_Gregory_X>"); strings.push_back("<http://www.mpii.de/yago/resource/Arezzo>"); strings.push_back("<http://www.mpii.de/yago/resource/Pope_Callixtus_III>"); strings.push_back("<http://www.mpii.de/yago/resource/Pope_Gregory_IX>"); strings.push_back("<http://www.mpii.de/yago/resource/Pope_Gregory_XI>"); strings.push_back("<http://www.mpii.de/yago/resource/Pope_Gregory_XIV>"); strings.push_back("<http://www.mpii.de/yago/resource/Pope_Gregory_XII>"); strings.push_back("<http://www.mpii.de/yago/resource/Recanati>"); strings.push_back("<http://www.mpii.de/yago/resource/Pope_Gregory_XIII>"); strings.push_back("<http://www.mpii.de/yago/resource/Paul_of_Tarsus>"); strings.push_back("<http://www.mpii.de/yago/resource/Pope_Sixtus_II>"); strings.push_back("<http://www.mpii.de/yago/resource/Pope_Sixtus_I>"); strings.push_back("<http://www.mpii.de/yago/resource/Pope_Sixtus_III>"); strings.push_back("<http://www.mpii.de/yago/resource/Pope_Urban_III>"); strings.push_back("<http://www.mpii.de/yago/resource/Pope_Urban_I>"); strings.push_back("<http://www.mpii.de/yago/resource/Pope_Urban_II>"); strings.push_back("<http://www.mpii.de/yago/resource/Pope_Urban_VII>"); strings.push_back("<http://www.mpii.de/yago/resource/Pope_Urban_VI>"); strings.push_back("<http://www.mpii.de/yago/resource/Pope_Urban_VIII>"); strings.push_back("<http://www.mpii.de/yago/resource/Pope_Stephen_I>"); strings.push_back("<http://www.mpii.de/yago/resource/Pope_Stephen_IV>"); strings.push_back("<http://www.mpii.de/yago/resource/Pope_Stephen_VIII>"); strings.push_back("<http://www.mpii.de/yago/resource/Pope_Sergius_IV>"); strings.push_back("<http://www.mpii.de/yago/resource/Pope_Sergius_III>"); strings.push_back("<http://www.mpii.de/yago/resource/Pope_Zachary>"); strings.push_back("<http://www.mpii.de/yago/resource/Pope_Victor_II>"); strings.push_back("<http://www.mpii.de/yago/resource/Pope_Victor_I>"); strings.push_back("<http://www.mpii.de/yago/resource/Plautus>"); strings.push_back("<http://www.mpii.de/yago/resource/Pope_Innocent_II>"); strings.push_back("<http://www.mpii.de/yago/resource/Pope_Innocent_V>"); strings.push_back("<http://www.mpii.de/yago/resource/Pope_Felix_I>"); strings.push_back("<http://www.mpii.de/yago/resource/Pope_Innocent_IV>"); strings.push_back("<http://www.mpii.de/yago/resource/Pierre_Curie>"); strings.push_back("<http://www.mpii.de/yago/resource/Pope_Anterus>"); strings.push_back("<http://www.mpii.de/yago/resource/Pope_Theodore_II>"); strings.push_back("<http://www.mpii.de/yago/resource/Plutarch>"); strings.push_back("<http://www.mpii.de/yago/resource/Delphi>"); strings.push_back("<http://www.mpii.de/yago/resource/Peter_Sellers>"); strings.push_back("<http://www.mpii.de/yago/resource/Pope_Formosus>"); strings.push_back("<http://www.mpii.de/yago/resource/Pope_Sylvester_II>"); strings.push_back("<http://www.mpii.de/yago/resource/Pope_Innocent_VII>"); strings.push_back("<http://www.mpii.de/yago/resource/Pope_Innocent_VIII>"); strings.push_back("<http://www.mpii.de/yago/resource/Pope_Innocent_IX>"); strings.push_back("<http://www.mpii.de/yago/resource/Pope_Innocent_X>"); strings.push_back("<http://www.mpii.de/yago/resource/Pope_Innocent_XI>"); strings.push_back("<http://www.mpii.de/yago/resource/Pope_Innocent_XII>"); strings.push_back("<http://www.mpii.de/yago/resource/Pope_Innocent_XIII>"); strings.push_back("<http://www.mpii.de/yago/resource/Pope_Julius_I>"); strings.push_back("<http://www.mpii.de/yago/resource/Pope_Eugene_I>"); strings.push_back("<http://www.mpii.de/yago/resource/Pope_Julius_III>"); strings.push_back("<http://www.mpii.de/yago/resource/Pope_Eugene_III>"); strings.push_back("<http://www.mpii.de/yago/resource/Tivoli,_Italy>"); strings.push_back("<http://www.mpii.de/yago/resource/Pope_Julius_II>"); strings.push_back("<http://www.mpii.de/yago/resource/Paul_Dirac>"); strings.push_back("<http://www.mpii.de/yago/resource/Tallahassee,_Florida>"); strings.push_back("<http://www.mpii.de/yago/resource/Pope_Sixtus_IV>"); strings.push_back("<http://www.mpii.de/yago/resource/Polycarp>"); strings.push_back("<http://www.mpii.de/yago/resource/Smyrna>"); strings.push_back("<http://www.mpii.de/yago/resource/Peter_Stuyvesant>"); strings.push_back("<http://www.mpii.de/yago/resource/Pierre_de_Coubertin>"); strings.push_back("<http://www.mpii.de/yago/resource/Patricia_Soltysik>"); strings.push_back("<http://www.mpii.de/yago/resource/Ren%C3%A9_Descartes>"); strings.push_back("<http://www.mpii.de/yago/resource/Stockholm>"); strings.push_back("<http://www.mpii.de/yago/resource/Richard_Feynman>"); strings.push_back("<http://www.mpii.de/yago/resource/Robert_Byrd>"); strings.push_back("<http://www.mpii.de/yago/resource/Falls_Church,_Virginia>"); strings.push_back("<http://www.mpii.de/yago/resource/Robert_Musil>"); strings.push_back("<http://www.mpii.de/yago/resource/Roy_Chapman_Andrews>"); strings.push_back("<http://www.mpii.de/yago/resource/Carmel-by-the-Sea,_California>"); strings.push_back("<http://www.mpii.de/yago/resource/Robert_E._Lee>"); strings.push_back("<http://www.mpii.de/yago/resource/Lexington,_Virginia>"); strings.push_back("<http://www.mpii.de/yago/resource/Robert_Menzies>"); strings.push_back("<http://www.mpii.de/yago/resource/Melbourne>"); strings.push_back("<http://www.mpii.de/yago/resource/Robert_Bunsen>"); strings.push_back("<http://www.mpii.de/yago/resource/Roberto_Clemente>"); strings.push_back("<http://www.mpii.de/yago/resource/San_Juan,_Puerto_Rico>"); strings.push_back("<http://www.mpii.de/yago/resource/Regiomontanus>"); strings.push_back("<http://www.mpii.de/yago/resource/Robert_Frost>"); strings.push_back("<http://www.mpii.de/yago/resource/Reinhard_Heydrich>"); strings.push_back("<http://www.mpii.de/yago/resource/Rudolf_II,_Holy_Roman_Emperor>"); strings.push_back("<http://www.mpii.de/yago/resource/Rajiv_Gandhi>"); strings.push_back("<http://www.mpii.de/yago/resource/Sriperumbudur>"); strings.push_back("<http://www.mpii.de/yago/resource/Robert_Fulton>"); strings.push_back("<http://www.mpii.de/yago/resource/Ralph_Abercromby>"); strings.push_back("<http://www.mpii.de/yago/resource/Robert_Jordan>"); strings.push_back("<http://www.mpii.de/yago/resource/Rainer_Maria_Rilke>"); strings.push_back("<http://www.mpii.de/yago/resource/Montreux>"); strings.push_back("<http://www.mpii.de/yago/resource/Rolf_Nevanlinna>"); strings.push_back("<http://www.mpii.de/yago/resource/Ruth_Benedict>"); strings.push_back("<http://www.mpii.de/yago/resource/Ragnar_Frisch>"); strings.push_back("<http://www.mpii.de/yago/resource/Robert_Moog>"); strings.push_back("<http://www.mpii.de/yago/resource/Asheville,_North_Carolina>"); strings.push_back("<http://www.mpii.de/yago/resource/Stendhal>"); strings.push_back("<http://www.mpii.de/yago/resource/Stanis%C5%82aw_Lem>"); strings.push_back("<http://www.mpii.de/yago/resource/Robert_Siodmak>"); strings.push_back("<http://www.mpii.de/yago/resource/Ascona>"); strings.push_back("<http://www.mpii.de/yago/resource/Samuel_Morse>"); strings.push_back("<http://www.mpii.de/yago/resource/Saladin>"); strings.push_back("<http://www.mpii.de/yago/resource/Damascus>"); strings.push_back("<http://www.mpii.de/yago/resource/Soad_Hosny>"); strings.push_back("<http://www.mpii.de/yago/resource/Sam_Peckinpah>"); strings.push_back("<http://www.mpii.de/yago/resource/Inglewood,_California>"); strings.push_back("<http://www.mpii.de/yago/resource/Samuel_Beckett>"); strings.push_back("<http://www.mpii.de/yago/resource/Susan_B._Anthony>"); strings.push_back("<http://www.mpii.de/yago/resource/Rochester,_New_York>"); strings.push_back("<http://www.mpii.de/yago/resource/Saint_Boniface>"); strings.push_back("<http://www.mpii.de/yago/resource/Dokkum>"); strings.push_back("<http://www.mpii.de/yago/resource/Nicolas_L%C3%A9onard_Sadi_Carnot>"); strings.push_back("<http://www.mpii.de/yago/resource/Steve_Biko>"); strings.push_back("<http://www.mpii.de/yago/resource/Pretoria>"); strings.push_back("<http://www.mpii.de/yago/resource/Saint_Stephen>"); strings.push_back("<http://www.mpii.de/yago/resource/Solomon>"); strings.push_back("<http://www.mpii.de/yago/resource/Soong_May-ling>"); strings.push_back("<http://www.mpii.de/yago/resource/Saint_Peter>"); strings.push_back("<http://www.mpii.de/yago/resource/Shah_Jahan>"); strings.push_back("<http://www.mpii.de/yago/resource/Sofonisba_Anguissola>"); strings.push_back("<http://www.mpii.de/yago/resource/Palermo>"); strings.push_back("<http://www.mpii.de/yago/resource/Saint_David>"); strings.push_back("<http://www.mpii.de/yago/resource/St_David's>"); strings.push_back("<http://www.mpii.de/yago/resource/Saint_Andrew>"); strings.push_back("<http://www.mpii.de/yago/resource/Patras>"); strings.push_back("<http://www.mpii.de/yago/resource/Saint_George>"); strings.push_back("<http://www.mpii.de/yago/resource/Seymour_Cray>"); strings.push_back("<http://www.mpii.de/yago/resource/Colorado_Springs,_Colorado>"); strings.push_back("<http://www.mpii.de/yago/resource/Sigrid_Undset>"); strings.push_back("<http://www.mpii.de/yago/resource/Lillehammer>"); strings.push_back("<http://www.mpii.de/yago/resource/Stanley_Elkin>"); strings.push_back("<http://www.mpii.de/yago/resource/St._Louis,_Missouri>"); strings.push_back("<http://www.mpii.de/yago/resource/Sonja_Henie>"); strings.push_back("<http://www.mpii.de/yago/resource/Shmuel_Yosef_Agnon>"); strings.push_back("<http://www.mpii.de/yago/resource/Stefan_Banach>"); strings.push_back("<http://www.mpii.de/yago/resource/Lviv>"); strings.push_back("<http://www.mpii.de/yago/resource/Thomas_Reid>"); strings.push_back("<http://www.mpii.de/yago/resource/Glasgow>"); strings.push_back("<http://www.mpii.de/yago/resource/Saddam_Hussein>"); strings.push_back("<http://www.mpii.de/yago/resource/Kadhimiya>"); strings.push_back("<http://www.mpii.de/yago/resource/Tycho_Brahe>"); strings.push_back("<http://www.mpii.de/yago/resource/Thomas_Mann>"); strings.push_back("<http://www.mpii.de/yago/resource/Thomas_Jefferson>"); strings.push_back("<http://www.mpii.de/yago/resource/Charlottesville,_Virginia>"); strings.push_back("<http://www.mpii.de/yago/resource/T._S._Eliot>"); strings.push_back("<http://www.mpii.de/yago/resource/Theodor_W._Adorno>"); strings.push_back("<http://www.mpii.de/yago/resource/Visp>"); strings.push_back("<http://www.mpii.de/yago/resource/Thomas_Gray>"); strings.push_back("<http://www.mpii.de/yago/resource/Thomas_Nast>"); strings.push_back("<http://www.mpii.de/yago/resource/Guayaquil>"); strings.push_back("<http://www.mpii.de/yago/resource/Thomas_Paine>"); strings.push_back("<http://www.mpii.de/yago/resource/Thomas_Brackett_Reed>"); strings.push_back("<http://www.mpii.de/yago/resource/Saint_Timothy>"); strings.push_back("<http://www.mpii.de/yago/resource/Masaccio>"); strings.push_back("<http://www.mpii.de/yago/resource/Thomas_Wolsey>"); strings.push_back("<http://www.mpii.de/yago/resource/Leicester>"); strings.push_back("<http://www.mpii.de/yago/resource/Themistocles>"); strings.push_back("<http://www.mpii.de/yago/resource/Magnesia_on_the_Maeander>"); strings.push_back("<http://www.mpii.de/yago/resource/Thomas_Mifflin>"); strings.push_back("<http://www.mpii.de/yago/resource/Lancaster,_Pennsylvania>"); strings.push_back("<http://www.mpii.de/yago/resource/Timothy_Leary>"); strings.push_back("<http://www.mpii.de/yago/resource/T._H._White>"); strings.push_back("<http://www.mpii.de/yago/resource/Piraeus>"); strings.push_back("<http://www.mpii.de/yago/resource/Thomas_McKean>"); strings.push_back("<http://www.mpii.de/yago/resource/Thomas_J._Watson>"); strings.push_back("<http://www.mpii.de/yago/resource/Thomas_R._Marshall>"); strings.push_back("<http://www.mpii.de/yago/resource/Thomas_Hunt_Morgan>"); strings.push_back("<http://www.mpii.de/yago/resource/Pasadena,_California>"); strings.push_back("<http://www.mpii.de/yago/resource/Timothy_McVeigh>"); strings.push_back("<http://www.mpii.de/yago/resource/Terre_Haute,_Indiana>"); strings.push_back("<http://www.mpii.de/yago/resource/Urho_Kekkonen>"); strings.push_back("<http://www.mpii.de/yago/resource/Vidkun_Quisling>"); strings.push_back("<http://www.mpii.de/yago/resource/Vladimir_Nabokov>"); strings.push_back("<http://www.mpii.de/yago/resource/Vladimir_Arnold>"); strings.push_back("<http://www.mpii.de/yago/resource/Andreas_Vesalius>"); strings.push_back("<http://www.mpii.de/yago/resource/Zakynthos>"); strings.push_back("<http://www.mpii.de/yago/resource/Vladimir_Vernadsky>"); strings.push_back("<http://www.mpii.de/yago/resource/Vladimir_Markovnikov>"); strings.push_back("<http://www.mpii.de/yago/resource/Victor_of_Aveyron>"); strings.push_back("<http://www.mpii.de/yago/resource/Vivien_Leigh>"); strings.push_back("<http://www.mpii.de/yago/resource/Walt_Disney>"); strings.push_back("<http://www.mpii.de/yago/resource/W._Somerset_Maugham>"); strings.push_back("<http://www.mpii.de/yago/resource/Nice>"); strings.push_back("<http://www.mpii.de/yago/resource/W%C5%82adys%C5%82aw_Reymont>"); strings.push_back("<http://www.mpii.de/yago/resource/Werner_Heisenberg>"); strings.push_back("<http://www.mpii.de/yago/resource/William_Henry_Harrison>"); strings.push_back("<http://www.mpii.de/yago/resource/William_Randolph_Hearst>"); strings.push_back("<http://www.mpii.de/yago/resource/William_Saroyan>"); strings.push_back("<http://www.mpii.de/yago/resource/Fresno,_California>"); strings.push_back("<http://www.mpii.de/yago/resource/William_McKinley>"); strings.push_back("<http://www.mpii.de/yago/resource/Buffalo,_New_York>"); strings.push_back("<http://www.mpii.de/yago/resource/William_Howard_Taft>"); strings.push_back("<http://www.mpii.de/yago/resource/William_of_Ockham>"); strings.push_back("<http://www.mpii.de/yago/resource/William_S._Burroughs>"); strings.push_back("<http://www.mpii.de/yago/resource/Lawrence,_Kansas>"); strings.push_back("<http://www.mpii.de/yago/resource/Walter_Gropius>"); strings.push_back("<http://www.mpii.de/yago/resource/Woodrow_Wilson>"); strings.push_back("<http://www.mpii.de/yago/resource/Walt_Whitman>"); strings.push_back("<http://www.mpii.de/yago/resource/Camden,_New_Jersey>"); strings.push_back("<http://www.mpii.de/yago/resource/William_I_of_Scotland>"); strings.push_back("<http://www.mpii.de/yago/resource/William_Bligh>"); strings.push_back("<http://www.mpii.de/yago/resource/Wernher_von_Braun>"); strings.push_back("<http://www.mpii.de/yago/resource/Wolfgang_Pauli>"); strings.push_back("<http://www.mpii.de/yago/resource/William_O'Dwyer>"); strings.push_back("<http://www.mpii.de/yago/resource/William_Congreve>"); strings.push_back("<http://www.mpii.de/yago/resource/Wilhelm_Ostwald>"); strings.push_back("<http://www.mpii.de/yago/resource/Wendell_Willkie>"); strings.push_back("<http://www.mpii.de/yago/resource/Yevgeny_Zamyatin>"); strings.push_back("<http://www.mpii.de/yago/resource/Yasser_Arafat>"); strings.push_back("<http://www.mpii.de/yago/resource/Zora_Neale_Hurston>"); strings.push_back("<http://www.mpii.de/yago/resource/Fort_Pierce,_Florida>"); strings.push_back("<http://www.mpii.de/yago/resource/Robert_Anton_Wilson>"); strings.push_back("<http://www.mpii.de/yago/resource/Capitola,_California>"); strings.push_back("<http://www.mpii.de/yago/resource/Svante_Arrhenius>"); strings.push_back("<http://www.mpii.de/yago/resource/George_Marshall>"); strings.push_back("<http://www.mpii.de/yago/resource/Pope_Gregory_I>"); strings.push_back("<http://www.mpii.de/yago/resource/Moustapha_Akkad>"); strings.push_back("<http://www.mpii.de/yago/resource/Amman>"); strings.push_back("<http://www.mpii.de/yago/resource/Giuseppe_Mazzini>"); strings.push_back("<http://www.mpii.de/yago/resource/Pericles>"); strings.push_back("<http://www.mpii.de/yago/resource/Pope_Gregory_VII>"); strings.push_back("<http://www.mpii.de/yago/resource/Salerno>"); strings.push_back("<http://www.mpii.de/yago/resource/Odoacer>"); strings.push_back("<http://www.mpii.de/yago/resource/Peter_Debye>"); strings.push_back("<http://www.mpii.de/yago/resource/Ithaca,_New_York>"); strings.push_back("<http://www.mpii.de/yago/resource/Zeno_of_Citium>"); strings.push_back("<http://www.mpii.de/yago/resource/Pope_Leo_VIII>"); strings.push_back("<http://www.mpii.de/yago/resource/Larry_Gelbart>"); strings.push_back("<http://www.mpii.de/yago/resource/Robert_Watson-Watt>"); strings.push_back("<http://www.mpii.de/yago/resource/Inverness>"); strings.push_back("<http://www.mpii.de/yago/resource/Thomas_Becket>"); strings.push_back("<http://www.mpii.de/yago/resource/Chrysippus>"); strings.push_back("<http://www.mpii.de/yago/resource/William_I_of_the_Netherlands>"); strings.push_back("<http://www.mpii.de/yago/resource/Booker_T._Washington>"); strings.push_back("<http://www.mpii.de/yago/resource/Josiah_Willard_Gibbs>"); strings.push_back("<http://www.mpii.de/yago/resource/Tristan_Tzara>"); strings.push_back("<http://www.mpii.de/yago/resource/Bruce_Lee>"); strings.push_back("<http://www.mpii.de/yago/resource/Hong_Kong>"); strings.push_back("<http://www.mpii.de/yago/resource/Harriet_Tubman>"); strings.push_back("<http://www.mpii.de/yago/resource/Auburn,_New_York>"); strings.push_back("<http://www.mpii.de/yago/resource/Hildegard_Knef>"); strings.push_back("<http://www.mpii.de/yago/resource/Pope_Leo_II>"); strings.push_back("<http://www.mpii.de/yago/resource/Pope_Leo_V>"); strings.push_back("<http://www.mpii.de/yago/resource/Pope_Leo_VI>"); strings.push_back("<http://www.mpii.de/yago/resource/Alfred_Kinsey>"); strings.push_back("<http://www.mpii.de/yago/resource/Bloomington,_Indiana>"); strings.push_back("<http://www.mpii.de/yago/resource/Roger_Zelazny>"); strings.push_back("<http://www.mpii.de/yago/resource/Santa_Fe,_New_Mexico>"); strings.push_back("<http://www.mpii.de/yago/resource/Felix_Dzerzhinsky>"); strings.push_back("<http://www.mpii.de/yago/resource/Pope_Leo_XI>"); strings.push_back("<http://www.mpii.de/yago/resource/August_Ferdinand_M%C3%B6bius>"); strings.push_back("<http://www.mpii.de/yago/resource/Pope_Leo_X>"); strings.push_back("<http://www.mpii.de/yago/resource/Gregory_of_Nyssa>"); strings.push_back("<http://www.mpii.de/yago/resource/Nev%C5%9Fehir>"); strings.push_back("<http://www.mpii.de/yago/resource/Max_Perutz>"); strings.push_back("<http://www.mpii.de/yago/resource/%C3%89mile_Durkheim>"); strings.push_back("<http://www.mpii.de/yago/resource/Oskar_Schindler>"); strings.push_back("<http://www.mpii.de/yago/resource/Hildesheim>"); strings.push_back("<http://www.mpii.de/yago/resource/Charles_XIV_John_of_Sweden>"); strings.push_back("<http://www.mpii.de/yago/resource/Oscar_I_of_Sweden>"); strings.push_back("<http://www.mpii.de/yago/resource/Louis_I_of_Hungary>"); strings.push_back("<http://www.mpii.de/yago/resource/Trnava>"); strings.push_back("<http://www.mpii.de/yago/resource/Georgy_Zhukov>"); strings.push_back("<http://www.mpii.de/yago/resource/Sigismund,_Holy_Roman_Emperor>"); strings.push_back("<http://www.mpii.de/yago/resource/Znojmo>"); strings.push_back("<http://www.mpii.de/yago/resource/Charles_IV,_Holy_Roman_Emperor>"); strings.push_back("<http://www.mpii.de/yago/resource/John_the_Apostle>"); strings.push_back("<http://www.mpii.de/yago/resource/Cary_Grant>"); strings.push_back("<http://www.mpii.de/yago/resource/Davenport,_Iowa>"); strings.push_back("<http://www.mpii.de/yago/resource/Boles%C5%82aw_I_Chrobry>"); strings.push_back("<http://www.mpii.de/yago/resource/Maximilian_I,_Holy_Roman_Emperor>"); strings.push_back("<http://www.mpii.de/yago/resource/Wels>"); strings.push_back("<http://www.mpii.de/yago/resource/Mary_Martin>"); strings.push_back("<http://www.mpii.de/yago/resource/Rancho_Mirage,_California>"); strings.push_back("<http://www.mpii.de/yago/resource/Franco_Maria_Malfatti>"); strings.push_back("<http://www.mpii.de/yago/resource/Pope_Lando>"); strings.push_back("<http://www.mpii.de/yago/resource/Adam_Gottlob_Oehlenschl%C3%A4ger>"); strings.push_back("<http://www.mpii.de/yago/resource/Lillian_Moller_Gilbreth>"); strings.push_back("<http://www.mpii.de/yago/resource/Mikhail_Bulgakov>"); strings.push_back("<http://www.mpii.de/yago/resource/Joseph_Banks>"); strings.push_back("<http://www.mpii.de/yago/resource/Myles_Coverdale>"); strings.push_back("<http://www.mpii.de/yago/resource/Roger_Williams_(theologian)>"); strings.push_back("<http://www.mpii.de/yago/resource/John_Philip_Sousa>"); strings.push_back("<http://www.mpii.de/yago/resource/Reading,_Pennsylvania>"); strings.push_back("<http://www.mpii.de/yago/resource/Sigismund_II_Augustus>"); strings.push_back("<http://www.mpii.de/yago/resource/Knyszyn>"); strings.push_back("<http://www.mpii.de/yago/resource/Charles_I_of_Naples>"); strings.push_back("<http://www.mpii.de/yago/resource/Foggia>"); strings.push_back("<http://www.mpii.de/yago/resource/William_Rowan_Hamilton>"); strings.push_back("<http://www.mpii.de/yago/resource/Charles_XV_of_Sweden>"); strings.push_back("<http://www.mpii.de/yago/resource/Malm%C3%B6>"); strings.push_back("<http://www.mpii.de/yago/resource/Richard_J._Daley>"); strings.push_back("<http://www.mpii.de/yago/resource/Edward_the_Confessor>"); strings.push_back("<http://www.mpii.de/yago/resource/Joseph_Medill>"); strings.push_back("<http://www.mpii.de/yago/resource/Carter_Harrison,_Jr.>"); strings.push_back("<http://www.mpii.de/yago/resource/John_Wentworth_(Illinois)>"); strings.push_back("<http://www.mpii.de/yago/resource/Carter_Harrison,_Sr.>"); strings.push_back("<http://www.mpii.de/yago/resource/William_Hale_Thompson>"); strings.push_back("<http://www.mpii.de/yago/resource/Harold_Washington>"); strings.push_back("<http://www.mpii.de/yago/resource/Howard_Florey,_Baron_Florey>"); strings.push_back("<http://www.mpii.de/yago/resource/Vladimir_I_of_Kiev>"); strings.push_back("<http://www.mpii.de/yago/resource/Thomas_Joannes_Stieltjes>"); strings.push_back("<http://www.mpii.de/yago/resource/Toulouse>"); strings.push_back("<http://www.mpii.de/yago/resource/William_Jennings_Bryan>"); strings.push_back("<http://www.mpii.de/yago/resource/Dayton,_Tennessee>"); strings.push_back("<http://www.mpii.de/yago/resource/Alexander_Hamilton>"); strings.push_back("<http://www.mpii.de/yago/resource/Stanislaw_Ulam>"); strings.push_back("<http://www.mpii.de/yago/resource/John_McLoughlin>"); strings.push_back("<http://www.mpii.de/yago/resource/Oregon_City,_Oregon>"); strings.push_back("<http://www.mpii.de/yago/resource/Ludwig_Erhard>"); strings.push_back("<http://www.mpii.de/yago/resource/Wilhelm_Grimm>"); strings.push_back("<http://www.mpii.de/yago/resource/Charles_%C3%89mile_Picard>"); strings.push_back("<http://www.mpii.de/yago/resource/Amedeo_Avogadro>"); strings.push_back("<http://www.mpii.de/yago/resource/Turin>"); strings.push_back("<http://www.mpii.de/yago/resource/John_Dillinger>"); strings.push_back("<http://www.mpii.de/yago/resource/Carl_Jung>"); strings.push_back("<http://www.mpii.de/yago/resource/Charles_M._Schulz>"); strings.push_back("<http://www.mpii.de/yago/resource/Santa_Rosa,_California>"); strings.push_back("<http://www.mpii.de/yago/resource/Ted_Demme>"); strings.push_back("<http://www.mpii.de/yago/resource/Purushottam_Laxman_Deshpande>"); strings.push_back("<http://www.mpii.de/yago/resource/Pune>"); strings.push_back("<http://www.mpii.de/yago/resource/Sigismund_I_the_Old>"); strings.push_back("<http://www.mpii.de/yago/resource/W%C5%82adys%C5%82aw_III_of_Poland>"); strings.push_back("<http://www.mpii.de/yago/resource/Varna>"); strings.push_back("<http://www.mpii.de/yago/resource/%C3%89amon_de_Valera>"); strings.push_back("<http://www.mpii.de/yago/resource/Jogaila>"); strings.push_back("<http://www.mpii.de/yago/resource/Horodok,_Lviv_Oblast>"); strings.push_back("<http://www.mpii.de/yago/resource/Grace_Kelly>"); strings.push_back("<http://www.mpii.de/yago/resource/Murasaki_Shikibu>"); strings.push_back("<http://www.mpii.de/yago/resource/Kyoto>"); strings.push_back("<http://www.mpii.de/yago/resource/Frank_Whittle>"); strings.push_back("<http://www.mpii.de/yago/resource/Columbia,_Maryland>"); strings.push_back("<http://www.mpii.de/yago/resource/Hubert_Humphrey>"); strings.push_back("<http://www.mpii.de/yago/resource/Waverly,_Minnesota>"); strings.push_back("<http://www.mpii.de/yago/resource/Alexander_Dub%C4%8Dek>"); strings.push_back("<http://www.mpii.de/yago/resource/Elia_Kazan>"); strings.push_back("<http://www.mpii.de/yago/resource/O._Henry>"); strings.push_back("<http://www.mpii.de/yago/resource/Richard_Wright_(author)>"); strings.push_back("<http://www.mpii.de/yago/resource/Pope_Soter>"); strings.push_back("<http://www.mpii.de/yago/resource/Nikita_Khrushchev>"); strings.push_back("<http://www.mpii.de/yago/resource/Erich_von_Drygalski>"); strings.push_back("<http://www.mpii.de/yago/resource/Elizabeth_Cady_Stanton>"); strings.push_back("<http://www.mpii.de/yago/resource/Melisende_of_Jerusalem>"); strings.push_back("<http://www.mpii.de/yago/resource/Georg_Forster>"); strings.push_back("<http://www.mpii.de/yago/resource/Johann_Friedrich_Struensee>"); strings.push_back("<http://www.mpii.de/yago/resource/Vittorio_Gassman>"); strings.push_back("<http://www.mpii.de/yago/resource/Philip_Larkin>"); strings.push_back("<http://www.mpii.de/yago/resource/Kingston_upon_Hull>"); strings.push_back("<http://www.mpii.de/yago/resource/Lew_Wallace>"); strings.push_back("<http://www.mpii.de/yago/resource/Crawfordsville,_Indiana>"); strings.push_back("<http://www.mpii.de/yago/resource/John_Dalton>"); strings.push_back("<http://www.mpii.de/yago/resource/Manchester>"); strings.push_back("<http://www.mpii.de/yago/resource/Catherine_I_of_Russia>"); strings.push_back("<http://www.mpii.de/yago/resource/Wilhelm_Johannsen>"); strings.push_back("<http://www.mpii.de/yago/resource/Catherine_II_of_Russia>"); strings.push_back("<http://www.mpii.de/yago/resource/Allen_G._Thurman>"); strings.push_back("<http://www.mpii.de/yago/resource/Columbus,_Ohio>"); strings.push_back("<http://www.mpii.de/yago/resource/Phoolan_Devi>"); strings.push_back("<http://www.mpii.de/yago/resource/Raphael>"); strings.push_back("<http://www.mpii.de/yago/resource/Tennessee_Williams>"); strings.push_back("<http://www.mpii.de/yago/resource/Pope_Leo_I>"); strings.push_back("<http://www.mpii.de/yago/resource/Mel_Blanc>"); strings.push_back("<http://www.mpii.de/yago/resource/Frederick_Theodore_Frelinghuysen>"); strings.push_back("<http://www.mpii.de/yago/resource/Newark,_New_Jersey>"); strings.push_back("<http://www.mpii.de/yago/resource/Pliny_the_Elder>"); strings.push_back("<http://www.mpii.de/yago/resource/Stabiae>"); strings.push_back("<http://www.mpii.de/yago/resource/Pope_Nicholas_V>"); strings.push_back("<http://www.mpii.de/yago/resource/%C3%89mile_Zola>"); strings.push_back("<http://www.mpii.de/yago/resource/Pope_Nicholas_III>"); strings.push_back("<http://www.mpii.de/yago/resource/L._Sprague_de_Camp>"); strings.push_back("<http://www.mpii.de/yago/resource/Plano,_Texas>"); strings.push_back("<http://www.mpii.de/yago/resource/Giacomo_Leopardi>"); strings.push_back("<http://www.mpii.de/yago/resource/Pope_Paschal_I>"); strings.push_back("<http://www.mpii.de/yago/resource/Pope_Paschal_II>"); strings.push_back("<http://www.mpii.de/yago/resource/Pope_Hilarius>"); strings.push_back("<http://www.mpii.de/yago/resource/Victor_McLaglen>"); strings.push_back("<http://www.mpii.de/yago/resource/Newport_Beach,_California>"); strings.push_back("<http://www.mpii.de/yago/resource/Pope_Lucius_III>"); strings.push_back("<http://www.mpii.de/yago/resource/Pope_Lucius_I>"); strings.push_back("<http://www.mpii.de/yago/resource/Winfield_Scott_Stratton>"); strings.push_back("<http://www.mpii.de/yago/resource/David_Foster_Wallace>"); strings.push_back("<http://www.mpii.de/yago/resource/Claremont,_California>"); strings.push_back("<http://www.mpii.de/yago/resource/Bal_Gangadhar_Tilak>"); strings.push_back("<http://www.mpii.de/yago/resource/Sarvepalli_Radhakrishnan>"); strings.push_back("<http://www.mpii.de/yago/resource/Chennai>"); strings.push_back("<http://www.mpii.de/yago/resource/A._C._Bhaktivedanta_Swami_Prabhupada>"); strings.push_back("<http://www.mpii.de/yago/resource/Vrindavan>"); strings.push_back("<http://www.mpii.de/yago/resource/Janet_Gaynor>"); strings.push_back("<http://www.mpii.de/yago/resource/Spencer_Tracy>"); strings.push_back("<http://www.mpii.de/yago/resource/Pim_Fortuyn>"); strings.push_back("<http://www.mpii.de/yago/resource/Hilversum>"); strings.push_back("<http://www.mpii.de/yago/resource/Charles_Ponzi>"); strings.push_back("<http://www.mpii.de/yago/resource/Rio_de_Janeiro>"); strings.push_back("<http://www.mpii.de/yago/resource/Alexander_John_Cuza>"); strings.push_back("<http://www.mpii.de/yago/resource/Pope_Evaristus>"); strings.push_back("<http://www.mpii.de/yago/resource/Pope_Nicholas_IV>"); strings.push_back("<http://www.mpii.de/yago/resource/Pope_Lucius_II>"); strings.push_back("<http://www.mpii.de/yago/resource/Frans_Hals>"); strings.push_back("<http://www.mpii.de/yago/resource/Haarlem>"); strings.push_back("<http://www.mpii.de/yago/resource/Bill_Hicks>"); strings.push_back("<http://www.mpii.de/yago/resource/Little_Rock,_Arkansas>"); strings.push_back("<http://www.mpii.de/yago/resource/Lev_Kamenev>"); strings.push_back("<http://www.mpii.de/yago/resource/Dudley_Moore>"); strings.push_back("<http://www.mpii.de/yago/resource/Plainfield,_New_Jersey>"); strings.push_back("<http://www.mpii.de/yago/resource/Jan_van_Eyck>"); strings.push_back("<http://www.mpii.de/yago/resource/Bruges>"); strings.push_back("<http://www.mpii.de/yago/resource/Nicholas_I_of_Russia>"); strings.push_back("<http://www.mpii.de/yago/resource/John_Sherman_(politician)>"); strings.push_back("<http://www.mpii.de/yago/resource/Samuel_of_Bulgaria>"); strings.push_back("<http://www.mpii.de/yago/resource/Prilep>"); strings.push_back("<http://www.mpii.de/yago/resource/Daniel_Bernoulli>"); strings.push_back("<http://www.mpii.de/yago/resource/Jesse_Owens>"); strings.push_back("<http://www.mpii.de/yago/resource/Demosthenes>"); strings.push_back("<http://www.mpii.de/yago/resource/Poros>"); strings.push_back("<http://www.mpii.de/yago/resource/William_Tecumseh_Sherman>"); strings.push_back("<http://www.mpii.de/yago/resource/Pope_Anicetus>"); strings.push_back("<http://www.mpii.de/yago/resource/Marcus_Licinius_Crassus>"); strings.push_back("<http://www.mpii.de/yago/resource/Harran>"); strings.push_back("<http://www.mpii.de/yago/resource/Henry_John_Stephen_Smith>"); strings.push_back("<http://www.mpii.de/yago/resource/Pope_Paul_II>"); strings.push_back("<http://www.mpii.de/yago/resource/Edgar_the_Peaceful>"); strings.push_back("<http://www.mpii.de/yago/resource/Winchester>"); strings.push_back("<http://www.mpii.de/yago/resource/Gabriele_d'Annunzio>"); strings.push_back("<http://www.mpii.de/yago/resource/Gardone_Riviera>"); strings.push_back("<http://www.mpii.de/yago/resource/Henry_Clay>"); strings.push_back("<http://www.mpii.de/yago/resource/Michel_Foucault>"); strings.push_back("<http://www.mpii.de/yago/resource/Pope_Paul_III>"); strings.push_back("<http://www.mpii.de/yago/resource/Jean_Auguste_Dominique_Ingres>"); strings.push_back("<http://www.mpii.de/yago/resource/Allan_Pinkerton>"); strings.push_back("<http://www.mpii.de/yago/resource/R._A._Lafferty>"); strings.push_back("<http://www.mpii.de/yago/resource/Broken_Arrow,_Oklahoma>"); strings.push_back("<http://www.mpii.de/yago/resource/Torquato_Tasso>"); strings.push_back("<http://www.mpii.de/yago/resource/Ambrosius_Holbein>"); strings.push_back("<http://www.mpii.de/yago/resource/Andrew_Marvell>"); strings.push_back("<http://www.mpii.de/yago/resource/Frederick_Augustus_I_of_Saxony>"); strings.push_back("<http://www.mpii.de/yago/resource/Frederick_Christian,_Elector_of_Saxony>"); strings.push_back("<http://www.mpii.de/yago/resource/Victor_Lustig>"); strings.push_back("<http://www.mpii.de/yago/resource/Springfield,_Missouri>"); strings.push_back("<http://www.mpii.de/yago/resource/Caratacus>"); strings.push_back("<http://www.mpii.de/yago/resource/Henri_Poincar%C3%A9>"); strings.push_back("<http://www.mpii.de/yago/resource/Caroline_of_Brunswick>"); strings.push_back("<http://www.mpii.de/yago/resource/Robert_Andrews_Millikan>"); strings.push_back("<http://www.mpii.de/yago/resource/Pope_Eugene_IV>"); strings.push_back("<http://www.mpii.de/yago/resource/Georg_Ohm>"); strings.push_back("<http://www.mpii.de/yago/resource/Pope_Anacletus>"); strings.push_back("<http://www.mpii.de/yago/resource/Trofim_Lysenko>"); strings.push_back("<http://www.mpii.de/yago/resource/Douglas_MacArthur>"); strings.push_back("<http://www.mpii.de/yago/resource/Nellie_Tayloe_Ross>"); strings.push_back("<http://www.mpii.de/yago/resource/Pope_Eleuterus>"); strings.push_back("<http://www.mpii.de/yago/resource/Tove_Jansson>"); strings.push_back("<http://www.mpii.de/yago/resource/Henry_Morton_Stanley>"); strings.push_back("<http://www.mpii.de/yago/resource/Axel_Oxenstierna>"); strings.push_back("<http://www.mpii.de/yago/resource/Henri_Lebesgue>"); strings.push_back("<http://www.mpii.de/yago/resource/Katsura_Tar%C5%8D>"); strings.push_back("<http://www.mpii.de/yago/resource/Nicolae_Ceau%C5%9Fescu>"); strings.push_back("<http://www.mpii.de/yago/resource/T%C3%A2rgovi%C5%9Fte>"); strings.push_back("<http://www.mpii.de/yago/resource/Mar%C3%ADa_F%C3%A9lix>"); strings.push_back("<http://www.mpii.de/yago/resource/James_Longstreet>"); strings.push_back("<http://www.mpii.de/yago/resource/Gainesville,_Georgia>"); strings.push_back("<http://www.mpii.de/yago/resource/It%C5%8D_Hirobumi>"); strings.push_back("<http://www.mpii.de/yago/resource/Harbin>"); strings.push_back("<http://www.mpii.de/yago/resource/Nathan_Bedford_Forrest>"); strings.push_back("<http://www.mpii.de/yago/resource/Adrien-Marie_Legendre>"); strings.push_back("<http://www.mpii.de/yago/resource/Christina_of_Sweden>"); strings.push_back("<http://www.mpii.de/yago/resource/Alonzo_Church>"); strings.push_back("<http://www.mpii.de/yago/resource/Hudson,_Ohio>"); strings.push_back("<http://www.mpii.de/yago/resource/Pope_Zephyrinus>"); strings.push_back("<http://www.mpii.de/yago/resource/Otto_von_Guericke>"); strings.push_back("<http://www.mpii.de/yago/resource/Pope_Clement_I>"); strings.push_back("<http://www.mpii.de/yago/resource/Chersonesos_Taurica>"); strings.push_back("<http://www.mpii.de/yago/resource/Pope_Leo_XII>"); strings.push_back("<http://www.mpii.de/yago/resource/Caracalla>"); strings.push_back("<http://www.mpii.de/yago/resource/Kate_Chopin>"); strings.push_back("<http://www.mpii.de/yago/resource/Otto_Neurath>"); strings.push_back("<http://www.mpii.de/yago/resource/Alexandra_Feodorovna_(Alix_of_Hesse)>"); strings.push_back("<http://www.mpii.de/yago/resource/Yuri_Andropov>"); strings.push_back("<http://www.mpii.de/yago/resource/Erich_Raeder>"); strings.push_back("<http://www.mpii.de/yago/resource/Kiel>"); strings.push_back("<http://www.mpii.de/yago/resource/Eric_Williams>"); strings.push_back("<http://www.mpii.de/yago/resource/Port_of_Spain>"); strings.push_back("<http://www.mpii.de/yago/resource/Paul_Revere>"); strings.push_back("<http://www.mpii.de/yago/resource/Robert_Walpole>"); strings.push_back("<http://www.mpii.de/yago/resource/Eugene_V._Debs>"); strings.push_back("<http://www.mpii.de/yago/resource/Elmhurst,_Illinois>"); strings.push_back("<http://www.mpii.de/yago/resource/Han_van_Meegeren>"); strings.push_back("<http://www.mpii.de/yago/resource/Amsterdam>"); strings.push_back("<http://www.mpii.de/yago/resource/Ford_Madox_Ford>"); strings.push_back("<http://www.mpii.de/yago/resource/Deauville>"); strings.push_back("<http://www.mpii.de/yago/resource/Matthias_Jakob_Schleiden>"); strings.push_back("<http://www.mpii.de/yago/resource/Frankfurt_am_Main>"); strings.push_back("<http://www.mpii.de/yago/resource/Mortimer_Wheeler>"); strings.push_back("<http://www.mpii.de/yago/resource/George_Farquhar>"); strings.push_back("<http://www.mpii.de/yago/resource/Charles_VII,_Holy_Roman_Emperor>"); strings.push_back("<http://www.mpii.de/yago/resource/Peter_Kropotkin>"); strings.push_back("<http://www.mpii.de/yago/resource/Dmitrov>"); strings.push_back("<http://www.mpii.de/yago/resource/Marty_Feldman>"); strings.push_back("<http://www.mpii.de/yago/resource/Mohamed_Farrah_Aidid>"); strings.push_back("<http://www.mpii.de/yago/resource/Mogadishu>"); strings.push_back("<http://www.mpii.de/yago/resource/Emilio_Lussu>"); strings.push_back("<http://www.mpii.de/yago/resource/Patrick_Troughton>"); strings.push_back("<http://www.mpii.de/yago/resource/Columbus,_Georgia>"); strings.push_back("<http://www.mpii.de/yago/resource/Thomas_Young_(scientist)>"); strings.push_back("<http://www.mpii.de/yago/resource/Pope_Dionysius>"); strings.push_back("<http://www.mpii.de/yago/resource/Valerian_(emperor)>"); strings.push_back("<http://www.mpii.de/yago/resource/Bishapur>"); strings.push_back("<http://www.mpii.de/yago/resource/Pope_Fabian>"); strings.push_back("<http://www.mpii.de/yago/resource/Vincent_R._Impellitteri>"); strings.push_back("<http://www.mpii.de/yago/resource/Bridgeport,_Connecticut>"); strings.push_back("<http://www.mpii.de/yago/resource/Farouk_of_Egypt>"); strings.push_back("<http://www.mpii.de/yago/resource/Joseph_Louis_Gay-Lussac>"); strings.push_back("<http://www.mpii.de/yago/resource/Julius_Pl%C3%BCcker>"); strings.push_back("<http://www.mpii.de/yago/resource/John_C._Calhoun>"); strings.push_back("<http://www.mpii.de/yago/resource/Charles_Lee_(general)>"); strings.push_back("<http://www.mpii.de/yago/resource/Ivan_Pavlov>"); strings.push_back("<http://www.mpii.de/yago/resource/Ulrike_Meinhof>"); strings.push_back("<http://www.mpii.de/yago/resource/Stuttgart>"); strings.push_back("<http://www.mpii.de/yago/resource/Aldo_Moro>"); strings.push_back("<http://www.mpii.de/yago/resource/Sigismund_III_Vasa>"); strings.push_back("<http://www.mpii.de/yago/resource/Albert_Brudzewski>"); strings.push_back("<http://www.mpii.de/yago/resource/John_McEwen>"); strings.push_back("<http://www.mpii.de/yago/resource/Louis_Sullivan>"); strings.push_back("<http://www.mpii.de/yago/resource/Pope_Paul_V>"); strings.push_back("<http://www.mpii.de/yago/resource/Jean-Charles_de_Borda>"); strings.push_back("<http://www.mpii.de/yago/resource/Basarab_I_of_Wallachia>"); strings.push_back("<http://www.mpii.de/yago/resource/C%C3%A2mpulung>"); strings.push_back("<http://www.mpii.de/yago/resource/John_Bellairs>"); strings.push_back("<http://www.mpii.de/yago/resource/Haverhill,_Massachusetts>"); strings.push_back("<http://www.mpii.de/yago/resource/Alexander_Pushkin>"); strings.push_back("<http://www.mpii.de/yago/resource/Gerard_Kuiper>"); strings.push_back("<http://www.mpii.de/yago/resource/Chandra_Levy>"); strings.push_back("<http://www.mpii.de/yago/resource/Pope_Paul_IV>"); strings.push_back("<http://www.mpii.de/yago/resource/David_Eddings>"); strings.push_back("<http://www.mpii.de/yago/resource/Carson_City,_Nevada>"); strings.push_back("<http://www.mpii.de/yago/resource/Ewald_Hering>"); strings.push_back("<http://www.mpii.de/yago/resource/Pope_Cornelius>"); strings.push_back("<http://www.mpii.de/yago/resource/Civitavecchia>"); strings.push_back("<http://www.mpii.de/yago/resource/Pope_Eutychian>"); strings.push_back("<http://www.mpii.de/yago/resource/Pope_Caius>"); strings.push_back("<http://www.mpii.de/yago/resource/Pope_Marcellinus>"); strings.push_back("<http://www.mpii.de/yago/resource/Eero_Saarinen>"); strings.push_back("<http://www.mpii.de/yago/resource/Ann_Arbor,_Michigan>"); strings.push_back("<http://www.mpii.de/yago/resource/Jacques_Derrida>"); strings.push_back("<http://www.mpii.de/yago/resource/Cole_Porter>"); strings.push_back("<http://www.mpii.de/yago/resource/Harry_Houdini>"); strings.push_back("<http://www.mpii.de/yago/resource/Detroit>"); strings.push_back("<http://www.mpii.de/yago/resource/Ray_Milland>"); strings.push_back("<http://www.mpii.de/yago/resource/Torrance,_California>"); strings.push_back("<http://www.mpii.de/yago/resource/Edward_Durell_Stone>"); strings.push_back("<http://www.mpii.de/yago/resource/Louis_Kahn>"); strings.push_back("<http://www.mpii.de/yago/resource/Ub_Iwerks>"); strings.push_back("<http://www.mpii.de/yago/resource/Moss_Hart>"); strings.push_back("<http://www.mpii.de/yago/resource/Sophus_Lie>"); strings.push_back("<http://www.mpii.de/yago/resource/Robert_Ludlum>"); strings.push_back("<http://www.mpii.de/yago/resource/Naples,_Florida>"); strings.push_back("<http://www.mpii.de/yago/resource/Harold_Wilson>"); strings.push_back("<http://www.mpii.de/yago/resource/Preston_Tucker>"); strings.push_back("<http://www.mpii.de/yago/resource/Ypsilanti,_Michigan>"); strings.push_back("<http://www.mpii.de/yago/resource/Mildred_Benson>"); strings.push_back("<http://www.mpii.de/yago/resource/Ladora,_Iowa>"); strings.push_back("<http://www.mpii.de/yago/resource/Charles_de_Secondat,_baron_de_Montesquieu>"); strings.push_back("<http://www.mpii.de/yago/resource/Ivo_Andri%C4%87>"); strings.push_back("<http://www.mpii.de/yago/resource/Belgrade>"); strings.push_back("<http://www.mpii.de/yago/resource/Puyi>"); strings.push_back("<http://www.mpii.de/yago/resource/Beijing>"); strings.push_back("<http://www.mpii.de/yago/resource/Ernst_Mach>"); strings.push_back("<http://www.mpii.de/yago/resource/Jean-Fran%C3%A7ois_Champollion>"); strings.push_back("<http://www.mpii.de/yago/resource/Roald_Dahl>"); strings.push_back("<http://www.mpii.de/yago/resource/Pope_Sabinian>"); strings.push_back("<http://www.mpii.de/yago/resource/Hans_Janmaat>"); strings.push_back("<http://www.mpii.de/yago/resource/Talcott_Parsons>"); strings.push_back("<http://www.mpii.de/yago/resource/Sim%C3%B3n_Bol%C3%ADvar>"); strings.push_back("<http://www.mpii.de/yago/resource/Santa_Marta>"); strings.push_back("<http://www.mpii.de/yago/resource/Gerald_of_Wales>"); strings.push_back("<http://www.mpii.de/yago/resource/Hereford>"); strings.push_back("<http://www.mpii.de/yago/resource/Antonio_Stradivari>"); strings.push_back("<http://www.mpii.de/yago/resource/Cremona>"); strings.push_back("<http://www.mpii.de/yago/resource/Fred_Gwynne>"); strings.push_back("<http://www.mpii.de/yago/resource/Taneytown,_Maryland>"); strings.push_back("<http://www.mpii.de/yago/resource/Paul_Lynde>"); strings.push_back("<http://www.mpii.de/yago/resource/Roberto_Calvi>"); strings.push_back("<http://www.mpii.de/yago/resource/Th%C3%A9ophile_Gautier>"); strings.push_back("<http://www.mpii.de/yago/resource/Abraham_de_Moivre>"); strings.push_back("<http://www.mpii.de/yago/resource/Walker_Percy>"); strings.push_back("<http://www.mpii.de/yago/resource/Covington,_Louisiana>"); strings.push_back("<http://www.mpii.de/yago/resource/Richard_von_Krafft-Ebing>"); strings.push_back("<http://www.mpii.de/yago/resource/Graz>"); strings.push_back("<http://www.mpii.de/yago/resource/%C5%BDeljko_Ra%C5%BEnatovi%C4%87>"); strings.push_back("<http://www.mpii.de/yago/resource/Bernard_Baruch>"); strings.push_back("<http://www.mpii.de/yago/resource/Rudolf_Carnap>"); strings.push_back("<http://www.mpii.de/yago/resource/Ian_Fleming>"); strings.push_back("<http://www.mpii.de/yago/resource/Pierre_Corneille>"); strings.push_back("<http://www.mpii.de/yago/resource/Alexander_Dallas_Bache>"); strings.push_back("<http://www.mpii.de/yago/resource/Newport,_Rhode_Island>"); strings.push_back("<http://www.mpii.de/yago/resource/Mikhail_Bakunin>"); strings.push_back("<http://www.mpii.de/yago/resource/Bern>"); strings.push_back("<http://www.mpii.de/yago/resource/Lawrence_Welk>"); strings.push_back("<http://www.mpii.de/yago/resource/Wright_brothers>"); strings.push_back("<http://www.mpii.de/yago/resource/Dayton,_Ohio>"); strings.push_back("<http://www.mpii.de/yago/resource/Pope_Hyginus>"); strings.push_back("<http://www.mpii.de/yago/resource/Pope_Gelasius_I>"); strings.push_back("<http://www.mpii.de/yago/resource/Pope_Gregory_XVI>"); strings.push_back("<http://www.mpii.de/yago/resource/Louis_Bonaparte>"); strings.push_back("<http://www.mpii.de/yago/resource/Livorno>"); strings.push_back("<http://www.mpii.de/yago/resource/Sardar_Vallabhbhai_Patel>"); strings.push_back("<http://www.mpii.de/yago/resource/Lola_Montez>"); strings.push_back("<http://www.mpii.de/yago/resource/Samuel_J._Tilden>"); strings.push_back("<http://www.mpii.de/yago/resource/Yonkers,_New_York>"); strings.push_back("<http://www.mpii.de/yago/resource/Jack_Buck>"); strings.push_back("<http://www.mpii.de/yago/resource/Sam_Houston>"); strings.push_back("<http://www.mpii.de/yago/resource/Huntsville,_Texas>"); strings.push_back("<http://www.mpii.de/yago/resource/Randy_Shughart>"); strings.push_back("<http://www.mpii.de/yago/resource/Gary_Gordon>"); strings.push_back("<http://www.mpii.de/yago/resource/Henri_Matisse>"); strings.push_back("<http://www.mpii.de/yago/resource/Anna_Leonowens>"); strings.push_back("<http://www.mpii.de/yago/resource/W%C5%82adys%C5%82aw_I_Herman>"); strings.push_back("<http://www.mpii.de/yago/resource/P%C5%82ock>"); strings.push_back("<http://www.mpii.de/yago/resource/Casimir_I_the_Restorer>"); strings.push_back("<http://www.mpii.de/yago/resource/Cleopatra_VII>"); strings.push_back("<http://www.mpii.de/yago/resource/Boles%C5%82aw_III_Wrymouth>"); strings.push_back("<http://www.mpii.de/yago/resource/Sochaczew>"); strings.push_back("<http://www.mpii.de/yago/resource/Gene_Rayburn>"); strings.push_back("<http://www.mpii.de/yago/resource/Georges_Carpentier>"); strings.push_back("<http://www.mpii.de/yago/resource/Boles%C5%82aw_Bierut>"); strings.push_back("<http://www.mpii.de/yago/resource/Robert_Browning>"); strings.push_back("<http://www.mpii.de/yago/resource/Rod_Steiger>"); strings.push_back("<http://www.mpii.de/yago/resource/Wilhelm_R%C3%B6ntgen>"); strings.push_back("<http://www.mpii.de/yago/resource/Louis_Braille>"); strings.push_back("<http://www.mpii.de/yago/resource/Ernest_L._Blumenschein>"); strings.push_back("<http://www.mpii.de/yago/resource/Albuquerque,_New_Mexico>"); strings.push_back("<http://www.mpii.de/yago/resource/Lars_Ahlfors>"); strings.push_back("<http://www.mpii.de/yago/resource/Pittsfield,_Massachusetts>"); strings.push_back("<http://www.mpii.de/yago/resource/E._Irving_Couse>"); strings.push_back("<http://www.mpii.de/yago/resource/Carol_Shields>"); strings.push_back("<http://www.mpii.de/yago/resource/Victoria,_British_Columbia>"); strings.push_back("<http://www.mpii.de/yago/resource/Guillaume_Apollinaire>"); strings.push_back("<http://www.mpii.de/yago/resource/Amedeo_Modigliani>"); strings.push_back("<http://www.mpii.de/yago/resource/Hyacinthe_Rigaud>"); strings.push_back("<http://www.mpii.de/yago/resource/Joaqu%C3%ADn_Balaguer>"); strings.push_back("<http://www.mpii.de/yago/resource/Santo_Domingo>"); strings.push_back("<http://www.mpii.de/yago/resource/William_Wyler>"); strings.push_back("<http://www.mpii.de/yago/resource/Catharina_of_W%C3%BCrttemberg>"); strings.push_back("<http://www.mpii.de/yago/resource/Lausanne>"); strings.push_back("<http://www.mpii.de/yago/resource/J._B._S._Haldane>"); strings.push_back("<http://www.mpii.de/yago/resource/Bhubaneswar>"); strings.push_back("<http://www.mpii.de/yago/resource/Lewis_Milestone>"); strings.push_back("<http://www.mpii.de/yago/resource/Lucien_Bonaparte>"); strings.push_back("<http://www.mpii.de/yago/resource/Eug%C3%A8ne_de_Beauharnais>"); strings.push_back("<http://www.mpii.de/yago/resource/Charles_X_of_France>"); strings.push_back("<http://www.mpii.de/yago/resource/Gorizia>"); strings.push_back("<http://www.mpii.de/yago/resource/Marie_Louise,_Duchess_of_Parma>"); strings.push_back("<http://www.mpii.de/yago/resource/Parma>"); strings.push_back("<http://www.mpii.de/yago/resource/Walter_Matthau>"); strings.push_back("<http://www.mpii.de/yago/resource/Pope_Adeodatus_I>"); strings.push_back("<http://www.mpii.de/yago/resource/Pope_Mark>"); strings.push_back("<http://www.mpii.de/yago/resource/Pope_Simplicius>"); strings.push_back("<http://www.mpii.de/yago/resource/Pope_Felix_III>"); strings.push_back("<http://www.mpii.de/yago/resource/Pope_Symmachus>"); strings.push_back("<http://www.mpii.de/yago/resource/Pope_John_I>"); strings.push_back("<http://www.mpii.de/yago/resource/Pope_Pelagius_I>"); strings.push_back("<http://www.mpii.de/yago/resource/Pope_John_III>"); strings.push_back("<http://www.mpii.de/yago/resource/Pope_Vigilius>"); strings.push_back("<http://www.mpii.de/yago/resource/Syracuse,_Sicily>"); strings.push_back("<http://www.mpii.de/yago/resource/Pope_Pelagius_II>"); strings.push_back("<http://www.mpii.de/yago/resource/Pope_Severinus>"); strings.push_back("<http://www.mpii.de/yago/resource/Claus_Schenk_Graf_von_Stauffenberg>"); strings.push_back("<http://www.mpii.de/yago/resource/Chaim_Soutine>"); strings.push_back("<http://www.mpii.de/yago/resource/James_Hilton>"); strings.push_back("<http://www.mpii.de/yago/resource/Long_Beach,_California>"); strings.push_back("<http://www.mpii.de/yago/resource/Joan_Mir%C3%B3>"); strings.push_back("<http://www.mpii.de/yago/resource/Palma,_Majorca>"); strings.push_back("<http://www.mpii.de/yago/resource/W._T._Cosgrave>"); strings.push_back("<http://www.mpii.de/yago/resource/Antoine_de_Saint-Exup%C3%A9ry>"); strings.push_back("<http://www.mpii.de/yago/resource/Friedrich_D%C3%BCrrenmatt>"); strings.push_back("<http://www.mpii.de/yago/resource/Neuch%C3%A2tel>"); strings.push_back("<http://www.mpii.de/yago/resource/Edgar_Degas>"); strings.push_back("<http://www.mpii.de/yago/resource/Fred_Quimby>"); strings.push_back("<http://www.mpii.de/yago/resource/Erich_Maria_Remarque>"); strings.push_back("<http://www.mpii.de/yago/resource/Locarno>"); strings.push_back("<http://www.mpii.de/yago/resource/Norbert_Wiener>"); strings.push_back("<http://www.mpii.de/yago/resource/Jaroslav_Seifert>"); strings.push_back("<http://www.mpii.de/yago/resource/Mikhail_Lomonosov>"); strings.push_back("<http://www.mpii.de/yago/resource/Maximilian_II_Emanuel,_Elector_of_Bavaria>"); strings.push_back("<http://www.mpii.de/yago/resource/Greta_Garbo>"); strings.push_back("<http://www.mpii.de/yago/resource/Claude_Rains>"); strings.push_back("<http://www.mpii.de/yago/resource/Laconia,_New_Hampshire>"); strings.push_back("<http://www.mpii.de/yago/resource/Patricia_Highsmith>"); strings.push_back("<http://www.mpii.de/yago/resource/Peter_Claver>"); strings.push_back("<http://www.mpii.de/yago/resource/Cartagena,_Colombia>"); strings.push_back("<http://www.mpii.de/yago/resource/Jean_Anouilh>"); strings.push_back("<http://www.mpii.de/yago/resource/William_Rivers>"); strings.push_back("<http://www.mpii.de/yago/resource/Kristian_Birkeland>"); strings.push_back("<http://www.mpii.de/yago/resource/Barry_Hannah>"); strings.push_back("<http://www.mpii.de/yago/resource/Oxford,_Mississippi>"); strings.push_back("<http://www.mpii.de/yago/resource/Ingeborg_Bachmann>"); strings.push_back("<http://www.mpii.de/yago/resource/Joris-Karl_Huysmans>"); strings.push_back("<http://www.mpii.de/yago/resource/Jacqueline_Kennedy_Onassis>"); strings.push_back("<http://www.mpii.de/yago/resource/Boris_Godunov>"); strings.push_back("<http://www.mpii.de/yago/resource/E._M._Forster>"); strings.push_back("<http://www.mpii.de/yago/resource/Coventry>"); strings.push_back("<http://www.mpii.de/yago/resource/Jacob_Bernoulli>"); strings.push_back("<http://www.mpii.de/yago/resource/Andr%C3%A9-Louis_Danjon>"); strings.push_back("<http://www.mpii.de/yago/resource/George_McFarland>"); strings.push_back("<http://www.mpii.de/yago/resource/Grapevine,_Texas>"); strings.push_back("<http://www.mpii.de/yago/resource/Narc%C3%ADs_Oller>"); strings.push_back("<http://www.mpii.de/yago/resource/Jiang_Qing>"); strings.push_back("<http://www.mpii.de/yago/resource/Graham_Greene>"); strings.push_back("<http://www.mpii.de/yago/resource/Edward_Hopper>"); strings.push_back("<http://www.mpii.de/yago/resource/Qian_Zhongshu>"); strings.push_back("<http://www.mpii.de/yago/resource/Stephen_Ambrose>"); strings.push_back("<http://www.mpii.de/yago/resource/Bay_St._Louis,_Mississippi>"); strings.push_back("<http://www.mpii.de/yago/resource/Olav_IV_of_Norway>"); strings.push_back("<http://www.mpii.de/yago/resource/Falsterbo>"); strings.push_back("<http://www.mpii.de/yago/resource/Henry_Wadsworth_Longfellow>"); strings.push_back("<http://www.mpii.de/yago/resource/Juan_Diego>"); strings.push_back("<http://www.mpii.de/yago/resource/Evel_Knievel>"); strings.push_back("<http://www.mpii.de/yago/resource/Clearwater,_Florida>"); strings.push_back("<http://www.mpii.de/yago/resource/Hugo_Grotius>"); strings.push_back("<http://www.mpii.de/yago/resource/Rostock>"); strings.push_back("<http://www.mpii.de/yago/resource/Golda_Meir>"); strings.push_back("<http://www.mpii.de/yago/resource/Philip_Jos%C3%A9_Farmer>"); strings.push_back("<http://www.mpii.de/yago/resource/Peoria,_Illinois>"); strings.push_back("<http://www.mpii.de/yago/resource/Alfonso_X_of_Castile>"); strings.push_back("<http://www.mpii.de/yago/resource/Gudrun_Ensslin>"); strings.push_back("<http://www.mpii.de/yago/resource/Richard_Francis_Burton>"); strings.push_back("<http://www.mpii.de/yago/resource/Trieste>"); strings.push_back("<http://www.mpii.de/yago/resource/Eugene_O'Neill>"); strings.push_back("<http://www.mpii.de/yago/resource/Errol_Flynn>"); strings.push_back("<http://www.mpii.de/yago/resource/Vancouver>"); strings.push_back("<http://www.mpii.de/yago/resource/Carlos_Castaneda>"); strings.push_back("<http://www.mpii.de/yago/resource/Chester_Gould>"); strings.push_back("<http://www.mpii.de/yago/resource/Woodstock,_Illinois>"); strings.push_back("<http://www.mpii.de/yago/resource/Pope_Leo_IX>"); strings.push_back("<http://www.mpii.de/yago/resource/Pope_Damasus_II>"); strings.push_back("<http://www.mpii.de/yago/resource/Palestrina>"); strings.push_back("<http://www.mpii.de/yago/resource/Baruch_Goldstein>"); strings.push_back("<http://www.mpii.de/yago/resource/Hebron>"); strings.push_back("<http://www.mpii.de/yago/resource/Ho_Chi_Minh>"); strings.push_back("<http://www.mpii.de/yago/resource/Hanoi>"); strings.push_back("<http://www.mpii.de/yago/resource/J%C3%B3zef_Pi%C5%82sudski>"); strings.push_back("<http://www.mpii.de/yago/resource/Robert_Wise>"); strings.push_back("<http://www.mpii.de/yago/resource/Francesc_Maci%C3%A0_i_Lluss%C3%A0>"); strings.push_back("<http://www.mpii.de/yago/resource/Herod_the_Great>"); strings.push_back("<http://www.mpii.de/yago/resource/Jericho>"); strings.push_back("<http://www.mpii.de/yago/resource/Richard_W._Thompson>"); strings.push_back("<http://www.mpii.de/yago/resource/Grand_Duchess_Tatiana_Nikolaevna_of_Russia>"); strings.push_back("<http://www.mpii.de/yago/resource/Llu%C3%ADs_Companys>"); strings.push_back("<http://www.mpii.de/yago/resource/Basil_Rathbone>"); strings.push_back("<http://www.mpii.de/yago/resource/Anna_Nicole_Smith>"); strings.push_back("<http://www.mpii.de/yago/resource/Hollywood,_Florida>"); strings.push_back("<http://www.mpii.de/yago/resource/Pope_Pius_VII>"); strings.push_back("<http://www.mpii.de/yago/resource/Mordechaj_Anielewicz>"); strings.push_back("<http://www.mpii.de/yago/resource/Charles_Emmanuel_I,_Duke_of_Savoy>"); strings.push_back("<http://www.mpii.de/yago/resource/Savigliano>"); strings.push_back("<http://www.mpii.de/yago/resource/Charles_Felix_of_Sardinia>"); strings.push_back("<http://www.mpii.de/yago/resource/Charles_Albert_of_Sardinia>"); strings.push_back("<http://www.mpii.de/yago/resource/Porto>"); strings.push_back("<http://www.mpii.de/yago/resource/Onesimus>"); strings.push_back("<http://www.mpii.de/yago/resource/Leo_McKern>"); strings.push_back("<http://www.mpii.de/yago/resource/Lillie_Langtry>"); strings.push_back("<http://www.mpii.de/yago/resource/Victor_Emmanuel_II_of_Italy>"); strings.push_back("<http://www.mpii.de/yago/resource/Umberto_II_of_Italy>"); strings.push_back("<http://www.mpii.de/yago/resource/Victor_Emmanuel_III_of_Italy>"); strings.push_back("<http://www.mpii.de/yago/resource/J._J._Thomson>"); strings.push_back("<http://www.mpii.de/yago/resource/George_Burns>"); strings.push_back("<http://www.mpii.de/yago/resource/Lucy_Webb_Hayes>"); strings.push_back("<http://www.mpii.de/yago/resource/Fremont,_Ohio>"); strings.push_back("<http://www.mpii.de/yago/resource/Cyrano_de_Bergerac>"); strings.push_back("<http://www.mpii.de/yago/resource/Maxime_Weygand>"); strings.push_back("<http://www.mpii.de/yago/resource/Slim_Pickens>"); strings.push_back("<http://www.mpii.de/yago/resource/Modesto,_California>"); strings.push_back("<http://www.mpii.de/yago/resource/Alexander_von_Humboldt>"); strings.push_back("<http://www.mpii.de/yago/resource/Ivan_IV_of_Russia>"); strings.push_back("<http://www.mpii.de/yago/resource/Hafez_al-Assad>"); strings.push_back("<http://www.mpii.de/yago/resource/Fran%C3%A7ois_Duvalier>"); strings.push_back("<http://www.mpii.de/yago/resource/Port-au-Prince>"); strings.push_back("<http://www.mpii.de/yago/resource/Idi_Amin>"); strings.push_back("<http://www.mpii.de/yago/resource/Jeddah>"); strings.push_back("<http://www.mpii.de/yago/resource/John_Backus>"); strings.push_back("<http://www.mpii.de/yago/resource/Ashland,_Oregon>"); strings.push_back("<http://www.mpii.de/yago/resource/Porfirio_D%C3%ADaz>"); strings.push_back("<http://www.mpii.de/yago/resource/Margaret_of_York>"); strings.push_back("<http://www.mpii.de/yago/resource/Mechelen>"); strings.push_back("<http://www.mpii.de/yago/resource/Vyacheslav_Molotov>"); strings.push_back("<http://www.mpii.de/yago/resource/Bob_Fosse>"); strings.push_back("<http://www.mpii.de/yago/resource/Hugo_Steinhaus>"); strings.push_back("<http://www.mpii.de/yago/resource/Alfred_Dreyfus>"); strings.push_back("<http://www.mpii.de/yago/resource/Earl_Warren>"); strings.push_back("<http://www.mpii.de/yago/resource/Mao_Dun>"); strings.push_back("<http://www.mpii.de/yago/resource/Eug%C3%A8ne_Ionesco>"); strings.push_back("<http://www.mpii.de/yago/resource/William_Harvey_Carney>"); strings.push_back("<http://www.mpii.de/yago/resource/Natalia_Brasova>"); strings.push_back("<http://www.mpii.de/yago/resource/Gabriel_Faur%C3%A9>"); strings.push_back("<http://www.mpii.de/yago/resource/Amadeo_of_Spain>"); strings.push_back("<http://www.mpii.de/yago/resource/Thomas_Lawrence>"); strings.push_back("<http://www.mpii.de/yago/resource/Louis_Comfort_Tiffany>"); strings.push_back("<http://www.mpii.de/yago/resource/Enrico_Mattei>"); strings.push_back("<http://www.mpii.de/yago/resource/Bascap%C3%A8>"); strings.push_back("<http://www.mpii.de/yago/resource/Constantius_Chlorus>"); strings.push_back("<http://www.mpii.de/yago/resource/Foster_Hewitt>"); strings.push_back("<http://www.mpii.de/yago/resource/Scarborough,_Ontario>"); strings.push_back("<http://www.mpii.de/yago/resource/John_William_Friso,_Prince_of_Orange>"); strings.push_back("<http://www.mpii.de/yago/resource/Dordrecht>"); strings.push_back("<http://www.mpii.de/yago/resource/James_Mason>"); strings.push_back("<http://www.mpii.de/yago/resource/George_Gamow>"); strings.push_back("<http://www.mpii.de/yago/resource/Boulder,_Colorado>"); strings.push_back("<http://www.mpii.de/yago/resource/Antonia_Minor>"); strings.push_back("<http://www.mpii.de/yago/resource/Livia>"); strings.push_back("<http://www.mpii.de/yago/resource/Pedro_de_Alvarado>"); strings.push_back("<http://www.mpii.de/yago/resource/Guadalajara,_Jalisco>"); strings.push_back("<http://www.mpii.de/yago/resource/Jeanne_Sauv%C3%A9>"); strings.push_back("<http://www.mpii.de/yago/resource/Archibald_Hill>"); strings.push_back("<http://www.mpii.de/yago/resource/Maximian>"); strings.push_back("<http://www.mpii.de/yago/resource/Ricardo_Montalb%C3%A1n>"); strings.push_back("<http://www.mpii.de/yago/resource/Grand_Duchess_Anastasia_Nikolaevna_of_Russia>"); strings.push_back("<http://www.mpii.de/yago/resource/Folke_Bernadotte>"); strings.push_back("<http://www.mpii.de/yago/resource/Cyrus_McCormick>"); strings.push_back("<http://www.mpii.de/yago/resource/Henry_II_of_France>"); strings.push_back("<http://www.mpii.de/yago/resource/Pierre-Joseph_Redout%C3%A9>"); strings.push_back("<http://www.mpii.de/yago/resource/Choi_Hong_Hi>"); strings.push_back("<http://www.mpii.de/yago/resource/Pyongyang>"); strings.push_back("<http://www.mpii.de/yago/resource/Louis_the_Child>"); strings.push_back("<http://www.mpii.de/yago/resource/Christian_J%C3%BCrgensen_Thomsen>"); strings.push_back("<http://www.mpii.de/yago/resource/John_I_of_France>"); strings.push_back("<http://www.mpii.de/yago/resource/Lu%C3%ADs_de_Cam%C3%B5es>"); strings.push_back("<http://www.mpii.de/yago/resource/Tigellinus>"); strings.push_back("<http://www.mpii.de/yago/resource/C._C._Beck>"); strings.push_back("<http://www.mpii.de/yago/resource/Gainesville,_Florida>"); strings.push_back("<http://www.mpii.de/yago/resource/John_Brown_(abolitionist)>"); strings.push_back("<http://www.mpii.de/yago/resource/Charles_Town,_West_Virginia>"); strings.push_back("<http://www.mpii.de/yago/resource/Louis_XII_of_France>"); strings.push_back("<http://www.mpii.de/yago/resource/Ali_Hassan_Salameh>"); strings.push_back("<http://www.mpii.de/yago/resource/Beirut>"); strings.push_back("<http://www.mpii.de/yago/resource/Juan_Antonio_Samaranch>"); strings.push_back("<http://www.mpii.de/yago/resource/William_Morris_Davis>"); strings.push_back("<http://www.mpii.de/yago/resource/Jack_Cole_(artist)>"); strings.push_back("<http://www.mpii.de/yago/resource/Crystal_Lake,_Illinois>"); strings.push_back("<http://www.mpii.de/yago/resource/James_Doohan>"); strings.push_back("<http://www.mpii.de/yago/resource/Redmond,_Washington>"); strings.push_back("<http://www.mpii.de/yago/resource/Lloyd_Berkner>"); strings.push_back("<http://www.mpii.de/yago/resource/Nevil_Shute>"); strings.push_back("<http://www.mpii.de/yago/resource/Didymus_Chalcenterus>"); strings.push_back("<http://www.mpii.de/yago/resource/Hans_Geiger>"); strings.push_back("<http://www.mpii.de/yago/resource/Potsdam>"); strings.push_back("<http://www.mpii.de/yago/resource/Paul_Ehrenfest>"); strings.push_back("<http://www.mpii.de/yago/resource/Alphonse_Daudet>"); strings.push_back("<http://www.mpii.de/yago/resource/William_Pitt_the_Younger>"); strings.push_back("<http://www.mpii.de/yago/resource/Charles_Wheatstone>"); strings.push_back("<http://www.mpii.de/yago/resource/Giuseppe_Piazzi>"); strings.push_back("<http://www.mpii.de/yago/resource/Igor_Tamm>"); strings.push_back("<http://www.mpii.de/yago/resource/Tr%E1%BA%A7n_V%C4%83n_Tr%C3%A0>"); strings.push_back("<http://www.mpii.de/yago/resource/Lon_Nol>"); strings.push_back("<http://www.mpii.de/yago/resource/Duong_Van_Minh>"); strings.push_back("<http://www.mpii.de/yago/resource/John_Gotti>"); strings.push_back("<http://www.mpii.de/yago/resource/Mike_Mansfield>"); strings.push_back("<http://www.mpii.de/yago/resource/Dean_Rusk>"); strings.push_back("<http://www.mpii.de/yago/resource/Athens,_Georgia>"); strings.push_back("<http://www.mpii.de/yago/resource/William_Westmoreland>"); strings.push_back("<http://www.mpii.de/yago/resource/J._C._Jacobsen>"); strings.push_back("<http://www.mpii.de/yago/resource/Lev_Landau>"); strings.push_back("<http://www.mpii.de/yago/resource/Anne_of_Austria>"); strings.push_back("<http://www.mpii.de/yago/resource/Uthman_ibn_Affan>"); strings.push_back("<http://www.mpii.de/yago/resource/Umar>"); strings.push_back("<http://www.mpii.de/yago/resource/Pedro_del_Valle>"); strings.push_back("<http://www.mpii.de/yago/resource/Annapolis,_Maryland>"); strings.push_back("<http://www.mpii.de/yago/resource/John_Kerr_(Governor-General)>"); strings.push_back("<http://www.mpii.de/yago/resource/Sydney>"); strings.push_back("<http://www.mpii.de/yago/resource/William_H._Seward>"); strings.push_back("<http://www.mpii.de/yago/resource/Alfred_Adler>"); strings.push_back("<http://www.mpii.de/yago/resource/Gaius_Marius>"); strings.push_back("<http://www.mpii.de/yago/resource/Carlos_Pr%C3%ADo_Socarr%C3%A1s>"); strings.push_back("<http://www.mpii.de/yago/resource/Miami>"); strings.push_back("<http://www.mpii.de/yago/resource/Franz_Brentano>"); strings.push_back("<http://www.mpii.de/yago/resource/Rainer_Werner_Fassbinder>"); strings.push_back("<http://www.mpii.de/yago/resource/Pedro_II_of_Brazil>"); strings.push_back("<http://www.mpii.de/yago/resource/F._W._Murnau>"); strings.push_back("<http://www.mpii.de/yago/resource/Boris_Vian>"); strings.push_back("<http://www.mpii.de/yago/resource/George_C._Scott>"); strings.push_back("<http://www.mpii.de/yago/resource/Westlake_Village,_California>"); strings.push_back("<http://www.mpii.de/yago/resource/Jack_Benny>"); strings.push_back("<http://www.mpii.de/yago/resource/Henry_James>"); strings.push_back("<http://www.mpii.de/yago/resource/Ptolemy_I_Soter>"); strings.push_back("<http://www.mpii.de/yago/resource/John_Kenneth_Galbraith>"); strings.push_back("<http://www.mpii.de/yago/resource/Allan_Bloom>"); strings.push_back("<http://www.mpii.de/yago/resource/Antiochus_III_the_Great>"); strings.push_back("<http://www.mpii.de/yago/resource/Susa>"); strings.push_back("<http://www.mpii.de/yago/resource/Ansel_Adams>"); strings.push_back("<http://www.mpii.de/yago/resource/John_N._Mitchell>"); strings.push_back("<http://www.mpii.de/yago/resource/Seleucus_I_Nicator>"); strings.push_back("<http://www.mpii.de/yago/resource/Lysimachia_(Thrace)>"); strings.push_back("<http://www.mpii.de/yago/resource/Jean_Seberg>"); strings.push_back("<http://www.mpii.de/yago/resource/Theodor_Fontane>"); strings.push_back("<http://www.mpii.de/yago/resource/Leo_McCarey>"); strings.push_back("<http://www.mpii.de/yago/resource/Maxim_Gorky>"); strings.push_back("<http://www.mpii.de/yago/resource/John_Buchan,_1st_Baron_Tweedsmuir>"); strings.push_back("<http://www.mpii.de/yago/resource/Elmo_Zumwalt>"); strings.push_back("<http://www.mpii.de/yago/resource/Durham,_North_Carolina>"); strings.push_back("<http://www.mpii.de/yago/resource/Pope_Nicholas_I>"); strings.push_back("<http://www.mpii.de/yago/resource/Cardinal_Richelieu>"); strings.push_back("<http://www.mpii.de/yago/resource/Catherine_of_Alexandria>"); strings.push_back("<http://www.mpii.de/yago/resource/James_Naismith>"); strings.push_back("<http://www.mpii.de/yago/resource/William_Chester_Minor>"); strings.push_back("<http://www.mpii.de/yago/resource/Wilhelm_Maybach>"); strings.push_back("<http://www.mpii.de/yago/resource/Ejnar_Hertzsprung>"); strings.push_back("<http://www.mpii.de/yago/resource/Roskilde>"); strings.push_back("<http://www.mpii.de/yago/resource/Sergey_Korolyov>"); strings.push_back("<http://www.mpii.de/yago/resource/Fred_MacMurray>"); strings.push_back("<http://www.mpii.de/yago/resource/Thomas_B._Costain>"); strings.push_back("<http://www.mpii.de/yago/resource/G._H._Hardy>"); strings.push_back("<http://www.mpii.de/yago/resource/Charles_Perrault>"); strings.push_back("<http://www.mpii.de/yago/resource/Joseph_Louis_Lagrange>"); strings.push_back("<http://www.mpii.de/yago/resource/Hendrik_Lorentz>"); strings.push_back("<http://www.mpii.de/yago/resource/Luigi_Galvani>"); strings.push_back("<http://www.mpii.de/yago/resource/Bologna>"); strings.push_back("<http://www.mpii.de/yago/resource/Sun_Yat-sen>"); strings.push_back("<http://www.mpii.de/yago/resource/Garret_Hobart>"); strings.push_back("<http://www.mpii.de/yago/resource/Paterson,_New_Jersey>"); strings.push_back("<http://www.mpii.de/yago/resource/George_M._Dallas>"); strings.push_back("<http://www.mpii.de/yago/resource/William_R._King>"); strings.push_back("<http://www.mpii.de/yago/resource/Selma,_Alabama>"); strings.push_back("<http://www.mpii.de/yago/resource/Schuyler_Colfax>"); strings.push_back("<http://www.mpii.de/yago/resource/Mankato,_Minnesota>"); strings.push_back("<http://www.mpii.de/yago/resource/John_C._Breckinridge>"); strings.push_back("<http://www.mpii.de/yago/resource/Lexington,_Kentucky>"); strings.push_back("<http://www.mpii.de/yago/resource/Henry_Wilson>"); strings.push_back("<http://www.mpii.de/yago/resource/Richard_Mentor_Johnson>"); strings.push_back("<http://www.mpii.de/yago/resource/Frankfort,_Kentucky>"); strings.push_back("<http://www.mpii.de/yago/resource/Dorothy_Tutin>"); strings.push_back("<http://www.mpii.de/yago/resource/Chichester>"); strings.push_back("<http://www.mpii.de/yago/resource/Hal_Foster>"); strings.push_back("<http://www.mpii.de/yago/resource/Winter_Park,_Florida>"); strings.push_back("<http://www.mpii.de/yago/resource/Errico_Malatesta>"); strings.push_back("<http://www.mpii.de/yago/resource/Harold_Pinter>"); strings.push_back("<http://www.mpii.de/yago/resource/Emmanuel_Levinas>"); strings.push_back("<http://www.mpii.de/yago/resource/George_Gobel>"); strings.push_back("<http://www.mpii.de/yago/resource/Bartel_Leendert_van_der_Waerden>"); strings.push_back("<http://www.mpii.de/yago/resource/John_C._Fr%C3%A9mont>"); strings.push_back("<http://www.mpii.de/yago/resource/Hugh_Paddick>"); strings.push_back("<http://www.mpii.de/yago/resource/Milton_Keynes>"); strings.push_back("<http://www.mpii.de/yago/resource/Adlai_E._Stevenson_I>"); strings.push_back("<http://www.mpii.de/yago/resource/James_S._Sherman>"); strings.push_back("<http://www.mpii.de/yago/resource/Utica,_New_York>"); strings.push_back("<http://www.mpii.de/yago/resource/Charles_Curtis>"); strings.push_back("<http://www.mpii.de/yago/resource/Charles_G._Dawes>"); strings.push_back("<http://www.mpii.de/yago/resource/Evanston,_Illinois>"); strings.push_back("<http://www.mpii.de/yago/resource/John_Nance_Garner>"); strings.push_back("<http://www.mpii.de/yago/resource/Uvalde,_Texas>"); strings.push_back("<http://www.mpii.de/yago/resource/Nils_Gabriel_Sefstr%C3%B6m>"); strings.push_back("<http://www.mpii.de/yago/resource/Alben_W._Barkley>"); strings.push_back("<http://www.mpii.de/yago/resource/W%C5%82adys%C5%82aw_I_the_Elbow-high>"); strings.push_back("<http://www.mpii.de/yago/resource/Henry_A._Wallace>"); strings.push_back("<http://www.mpii.de/yago/resource/Danbury,_Connecticut>"); strings.push_back("<http://www.mpii.de/yago/resource/George_C._Day>"); strings.push_back("<http://www.mpii.de/yago/resource/Albert_Abraham_Michelson>"); strings.push_back("<http://www.mpii.de/yago/resource/Conrad_Hilton>"); strings.push_back("<http://www.mpii.de/yago/resource/Johann_Heinrich_Lambert>"); strings.push_back("<http://www.mpii.de/yago/resource/Karl_Weierstrass>"); strings.push_back("<http://www.mpii.de/yago/resource/Robin_Milner>"); strings.push_back("<http://www.mpii.de/yago/resource/Friedrich_Wilhelm_von_Steuben>"); strings.push_back("<http://www.mpii.de/yago/resource/C%C3%A9sar_Vallejo>"); strings.push_back("<http://www.mpii.de/yago/resource/Samuel_Pierpont_Langley>"); strings.push_back("<http://www.mpii.de/yago/resource/Aiken,_South_Carolina>"); strings.push_back("<http://www.mpii.de/yago/resource/Athanasius_Kircher>"); strings.push_back("<http://www.mpii.de/yago/resource/Marc_Isambard_Brunel>"); strings.push_back("<http://www.mpii.de/yago/resource/Aelia_Eudocia>"); strings.push_back("<http://www.mpii.de/yago/resource/Luis_A._Ferr%C3%A9>"); strings.push_back("<http://www.mpii.de/yago/resource/Alexis_of_Russia>"); strings.push_back("<http://www.mpii.de/yago/resource/John_Vincent_Atanasoff>"); strings.push_back("<http://www.mpii.de/yago/resource/Frederick,_Maryland>"); strings.push_back("<http://www.mpii.de/yago/resource/James_Smithson>"); strings.push_back("<http://www.mpii.de/yago/resource/Genoa>"); strings.push_back("<http://www.mpii.de/yago/resource/Matthew_Shepard>"); strings.push_back("<http://www.mpii.de/yago/resource/Fort_Collins,_Colorado>"); strings.push_back("<http://www.mpii.de/yago/resource/Alex_Haley>"); strings.push_back("<http://www.mpii.de/yago/resource/Gabrielle_d'Estr%C3%A9es>"); strings.push_back("<http://www.mpii.de/yago/resource/Martial>"); strings.push_back("<http://www.mpii.de/yago/resource/Max_Oph%C3%BCls>"); strings.push_back("<http://www.mpii.de/yago/resource/William_Moulton_Marston>"); strings.push_back("<http://www.mpii.de/yago/resource/Rye_(city),_New_York>"); strings.push_back("<http://www.mpii.de/yago/resource/Isaac_Barrow>"); strings.push_back("<http://www.mpii.de/yago/resource/Willem_Drees>"); strings.push_back("<http://www.mpii.de/yago/resource/Barend_Biesheuvel>"); strings.push_back("<http://www.mpii.de/yago/resource/Theophrastus>"); strings.push_back("<http://www.mpii.de/yago/resource/John_Abbott>"); strings.push_back("<http://www.mpii.de/yago/resource/Martha>"); strings.push_back("<http://www.mpii.de/yago/resource/Larnaca>"); strings.push_back("<http://www.mpii.de/yago/resource/Pope_John_XIII>"); strings.push_back("<http://www.mpii.de/yago/resource/Joop_den_Uyl>"); strings.push_back("<http://www.mpii.de/yago/resource/Jo_Cals>"); strings.push_back("<http://www.mpii.de/yago/resource/Andrei_Chikatilo>"); strings.push_back("<http://www.mpii.de/yago/resource/Novocherkassk>"); strings.push_back("<http://www.mpii.de/yago/resource/J%C3%A1nos_Bolyai>"); strings.push_back("<http://www.mpii.de/yago/resource/T%C3%A2rgu_Mure%C5%9F>"); strings.push_back("<http://www.mpii.de/yago/resource/Georg_Ernst_Stahl>"); strings.push_back("<http://www.mpii.de/yago/resource/Charles_Boyer>"); strings.push_back("<http://www.mpii.de/yago/resource/Jimmy_Durante>"); strings.push_back("<http://www.mpii.de/yago/resource/Richard_Hamming>"); strings.push_back("<http://www.mpii.de/yago/resource/Frederick_II_of_Prussia>"); strings.push_back("<http://www.mpii.de/yago/resource/Philip_V_of_Macedon>"); strings.push_back("<http://www.mpii.de/yago/resource/Amphipolis>"); strings.push_back("<http://www.mpii.de/yago/resource/Prince_Claus_of_the_Netherlands>"); strings.push_back("<http://www.mpii.de/yago/resource/Fred_Zinnemann>"); strings.push_back("<http://www.mpii.de/yago/resource/Hua_Guofeng>"); strings.push_back("<http://www.mpii.de/yago/resource/Charles_Cros>"); strings.push_back("<http://www.mpii.de/yago/resource/Josemar%C3%ADa_Escriv%C3%A1>"); strings.push_back("<http://www.mpii.de/yago/resource/Arrian>"); strings.push_back("<http://www.mpii.de/yago/resource/Maurice_of_Nassau,_Prince_of_Orange>"); strings.push_back("<http://www.mpii.de/yago/resource/Gian-Carlo_Rota>"); strings.push_back("<http://www.mpii.de/yago/resource/K._R._Narayanan>"); strings.push_back("<http://www.mpii.de/yago/resource/Antonio_da_Correggio>"); strings.push_back("<http://www.mpii.de/yago/resource/Correggio,_Italy>"); strings.push_back("<http://www.mpii.de/yago/resource/Paulus_Potter>"); strings.push_back("<http://www.mpii.de/yago/resource/Douglas_Sirk>"); strings.push_back("<http://www.mpii.de/yago/resource/Lugano>"); strings.push_back("<http://www.mpii.de/yago/resource/Papias_of_Hierapolis>"); strings.push_back("<http://www.mpii.de/yago/resource/John_Kennedy_Toole>"); strings.push_back("<http://www.mpii.de/yago/resource/Biloxi,_Mississippi>"); strings.push_back("<http://www.mpii.de/yago/resource/Sally_Hemings>"); strings.push_back("<http://www.mpii.de/yago/resource/Huey_Long>"); strings.push_back("<http://www.mpii.de/yago/resource/Baton_Rouge,_Louisiana>"); strings.push_back("<http://www.mpii.de/yago/resource/David_Farragut>"); strings.push_back("<http://www.mpii.de/yago/resource/Portsmouth,_New_Hampshire>"); strings.push_back("<http://www.mpii.de/yago/resource/Abigail_Adams>"); strings.push_back("<http://www.mpii.de/yago/resource/Quincy,_Massachusetts>"); strings.push_back("<http://www.mpii.de/yago/resource/Brandon_Teena>"); strings.push_back("<http://www.mpii.de/yago/resource/Humboldt,_Nebraska>"); strings.push_back("<http://www.mpii.de/yago/resource/P.G.T._Beauregard>"); strings.push_back("<http://www.mpii.de/yago/resource/New_Orleans>"); strings.push_back("<http://www.mpii.de/yago/resource/Patrick_O'Brian>"); strings.push_back("<http://www.mpii.de/yago/resource/Alphonse_Mucha>"); strings.push_back("<http://www.mpii.de/yago/resource/Algernon_Charles_Swinburne>"); strings.push_back("<http://www.mpii.de/yago/resource/Wallace_Stevens>"); strings.push_back("<http://www.mpii.de/yago/resource/Hartford,_Connecticut>"); strings.push_back("<http://www.mpii.de/yago/resource/Kirby_Puckett>"); strings.push_back("<http://www.mpii.de/yago/resource/Benito_Ju%C3%A1rez>"); strings.push_back("<http://www.mpii.de/yago/resource/Everett_Dirksen>"); strings.push_back("<http://www.mpii.de/yago/resource/Jean_Rhys>"); strings.push_back("<http://www.mpii.de/yago/resource/Exeter>"); strings.push_back("<http://www.mpii.de/yago/resource/Mary_Renault>"); strings.push_back("<http://www.mpii.de/yago/resource/Cape_Town>"); strings.push_back("<http://www.mpii.de/yago/resource/George_Abbott>"); strings.push_back("<http://www.mpii.de/yago/resource/Miami_Beach,_Florida>"); strings.push_back("<http://www.mpii.de/yago/resource/Gustav_IV_Adolf_of_Sweden>"); strings.push_back("<http://www.mpii.de/yago/resource/St._Gallen>"); strings.push_back("<http://www.mpii.de/yago/resource/Alf_Landon>"); strings.push_back("<http://www.mpii.de/yago/resource/Topeka,_Kansas>"); strings.push_back("<http://www.mpii.de/yago/resource/Heinrich_Heine>"); strings.push_back("<http://www.mpii.de/yago/resource/Frederick_of_Sweden>"); strings.push_back("<http://www.mpii.de/yago/resource/Ulrika_Eleonora_of_Sweden>"); strings.push_back("<http://www.mpii.de/yago/resource/Charles_X_Gustav_of_Sweden>"); strings.push_back("<http://www.mpii.de/yago/resource/Gothenburg>"); strings.push_back("<http://www.mpii.de/yago/resource/Charles_XII_of_Sweden>"); strings.push_back("<http://www.mpii.de/yago/resource/Halden>"); strings.push_back("<http://www.mpii.de/yago/resource/Leopold_Vietoris>"); strings.push_back("<http://www.mpii.de/yago/resource/Innsbruck>"); strings.push_back("<http://www.mpii.de/yago/resource/Charles_Whitman>"); strings.push_back("<http://www.mpii.de/yago/resource/Austin,_Texas>"); strings.push_back("<http://www.mpii.de/yago/resource/Jean_Renoir>"); strings.push_back("<http://www.mpii.de/yago/resource/George_B._McClellan>"); strings.push_back("<http://www.mpii.de/yago/resource/Orange,_New_Jersey>"); strings.push_back("<http://www.mpii.de/yago/resource/John_Singer_Sargent>"); strings.push_back("<http://www.mpii.de/yago/resource/Sofia_Kovalevskaya>"); strings.push_back("<http://www.mpii.de/yago/resource/Julian_Grenfell>"); strings.push_back("<http://www.mpii.de/yago/resource/Boulogne-sur-Mer>"); strings.push_back("<http://www.mpii.de/yago/resource/Samuel_Huntington_(statesman)>"); strings.push_back("<http://www.mpii.de/yago/resource/Norwich,_Connecticut>"); strings.push_back("<http://www.mpii.de/yago/resource/P%C3%A4r_Lagerkvist>"); strings.push_back("<http://www.mpii.de/yago/resource/Auguste_Piccard>"); strings.push_back("<http://www.mpii.de/yago/resource/Lou_Costello>"); strings.push_back("<http://www.mpii.de/yago/resource/Gustav_Heinemann>"); strings.push_back("<http://www.mpii.de/yago/resource/Essen>"); strings.push_back("<http://www.mpii.de/yago/resource/Joseph_Nathan_Kane>"); strings.push_back("<http://www.mpii.de/yago/resource/West_Palm_Beach,_Florida>"); strings.push_back("<http://www.mpii.de/yago/resource/Georg_Simmel>"); strings.push_back("<http://www.mpii.de/yago/resource/Strasbourg>"); strings.push_back("<http://www.mpii.de/yago/resource/Pierre_Bourdieu>"); strings.push_back("<http://www.mpii.de/yago/resource/Jos%C3%A9_Ferrer>"); strings.push_back("<http://www.mpii.de/yago/resource/Coral_Gables,_Florida>"); strings.push_back("<http://www.mpii.de/yago/resource/Wong_Fei-hung>"); strings.push_back("<http://www.mpii.de/yago/resource/Guangzhou>"); strings.push_back("<http://www.mpii.de/yago/resource/Roman_Tam>"); strings.push_back("<http://www.mpii.de/yago/resource/Howard_Keel>"); strings.push_back("<http://www.mpii.de/yago/resource/Palm_Desert,_California>"); strings.push_back("<http://www.mpii.de/yago/resource/W._O._Mitchell>"); strings.push_back("<http://www.mpii.de/yago/resource/Calgary>"); strings.push_back("<http://www.mpii.de/yago/resource/Wang_Jingwei>"); strings.push_back("<http://www.mpii.de/yago/resource/Nagoya>"); strings.push_back("<http://www.mpii.de/yago/resource/Gregory_Palamas>"); strings.push_back("<http://www.mpii.de/yago/resource/Thessaloniki>"); strings.push_back("<http://www.mpii.de/yago/resource/Mary_Baker_Eddy>"); strings.push_back("<http://www.mpii.de/yago/resource/Newton,_Massachusetts>"); strings.push_back("<http://www.mpii.de/yago/resource/Diana_Mitford>"); strings.push_back("<http://www.mpii.de/yago/resource/Hans_Fritzsche>"); strings.push_back("<http://www.mpii.de/yago/resource/Neil_Aspinall>"); strings.push_back("<http://www.mpii.de/yago/resource/Ezra_Stiles>"); strings.push_back("<http://www.mpii.de/yago/resource/Auguste_Comte>"); strings.push_back("<http://www.mpii.de/yago/resource/Sarojini_Naidu>"); strings.push_back("<http://www.mpii.de/yago/resource/Allahabad>"); strings.push_back("<http://www.mpii.de/yago/resource/Jesse_Helms>"); strings.push_back("<http://www.mpii.de/yago/resource/Raleigh,_North_Carolina>"); strings.push_back("<http://www.mpii.de/yago/resource/Adolph_Green>"); strings.push_back("<http://www.mpii.de/yago/resource/Lal_Bahadur_Shastri>"); strings.push_back("<http://www.mpii.de/yago/resource/Tashkent>"); strings.push_back("<http://www.mpii.de/yago/resource/Yasujir%C5%8D_Ozu>"); strings.push_back("<http://www.mpii.de/yago/resource/Fred_Rogers>"); strings.push_back("<http://www.mpii.de/yago/resource/Richard_Harris>"); strings.push_back("<http://www.mpii.de/yago/resource/Toshir%C5%8D_Mifune>"); strings.push_back("<http://www.mpii.de/yago/resource/Mitaka,_Tokyo>"); strings.push_back("<http://www.mpii.de/yago/resource/Tadeusz_Ko%C5%9Bciuszko>"); strings.push_back("<http://www.mpii.de/yago/resource/Solothurn>"); strings.push_back("<http://www.mpii.de/yago/resource/Khosrau_II>"); strings.push_back("<http://www.mpii.de/yago/resource/Ctesiphon>"); strings.push_back("<http://www.mpii.de/yago/resource/Hugh_Trevor-Roper>"); strings.push_back("<http://www.mpii.de/yago/resource/Yazdegerd_III>"); strings.push_back("<http://www.mpii.de/yago/resource/Merv>"); strings.push_back("<http://www.mpii.de/yago/resource/Shapur_II>"); strings.push_back("<http://www.mpii.de/yago/resource/Gordian_I>"); strings.push_back("<http://www.mpii.de/yago/resource/Carthage>"); strings.push_back("<http://www.mpii.de/yago/resource/Francesco_Redi>"); strings.push_back("<http://www.mpii.de/yago/resource/Giorgione>"); strings.push_back("<http://www.mpii.de/yago/resource/Rudolf_Virchow>"); strings.push_back("<http://www.mpii.de/yago/resource/Prince_William,_Duke_of_Cumberland>"); strings.push_back("<http://www.mpii.de/yago/resource/Michiel_de_Ruyter>"); strings.push_back("<http://www.mpii.de/yago/resource/Ronald_Fisher>"); strings.push_back("<http://www.mpii.de/yago/resource/Adelaide>"); strings.push_back("<http://www.mpii.de/yago/resource/Joe_Shuster>"); strings.push_back("<http://www.mpii.de/yago/resource/Robbie_Ross>"); strings.push_back("<http://www.mpii.de/yago/resource/William_II,_Prince_of_Orange>"); strings.push_back("<http://www.mpii.de/yago/resource/Enrico_De_Nicola>"); strings.push_back("<http://www.mpii.de/yago/resource/Torre_del_Greco>"); strings.push_back("<http://www.mpii.de/yago/resource/Lon_Chaney,_Jr.>"); strings.push_back("<http://www.mpii.de/yago/resource/San_Clemente,_California>"); strings.push_back("<http://www.mpii.de/yago/resource/Chang-Lin_Tien>"); strings.push_back("<http://www.mpii.de/yago/resource/Redwood_City,_California>"); strings.push_back("<http://www.mpii.de/yago/resource/Robert_Toombs>"); strings.push_back("<http://www.mpii.de/yago/resource/Washington,_Georgia>"); strings.push_back("<http://www.mpii.de/yago/resource/William_Godwin>"); strings.push_back("<http://www.mpii.de/yago/resource/Vivien_Merchant>"); strings.push_back("<http://www.mpii.de/yago/resource/Warner_Baxter>"); strings.push_back("<http://www.mpii.de/yago/resource/George_Bancroft>"); strings.push_back("<http://www.mpii.de/yago/resource/Douglas_Haig,_1st_Earl_Haig>"); strings.push_back("<http://www.mpii.de/yago/resource/Ronald_Colman>"); strings.push_back("<http://www.mpii.de/yago/resource/William_Hellier_Baily>"); strings.push_back("<http://www.mpii.de/yago/resource/Francis_Baily>"); strings.push_back("<http://www.mpii.de/yago/resource/Edward_Hodges_Baily>"); strings.push_back("<http://www.mpii.de/yago/resource/Tom_McCall>"); strings.push_back("<http://www.mpii.de/yago/resource/Portland,_Oregon>"); strings.push_back("<http://www.mpii.de/yago/resource/Saint_Mungo>"); strings.push_back("<http://www.mpii.de/yago/resource/William_Bainbridge>"); strings.push_back("<http://www.mpii.de/yago/resource/George_Thomas,_1st_Viscount_Tonypandy>"); strings.push_back("<http://www.mpii.de/yago/resource/Cardiff>"); strings.push_back("<http://www.mpii.de/yago/resource/Juan_Ponce_de_Le%C3%B3n>"); strings.push_back("<http://www.mpii.de/yago/resource/Havana>"); strings.push_back("<http://www.mpii.de/yago/resource/Pietro_Bembo>"); strings.push_back("<http://www.mpii.de/yago/resource/Jaroslav_Heyrovsk%C3%BD>"); strings.push_back("<http://www.mpii.de/yago/resource/Albert_Ballin>"); strings.push_back("<http://www.mpii.de/yago/resource/Emilio_Aguinaldo>"); strings.push_back("<http://www.mpii.de/yago/resource/Quezon_City>"); strings.push_back("<http://www.mpii.de/yago/resource/H._R._Haldeman>"); strings.push_back("<http://www.mpii.de/yago/resource/Lucius_Verus>"); strings.push_back("<http://www.mpii.de/yago/resource/Baldwin_III_of_Jerusalem>"); strings.push_back("<http://www.mpii.de/yago/resource/Adolphe_Menjou>"); strings.push_back("<http://www.mpii.de/yago/resource/Basiliscus>"); strings.push_back("<http://www.mpii.de/yago/resource/Manuel_I_of_Portugal>"); strings.push_back("<http://www.mpii.de/yago/resource/Dashiell_Hammett>"); strings.push_back("<http://www.mpii.de/yago/resource/Joan_Greenwood>"); strings.push_back("<http://www.mpii.de/yago/resource/Frank_Morgan>"); strings.push_back("<http://www.mpii.de/yago/resource/Yves_Saint_Laurent_(designer)>"); strings.push_back("<http://www.mpii.de/yago/resource/Marlene_Dietrich>"); strings.push_back("<http://www.mpii.de/yago/resource/Guy_of_Lusignan>"); strings.push_back("<http://www.mpii.de/yago/resource/Nicosia>"); strings.push_back("<http://www.mpii.de/yago/resource/Axel_Munthe>"); strings.push_back("<http://www.mpii.de/yago/resource/Paul_Lukas>"); strings.push_back("<http://www.mpii.de/yago/resource/Tangier>"); strings.push_back("<http://www.mpii.de/yago/resource/Jean-Baptiste_Lamarck>"); strings.push_back("<http://www.mpii.de/yago/resource/Austen_Henry_Layard>"); strings.push_back("<http://www.mpii.de/yago/resource/Margaret_Brown>"); strings.push_back("<http://www.mpii.de/yago/resource/Princess_Margaret_of_Connaught>"); strings.push_back("<http://www.mpii.de/yago/resource/Ine_of_Wessex>"); strings.push_back("<http://www.mpii.de/yago/resource/Andreas_Baader>"); strings.push_back("<http://www.mpii.de/yago/resource/Bob_Crane>"); strings.push_back("<http://www.mpii.de/yago/resource/Scottsdale,_Arizona>"); strings.push_back("<http://www.mpii.de/yago/resource/Francis_Maitland_Balfour>"); strings.push_back("<http://www.mpii.de/yago/resource/Chamonix>"); strings.push_back("<http://www.mpii.de/yago/resource/Albert_David>"); strings.push_back("<http://www.mpii.de/yago/resource/Norfolk,_Virginia>"); strings.push_back("<http://www.mpii.de/yago/resource/Trebonianus_Gallus>"); strings.push_back("<http://www.mpii.de/yago/resource/Terni>"); strings.push_back("<http://www.mpii.de/yago/resource/Sugar_Ray_Robinson>"); strings.push_back("<http://www.mpii.de/yago/resource/Culver_City,_California>"); strings.push_back("<http://www.mpii.de/yago/resource/Sh%C5%ABsui_K%C5%8Dtoku>"); strings.push_back("<http://www.mpii.de/yago/resource/George_Meade>"); strings.push_back("<http://www.mpii.de/yago/resource/Barry_Fitzgerald>"); strings.push_back("<http://www.mpii.de/yago/resource/Patrick_Hillery>"); strings.push_back("<http://www.mpii.de/yago/resource/George_Pickett>"); strings.push_back("<http://www.mpii.de/yago/resource/George_Dewey>"); strings.push_back("<http://www.mpii.de/yago/resource/Philip_the_Apostle>"); strings.push_back("<http://www.mpii.de/yago/resource/Emlyn_Williams>"); strings.push_back("<http://www.mpii.de/yago/resource/John_III_of_Portugal>"); strings.push_back("<http://www.mpii.de/yago/resource/Auguste_de_Montferrand>"); strings.push_back("<http://www.mpii.de/yago/resource/Mervyn_LeRoy>"); strings.push_back("<http://www.mpii.de/yago/resource/George_Stevens>"); strings.push_back("<http://www.mpii.de/yago/resource/Lancaster,_California>"); strings.push_back("<http://www.mpii.de/yago/resource/Alastair_Sim>"); strings.push_back("<http://www.mpii.de/yago/resource/Tex_Avery>"); strings.push_back("<http://www.mpii.de/yago/resource/George_Clinton_(vice_president)>"); strings.push_back("<http://www.mpii.de/yago/resource/Duncan_I_of_Scotland>"); strings.push_back("<http://www.mpii.de/yago/resource/Elgin,_Moray>"); strings.push_back("<http://www.mpii.de/yago/resource/Constantine_III_of_Scotland>"); strings.push_back("<http://www.mpii.de/yago/resource/Perth,_Scotland>"); strings.push_back("<http://www.mpii.de/yago/resource/Edgar_of_Scotland>"); strings.push_back("<http://www.mpii.de/yago/resource/James_M._Cox>"); strings.push_back("<http://www.mpii.de/yago/resource/Kettering,_Ohio>"); strings.push_back("<http://www.mpii.de/yago/resource/Ivan_I_of_Moscow>"); strings.push_back("<http://www.mpii.de/yago/resource/Simeon_of_Moscow>"); strings.push_back("<http://www.mpii.de/yago/resource/Vasily_II_of_Moscow>"); strings.push_back("<http://www.mpii.de/yago/resource/Feodor_I_of_Russia>"); strings.push_back("<http://www.mpii.de/yago/resource/Vasili_III_of_Russia>"); strings.push_back("<http://www.mpii.de/yago/resource/Feodor_III_of_Russia>"); strings.push_back("<http://www.mpii.de/yago/resource/Ivan_III_of_Russia>"); strings.push_back("<http://www.mpii.de/yago/resource/Robert_Michael_Ballantyne>"); strings.push_back("<http://www.mpii.de/yago/resource/Francis_I,_Holy_Roman_Emperor>"); strings.push_back("<http://www.mpii.de/yago/resource/Lucky_Luciano>"); strings.push_back("<http://www.mpii.de/yago/resource/James_B._Weaver>"); strings.push_back("<http://www.mpii.de/yago/resource/Des_Moines,_Iowa>"); strings.push_back("<http://www.mpii.de/yago/resource/Bugsy_Siegel>"); strings.push_back("<http://www.mpii.de/yago/resource/Dorothea_Dix>"); strings.push_back("<http://www.mpii.de/yago/resource/Trenton,_New_Jersey>"); strings.push_back("<http://www.mpii.de/yago/resource/Karl_Menger>"); strings.push_back("<http://www.mpii.de/yago/resource/Highland_Park,_Illinois>"); strings.push_back("<http://www.mpii.de/yago/resource/Charles_IV_of_Spain>"); strings.push_back("<http://www.mpii.de/yago/resource/Sonny_Liston>"); strings.push_back("<http://www.mpii.de/yago/resource/Las_Vegas,_Nevada>"); strings.push_back("<http://www.mpii.de/yago/resource/Wilhelm_Wien>"); strings.push_back("<http://www.mpii.de/yago/resource/Nathaniel_P._Banks>"); strings.push_back("<http://www.mpii.de/yago/resource/Waltham,_Massachusetts>"); strings.push_back("<http://www.mpii.de/yago/resource/Milutin_Milankovi%C4%87>"); strings.push_back("<http://www.mpii.de/yago/resource/Christian_V_of_Denmark>"); strings.push_back("<http://www.mpii.de/yago/resource/Frederick_VIII_of_Denmark>"); strings.push_back("<http://www.mpii.de/yago/resource/Angelica_Kauffmann>"); strings.push_back("<http://www.mpii.de/yago/resource/Paul_Emile_Lecoq_de_Boisbaudran>"); strings.push_back("<http://www.mpii.de/yago/resource/Frederick_IX_of_Denmark>"); strings.push_back("<http://www.mpii.de/yago/resource/Frederick_M._Smith>"); strings.push_back("<http://www.mpii.de/yago/resource/Independence,_Missouri>"); strings.push_back("<http://www.mpii.de/yago/resource/Jos%C3%A9_Celso_Barbosa>"); strings.push_back("<http://www.mpii.de/yago/resource/Vincent_Price>"); strings.push_back("<http://www.mpii.de/yago/resource/Stephen_Decatur>"); strings.push_back("<http://www.mpii.de/yago/resource/John_Law_(economist)>"); strings.push_back("<http://www.mpii.de/yago/resource/Paracelsus>"); strings.push_back("<http://www.mpii.de/yago/resource/Salzburg>"); strings.push_back("<http://www.mpii.de/yago/resource/Jean_Arp>"); strings.push_back("<http://www.mpii.de/yago/resource/Verne_Winchell>"); strings.push_back("<http://www.mpii.de/yago/resource/Alexander_Nevsky>"); strings.push_back("<http://www.mpii.de/yago/resource/Gorodets>"); strings.push_back("<http://www.mpii.de/yago/resource/Salvatore_Maranzano>"); strings.push_back("<http://www.mpii.de/yago/resource/Magda_Gabor>"); strings.push_back("<http://www.mpii.de/yago/resource/Kim_Dae-jung>"); strings.push_back("<http://www.mpii.de/yago/resource/Seoul>"); strings.push_back("<http://www.mpii.de/yago/resource/Elisabeth_of_Bavaria>"); strings.push_back("<http://www.mpii.de/yago/resource/Henry_Cabot_Lodge,_Jr.>"); strings.push_back("<http://www.mpii.de/yago/resource/Beverly,_Massachusetts>"); strings.push_back("<http://www.mpii.de/yago/resource/Henry_Cabot_Lodge>"); strings.push_back("<http://www.mpii.de/yago/resource/Hugh_Gaitskell>"); strings.push_back("<http://www.mpii.de/yago/resource/Luis_Mu%C3%B1oz_Mar%C3%ADn>"); strings.push_back("<http://www.mpii.de/yago/resource/Friedrich_Ernst_Dorn>"); strings.push_back("<http://www.mpii.de/yago/resource/Abraham_Beame>"); strings.push_back("<http://www.mpii.de/yago/resource/John_VI_of_Portugal>"); strings.push_back("<http://www.mpii.de/yago/resource/Theobald_of_Bec>"); strings.push_back("<http://www.mpii.de/yago/resource/Murray_Bookchin>"); strings.push_back("<http://www.mpii.de/yago/resource/Jorge_Porcel>"); strings.push_back("<http://www.mpii.de/yago/resource/Octave_Mirbeau>"); strings.push_back("<http://www.mpii.de/yago/resource/Sejanus>"); strings.push_back("<http://www.mpii.de/yago/resource/Romy_Schneider>"); strings.push_back("<http://www.mpii.de/yago/resource/Titian>"); strings.push_back("<http://www.mpii.de/yago/resource/Fritz_Perls>"); strings.push_back("<http://www.mpii.de/yago/resource/T%C5%8Dg%C5%8D_Heihachir%C5%8D>"); strings.push_back("<http://www.mpii.de/yago/resource/Broderick_Crawford>"); strings.push_back("<http://www.mpii.de/yago/resource/Rocky_Marciano>"); strings.push_back("<http://www.mpii.de/yago/resource/Newton,_Iowa>"); strings.push_back("<http://www.mpii.de/yago/resource/Rainier_III,_Prince_of_Monaco>"); strings.push_back("<http://www.mpii.de/yago/resource/Odysseas_Elytis>"); strings.push_back("<http://www.mpii.de/yago/resource/Giorgos_Seferis>"); strings.push_back("<http://www.mpii.de/yago/resource/Milton_H._Erickson>"); strings.push_back("<http://www.mpii.de/yago/resource/Sam_Walton>"); strings.push_back("<http://www.mpii.de/yago/resource/William_Reddington_Hewlett>"); strings.push_back("<http://www.mpii.de/yago/resource/Portola_Valley,_California>"); strings.push_back("<http://www.mpii.de/yago/resource/Frank_Forde>"); strings.push_back("<http://www.mpii.de/yago/resource/Brisbane>"); strings.push_back("<http://www.mpii.de/yago/resource/John_Curtin>"); strings.push_back("<http://www.mpii.de/yago/resource/Canberra>"); strings.push_back("<http://www.mpii.de/yago/resource/V%C3%A1clav_Prokop_Divi%C5%A1>"); strings.push_back("<http://www.mpii.de/yago/resource/Sandford_Fleming>"); strings.push_back("<http://www.mpii.de/yago/resource/City_of_Halifax>"); strings.push_back("<http://www.mpii.de/yago/resource/Christopher_Isherwood>"); strings.push_back("<http://www.mpii.de/yago/resource/William_de_Corbeil>"); strings.push_back("<http://www.mpii.de/yago/resource/Truman_Capote>"); strings.push_back("<http://www.mpii.de/yago/resource/Alexander_Prokhorov>"); strings.push_back("<http://www.mpii.de/yago/resource/Gilbert_du_Motier,_marquis_de_Lafayette>"); strings.push_back("<http://www.mpii.de/yago/resource/Thomas_Gold>"); strings.push_back("<http://www.mpii.de/yago/resource/Ilya_Ilyich_Mechnikov>"); strings.push_back("<http://www.mpii.de/yago/resource/John_Wilkins>"); strings.push_back("<http://www.mpii.de/yago/resource/Caspar_Weinberger>"); strings.push_back("<http://www.mpii.de/yago/resource/Swithun>"); strings.push_back("<http://www.mpii.de/yago/resource/Alexandre_Dumas,_p%C3%A8re>"); strings.push_back("<http://www.mpii.de/yago/resource/Dieppe,_Seine-Maritime>"); strings.push_back("<http://www.mpii.de/yago/resource/Mircea_Eliade>"); strings.push_back("<http://www.mpii.de/yago/resource/Karl_Schwarzschild>"); strings.push_back("<http://www.mpii.de/yago/resource/Ned_Kelly>"); strings.push_back("<http://www.mpii.de/yago/resource/John_William_Colenso>"); strings.push_back("<http://www.mpii.de/yago/resource/Durban>"); strings.push_back("<http://www.mpii.de/yago/resource/Edward_Bernays>"); strings.push_back("<http://www.mpii.de/yago/resource/Burl_Ives>"); strings.push_back("<http://www.mpii.de/yago/resource/Anacortes,_Washington>"); strings.push_back("<http://www.mpii.de/yago/resource/Adam_Mickiewicz>"); strings.push_back("<http://www.mpii.de/yago/resource/Istanbul>"); strings.push_back("<http://www.mpii.de/yago/resource/John_Edensor_Littlewood>"); strings.push_back("<http://www.mpii.de/yago/resource/Igor_of_Kiev>"); strings.push_back("<http://www.mpii.de/yago/resource/Korosten>"); strings.push_back("<http://www.mpii.de/yago/resource/Yaropolk_I_of_Kiev>"); strings.push_back("<http://www.mpii.de/yago/resource/Kaniv>"); strings.push_back("<http://www.mpii.de/yago/resource/Hyder_Ali>"); strings.push_back("<http://www.mpii.de/yago/resource/Chittoor>"); strings.push_back("<http://www.mpii.de/yago/resource/Harry_Nyquist>"); strings.push_back("<http://www.mpii.de/yago/resource/Harlingen,_Texas>"); strings.push_back("<http://www.mpii.de/yago/resource/Andr%C3%A9_Mass%C3%A9na>"); strings.push_back("<http://www.mpii.de/yago/resource/Julian_Beck>"); strings.push_back("<http://www.mpii.de/yago/resource/Pheidippides>"); strings.push_back("<http://www.mpii.de/yago/resource/Edgar_Cayce>"); strings.push_back("<http://www.mpii.de/yago/resource/Virginia_Beach>"); strings.push_back("<http://www.mpii.de/yago/resource/Akseli_Gallen-Kallela>"); strings.push_back("<http://www.mpii.de/yago/resource/Peter_Cushing>"); strings.push_back("<http://www.mpii.de/yago/resource/Italo_Svevo>"); strings.push_back("<http://www.mpii.de/yago/resource/Motta_di_Livenza>"); strings.push_back("<http://www.mpii.de/yago/resource/Max_Gaines>"); strings.push_back("<http://www.mpii.de/yago/resource/Lake_Placid,_New_York>"); strings.push_back("<http://www.mpii.de/yago/resource/Mahmoud_Hessaby>"); strings.push_back("<http://www.mpii.de/yago/resource/John_Smith_(Labour_Party_leader)>"); strings.push_back("<http://www.mpii.de/yago/resource/Caesar_Baronius>"); strings.push_back("<http://www.mpii.de/yago/resource/P._T._Barnum>"); strings.push_back("<http://www.mpii.de/yago/resource/Alexander_of_Greece_(king)>"); strings.push_back("<http://www.mpii.de/yago/resource/Constantine_I_of_Greece>"); strings.push_back("<http://www.mpii.de/yago/resource/Roberto_S%C3%A1nchez_Vilella>"); strings.push_back("<http://www.mpii.de/yago/resource/Wilson_Barrett>"); strings.push_back("<http://www.mpii.de/yago/resource/Andy_Devine>"); strings.push_back("<http://www.mpii.de/yago/resource/Orange,_California>"); strings.push_back("<http://www.mpii.de/yago/resource/Jonathan_Mayhew_Wainwright_IV>"); strings.push_back("<http://www.mpii.de/yago/resource/San_Antonio>"); strings.push_back("<http://www.mpii.de/yago/resource/Victor_Fleming>"); strings.push_back("<http://www.mpii.de/yago/resource/Cottonwood,_Arizona>"); strings.push_back("<http://www.mpii.de/yago/resource/Krzysztof_Kie%C5%9Blowski>"); strings.push_back("<http://www.mpii.de/yago/resource/Douglas_Hyde>"); strings.push_back("<http://www.mpii.de/yago/resource/Johnny_Appleseed>"); strings.push_back("<http://www.mpii.de/yago/resource/Fort_Wayne,_Indiana>"); strings.push_back("<http://www.mpii.de/yago/resource/Jean_Bart>"); strings.push_back("<http://www.mpii.de/yago/resource/Dunkirk>"); strings.push_back("<http://www.mpii.de/yago/resource/Gerd_von_Rundstedt>"); strings.push_back("<http://www.mpii.de/yago/resource/Lucy_Stone>"); strings.push_back("<http://www.mpii.de/yago/resource/Richard_K._Sutherland>"); strings.push_back("<http://www.mpii.de/yago/resource/Louis_II,_Prince_of_Monaco>"); strings.push_back("<http://www.mpii.de/yago/resource/Princess_Charlotte,_Duchess_of_Valentinois>"); strings.push_back("<http://www.mpii.de/yago/resource/Dan_O'Herlihy>"); strings.push_back("<http://www.mpii.de/yago/resource/Laurence_Harvey>"); strings.push_back("<http://www.mpii.de/yago/resource/Robert_Franklin_Stroud>"); strings.push_back("<http://www.mpii.de/yago/resource/Charles_II_of_Naples>"); strings.push_back("<http://www.mpii.de/yago/resource/Ladislaus_I_of_Hungary>"); strings.push_back("<http://www.mpii.de/yago/resource/Nitra>"); strings.push_back("<http://www.mpii.de/yago/resource/George_Roy_Hill>"); strings.push_back("<http://www.mpii.de/yago/resource/Jedediah_Smith>"); strings.push_back("<http://www.mpii.de/yago/resource/Ulysses,_Kansas>"); strings.push_back("<http://www.mpii.de/yago/resource/Vladimir_Mayakovsky>"); strings.push_back("<http://www.mpii.de/yago/resource/Maurice_Maeterlinck>"); strings.push_back("<http://www.mpii.de/yago/resource/Albert_I,_Prince_of_Monaco>"); strings.push_back("<http://www.mpii.de/yago/resource/Mark_Hanna>"); strings.push_back("<http://www.mpii.de/yago/resource/Samantha_Smith>"); strings.push_back("<http://www.mpii.de/yago/resource/Lewiston,_Maine>"); strings.push_back("<http://www.mpii.de/yago/resource/Richard_Brinsley_Sheridan>"); strings.push_back("<http://www.mpii.de/yago/resource/Naunton_Wayne>"); strings.push_back("<http://www.mpii.de/yago/resource/Octavio_Paz>"); strings.push_back("<http://www.mpii.de/yago/resource/Louis_Bl%C3%A9riot>"); strings.push_back("<http://www.mpii.de/yago/resource/Joan_Littlewood>"); strings.push_back("<http://www.mpii.de/yago/resource/Eurico_Gaspar_Dutra>"); strings.push_back("<http://www.mpii.de/yago/resource/Almon_Brown_Strowger>"); strings.push_back("<http://www.mpii.de/yago/resource/John_Winthrop>"); strings.push_back("<http://www.mpii.de/yago/resource/John_Boyd_(military_strategist)>"); strings.push_back("<http://www.mpii.de/yago/resource/Claude_Chappe>"); strings.push_back("<http://www.mpii.de/yago/resource/Philomena>"); strings.push_back("<http://www.mpii.de/yago/resource/Eamonn_Andrews>"); strings.push_back("<http://www.mpii.de/yago/resource/Charles_Pinckney_(governor)>"); strings.push_back("<http://www.mpii.de/yago/resource/Rafael_Trujillo>"); strings.push_back("<http://www.mpii.de/yago/resource/Fran%C3%A7ois_Mauriac>"); strings.push_back("<http://www.mpii.de/yago/resource/James_Whitmore>"); strings.push_back("<http://www.mpii.de/yago/resource/John_Caius>"); strings.push_back("<http://www.mpii.de/yago/resource/Marcello_Mastroianni>"); strings.push_back("<http://www.mpii.de/yago/resource/Walther_Rathenau>"); strings.push_back("<http://www.mpii.de/yago/resource/Willa_Cather>"); strings.push_back("<http://www.mpii.de/yago/resource/Joe_Foss>"); strings.push_back("<http://www.mpii.de/yago/resource/Gottfried_Kinkel>"); strings.push_back("<http://www.mpii.de/yago/resource/Michael_Hordern>"); strings.push_back("<http://www.mpii.de/yago/resource/John_Earle_(bishop)>"); strings.push_back("<http://www.mpii.de/yago/resource/Pierre_Puvis_de_Chavannes>"); strings.push_back("<http://www.mpii.de/yago/resource/Roy_Scheider>"); strings.push_back("<http://www.mpii.de/yago/resource/Ivan_Bunin>"); strings.push_back("<http://www.mpii.de/yago/resource/Chesty_Puller>"); strings.push_back("<http://www.mpii.de/yago/resource/Hampton,_Virginia>"); strings.push_back("<http://www.mpii.de/yago/resource/Ky%C3%B6sti_Kallio>"); strings.push_back("<http://www.mpii.de/yago/resource/Lauri_Kristian_Relander>"); strings.push_back("<http://www.mpii.de/yago/resource/Juho_Kusti_Paasikivi>"); strings.push_back("<http://www.mpii.de/yago/resource/Mika_Waltari>"); strings.push_back("<http://www.mpii.de/yago/resource/Kaarlo_Juho_St%C3%A5hlberg>"); strings.push_back("<http://www.mpii.de/yago/resource/Risto_Ryti>"); strings.push_back("<http://www.mpii.de/yago/resource/Roy_O._Disney>"); strings.push_back("<http://www.mpii.de/yago/resource/Odilon_Redon>"); strings.push_back("<http://www.mpii.de/yago/resource/Izaak_Walton>"); strings.push_back("<http://www.mpii.de/yago/resource/Carl_Gustaf_Emil_Mannerheim>"); strings.push_back("<http://www.mpii.de/yago/resource/William_Gilbert>"); strings.push_back("<http://www.mpii.de/yago/resource/Gale_Storm>"); strings.push_back("<http://www.mpii.de/yago/resource/Danville,_California>"); strings.push_back("<http://www.mpii.de/yago/resource/Roy_E._Disney>"); strings.push_back("<http://www.mpii.de/yago/resource/Cyrus_Vance>"); strings.push_back("<http://www.mpii.de/yago/resource/Bernard_le_Bovier_de_Fontenelle>"); strings.push_back("<http://www.mpii.de/yago/resource/Sid_Gillman>"); strings.push_back("<http://www.mpii.de/yago/resource/Carlsbad,_California>"); strings.push_back("<http://www.mpii.de/yago/resource/Felicia_Hemans>"); strings.push_back("<http://www.mpii.de/yago/resource/Lucian>"); strings.push_back("<http://www.mpii.de/yago/resource/Cornelius_Vanderbilt>"); strings.push_back("<http://www.mpii.de/yago/resource/Gaston_Eyskens>"); strings.push_back("<http://www.mpii.de/yago/resource/Leuven>"); strings.push_back("<http://www.mpii.de/yago/resource/Fran%C3%A7ois-Ren%C3%A9_de_Chateaubriand>"); strings.push_back("<http://www.mpii.de/yago/resource/Immanuel_Hermann_Fichte>"); strings.push_back("<http://www.mpii.de/yago/resource/Conrad_Hall>"); strings.push_back("<http://www.mpii.de/yago/resource/Rudi_Dornbusch>"); strings.push_back("<http://www.mpii.de/yago/resource/Omar_Bradley>"); strings.push_back("<http://www.mpii.de/yago/resource/Pierre_Boulle>"); strings.push_back("<http://www.mpii.de/yago/resource/Allan_Kardec>"); strings.push_back("<http://www.mpii.de/yago/resource/Ludwig_I_of_Bavaria>"); strings.push_back("<http://www.mpii.de/yago/resource/Alan_Freed>"); strings.push_back("<http://www.mpii.de/yago/resource/Edwin_Thompson_Jaynes>"); strings.push_back("<http://www.mpii.de/yago/resource/Eugene_McCarthy>"); strings.push_back("<http://www.mpii.de/yago/resource/Walter_Cronkite>"); strings.push_back("<http://www.mpii.de/yago/resource/Alfredo_Stroessner>"); strings.push_back("<http://www.mpii.de/yago/resource/Bras%C3%ADlia>"); strings.push_back("<http://www.mpii.de/yago/resource/Alan_Sillitoe>"); strings.push_back("<http://www.mpii.de/yago/resource/Stanley_Bruce>"); strings.push_back("<http://www.mpii.de/yago/resource/Jacques_Plante>"); strings.push_back("<http://www.mpii.de/yago/resource/Alexander_Korda>"); strings.push_back("<http://www.mpii.de/yago/resource/Artturi_Ilmari_Virtanen>"); strings.push_back("<http://www.mpii.de/yago/resource/Helena_Blavatsky>"); strings.push_back("<http://www.mpii.de/yago/resource/Larry_Gene_Ashbrook>"); strings.push_back("<http://www.mpii.de/yago/resource/Fort_Worth,_Texas>"); strings.push_back("<http://www.mpii.de/yago/resource/Denholm_Elliott>"); strings.push_back("<http://www.mpii.de/yago/resource/Ibiza>"); strings.push_back("<http://www.mpii.de/yago/resource/Daniel_O'Connell>"); strings.push_back("<http://www.mpii.de/yago/resource/Franjo_Tu%C4%91man>"); strings.push_back("<http://www.mpii.de/yago/resource/Zagreb>"); strings.push_back("<http://www.mpii.de/yago/resource/Eric_of_Pomerania>"); strings.push_back("<http://www.mpii.de/yago/resource/Dar%C5%82owo>"); strings.push_back("<http://www.mpii.de/yago/resource/C._Douglas_Dillon>"); strings.push_back("<http://www.mpii.de/yago/resource/JonBen%C3%A9t_Ramsey>"); strings.push_back("<http://www.mpii.de/yago/resource/Lazzaro_Spallanzani>"); strings.push_back("<http://www.mpii.de/yago/resource/Pavia>"); strings.push_back("<http://www.mpii.de/yago/resource/Hans_Adolf_Krebs>"); strings.push_back("<http://www.mpii.de/yago/resource/Alan_Bates>"); strings.push_back("<http://www.mpii.de/yago/resource/City_of_Westminster>"); strings.push_back("<http://www.mpii.de/yago/resource/Luis_Bu%C3%B1uel>"); strings.push_back("<http://www.mpii.de/yago/resource/Jacques_Charles>"); strings.push_back("<http://www.mpii.de/yago/resource/Max_Delbr%C3%BCck>"); strings.push_back("<http://www.mpii.de/yago/resource/Jacques_Mesrine>"); strings.push_back("<http://www.mpii.de/yago/resource/Abraham-Louis_Breguet>"); strings.push_back("<http://www.mpii.de/yago/resource/Eug%C3%A8ne_Delacroix>"); strings.push_back("<http://www.mpii.de/yago/resource/Aleksandr_Kolchak>"); strings.push_back("<http://www.mpii.de/yago/resource/Irkutsk>"); strings.push_back("<http://www.mpii.de/yago/resource/George_Curzon,_1st_Marquess_Curzon_of_Kedleston>"); strings.push_back("<http://www.mpii.de/yago/resource/Princess_Ingeborg_of_Denmark>"); strings.push_back("<http://www.mpii.de/yago/resource/Alphonse_de_Lamartine>"); strings.push_back("<http://www.mpii.de/yago/resource/Jeremy_Brett>"); strings.push_back("<http://www.mpii.de/yago/resource/Peter_Finch>"); strings.push_back("<http://www.mpii.de/yago/resource/August_Wilson>"); strings.push_back("<http://www.mpii.de/yago/resource/Irving_Thalberg>"); strings.push_back("<http://www.mpii.de/yago/resource/Jomo_Kenyatta>"); strings.push_back("<http://www.mpii.de/yago/resource/Mombasa>"); strings.push_back("<http://www.mpii.de/yago/resource/Arcesilaus>"); strings.push_back("<http://www.mpii.de/yago/resource/Cleanthes>"); strings.push_back("<http://www.mpii.de/yago/resource/John_Reith,_1st_Baron_Reith>"); strings.push_back("<http://www.mpii.de/yago/resource/David_Bomberg>"); strings.push_back("<http://www.mpii.de/yago/resource/Henry_Pelham>"); strings.push_back("<http://www.mpii.de/yago/resource/Joseph_Wheeler>"); strings.push_back("<http://www.mpii.de/yago/resource/Al_Hirschfeld>"); strings.push_back("<http://www.mpii.de/yago/resource/Harry_Von_Tilzer>"); strings.push_back("<http://www.mpii.de/yago/resource/Peter_Medawar>"); strings.push_back("<http://www.mpii.de/yago/resource/Ruth_Chatterton>"); strings.push_back("<http://www.mpii.de/yago/resource/Norwalk,_Connecticut>"); strings.push_back("<http://www.mpii.de/yago/resource/Jeanne_Eagels>"); strings.push_back("<http://www.mpii.de/yago/resource/John_Dickson_Carr>"); strings.push_back("<http://www.mpii.de/yago/resource/Greenville,_South_Carolina>"); strings.push_back("<http://www.mpii.de/yago/resource/Al_Smith>"); strings.push_back("<http://www.mpii.de/yago/resource/Julius_Vogel>"); strings.push_back("<http://www.mpii.de/yago/resource/Linda_McCartney>"); strings.push_back("<http://www.mpii.de/yago/resource/Luis_Vigoreaux>"); strings.push_back("<http://www.mpii.de/yago/resource/Jack_Valenti>"); strings.push_back("<http://www.mpii.de/yago/resource/Walther_Funk>"); strings.push_back("<http://www.mpii.de/yago/resource/D%C3%BCsseldorf>"); strings.push_back("<http://www.mpii.de/yago/resource/Harold_Lloyd>"); strings.push_back("<http://www.mpii.de/yago/resource/Clare_Boothe_Luce>"); strings.push_back("<http://www.mpii.de/yago/resource/Dennis_Gabor>"); strings.push_back("<http://www.mpii.de/yago/resource/John_DeLorean>"); strings.push_back("<http://www.mpii.de/yago/resource/Summit,_New_Jersey>"); strings.push_back("<http://www.mpii.de/yago/resource/Calvin_Bridges>"); strings.push_back("<http://www.mpii.de/yago/resource/Ferdinand_I_of_the_Two_Sicilies>"); strings.push_back("<http://www.mpii.de/yago/resource/Nell_Carter>"); strings.push_back("<http://www.mpii.de/yago/resource/Bill_Mauldin>"); strings.push_back("<http://www.mpii.de/yago/resource/Sarah_Knauss>"); strings.push_back("<http://www.mpii.de/yago/resource/Allentown,_Pennsylvania>"); strings.push_back("<http://www.mpii.de/yago/resource/Octavia_E._Butler>"); strings.push_back("<http://www.mpii.de/yago/resource/Lake_Forest_Park,_Washington>"); strings.push_back("<http://www.mpii.de/yago/resource/Edwin_H._Land>"); strings.push_back("<http://www.mpii.de/yago/resource/Ladislaus_Bortkiewicz>"); strings.push_back("<http://www.mpii.de/yago/resource/David_Hartley_(philosopher)>"); strings.push_back("<http://www.mpii.de/yago/resource/Daniel_Massey_(actor)>"); strings.push_back("<http://www.mpii.de/yago/resource/Kuroda_Kiyotaka>"); strings.push_back("<http://www.mpii.de/yago/resource/Matsukata_Masayoshi>"); strings.push_back("<http://www.mpii.de/yago/resource/Yamagata_Aritomo>"); strings.push_back("<http://www.mpii.de/yago/resource/Kat%C5%8D_Tomosabur%C5%8D>"); strings.push_back("<http://www.mpii.de/yago/resource/Takahashi_Korekiyo>"); strings.push_back("<http://www.mpii.de/yago/resource/Hara_Takashi>"); strings.push_back("<http://www.mpii.de/yago/resource/Kiyoura_Keigo>"); strings.push_back("<http://www.mpii.de/yago/resource/Wakatsuki_Reijir%C5%8D>"); strings.push_back("<http://www.mpii.de/yago/resource/Kat%C5%8D_Takaaki>"); strings.push_back("<http://www.mpii.de/yago/resource/Osachi_Hamaguchi>"); strings.push_back("<http://www.mpii.de/yago/resource/Tanaka_Giichi>"); strings.push_back("<http://www.mpii.de/yago/resource/Inukai_Tsuyoshi>"); strings.push_back("<http://www.mpii.de/yago/resource/Senj%C5%ABr%C5%8D_Hayashi>"); strings.push_back("<http://www.mpii.de/yago/resource/Hiranuma_Kiichir%C5%8D>"); strings.push_back("<http://www.mpii.de/yago/resource/Sait%C5%8D_Makoto>"); strings.push_back("<http://www.mpii.de/yago/resource/Kij%C5%ABr%C5%8D_Shidehara>"); strings.push_back("<http://www.mpii.de/yago/resource/Kuniaki_Koiso>"); strings.push_back("<http://www.mpii.de/yago/resource/Shigeru_Yoshida>"); strings.push_back("<http://www.mpii.de/yago/resource/Prince_Higashikuni_Naruhiko>"); strings.push_back("<http://www.mpii.de/yago/resource/Terauchi_Masatake>"); strings.push_back("<http://www.mpii.de/yago/resource/Hayato_Ikeda>"); strings.push_back("<http://www.mpii.de/yago/resource/Zenko_Suzuki>"); strings.push_back("<http://www.mpii.de/yago/resource/Eisaku_Sat%C5%8D>"); strings.push_back("<http://www.mpii.de/yago/resource/S%C5%8Dsuke_Uno>"); strings.push_back("<http://www.mpii.de/yago/resource/Moriyama,_Shiga>"); strings.push_back("<http://www.mpii.de/yago/resource/%C5%8Ckuma_Shigenobu>"); strings.push_back("<http://www.mpii.de/yago/resource/David_Low_(cartoonist)>"); strings.push_back("<http://www.mpii.de/yago/resource/Prescott_Bush>"); strings.push_back("<http://www.mpii.de/yago/resource/James_Chadwick>"); strings.push_back("<http://www.mpii.de/yago/resource/Fritz_Haber>"); strings.push_back("<http://www.mpii.de/yago/resource/Carl_Bosch>"); strings.push_back("<http://www.mpii.de/yago/resource/Thomas_Browne>"); strings.push_back("<http://www.mpii.de/yago/resource/Norwich>"); strings.push_back("<http://www.mpii.de/yago/resource/George_Grenville>"); strings.push_back("<http://www.mpii.de/yago/resource/Nancy_Carroll>"); strings.push_back("<http://www.mpii.de/yago/resource/Willem_Drost>"); strings.push_back("<http://www.mpii.de/yago/resource/Bessie_Love>"); strings.push_back("<http://www.mpii.de/yago/resource/David_Hampton>"); strings.push_back("<http://www.mpii.de/yago/resource/Passaic,_New_Jersey>"); strings.push_back("<http://www.mpii.de/yago/resource/Medgar_Evers>"); strings.push_back("<http://www.mpii.de/yago/resource/Jackson,_Mississippi>"); strings.push_back("<http://www.mpii.de/yago/resource/Jean_Piccard>"); strings.push_back("<http://www.mpii.de/yago/resource/Minneapolis>"); strings.push_back("<http://www.mpii.de/yago/resource/Diego_Vel%C3%A1zquez_de_Cu%C3%A9llar>"); strings.push_back("<http://www.mpii.de/yago/resource/Santiago_de_Cuba>"); strings.push_back("<http://www.mpii.de/yago/resource/Bartolom%C3%A9_Esteban_Murillo>"); strings.push_back("<http://www.mpii.de/yago/resource/John_of_Denmark>"); strings.push_back("<http://www.mpii.de/yago/resource/Aalborg>"); strings.push_back("<http://www.mpii.de/yago/resource/Tom_Van_Flandern>"); strings.push_back("<http://www.mpii.de/yago/resource/Sequim,_Washington>"); strings.push_back("<http://www.mpii.de/yago/resource/Jean_Louis_Marie_Poiseuille>"); strings.push_back("<http://www.mpii.de/yago/resource/Urbain_Le_Verrier>"); strings.push_back("<http://www.mpii.de/yago/resource/John_Couch_Adams>"); strings.push_back("<http://www.mpii.de/yago/resource/Leon_Czolgosz>"); strings.push_back("<http://www.mpii.de/yago/resource/Stephen_Foster>"); strings.push_back("<http://www.mpii.de/yago/resource/Roger_Babson>"); strings.push_back("<http://www.mpii.de/yago/resource/Lake_Wales,_Florida>"); strings.push_back("<http://www.mpii.de/yago/resource/Tot%C3%B2>"); strings.push_back("<http://www.mpii.de/yago/resource/Tom_C._Clark>"); strings.push_back("<http://www.mpii.de/yago/resource/Buster_Crabbe>"); strings.push_back("<http://www.mpii.de/yago/resource/Zip_the_Pinhead>"); strings.push_back("<http://www.mpii.de/yago/resource/Charles_Wesley>"); strings.push_back("<http://www.mpii.de/yago/resource/J._R._D._Tata>"); strings.push_back("<http://www.mpii.de/yago/resource/Sextus_Empiricus>"); strings.push_back("<http://www.mpii.de/yago/resource/Hans_Eysenck>"); strings.push_back("<http://www.mpii.de/yago/resource/Marianne_Moore>"); strings.push_back("<http://www.mpii.de/yago/resource/Diana_Wynyard>"); strings.push_back("<http://www.mpii.de/yago/resource/Elisabeth_Bergner>"); strings.push_back("<http://www.mpii.de/yago/resource/John_Breckinridge_(Attorney_General)>"); strings.push_back("<http://www.mpii.de/yago/resource/Jan_Toorop>"); strings.push_back("<http://www.mpii.de/yago/resource/Jacobus_Kapteyn>"); strings.push_back("<http://www.mpii.de/yago/resource/John_A._Logan>"); strings.push_back("<http://www.mpii.de/yago/resource/Cesare_Lombroso>"); strings.push_back("<http://www.mpii.de/yago/resource/%C3%89mile_Nelligan>"); strings.push_back("<http://www.mpii.de/yago/resource/Sergei_Bondarchuk>"); strings.push_back("<http://www.mpii.de/yago/resource/Art_Linkletter>"); strings.push_back("<http://www.mpii.de/yago/resource/Per_Albin_Hansson>"); strings.push_back("<http://www.mpii.de/yago/resource/Alistair_Cooke>"); strings.push_back("<http://www.mpii.de/yago/resource/Duk_Koo_Kim>"); strings.push_back("<http://www.mpii.de/yago/resource/Harvey_Fletcher>"); strings.push_back("<http://www.mpii.de/yago/resource/Jean_Baptiste_Joseph_Delambre>"); strings.push_back("<http://www.mpii.de/yago/resource/Whittaker_Chambers>"); strings.push_back("<http://www.mpii.de/yago/resource/Westminster,_Maryland>"); strings.push_back("<http://www.mpii.de/yago/resource/G%C3%A9rard_de_Nerval>"); strings.push_back("<http://www.mpii.de/yago/resource/Geoffrey_II,_Duke_of_Brittany>"); strings.push_back("<http://www.mpii.de/yago/resource/James_Dickey>"); strings.push_back("<http://www.mpii.de/yago/resource/Columbia,_South_Carolina>"); strings.push_back("<http://www.mpii.de/yago/resource/Saul_Alinsky>"); strings.push_back("<http://www.mpii.de/yago/resource/Jiddu_Krishnamurti>"); strings.push_back("<http://www.mpii.de/yago/resource/Ojai,_California>"); strings.push_back("<http://www.mpii.de/yago/resource/Joseph_Joffre>"); strings.push_back("<http://www.mpii.de/yago/resource/Margaret_Sullavan>"); strings.push_back("<http://www.mpii.de/yago/resource/Friedrich_Carl_von_Savigny>"); strings.push_back("<http://www.mpii.de/yago/resource/Gummo_Marx>"); strings.push_back("<http://www.mpii.de/yago/resource/Charles_R._Drew>"); strings.push_back("<http://www.mpii.de/yago/resource/Burlington,_North_Carolina>"); strings.push_back("<http://www.mpii.de/yago/resource/Adolphe_Niel>"); strings.push_back("<http://www.mpii.de/yago/resource/Eyvind_Johnson>"); strings.push_back("<http://www.mpii.de/yago/resource/Marcus_Garvey>"); strings.push_back("<http://www.mpii.de/yago/resource/Thomas_Robert_Bugeaud>"); strings.push_back("<http://www.mpii.de/yago/resource/William_Hobson>"); strings.push_back("<http://www.mpii.de/yago/resource/Auckland>"); strings.push_back("<http://www.mpii.de/yago/resource/Georges_Simenon>"); strings.push_back("<http://www.mpii.de/yago/resource/Khalil_Gibran>"); strings.push_back("<http://www.mpii.de/yago/resource/Victoria_of_Baden>"); strings.push_back("<http://www.mpii.de/yago/resource/Jozef_Tiso>"); strings.push_back("<http://www.mpii.de/yago/resource/Bratislava>"); strings.push_back("<http://www.mpii.de/yago/resource/Mansfield_Smith-Cumming>"); strings.push_back("<http://www.mpii.de/yago/resource/Levi_Eshkol>"); strings.push_back("<http://www.mpii.de/yago/resource/Richard_Jordan_Gatling>"); strings.push_back("<http://www.mpii.de/yago/resource/June_Havoc>"); strings.push_back("<http://www.mpii.de/yago/resource/Stamford,_Connecticut>"); strings.push_back("<http://www.mpii.de/yago/resource/Anders_Zorn>"); strings.push_back("<http://www.mpii.de/yago/resource/Eddie_Rickenbacker>"); strings.push_back("<http://www.mpii.de/yago/resource/Lothair_II_of_Lotharingia>"); strings.push_back("<http://www.mpii.de/yago/resource/Piacenza>"); strings.push_back("<http://www.mpii.de/yago/resource/Idries_Shah>"); strings.push_back("<http://www.mpii.de/yago/resource/Walter_Winchell>"); strings.push_back("<http://www.mpii.de/yago/resource/Billy_Mitchell>"); strings.push_back("<http://www.mpii.de/yago/resource/Maya_Deren>"); strings.push_back("<http://www.mpii.de/yago/resource/Jaime_Escalante>"); strings.push_back("<http://www.mpii.de/yago/resource/Roseville,_California>"); strings.push_back("<http://www.mpii.de/yago/resource/Josiah_Harmar>"); strings.push_back("<http://www.mpii.de/yago/resource/Alexei_Nikolaevich,_Tsarevich_of_Russia>"); strings.push_back("<http://www.mpii.de/yago/resource/Elijah_McCoy>"); strings.push_back("<http://www.mpii.de/yago/resource/V%C3%A4in%C3%B6_Linna>"); strings.push_back("<http://www.mpii.de/yago/resource/Tampere>"); strings.push_back("<http://www.mpii.de/yago/resource/Nellie_Bly>"); strings.push_back("<http://www.mpii.de/yago/resource/Hans_Bethe>"); strings.push_back("<http://www.mpii.de/yago/resource/Douglas_Shearer>"); strings.push_back("<http://www.mpii.de/yago/resource/David_Bohm>"); strings.push_back("<http://www.mpii.de/yago/resource/Shimaki_Kensaku>"); strings.push_back("<http://www.mpii.de/yago/resource/Kamakura,_Kanagawa>"); strings.push_back("<http://www.mpii.de/yago/resource/It%C5%8D_Sachio>"); strings.push_back("<http://www.mpii.de/yago/resource/Kunikida_Doppo>"); strings.push_back("<http://www.mpii.de/yago/resource/Osamu_Dazai>"); strings.push_back("<http://www.mpii.de/yago/resource/Yumeno_Ky%C5%ABsaku>"); strings.push_back("<http://www.mpii.de/yago/resource/Motojir%C5%8D_Kajii>"); strings.push_back("<http://www.mpii.de/yago/resource/Osaka>"); strings.push_back("<http://www.mpii.de/yago/resource/Kenji_Miyazawa>"); strings.push_back("<http://www.mpii.de/yago/resource/Hanamaki,_Iwate>"); strings.push_back("<http://www.mpii.de/yago/resource/Osho_(Bhagwan_Shree_Rajneesh)>"); strings.push_back("<http://www.mpii.de/yago/resource/Robin_Cook>"); strings.push_back("<http://www.mpii.de/yago/resource/Shelley_Winters>"); strings.push_back("<http://www.mpii.de/yago/resource/Edward_Rutledge>"); strings.push_back("<http://www.mpii.de/yago/resource/Arthur_Coles>"); strings.push_back("<http://www.mpii.de/yago/resource/Jeanne_Crain>"); strings.push_back("<http://www.mpii.de/yago/resource/George_I_of_Greece>"); strings.push_back("<http://www.mpii.de/yago/resource/Maggie_McNamara>"); strings.push_back("<http://www.mpii.de/yago/resource/Hideki_Yukawa>"); strings.push_back("<http://www.mpii.de/yago/resource/Natsume_S%C5%8Dseki>"); strings.push_back("<http://www.mpii.de/yago/resource/Christopher_of_Bavaria>"); strings.push_back("<http://www.mpii.de/yago/resource/Helsingborg>"); strings.push_back("<http://www.mpii.de/yago/resource/Chandragupta_Maurya>"); strings.push_back("<http://www.mpii.de/yago/resource/Shravanabelagola>"); strings.push_back("<http://www.mpii.de/yago/resource/Hakush%C5%AB_Kitahara>"); strings.push_back("<http://www.mpii.de/yago/resource/Jan_Tinbergen>"); strings.push_back("<http://www.mpii.de/yago/resource/Franz_B%C3%A4ke>"); strings.push_back("<http://www.mpii.de/yago/resource/Hagen>"); strings.push_back("<http://www.mpii.de/yago/resource/Max_Fleischer>"); strings.push_back("<http://www.mpii.de/yago/resource/Ruby_Keeler>"); strings.push_back("<http://www.mpii.de/yago/resource/Alberto_Sordi>"); strings.push_back("<http://www.mpii.de/yago/resource/Chaim_Weizmann>"); strings.push_back("<http://www.mpii.de/yago/resource/Rehovot>"); strings.push_back("<http://www.mpii.de/yago/resource/Jack_Warner_(actor)>"); strings.push_back("<http://www.mpii.de/yago/resource/Jacques_de_Molay>"); strings.push_back("<http://www.mpii.de/yago/resource/Carl_Auer_von_Welsbach>"); strings.push_back("<http://www.mpii.de/yago/resource/M%C3%B6lbling>"); strings.push_back("<http://www.mpii.de/yago/resource/Christian_Herter>"); strings.push_back("<http://www.mpii.de/yago/resource/George-%C3%89tienne_Cartier>"); strings.push_back("<http://www.mpii.de/yago/resource/Hidemitsu_Tanaka>"); strings.push_back("<http://www.mpii.de/yago/resource/Louis-Hippolyte_Lafontaine>"); strings.push_back("<http://www.mpii.de/yago/resource/Anna_Magnani>"); strings.push_back("<http://www.mpii.de/yago/resource/Maurice_Duplessis>"); strings.push_back("<http://www.mpii.de/yago/resource/Schefferville,_Quebec>"); strings.push_back("<http://www.mpii.de/yago/resource/Frank_Winfield_Woolworth>"); strings.push_back("<http://www.mpii.de/yago/resource/Glen_Cove,_New_York>"); strings.push_back("<http://www.mpii.de/yago/resource/Vladislav_Listyev>"); strings.push_back("<http://www.mpii.de/yago/resource/Kuno_Fischer>"); strings.push_back("<http://www.mpii.de/yago/resource/Rudolf_Hermann_Lotze>"); strings.push_back("<http://www.mpii.de/yago/resource/Michael_Servetus>"); strings.push_back("<http://www.mpii.de/yago/resource/Juliette_Gordon_Low>"); strings.push_back("<http://www.mpii.de/yago/resource/Savannah,_Georgia>"); strings.push_back("<http://www.mpii.de/yago/resource/Otto_H%C3%B6lder>"); strings.push_back("<http://www.mpii.de/yago/resource/John_Joly>"); strings.push_back("<http://www.mpii.de/yago/resource/Antoine_J%C3%A9r%C3%B4me_Balard>"); strings.push_back("<http://www.mpii.de/yago/resource/Antoine_Fran%C3%A7ois,_comte_de_Fourcroy>"); strings.push_back("<http://www.mpii.de/yago/resource/Darryl_F._Zanuck>"); strings.push_back("<http://www.mpii.de/yago/resource/%C5%8Cyama_Iwao>"); strings.push_back("<http://www.mpii.de/yago/resource/Jacob_Jordaens>"); strings.push_back("<http://www.mpii.de/yago/resource/Antwerp>"); strings.push_back("<http://www.mpii.de/yago/resource/James_K._Baxter>"); strings.push_back("<http://www.mpii.de/yago/resource/Joe_Rosenthal>"); strings.push_back("<http://www.mpii.de/yago/resource/Novato,_California>"); strings.push_back("<http://www.mpii.de/yago/resource/Bill_Werbeniuk>"); strings.push_back("<http://www.mpii.de/yago/resource/Abraham_Fischer>"); strings.push_back("<http://www.mpii.de/yago/resource/Margherita_of_Savoy>"); strings.push_back("<http://www.mpii.de/yago/resource/Bordighera>"); strings.push_back("<http://www.mpii.de/yago/resource/Jean-Jacques_Dessalines>"); strings.push_back("<http://www.mpii.de/yago/resource/Melina_Mercouri>"); strings.push_back("<http://www.mpii.de/yago/resource/Anna_Pavlovna_of_Russia>"); strings.push_back("<http://www.mpii.de/yago/resource/Spike_Jones>"); strings.push_back("<http://www.mpii.de/yago/resource/Raymond_Carver>"); strings.push_back("<http://www.mpii.de/yago/resource/Port_Angeles,_Washington>"); strings.push_back("<http://www.mpii.de/yago/resource/Theodore_von_K%C3%A1rm%C3%A1n>"); strings.push_back("<http://www.mpii.de/yago/resource/Madame_de_Pompadour>"); strings.push_back("<http://www.mpii.de/yago/resource/Madame_du_Barry>"); strings.push_back("<http://www.mpii.de/yago/resource/Lawrence_of_Rome>"); strings.push_back("<http://www.mpii.de/yago/resource/Per_Borten>"); strings.push_back("<http://www.mpii.de/yago/resource/Trondheim>"); strings.push_back("<http://www.mpii.de/yago/resource/Henry_Ireton>"); strings.push_back("<http://www.mpii.de/yago/resource/Limerick>"); strings.push_back("<http://www.mpii.de/yago/resource/Tauno_Palo>"); strings.push_back("<http://www.mpii.de/yago/resource/Faisal_I_of_Iraq>"); strings.push_back("<http://www.mpii.de/yago/resource/Leonid_Kantorovich>"); strings.push_back("<http://www.mpii.de/yago/resource/Beryl_Markham>"); strings.push_back("<http://www.mpii.de/yago/resource/Nairobi>"); strings.push_back("<http://www.mpii.de/yago/resource/Sammy_Davis,_Jr.>"); strings.push_back("<http://www.mpii.de/yago/resource/Mihai_Eminescu>"); strings.push_back("<http://www.mpii.de/yago/resource/Zoran_%C4%90in%C4%91i%C4%87>"); strings.push_back("<http://www.mpii.de/yago/resource/Pierre_Gaspard_Chaumette>"); strings.push_back("<http://www.mpii.de/yago/resource/Rose_Wilder_Lane>"); strings.push_back("<http://www.mpii.de/yago/resource/Laura_Ingalls_Wilder>"); strings.push_back("<http://www.mpii.de/yago/resource/Mansfield,_Missouri>"); strings.push_back("<http://www.mpii.de/yago/resource/Jos%C3%A9_Clemente_Orozco>"); strings.push_back("<http://www.mpii.de/yago/resource/Edwin_Drake>"); strings.push_back("<http://www.mpii.de/yago/resource/Bethlehem,_Pennsylvania>"); strings.push_back("<http://www.mpii.de/yago/resource/Ida_M._Tarbell>"); strings.push_back("<http://www.mpii.de/yago/resource/Jacob_Aaron_Westervelt>"); strings.push_back("<http://www.mpii.de/yago/resource/Pierre_Louis_Maupertuis>"); strings.push_back("<http://www.mpii.de/yago/resource/J%C3%A9r%C3%B4me_Lalande>"); strings.push_back("<http://www.mpii.de/yago/resource/Alija_Izetbegovi%C4%87>"); strings.push_back("<http://www.mpii.de/yago/resource/Sarajevo>"); strings.push_back("<http://www.mpii.de/yago/resource/William_Joseph_Donovan>"); strings.push_back("<http://www.mpii.de/yago/resource/Edwin_Arlington_Robinson>"); strings.push_back("<http://www.mpii.de/yago/resource/Nicholas_Saunderson>"); strings.push_back("<http://www.mpii.de/yago/resource/Gilles_de_Roberval>"); strings.push_back("<http://www.mpii.de/yago/resource/Friz_Freleng>"); strings.push_back("<http://www.mpii.de/yago/resource/Nils_Ericson>"); strings.push_back("<http://www.mpii.de/yago/resource/Rachel_Corrie>"); strings.push_back("<http://www.mpii.de/yago/resource/Rafah>"); strings.push_back("<http://www.mpii.de/yago/resource/Johan_Ludvig_Runeberg>"); strings.push_back("<http://www.mpii.de/yago/resource/Porvoo>"); strings.push_back("<http://www.mpii.de/yago/resource/B._R._Ambedkar>"); strings.push_back("<http://www.mpii.de/yago/resource/Wilhelm_von_Gloeden>"); strings.push_back("<http://www.mpii.de/yago/resource/Taormina>"); strings.push_back("<http://www.mpii.de/yago/resource/Hans_Lippershey>"); strings.push_back("<http://www.mpii.de/yago/resource/Middelburg>"); strings.push_back("<http://www.mpii.de/yago/resource/Jessica_Dubroff>"); strings.push_back("<http://www.mpii.de/yago/resource/Cheyenne,_Wyoming>"); strings.push_back("<http://www.mpii.de/yago/resource/Robert_McKimson>"); strings.push_back("<http://www.mpii.de/yago/resource/Bob_Clampett>"); strings.push_back("<http://www.mpii.de/yago/resource/David_Sarnoff>"); strings.push_back("<http://www.mpii.de/yago/resource/John_Harvard_(clergyman)>"); strings.push_back("<http://www.mpii.de/yago/resource/Charlestown,_Boston>"); strings.push_back("<http://www.mpii.de/yago/resource/Lucian_Truscott>"); strings.push_back("<http://www.mpii.de/yago/resource/Alexandria,_Virginia>"); strings.push_back("<http://www.mpii.de/yago/resource/Otto_Frank>"); strings.push_back("<http://www.mpii.de/yago/resource/Birsfelden>"); strings.push_back("<http://www.mpii.de/yago/resource/Michael_Smith_(chemist)>"); strings.push_back("<http://www.mpii.de/yago/resource/Paul_Tibbets>"); strings.push_back("<http://www.mpii.de/yago/resource/Bettie_Page>"); strings.push_back("<http://www.mpii.de/yago/resource/Bernard_Dowiyogo>"); strings.push_back("<http://www.mpii.de/yago/resource/Kiichi_Miyazawa>"); strings.push_back("<http://www.mpii.de/yago/resource/Empress_K%C5%8Djun>"); strings.push_back("<http://www.mpii.de/yago/resource/Ibn_Arabi>"); strings.push_back("<http://www.mpii.de/yago/resource/Henry_Thomas_Colebrooke>"); strings.push_back("<http://www.mpii.de/yago/resource/Francesco_Scipione,_marchese_di_Maffei>"); strings.push_back("<http://www.mpii.de/yago/resource/Harry_Martinson>"); strings.push_back("<http://www.mpii.de/yago/resource/Johann_Joachim_Winckelmann>"); strings.push_back("<http://www.mpii.de/yago/resource/Benjamin_Tillman>"); strings.push_back("<http://www.mpii.de/yago/resource/William_Orlando_Darby>"); strings.push_back("<http://www.mpii.de/yago/resource/Trento>"); strings.push_back("<http://www.mpii.de/yago/resource/George_Winterton>"); strings.push_back("<http://www.mpii.de/yago/resource/Matti_Pellonp%C3%A4%C3%A4>"); strings.push_back("<http://www.mpii.de/yago/resource/Vaasa>"); strings.push_back("<http://www.mpii.de/yago/resource/Gordon_R._Dickson>"); strings.push_back("<http://www.mpii.de/yago/resource/Richfield,_Minnesota>"); strings.push_back("<http://www.mpii.de/yago/resource/Archibald_Wavell,_1st_Earl_Wavell>"); strings.push_back("<http://www.mpii.de/yago/resource/Rani_Lakshmibai>"); strings.push_back("<http://www.mpii.de/yago/resource/Gwalior>"); strings.push_back("<http://www.mpii.de/yago/resource/Daniel_Patrick_Moynihan>"); strings.push_back("<http://www.mpii.de/yago/resource/Richard_Pearse>"); strings.push_back("<http://www.mpii.de/yago/resource/Christchurch>"); strings.push_back("<http://www.mpii.de/yago/resource/Carl_Zeiss>"); strings.push_back("<http://www.mpii.de/yago/resource/Jena>"); strings.push_back("<http://www.mpii.de/yago/resource/Rodolfo_Graziani>"); strings.push_back("<http://www.mpii.de/yago/resource/George_du_Maurier>"); strings.push_back("<http://www.mpii.de/yago/resource/Gustaf_Bonde>"); strings.push_back("<http://www.mpii.de/yago/resource/Eliza_Lynch>"); strings.push_back("<http://www.mpii.de/yago/resource/Agnes_Moorehead>"); strings.push_back("<http://www.mpii.de/yago/resource/Rochester,_Minnesota>"); strings.push_back("<http://www.mpii.de/yago/resource/Capucine>"); strings.push_back("<http://www.mpii.de/yago/resource/Rosemary_Sutcliff>"); strings.push_back("<http://www.mpii.de/yago/resource/Daniel_Pearl>"); strings.push_back("<http://www.mpii.de/yago/resource/Karachi>"); strings.push_back("<http://www.mpii.de/yago/resource/Richard_Evelyn_Byrd>"); strings.push_back("<http://www.mpii.de/yago/resource/Gustav_Fechner>"); strings.push_back("<http://www.mpii.de/yago/resource/Abdullah_I_of_Jordan>"); strings.push_back("<http://www.mpii.de/yago/resource/Richard_O'Connor>"); strings.push_back("<http://www.mpii.de/yago/resource/Ch%C3%B6gyam_Trungpa>"); strings.push_back("<http://www.mpii.de/yago/resource/Johann_Christoph_Gottsched>"); strings.push_back("<http://www.mpii.de/yago/resource/Friedrich_Heinrich_Jacobi>"); strings.push_back("<http://www.mpii.de/yago/resource/Algis_Budrys>"); strings.push_back("<http://www.mpii.de/yago/resource/Hafez>"); strings.push_back("<http://www.mpii.de/yago/resource/Shiraz>"); strings.push_back("<http://www.mpii.de/yago/resource/Oskar_Kokoschka>"); strings.push_back("<http://www.mpii.de/yago/resource/Jacob_Radcliff>"); strings.push_back("<http://www.mpii.de/yago/resource/Troy,_New_York>"); strings.push_back("<http://www.mpii.de/yago/resource/Soong_Ching-ling>"); strings.push_back("<http://www.mpii.de/yago/resource/Helge_Ingstad>"); strings.push_back("<http://www.mpii.de/yago/resource/Frederick_Muhlenberg>"); strings.push_back("<http://www.mpii.de/yago/resource/John_Redmond>"); strings.push_back("<http://www.mpii.de/yago/resource/Thomas_Disch>"); strings.push_back("<http://www.mpii.de/yago/resource/Matthew_C._Perry>"); strings.push_back("<http://www.mpii.de/yago/resource/Joan_I_of_Naples>"); strings.push_back("<http://www.mpii.de/yago/resource/San_Fele>"); strings.push_back("<http://www.mpii.de/yago/resource/Valentin_Pavlov>"); strings.push_back("<http://www.mpii.de/yago/resource/Christian_Gottfried_Ehrenberg>"); strings.push_back("<http://www.mpii.de/yago/resource/Hjalmar_Siilasvuo>"); strings.push_back("<http://www.mpii.de/yago/resource/Oulu>"); strings.push_back("<http://www.mpii.de/yago/resource/Ian_Smith>"); strings.push_back("<http://www.mpii.de/yago/resource/Gabriel_Gustafsson_Oxenstierna>"); strings.push_back("<http://www.mpii.de/yago/resource/William_Whewell>"); strings.push_back("<http://www.mpii.de/yago/resource/Mary_Augusta_Ward>"); strings.push_back("<http://www.mpii.de/yago/resource/Lester_del_Rey>"); strings.push_back("<http://www.mpii.de/yago/resource/Oscar_Micheaux>"); strings.push_back("<http://www.mpii.de/yago/resource/Charlotte,_North_Carolina>"); strings.push_back("<http://www.mpii.de/yago/resource/Calouste_Gulbenkian>"); strings.push_back("<http://www.mpii.de/yago/resource/Jo_Grimond>"); strings.push_back("<http://www.mpii.de/yago/resource/Clifford_D._Simak>"); strings.push_back("<http://www.mpii.de/yago/resource/Ian_Hamilton_Finlay>"); strings.push_back("<http://www.mpii.de/yago/resource/Henry_H._Arnold>"); strings.push_back("<http://www.mpii.de/yago/resource/Sonoma,_California>"); strings.push_back("<http://www.mpii.de/yago/resource/Isaac_Todhunter>"); strings.push_back("<http://www.mpii.de/yago/resource/Liane_Haid>"); strings.push_back("<http://www.mpii.de/yago/resource/Johanna_Spyri>"); strings.push_back("<http://www.mpii.de/yago/resource/Elizabeth_Smart_(author)>"); strings.push_back("<http://www.mpii.de/yago/resource/Nikolai_Kibalchich>"); strings.push_back("<http://www.mpii.de/yago/resource/William_Moultrie>"); strings.push_back("<http://www.mpii.de/yago/resource/Albert_Lebrun>"); strings.push_back("<http://www.mpii.de/yago/resource/Mirabeau_B._Lamar>"); strings.push_back("<http://www.mpii.de/yago/resource/Richmond,_Texas>"); strings.push_back("<http://www.mpii.de/yago/resource/Brandon_Lee>"); strings.push_back("<http://www.mpii.de/yago/resource/Wilmington,_North_Carolina>"); strings.push_back("<http://www.mpii.de/yago/resource/Jan_Santini_Aichel>"); strings.push_back("<http://www.mpii.de/yago/resource/David_Halberstam>"); strings.push_back("<http://www.mpii.de/yago/resource/Menlo_Park,_California>"); strings.push_back("<http://www.mpii.de/yago/resource/P._B._S._Pinchback>"); strings.push_back("<http://www.mpii.de/yago/resource/Jean-Baptiste-Camille_Corot>"); strings.push_back("<http://www.mpii.de/yago/resource/Edmund_Allenby,_1st_Viscount_Allenby>"); strings.push_back("<http://www.mpii.de/yago/resource/Austin_Osman_Spare>"); strings.push_back("<http://www.mpii.de/yago/resource/Georges_Bataille>"); strings.push_back("<http://www.mpii.de/yago/resource/Pieter_Zeeman>"); strings.push_back("<http://www.mpii.de/yago/resource/Gustave_Courbet>"); strings.push_back("<http://www.mpii.de/yago/resource/La_Tour-de-Peilz>"); strings.push_back("<http://www.mpii.de/yago/resource/Charles_Edison>"); strings.push_back("<http://www.mpii.de/yago/resource/A._Bertram_Chandler>"); strings.push_back("<http://www.mpii.de/yago/resource/%C3%86lfweard_of_Wessex>"); strings.push_back("<http://www.mpii.de/yago/resource/Lennart_Torstenson>"); strings.push_back("<http://www.mpii.de/yago/resource/Peter_II_of_Yugoslavia>"); strings.push_back("<http://www.mpii.de/yago/resource/Denver>"); strings.push_back("<http://www.mpii.de/yago/resource/Alphaeus_Philemon_Cole>"); strings.push_back("<http://www.mpii.de/yago/resource/Rachel_Roberts_(actress)>"); strings.push_back("<http://www.mpii.de/yago/resource/Erik_Dahlbergh>"); strings.push_back("<http://www.mpii.de/yago/resource/Carl_Gustav_Jacob_Jacobi>"); strings.push_back("<http://www.mpii.de/yago/resource/William_E._Simon>"); strings.push_back("<http://www.mpii.de/yago/resource/Henry_Briggs_(mathematician)>"); strings.push_back("<http://www.mpii.de/yago/resource/Brook_Taylor>"); strings.push_back("<http://www.mpii.de/yago/resource/Kray_twins>"); strings.push_back("<http://www.mpii.de/yago/resource/Richard_of_Conisburgh,_3rd_Earl_of_Cambridge>"); strings.push_back("<http://www.mpii.de/yago/resource/Southampton>"); strings.push_back("<http://www.mpii.de/yago/resource/Kalevi_Sorsa>"); strings.push_back("<http://www.mpii.de/yago/resource/Sarah_Louise_Delany>"); strings.push_back("<http://www.mpii.de/yago/resource/Mount_Vernon,_New_York>"); strings.push_back("<http://www.mpii.de/yago/resource/Derek_Nimmo>"); strings.push_back("<http://www.mpii.de/yago/resource/Frank_Aiken>"); strings.push_back("<http://www.mpii.de/yago/resource/Charles-Augustin_de_Coulomb>"); strings.push_back("<http://www.mpii.de/yago/resource/Richard_Sorge>"); strings.push_back("<http://www.mpii.de/yago/resource/Noah_Porter>"); strings.push_back("<http://www.mpii.de/yago/resource/Thomas_of_Woodstock,_1st_Duke_of_Gloucester>"); strings.push_back("<http://www.mpii.de/yago/resource/Calais>"); strings.push_back("<http://www.mpii.de/yago/resource/John_Hersey>"); strings.push_back("<http://www.mpii.de/yago/resource/Key_West,_Florida>"); strings.push_back("<http://www.mpii.de/yago/resource/Henry_Edward_Manning>"); strings.push_back("<http://www.mpii.de/yago/resource/George_Stokes,_1st_Baronet>"); strings.push_back("<http://www.mpii.de/yago/resource/Murder_of_Laci_Peterson>"); strings.push_back("<http://www.mpii.de/yago/resource/Tung_Chao_Yung>"); strings.push_back("<http://www.mpii.de/yago/resource/James_Short_(mathematician)>"); strings.push_back("<http://www.mpii.de/yago/resource/Alexander_Radishchev>"); strings.push_back("<http://www.mpii.de/yago/resource/Frederick_William_II_of_Prussia>"); strings.push_back("<http://www.mpii.de/yago/resource/Sergei_Witte>"); strings.push_back("<http://www.mpii.de/yago/resource/Arnold_Sommerfeld>"); strings.push_back("<http://www.mpii.de/yago/resource/Mark_O._Barton>"); strings.push_back("<http://www.mpii.de/yago/resource/Acworth,_Georgia>"); strings.push_back("<http://www.mpii.de/yago/resource/L%C3%A9on_Foucault>"); strings.push_back("<http://www.mpii.de/yago/resource/Canaletto>"); strings.push_back("<http://www.mpii.de/yago/resource/Pyotr_Stolypin>"); strings.push_back("<http://www.mpii.de/yago/resource/Andrew_Cunanan>"); strings.push_back("<http://www.mpii.de/yago/resource/Piero_della_Francesca>"); strings.push_back("<http://www.mpii.de/yago/resource/Sansepolcro>"); strings.push_back("<http://www.mpii.de/yago/resource/Dennis_O'Keefe>"); strings.push_back("<http://www.mpii.de/yago/resource/Gentile_da_Fabriano>"); strings.push_back("<http://www.mpii.de/yago/resource/Andrea_del_Verrocchio>"); strings.push_back("<http://www.mpii.de/yago/resource/Edsel_Ford>"); strings.push_back("<http://www.mpii.de/yago/resource/Grosse_Pointe_Shores,_Michigan>"); strings.push_back("<http://www.mpii.de/yago/resource/Jeanne_Mance>"); strings.push_back("<http://www.mpii.de/yago/resource/Essad_Pasha>"); strings.push_back("<http://www.mpii.de/yago/resource/Friedrich_de_la_Motte_Fouqu%C3%A9>"); strings.push_back("<http://www.mpii.de/yago/resource/P._L._Travers>"); strings.push_back("<http://www.mpii.de/yago/resource/Thomas_de_Hartmann>"); strings.push_back("<http://www.mpii.de/yago/resource/Vincent_Gigante>"); strings.push_back("<http://www.mpii.de/yago/resource/Bernard_Katz>"); strings.push_back("<http://www.mpii.de/yago/resource/William_Clark_(explorer)>"); strings.push_back("<http://www.mpii.de/yago/resource/Kirk_Fordice>"); strings.push_back("<http://www.mpii.de/yago/resource/Miles_Malleson>"); strings.push_back("<http://www.mpii.de/yago/resource/Devika_Rani>"); strings.push_back("<http://www.mpii.de/yago/resource/Bangalore>"); strings.push_back("<http://www.mpii.de/yago/resource/Lady_Bird_Johnson>"); strings.push_back("<http://www.mpii.de/yago/resource/West_Lake_Hills,_Texas>"); strings.push_back("<http://www.mpii.de/yago/resource/Judah_P._Benjamin>"); strings.push_back("<http://www.mpii.de/yago/resource/Friedrich_Gottlieb_Klopstock>"); strings.push_back("<http://www.mpii.de/yago/resource/Moshe_Sharett>"); strings.push_back("<http://www.mpii.de/yago/resource/Flinders_Petrie>"); strings.push_back("<http://www.mpii.de/yago/resource/Leo_Ornstein>"); strings.push_back("<http://www.mpii.de/yago/resource/Green_Bay,_Wisconsin>"); strings.push_back("<http://www.mpii.de/yago/resource/Carl_Schurz>"); strings.push_back("<http://www.mpii.de/yago/resource/Amos_T._Akerman>"); strings.push_back("<http://www.mpii.de/yago/resource/Cartersville,_Georgia>"); strings.push_back("<http://www.mpii.de/yago/resource/Ross_Barnett>"); strings.push_back("<http://www.mpii.de/yago/resource/Sukarno>"); strings.push_back("<http://www.mpii.de/yago/resource/Jakarta>"); strings.push_back("<http://www.mpii.de/yago/resource/William_Beveridge>"); strings.push_back("<http://www.mpii.de/yago/resource/Suharto>"); strings.push_back("<http://www.mpii.de/yago/resource/Zebulon_Pike>"); strings.push_back("<http://www.mpii.de/yago/resource/York,_Upper_Canada>"); strings.push_back("<http://www.mpii.de/yago/resource/Aldo_Leopold>"); strings.push_back("<http://www.mpii.de/yago/resource/Baraboo,_Wisconsin>"); strings.push_back("<http://www.mpii.de/yago/resource/Carrie_Snodgress>"); strings.push_back("<http://www.mpii.de/yago/resource/John_C._Stennis>"); strings.push_back("<http://www.mpii.de/yago/resource/Benjamin_G._Humphreys>"); strings.push_back("<http://www.mpii.de/yago/resource/Jeremy_Michael_Boorda>"); strings.push_back("<http://www.mpii.de/yago/resource/Henry_Clinton_(American_War_of_Independence)>"); strings.push_back("<http://www.mpii.de/yago/resource/William_Howe,_5th_Viscount_Howe>"); strings.push_back("<http://www.mpii.de/yago/resource/Plymouth>"); strings.push_back("<http://www.mpii.de/yago/resource/Ralph_Bates>"); strings.push_back("<http://www.mpii.de/yago/resource/John_L._Lewis>"); strings.push_back("<http://www.mpii.de/yago/resource/Donato_Bramante>"); strings.push_back("<http://www.mpii.de/yago/resource/Adelbert_Ames>"); strings.push_back("<http://www.mpii.de/yago/resource/Ormond_Beach,_Florida>"); strings.push_back("<http://www.mpii.de/yago/resource/Walter_Lantz>"); strings.push_back("<http://www.mpii.de/yago/resource/Frederick_William_III_of_Prussia>"); strings.push_back("<http://www.mpii.de/yago/resource/James_Gregory_(mathematician)>"); strings.push_back("<http://www.mpii.de/yago/resource/Martti_Miettunen>"); strings.push_back("<http://www.mpii.de/yago/resource/Lauri_Ingman>"); strings.push_back("<http://www.mpii.de/yago/resource/Turku>"); strings.push_back("<http://www.mpii.de/yago/resource/Dionysius_Lardner>"); strings.push_back("<http://www.mpii.de/yago/resource/Christian_F%C3%BCrchtegott_Gellert>"); strings.push_back("<http://www.mpii.de/yago/resource/Charlotte_Corday>"); strings.push_back("<http://www.mpii.de/yago/resource/Walter_Johnson>"); strings.push_back("<http://www.mpii.de/yago/resource/Ernest_Gellner>"); strings.push_back("<http://www.mpii.de/yago/resource/Woodbridge_Nathan_Ferris>"); strings.push_back("<http://www.mpii.de/yago/resource/Bonar_Law>"); strings.push_back("<http://www.mpii.de/yago/resource/Deng_Yingchao>"); strings.push_back("<http://www.mpii.de/yago/resource/Richard_Cumberland_(dramatist)>"); strings.push_back("<http://www.mpii.de/yago/resource/Sarah_Siddons>"); strings.push_back("<http://www.mpii.de/yago/resource/H%C5%8Dnen>"); strings.push_back("<http://www.mpii.de/yago/resource/Geoffrey_Perkins>"); strings.push_back("<http://www.mpii.de/yago/resource/Igor_Kurchatov>"); strings.push_back("<http://www.mpii.de/yago/resource/John_Flaxman>"); strings.push_back("<http://www.mpii.de/yago/resource/Andr%C3%A9s_Rodr%C3%ADguez_(President)>"); strings.push_back("<http://www.mpii.de/yago/resource/Mildred_Gillars>"); strings.push_back("<http://www.mpii.de/yago/resource/Nicol%C3%A1s_Guill%C3%A9n>"); strings.push_back("<http://www.mpii.de/yago/resource/Wall_Doxey>"); strings.push_back("<http://www.mpii.de/yago/resource/Pat_Harrison>"); strings.push_back("<http://www.mpii.de/yago/resource/Harald_Cram%C3%A9r>"); strings.push_back("<http://www.mpii.de/yago/resource/Marcus_Daly>"); strings.push_back("<http://www.mpii.de/yago/resource/Benny_Paret>"); strings.push_back("<http://www.mpii.de/yago/resource/Thomas_Hutchinson_(governor)>"); strings.push_back("<http://www.mpii.de/yago/resource/Dorothy_Gish>"); strings.push_back("<http://www.mpii.de/yago/resource/Rapallo>"); strings.push_back("<http://www.mpii.de/yago/resource/John_Opie>"); strings.push_back("<http://www.mpii.de/yago/resource/David_Hunter>"); strings.push_back("<http://www.mpii.de/yago/resource/Emanuel_Swedenborg>"); strings.push_back("<http://www.mpii.de/yago/resource/Russell_B._Long>"); strings.push_back("<http://www.mpii.de/yago/resource/Georges_Lema%C3%AEtre>"); strings.push_back("<http://www.mpii.de/yago/resource/Fred_G._Aandahl>"); strings.push_back("<http://www.mpii.de/yago/resource/Valley_City,_North_Dakota>"); strings.push_back("<http://www.mpii.de/yago/resource/Walker_Evans>"); strings.push_back("<http://www.mpii.de/yago/resource/Carl_Adam_Petri>"); strings.push_back("<http://www.mpii.de/yago/resource/Siegburg>"); strings.push_back("<http://www.mpii.de/yago/resource/Bronis%C5%82aw_Malinowski>"); strings.push_back("<http://www.mpii.de/yago/resource/Harry_Kendall_Thaw>"); strings.push_back("<http://www.mpii.de/yago/resource/Sri_Chinmoy>"); strings.push_back("<http://www.mpii.de/yago/resource/Saint_Dismas>"); strings.push_back("<http://www.mpii.de/yago/resource/Sam_Wanamaker>"); strings.push_back("<http://www.mpii.de/yago/resource/Gene_Sarazen>"); strings.push_back("<http://www.mpii.de/yago/resource/William_Franklin>"); strings.push_back("<http://www.mpii.de/yago/resource/John_Savage_(politician)>"); strings.push_back("<http://www.mpii.de/yago/resource/Dartmouth,_Nova_Scotia>"); strings.push_back("<http://www.mpii.de/yago/resource/G._M._Trevelyan>"); strings.push_back("<http://www.mpii.de/yago/resource/Sid_Davis>"); strings.push_back("<http://www.mpii.de/yago/resource/Nikolaus_Otto>"); strings.push_back("<http://www.mpii.de/yago/resource/James_A._Michener>"); strings.push_back("<http://www.mpii.de/yago/resource/Charles_Eliot_Norton>"); strings.push_back("<http://www.mpii.de/yago/resource/Joachim_Neander>"); strings.push_back("<http://www.mpii.de/yago/resource/Prince_Sadruddin_Aga_Khan>"); strings.push_back("<http://www.mpii.de/yago/resource/Robert_Bosch>"); strings.push_back("<http://www.mpii.de/yago/resource/Rudolf_Christoph_Eucken>"); strings.push_back("<http://www.mpii.de/yago/resource/Friedrich_Miescher>"); strings.push_back("<http://www.mpii.de/yago/resource/Davos>"); strings.push_back("<http://www.mpii.de/yago/resource/Ruth_Handler>"); strings.push_back("<http://www.mpii.de/yago/resource/Tikhon_of_Moscow>"); strings.push_back("<http://www.mpii.de/yago/resource/Martin_Buber>"); strings.push_back("<http://www.mpii.de/yago/resource/Karl_Barth>"); strings.push_back("<http://www.mpii.de/yago/resource/Irving_Kristol>"); strings.push_back("<http://www.mpii.de/yago/resource/Douglas_Fairbanks,_Jr.>"); strings.push_back("<http://www.mpii.de/yago/resource/Douglas_Fairbanks>"); strings.push_back("<http://www.mpii.de/yago/resource/Noel_Godfrey_Chavasse>"); strings.push_back("<http://www.mpii.de/yago/resource/Brandhoek>"); strings.push_back("<http://www.mpii.de/yago/resource/Stanis%C5%82aw_Szukalski>"); strings.push_back("<http://www.mpii.de/yago/resource/Fielding_L._Wright>"); strings.push_back("<http://www.mpii.de/yago/resource/Michel_Ney>"); strings.push_back("<http://www.mpii.de/yago/resource/William_Hepworth_Thompson>"); strings.push_back("<http://www.mpii.de/yago/resource/Stephen_Hopkins_(politician)>"); strings.push_back("<http://www.mpii.de/yago/resource/Norman_McLaren>"); strings.push_back("<http://www.mpii.de/yago/resource/Fan_S._Noli>"); strings.push_back("<http://www.mpii.de/yago/resource/Paul_B._Johnson,_Sr.>"); strings.push_back("<http://www.mpii.de/yago/resource/Hattiesburg,_Mississippi>"); strings.push_back("<http://www.mpii.de/yago/resource/John_Bell_Williams>"); strings.push_back("<http://www.mpii.de/yago/resource/Brandon,_Mississippi>"); strings.push_back("<http://www.mpii.de/yago/resource/Paul_B._Johnson,_Jr.>"); strings.push_back("<http://www.mpii.de/yago/resource/Robert_Morris_(financier)>"); strings.push_back("<http://www.mpii.de/yago/resource/Lo%C3%AFc_Leferme>"); strings.push_back("<http://www.mpii.de/yago/resource/Villefranche-sur-Mer>"); strings.push_back("<http://www.mpii.de/yago/resource/Willem_Frederik_Hermans>"); strings.push_back("<http://www.mpii.de/yago/resource/Ayub_Khan>"); strings.push_back("<http://www.mpii.de/yago/resource/Islamabad>"); strings.push_back("<http://www.mpii.de/yago/resource/Johannes_Diderik_van_der_Waals>"); strings.push_back("<http://www.mpii.de/yago/resource/Charles_Francis_Richter>"); strings.push_back("<http://www.mpii.de/yago/resource/Zhu_De>"); strings.push_back("<http://www.mpii.de/yago/resource/Jean_Baudrillard>"); strings.push_back("<http://www.mpii.de/yago/resource/Edward_Augustus_Freeman>"); strings.push_back("<http://www.mpii.de/yago/resource/Alicante>"); strings.push_back("<http://www.mpii.de/yago/resource/James_K._Vardaman>"); strings.push_back("<http://www.mpii.de/yago/resource/Birmingham,_Alabama>"); strings.push_back("<http://www.mpii.de/yago/resource/Tenzing_Norgay>"); strings.push_back("<http://www.mpii.de/yago/resource/Darjeeling>"); strings.push_back("<http://www.mpii.de/yago/resource/Frederick_Rolfe>"); strings.push_back("<http://www.mpii.de/yago/resource/Giacomo_Casanova>"); strings.push_back("<http://www.mpii.de/yago/resource/Duchcov>"); strings.push_back("<http://www.mpii.de/yago/resource/Hong_Xiuquan>"); strings.push_back("<http://www.mpii.de/yago/resource/Nanjing>"); strings.push_back("<http://www.mpii.de/yago/resource/Maybelle_Carter>"); strings.push_back("<http://www.mpii.de/yago/resource/Ben_Turpin>"); strings.push_back("<http://www.mpii.de/yago/resource/Antonio_del_Pollaiolo>"); strings.push_back("<http://www.mpii.de/yago/resource/Niels_Ryberg_Finsen>"); strings.push_back("<http://www.mpii.de/yago/resource/John_Bigelow>"); strings.push_back("<http://www.mpii.de/yago/resource/Ernest_Manning>"); strings.push_back("<http://www.mpii.de/yago/resource/Hugh_Trenchard,_1st_Viscount_Trenchard>"); strings.push_back("<http://www.mpii.de/yago/resource/Vincent_Massey>"); strings.push_back("<http://www.mpii.de/yago/resource/Herbert_Greenfield>"); strings.push_back("<http://www.mpii.de/yago/resource/John_Edward_Brownlee>"); strings.push_back("<http://www.mpii.de/yago/resource/Diogenes_of_Sinope>"); strings.push_back("<http://www.mpii.de/yago/resource/Corinth>"); strings.push_back("<http://www.mpii.de/yago/resource/Alexander_Cameron_Rutherford>"); strings.push_back("<http://www.mpii.de/yago/resource/Edmonton>"); strings.push_back("<http://www.mpii.de/yago/resource/Richard_Gavin_Reid>"); strings.push_back("<http://www.mpii.de/yago/resource/Mikhail_Loris-Melikov>"); strings.push_back("<http://www.mpii.de/yago/resource/James_Joseph_Sylvester>"); strings.push_back("<http://www.mpii.de/yago/resource/Jacob_De_la_Gardie>"); strings.push_back("<http://www.mpii.de/yago/resource/Studs_Terkel>"); strings.push_back("<http://www.mpii.de/yago/resource/John_A._Quitman>"); strings.push_back("<http://www.mpii.de/yago/resource/Natchez,_Mississippi>"); strings.push_back("<http://www.mpii.de/yago/resource/George_Hendrik_Breitner>"); strings.push_back("<http://www.mpii.de/yago/resource/Jules_Dupuit>"); strings.push_back("<http://www.mpii.de/yago/resource/Dimitri_Tiomkin>"); strings.push_back("<http://www.mpii.de/yago/resource/Ioannis_Metaxas>"); strings.push_back("<http://www.mpii.de/yago/resource/William_Livingston>"); strings.push_back("<http://www.mpii.de/yago/resource/Elizabeth,_New_Jersey>"); strings.push_back("<http://www.mpii.de/yago/resource/Dag_Hammarskj%C3%B6ld>"); strings.push_back("<http://www.mpii.de/yago/resource/Ndola>"); strings.push_back("<http://www.mpii.de/yago/resource/Frederick_William_IV_of_Prussia>"); strings.push_back("<http://www.mpii.de/yago/resource/Roger_Cotes>"); strings.push_back("<http://www.mpii.de/yago/resource/Amor_De_Cosmos>"); strings.push_back("<http://www.mpii.de/yago/resource/Baltzar_von_Platen_(statesman)>"); strings.push_back("<http://www.mpii.de/yago/resource/Alexander_Tilloch_Galt>"); strings.push_back("<http://www.mpii.de/yago/resource/Harold_Stassen>"); strings.push_back("<http://www.mpii.de/yago/resource/Bloomington,_Minnesota>"); strings.push_back("<http://www.mpii.de/yago/resource/Gloria_Foster>"); strings.push_back("<http://www.mpii.de/yago/resource/Angela_Morley>"); strings.push_back("<http://www.mpii.de/yago/resource/Daniel_Morgan>"); strings.push_back("<http://www.mpii.de/yago/resource/Winchester,_Virginia>"); strings.push_back("<http://www.mpii.de/yago/resource/John_Singleton_Copley>"); strings.push_back("<http://www.mpii.de/yago/resource/Anna_Anderson>"); strings.push_back("<http://www.mpii.de/yago/resource/Tribhuvan_of_Nepal>"); strings.push_back("<http://www.mpii.de/yago/resource/John_Wallis>"); strings.push_back("<http://www.mpii.de/yago/resource/Otto_B%C3%BCtschli>"); strings.push_back("<http://www.mpii.de/yago/resource/George_Reid_(Australian_politician)>"); strings.push_back("<http://www.mpii.de/yago/resource/Leo_Carrillo>"); strings.push_back("<http://www.mpii.de/yago/resource/Pope_John_XIX>"); strings.push_back("<http://www.mpii.de/yago/resource/Peter_Drucker>"); strings.push_back("<http://www.mpii.de/yago/resource/Charles_Louis_Alphonse_Laveran>"); strings.push_back("<http://www.mpii.de/yago/resource/Allvar_Gullstrand>"); strings.push_back("<http://www.mpii.de/yago/resource/Ronald_Ross>"); strings.push_back("<http://www.mpii.de/yago/resource/Eug%C3%A8ne_Borel>"); strings.push_back("<http://www.mpii.de/yago/resource/Hans-Peter_Tschudi>"); strings.push_back("<http://www.mpii.de/yago/resource/Carl_Spitzweg>"); strings.push_back("<http://www.mpii.de/yago/resource/Robert_Blake_(admiral)>"); strings.push_back("<http://www.mpii.de/yago/resource/Christiaan_Eijkman>"); strings.push_back("<http://www.mpii.de/yago/resource/Henry_Hallett_Dale>"); strings.push_back("<http://www.mpii.de/yago/resource/Otto_Heinrich_Warburg>"); strings.push_back("<http://www.mpii.de/yago/resource/Johann_de_Kalb>"); strings.push_back("<http://www.mpii.de/yago/resource/Camden,_South_Carolina>"); strings.push_back("<http://www.mpii.de/yago/resource/Walter_Hallstein>"); strings.push_back("<http://www.mpii.de/yago/resource/Kurt_Tank>"); strings.push_back("<http://www.mpii.de/yago/resource/Giorgio_de_Chirico>"); strings.push_back("<http://www.mpii.de/yago/resource/Charles_Grandison_Finney>"); strings.push_back("<http://www.mpii.de/yago/resource/Oberlin,_Ohio>"); strings.push_back("<http://www.mpii.de/yago/resource/John_Byrom>"); strings.push_back("<http://www.mpii.de/yago/resource/Peng_Dehuai>"); strings.push_back("<http://www.mpii.de/yago/resource/Jean-Fran%C3%A7ois_Lyotard>"); strings.push_back("<http://www.mpii.de/yago/resource/Milton_Obote>"); strings.push_back("<http://www.mpii.de/yago/resource/Johannesburg>"); strings.push_back("<http://www.mpii.de/yago/resource/Adolf_von_Harnack>"); strings.push_back("<http://www.mpii.de/yago/resource/Emma,_Lady_Hamilton>"); strings.push_back("<http://www.mpii.de/yago/resource/Siad_Barre>"); strings.push_back("<http://www.mpii.de/yago/resource/Lagos>"); strings.push_back("<http://www.mpii.de/yago/resource/Arthur_Gould_(rugby_player)>"); strings.push_back("<http://www.mpii.de/yago/resource/Newport>"); strings.push_back("<http://www.mpii.de/yago/resource/Grant_Wood>"); strings.push_back("<http://www.mpii.de/yago/resource/Iowa_City,_Iowa>"); strings.push_back("<http://www.mpii.de/yago/resource/Ed_Wynn>"); strings.push_back("<http://www.mpii.de/yago/resource/Amrish_Puri>"); strings.push_back("<http://www.mpii.de/yago/resource/Ray_Walston>"); strings.push_back("<http://www.mpii.de/yago/resource/Louis_A._Johnson>"); strings.push_back("<http://www.mpii.de/yago/resource/George_Green>"); strings.push_back("<http://www.mpii.de/yago/resource/Nottingham>"); strings.push_back("<http://www.mpii.de/yago/resource/Donald_Regan>"); strings.push_back("<http://www.mpii.de/yago/resource/Williamsburg,_Virginia>"); strings.push_back("<http://www.mpii.de/yago/resource/Dorothy_Dunnett>"); strings.push_back("<http://www.mpii.de/yago/resource/Jean-Baptiste_Jourdan>"); strings.push_back("<http://www.mpii.de/yago/resource/Terence_Cooke>"); strings.push_back("<http://www.mpii.de/yago/resource/John_Joseph_O'Connor>"); strings.push_back("<http://www.mpii.de/yago/resource/Frits_Zernike>"); strings.push_back("<http://www.mpii.de/yago/resource/Amersfoort>"); strings.push_back("<http://www.mpii.de/yago/resource/David_Brinkley>"); strings.push_back("<http://www.mpii.de/yago/resource/Houston>"); strings.push_back("<http://www.mpii.de/yago/resource/Patrick_Joseph_Hayes>"); strings.push_back("<http://www.mpii.de/yago/resource/John_Hughes_(archbishop)>"); strings.push_back("<http://www.mpii.de/yago/resource/John_McCloskey>"); strings.push_back("<http://www.mpii.de/yago/resource/Franz_B%C3%BCcheler>"); strings.push_back("<http://www.mpii.de/yago/resource/Francis_Spellman>"); strings.push_back("<http://www.mpii.de/yago/resource/Emil_Artin>"); strings.push_back("<http://www.mpii.de/yago/resource/W%C5%82adys%C5%82aw_Gomu%C5%82ka>"); strings.push_back("<http://www.mpii.de/yago/resource/Konstancin-Jeziorna>"); strings.push_back("<http://www.mpii.de/yago/resource/Willard_Libby>"); strings.push_back("<http://www.mpii.de/yago/resource/Erich_Mielke>"); strings.push_back("<http://www.mpii.de/yago/resource/Carroll_O'Connor>"); strings.push_back("<http://www.mpii.de/yago/resource/Robert_Cade>"); strings.push_back("<http://www.mpii.de/yago/resource/Ottokar_I_of_Bohemia>"); strings.push_back("<http://www.mpii.de/yago/resource/Ottokar_II_of_Bohemia>"); strings.push_back("<http://www.mpii.de/yago/resource/D%C3%BCrnkrut,_Austria>"); strings.push_back("<http://www.mpii.de/yago/resource/Pierre_Le_Moyne_d'Iberville>"); strings.push_back("<http://www.mpii.de/yago/resource/John_McCrae>"); strings.push_back("<http://www.mpii.de/yago/resource/Albrecht_von_Wallenstein>"); strings.push_back("<http://www.mpii.de/yago/resource/Cheb>"); strings.push_back("<http://www.mpii.de/yago/resource/Augustus_III_of_Poland>"); strings.push_back("<http://www.mpii.de/yago/resource/Augustus_II_the_Strong>"); strings.push_back("<http://www.mpii.de/yago/resource/Alain-Ren%C3%A9_Lesage>"); strings.push_back("<http://www.mpii.de/yago/resource/John_Keel>"); strings.push_back("<http://www.mpii.de/yago/resource/Walter_Model>"); strings.push_back("<http://www.mpii.de/yago/resource/Duisburg>"); strings.push_back("<http://www.mpii.de/yago/resource/Rosemary_Kennedy>"); strings.push_back("<http://www.mpii.de/yago/resource/Fort_Atkinson,_Wisconsin>"); strings.push_back("<http://www.mpii.de/yago/resource/Rom%C3%A1n_Baldorioty_de_Castro>"); strings.push_back("<http://www.mpii.de/yago/resource/Ponce,_Puerto_Rico>"); strings.push_back("<http://www.mpii.de/yago/resource/George_Beurling>"); strings.push_back("<http://www.mpii.de/yago/resource/Red_Skelton>"); strings.push_back("<http://www.mpii.de/yago/resource/Corey_Haim>"); strings.push_back("<http://www.mpii.de/yago/resource/Lysimachus>"); strings.push_back("<http://www.mpii.de/yago/resource/Sardis>"); strings.push_back("<http://www.mpii.de/yago/resource/Kemmons_Wilson>"); strings.push_back("<http://www.mpii.de/yago/resource/Li_Hongzhang>"); strings.push_back("<http://www.mpii.de/yago/resource/Virginia_Apgar>"); strings.push_back("<http://www.mpii.de/yago/resource/Edward_John_Thye>"); strings.push_back("<http://www.mpii.de/yago/resource/Northfield,_Minnesota>"); strings.push_back("<http://www.mpii.de/yago/resource/Abe_Fortas>"); strings.push_back("<http://www.mpii.de/yago/resource/Luther_Youngdahl>"); strings.push_back("<http://www.mpii.de/yago/resource/Emil_du_Bois-Reymond>"); strings.push_back("<http://www.mpii.de/yago/resource/Hjalmar_Petersen>"); strings.push_back("<http://www.mpii.de/yago/resource/Elizabeth_Siddal>"); strings.push_back("<http://www.mpii.de/yago/resource/Henry_Martyn>"); strings.push_back("<http://www.mpii.de/yago/resource/Tokat>"); strings.push_back("<http://www.mpii.de/yago/resource/Henry_Adoniram_Swift>"); strings.push_back("<http://www.mpii.de/yago/resource/St._Peter,_Minnesota>"); strings.push_back("<http://www.mpii.de/yago/resource/Cushman_Kellogg_Davis>"); strings.push_back("<http://www.mpii.de/yago/resource/Saint_Paul,_Minnesota>"); strings.push_back("<http://www.mpii.de/yago/resource/Henry_Hastings_Sibley>"); strings.push_back("<http://www.mpii.de/yago/resource/Samuel_Medary>"); strings.push_back("<http://www.mpii.de/yago/resource/Matthew_Boulton>"); strings.push_back("<http://www.mpii.de/yago/resource/Birmingham>"); strings.push_back("<http://www.mpii.de/yago/resource/Rez%C4%81_Sh%C4%81h>"); strings.push_back("<http://www.mpii.de/yago/resource/Michael_Andreas_Barclay_de_Tolly>"); strings.push_back("<http://www.mpii.de/yago/resource/Chernyakhovsk>"); strings.push_back("<http://www.mpii.de/yago/resource/Hugh_Childers>"); strings.push_back("<http://www.mpii.de/yago/resource/Richard_Mulcahy>"); strings.push_back("<http://www.mpii.de/yago/resource/Stephen_Miller>"); strings.push_back("<http://www.mpii.de/yago/resource/Worthington,_Minnesota>"); strings.push_back("<http://www.mpii.de/yago/resource/William_Rainey_Marshall>"); strings.push_back("<http://www.mpii.de/yago/resource/David_Marston_Clough>"); strings.push_back("<http://www.mpii.de/yago/resource/Everett,_Washington>"); strings.push_back("<http://www.mpii.de/yago/resource/Samuel_Rinnah_Van_Sant>"); strings.push_back("<http://www.mpii.de/yago/resource/Attica,_Indiana>"); strings.push_back("<http://www.mpii.de/yago/resource/Wenceslaus_II_of_Bohemia>"); strings.push_back("<http://www.mpii.de/yago/resource/Juan_Rulfo>"); strings.push_back("<http://www.mpii.de/yago/resource/Ormer_Locklear>"); strings.push_back("<http://www.mpii.de/yago/resource/Chien-Shiung_Wu>"); strings.push_back("<http://www.mpii.de/yago/resource/Rollo_May>"); strings.push_back("<http://www.mpii.de/yago/resource/Tiburon,_California>"); strings.push_back("<http://www.mpii.de/yago/resource/Whitley_Stokes>"); strings.push_back("<http://www.mpii.de/yago/resource/Paul_Vinogradoff>"); strings.push_back("<http://www.mpii.de/yago/resource/Nogi_Maresuke>"); strings.push_back("<http://www.mpii.de/yago/resource/Carl_Ferdinand_Cori>"); strings.push_back("<http://www.mpii.de/yago/resource/Jack_Herer>"); strings.push_back("<http://www.mpii.de/yago/resource/Eugene,_Oregon>"); strings.push_back("<http://www.mpii.de/yago/resource/Peter_I_of_Portugal>"); strings.push_back("<http://www.mpii.de/yago/resource/Estremoz>"); strings.push_back("<http://www.mpii.de/yago/resource/Robert_Stephenson>"); strings.push_back("<http://www.mpii.de/yago/resource/Pavel_Cherenkov>"); strings.push_back("<http://www.mpii.de/yago/resource/Denis_Thatcher>"); strings.push_back("<http://www.mpii.de/yago/resource/Williamina_Fleming>"); strings.push_back("<http://www.mpii.de/yago/resource/Henry_M._Jackson>"); strings.push_back("<http://www.mpii.de/yago/resource/Samuel_Doe>"); strings.push_back("<http://www.mpii.de/yago/resource/Monrovia>"); strings.push_back("<http://www.mpii.de/yago/resource/Karel_Appel>"); strings.push_back("<http://www.mpii.de/yago/resource/Edward_of_Portugal>"); strings.push_back("<http://www.mpii.de/yago/resource/Tomar>"); strings.push_back("<http://www.mpii.de/yago/resource/Denis_of_Portugal>"); strings.push_back("<http://www.mpii.de/yago/resource/Santar%C3%A9m,_Portugal>"); strings.push_back("<http://www.mpii.de/yago/resource/Arthur_Lowe>"); strings.push_back("<http://www.mpii.de/yago/resource/James_Russell_Lowell>"); strings.push_back("<http://www.mpii.de/yago/resource/Boles%C5%82aw_II_the_Bold>"); strings.push_back("<http://www.mpii.de/yago/resource/Ossiach>"); strings.push_back("<http://www.mpii.de/yago/resource/Eddie_Cantor>"); strings.push_back("<http://www.mpii.de/yago/resource/Maria_I_of_Portugal>"); strings.push_back("<http://www.mpii.de/yago/resource/Louis_Antoine_de_Bougainville>"); strings.push_back("<http://www.mpii.de/yago/resource/Miguel_of_Portugal>"); strings.push_back("<http://www.mpii.de/yago/resource/Karlsruhe>"); strings.push_back("<http://www.mpii.de/yago/resource/Maria_II_of_Portugal>"); strings.push_back("<http://www.mpii.de/yago/resource/Zengi>"); strings.push_back("<http://www.mpii.de/yago/resource/Se%C3%A1n_MacBride>"); strings.push_back("<http://www.mpii.de/yago/resource/Nur_ad-Din_Zangi>"); strings.push_back("<http://www.mpii.de/yago/resource/Antonello_da_Messina>"); strings.push_back("<http://www.mpii.de/yago/resource/Messina>"); strings.push_back("<http://www.mpii.de/yago/resource/Percy_Grainger>"); strings.push_back("<http://www.mpii.de/yago/resource/White_Plains,_New_York>"); strings.push_back("<http://www.mpii.de/yago/resource/Baldwin_II_of_Jerusalem>"); strings.push_back("<http://www.mpii.de/yago/resource/Richard_Neutra>"); strings.push_back("<http://www.mpii.de/yago/resource/Wuppertal>"); strings.push_back("<http://www.mpii.de/yago/resource/Vasily_Zaytsev>"); strings.push_back("<http://www.mpii.de/yago/resource/A._Philip_Randolph>"); strings.push_back("<http://www.mpii.de/yago/resource/Fra_Diavolo>"); strings.push_back("<http://www.mpii.de/yago/resource/Nancy_Spungen>"); strings.push_back("<http://www.mpii.de/yago/resource/Jeremiah_McLain_Rusk>"); strings.push_back("<http://www.mpii.de/yago/resource/Viroqua,_Wisconsin>"); strings.push_back("<http://www.mpii.de/yago/resource/Eric_Temple_Bell>"); strings.push_back("<http://www.mpii.de/yago/resource/Watsonville,_California>"); strings.push_back("<http://www.mpii.de/yago/resource/Camillo_Benso,_conte_di_Cavour>"); strings.push_back("<http://www.mpii.de/yago/resource/Robert_M._La_Follette,_Sr.>"); strings.push_back("<http://www.mpii.de/yago/resource/Hugh_MacLennan>"); strings.push_back("<http://www.mpii.de/yago/resource/Edward_Clark_(governor)>"); strings.push_back("<http://www.mpii.de/yago/resource/Marshall,_Texas>"); strings.push_back("<http://www.mpii.de/yago/resource/Jim_Varney>"); strings.push_back("<http://www.mpii.de/yago/resource/White_House,_Tennessee>"); strings.push_back("<http://www.mpii.de/yago/resource/Thomas_D._Schall>"); strings.push_back("<http://www.mpii.de/yago/resource/Magnus_Johnson>"); strings.push_back("<http://www.mpii.de/yago/resource/Litchfield,_Minnesota>"); strings.push_back("<http://www.mpii.de/yago/resource/Henrik_Shipstead>"); strings.push_back("<http://www.mpii.de/yago/resource/Alexandria,_Minnesota>"); strings.push_back("<http://www.mpii.de/yago/resource/Daniel_Sheldon_Norton>"); strings.push_back("<http://www.mpii.de/yago/resource/Hibbing,_Minnesota>"); strings.push_back("<http://www.mpii.de/yago/resource/Alonzo_J._Edgerton>"); strings.push_back("<http://www.mpii.de/yago/resource/Sioux_Falls,_South_Dakota>"); strings.push_back("<http://www.mpii.de/yago/resource/William_Windom>"); strings.push_back("<http://www.mpii.de/yago/resource/Morton_S._Wilkinson>"); strings.push_back("<http://www.mpii.de/yago/resource/Buddy_Hackett>"); strings.push_back("<http://www.mpii.de/yago/resource/Peter_Guthrie_Tait>"); strings.push_back("<http://www.mpii.de/yago/resource/Kangxi_Emperor>"); strings.push_back("<http://www.mpii.de/yago/resource/Henry_Brant>"); strings.push_back("<http://www.mpii.de/yago/resource/Frederick_III,_Elector_of_Saxony>"); strings.push_back("<http://www.mpii.de/yago/resource/Langau>"); strings.push_back("<http://www.mpii.de/yago/resource/Ismail_Qemali>"); strings.push_back("<http://www.mpii.de/yago/resource/Bari>"); strings.push_back("<http://www.mpii.de/yago/resource/Mariano_Arista>"); strings.push_back("<http://www.mpii.de/yago/resource/Abraham_Pineo_Gesner>"); strings.push_back("<http://www.mpii.de/yago/resource/Andr%C3%A9-Louis_Debierne>"); strings.push_back("<http://www.mpii.de/yago/resource/Tommy_Loughran>"); strings.push_back("<http://www.mpii.de/yago/resource/Altoona,_Pennsylvania>"); strings.push_back("<http://www.mpii.de/yago/resource/Harry_Greb>"); strings.push_back("<http://www.mpii.de/yago/resource/Atlantic_City,_New_Jersey>"); strings.push_back("<http://www.mpii.de/yago/resource/Sherman_Minton>"); strings.push_back("<http://www.mpii.de/yago/resource/New_Albany,_Indiana>"); strings.push_back("<http://www.mpii.de/yago/resource/Yang_Shangkun>"); strings.push_back("<http://www.mpii.de/yago/resource/Huang_Ju>"); strings.push_back("<http://www.mpii.de/yago/resource/Hans_von_Ohain>"); strings.push_back("<http://www.mpii.de/yago/resource/Melbourne,_Florida>"); strings.push_back("<http://www.mpii.de/yago/resource/Israel_Regardie>"); strings.push_back("<http://www.mpii.de/yago/resource/Sedona,_Arizona>"); strings.push_back("<http://www.mpii.de/yago/resource/Miss_Elizabeth>"); strings.push_back("<http://www.mpii.de/yago/resource/Marietta,_Georgia>"); strings.push_back("<http://www.mpii.de/yago/resource/George_Wallace>"); strings.push_back("<http://www.mpii.de/yago/resource/Montgomery,_Alabama>"); strings.push_back("<http://www.mpii.de/yago/resource/William_Ellery>"); strings.push_back("<http://www.mpii.de/yago/resource/Button_Gwinnett>"); strings.push_back("<http://www.mpii.de/yago/resource/Philip_Livingston>"); strings.push_back("<http://www.mpii.de/yago/resource/York,_Pennsylvania>"); strings.push_back("<http://www.mpii.de/yago/resource/Samuel_Chase>"); strings.push_back("<http://www.mpii.de/yago/resource/Maximilian_II_of_Bavaria>"); strings.push_back("<http://www.mpii.de/yago/resource/Benjamin_Rush>"); strings.push_back("<http://www.mpii.de/yago/resource/John_Hart>"); strings.push_back("<http://www.mpii.de/yago/resource/Thomas_Stone>"); strings.push_back("<http://www.mpii.de/yago/resource/George_Walton>"); strings.push_back("<http://www.mpii.de/yago/resource/Augusta,_Georgia>"); strings.push_back("<http://www.mpii.de/yago/resource/George_Colley>"); strings.push_back("<http://www.mpii.de/yago/resource/George_Read_(U.S._statesman)>"); strings.push_back("<http://www.mpii.de/yago/resource/New_Castle,_Delaware>"); strings.push_back("<http://www.mpii.de/yago/resource/Ernst_Heinkel>"); strings.push_back("<http://www.mpii.de/yago/resource/Robert_Burns_Woodward>"); strings.push_back("<http://www.mpii.de/yago/resource/Hermann_Hoth>"); strings.push_back("<http://www.mpii.de/yago/resource/Goslar>"); strings.push_back("<http://www.mpii.de/yago/resource/Bob_Denard>"); strings.push_back("<http://www.mpii.de/yago/resource/John_W._Davis>"); strings.push_back("<http://www.mpii.de/yago/resource/Paul_Winchell>"); strings.push_back("<http://www.mpii.de/yago/resource/Henry_E._Huntington>"); strings.push_back("<http://www.mpii.de/yago/resource/William_John_Macquorn_Rankine>"); strings.push_back("<http://www.mpii.de/yago/resource/Jean_Drapeau>"); strings.push_back("<http://www.mpii.de/yago/resource/Ben_Hogan>"); strings.push_back("<http://www.mpii.de/yago/resource/Bob_Semple>"); strings.push_back("<http://www.mpii.de/yago/resource/New_Plymouth>"); strings.push_back("<http://www.mpii.de/yago/resource/Chen_Yun>"); strings.push_back("<http://www.mpii.de/yago/resource/Neil_Blaney>"); strings.push_back("<http://www.mpii.de/yago/resource/Pierre_Choderlos_de_Laclos>"); strings.push_back("<http://www.mpii.de/yago/resource/Taranto>"); strings.push_back("<http://www.mpii.de/yago/resource/Tony_Anholt>"); strings.push_back("<http://www.mpii.de/yago/resource/Se%C3%A1n_MacEntee>"); strings.push_back("<http://www.mpii.de/yago/resource/Doug_Henning>"); strings.push_back("<http://www.mpii.de/yago/resource/Peter_K%C3%BCrten>"); strings.push_back("<http://www.mpii.de/yago/resource/Ray_Kroc>"); strings.push_back("<http://www.mpii.de/yago/resource/William_Norton>"); strings.push_back("<http://www.mpii.de/yago/resource/John_Stapp>"); strings.push_back("<http://www.mpii.de/yago/resource/Alamogordo,_New_Mexico>"); strings.push_back("<http://www.mpii.de/yago/resource/Dorothy_Day>"); strings.push_back("<http://www.mpii.de/yago/resource/Roman_Lyashenko>"); strings.push_back("<http://www.mpii.de/yago/resource/Antalya>"); strings.push_back("<http://www.mpii.de/yago/resource/Stephen_III_of_Moldavia>"); strings.push_back("<http://www.mpii.de/yago/resource/Suceava>"); strings.push_back("<http://www.mpii.de/yago/resource/George_Washington_Goethals>"); strings.push_back("<http://www.mpii.de/yago/resource/Edward_Porter_Alexander>"); strings.push_back("<http://www.mpii.de/yago/resource/Joseph_E._Johnston>"); strings.push_back("<http://www.mpii.de/yago/resource/Braxton_Bragg>"); strings.push_back("<http://www.mpii.de/yago/resource/Galveston,_Texas>"); strings.push_back("<http://www.mpii.de/yago/resource/Brian_Lenihan,_Snr>"); strings.push_back("<http://www.mpii.de/yago/resource/Winston_Graham>"); strings.push_back("<http://www.mpii.de/yago/resource/Empress_Dowager_Cixi>"); strings.push_back("<http://www.mpii.de/yago/resource/Lasc%C4%83r_Catargiu>"); strings.push_back("<http://www.mpii.de/yago/resource/Joseph_William_Martin,_Jr.>"); strings.push_back("<http://www.mpii.de/yago/resource/William_B._Bankhead>"); strings.push_back("<http://www.mpii.de/yago/resource/Carl_Albert>"); strings.push_back("<http://www.mpii.de/yago/resource/McAlester,_Oklahoma>"); strings.push_back("<http://www.mpii.de/yago/resource/Guangxu_Emperor>"); strings.push_back("<http://www.mpii.de/yago/resource/Yongzheng_Emperor>"); strings.push_back("<http://www.mpii.de/yago/resource/Thomas_Gore_Browne>"); strings.push_back("<http://www.mpii.de/yago/resource/Jim_Mollison>"); strings.push_back("<http://www.mpii.de/yago/resource/Gustave_Dor%C3%A9>"); strings.push_back("<http://www.mpii.de/yago/resource/Anson_Burlingame>"); strings.push_back("<http://www.mpii.de/yago/resource/Walter_Jenkins>"); strings.push_back("<http://www.mpii.de/yago/resource/Ernest_Augustus_I_of_Hanover>"); strings.push_back("<http://www.mpii.de/yago/resource/Keith_Park>"); strings.push_back("<http://www.mpii.de/yago/resource/Cave_Johnson>"); strings.push_back("<http://www.mpii.de/yago/resource/Clarksville,_Tennessee>"); strings.push_back("<http://www.mpii.de/yago/resource/Harvey_Williams_Cushing>"); strings.push_back("<http://www.mpii.de/yago/resource/Harry_Caray>"); strings.push_back("<http://www.mpii.de/yago/resource/Cordell_Hull>"); strings.push_back("<http://www.mpii.de/yago/resource/Kevin_O'Higgins>"); strings.push_back("<http://www.mpii.de/yago/resource/Carlo_Tresca>"); strings.push_back("<http://www.mpii.de/yago/resource/Gary_Gilmore>"); strings.push_back("<http://www.mpii.de/yago/resource/Draper,_Utah>"); strings.push_back("<http://www.mpii.de/yago/resource/Johann_Bernoulli>"); strings.push_back("<http://www.mpii.de/yago/resource/Jacob_Johan_Anckarstr%C3%B6m>"); strings.push_back("<http://www.mpii.de/yago/resource/Don_Knotts>"); strings.push_back("<http://www.mpii.de/yago/resource/Maria_of_Yugoslavia>"); strings.push_back("<http://www.mpii.de/yago/resource/Alexander_I_of_Yugoslavia>"); strings.push_back("<http://www.mpii.de/yago/resource/Ottmar_Mergenthaler>"); strings.push_back("<http://www.mpii.de/yago/resource/Roberto_Cofres%C3%AD>"); strings.push_back("<http://www.mpii.de/yago/resource/Oscar_Levant>"); strings.push_back("<http://www.mpii.de/yago/resource/Armand_David>"); strings.push_back("<http://www.mpii.de/yago/resource/Robert_FitzRoy>"); strings.push_back("<http://www.mpii.de/yago/resource/Radama_II>"); strings.push_back("<http://www.mpii.de/yago/resource/Antananarivo>"); strings.push_back("<http://www.mpii.de/yago/resource/Ranavalona_III>"); strings.push_back("<http://www.mpii.de/yago/resource/Algiers>"); strings.push_back("<http://www.mpii.de/yago/resource/Jorge_Ubico>"); strings.push_back("<http://www.mpii.de/yago/resource/Ibn_Taymiyyah>"); strings.push_back("<http://www.mpii.de/yago/resource/R._Budd_Dwyer>"); strings.push_back("<http://www.mpii.de/yago/resource/Harrisburg,_Pennsylvania>"); strings.push_back("<http://www.mpii.de/yago/resource/George_Grey>"); strings.push_back("<http://www.mpii.de/yago/resource/Canute_IV_of_Denmark>"); strings.push_back("<http://www.mpii.de/yago/resource/Odense>"); strings.push_back("<http://www.mpii.de/yago/resource/John_Ritter>"); strings.push_back("<http://www.mpii.de/yago/resource/Bessie_Coleman>"); strings.push_back("<http://www.mpii.de/yago/resource/Jacksonville,_Florida>"); strings.push_back("<http://www.mpii.de/yago/resource/Joseph_Story>"); strings.push_back("<http://www.mpii.de/yago/resource/Sam_Francis>"); strings.push_back("<http://www.mpii.de/yago/resource/Charles_Sumner>"); strings.push_back("<http://www.mpii.de/yago/resource/Clarence_King>"); strings.push_back("<http://www.mpii.de/yago/resource/Aharon_Kotler>"); strings.push_back("<http://www.mpii.de/yago/resource/George_Catlin>"); strings.push_back("<http://www.mpii.de/yago/resource/Jersey_City,_New_Jersey>"); strings.push_back("<http://www.mpii.de/yago/resource/John_Machin>"); strings.push_back("<http://www.mpii.de/yago/resource/Charles_Dana_Gibson>"); strings.push_back("<http://www.mpii.de/yago/resource/Robert_Rosen>"); strings.push_back("<http://www.mpii.de/yago/resource/Theodore_Harold_Maiman>"); strings.push_back("<http://www.mpii.de/yago/resource/John_Schlesinger>"); strings.push_back("<http://www.mpii.de/yago/resource/Brock_Peters>"); strings.push_back("<http://www.mpii.de/yago/resource/Oliver_O._Howard>"); strings.push_back("<http://www.mpii.de/yago/resource/Norman_Borlaug>"); strings.push_back("<http://www.mpii.de/yago/resource/Dallas>"); strings.push_back("<http://www.mpii.de/yago/resource/Aaron_Spelling>"); strings.push_back("<http://www.mpii.de/yago/resource/C._V._Raman>"); strings.push_back("<http://www.mpii.de/yago/resource/Fabi%C3%A1n_Bielinsky>"); strings.push_back("<http://www.mpii.de/yago/resource/S%C3%A3o_Paulo>"); strings.push_back("<http://www.mpii.de/yago/resource/Nnamdi_Azikiwe>"); strings.push_back("<http://www.mpii.de/yago/resource/Enugu>"); strings.push_back("<http://www.mpii.de/yago/resource/William_Benjamin_Carpenter>"); strings.push_back("<http://www.mpii.de/yago/resource/Mokshagundam_Visvesvarayya>"); strings.push_back("<http://www.mpii.de/yago/resource/V._V._Giri>"); strings.push_back("<http://www.mpii.de/yago/resource/William_R._Tolbert,_Jr.>"); strings.push_back("<http://www.mpii.de/yago/resource/Hammer_DeRoburt>"); strings.push_back("<http://www.mpii.de/yago/resource/Johann_Tserclaes,_Count_of_Tilly>"); strings.push_back("<http://www.mpii.de/yago/resource/Ingolstadt>"); strings.push_back("<http://www.mpii.de/yago/resource/Louis_Philippe_II,_Duke_of_Orl%C3%A9ans>"); strings.push_back("<http://www.mpii.de/yago/resource/Milton_Margai>"); strings.push_back("<http://www.mpii.de/yago/resource/Freetown>"); strings.push_back("<http://www.mpii.de/yago/resource/Corazon_Aquino>"); strings.push_back("<http://www.mpii.de/yago/resource/Makati_City>"); strings.push_back("<http://www.mpii.de/yago/resource/James_Bruce,_8th_Earl_of_Elgin>"); strings.push_back("<http://www.mpii.de/yago/resource/Dharamsala>"); strings.push_back("<http://www.mpii.de/yago/resource/Jerome_Cavanagh>"); strings.push_back("<http://www.mpii.de/yago/resource/Prince_Aly_Khan>"); strings.push_back("<http://www.mpii.de/yago/resource/Johannes_Virolainen>"); strings.push_back("<http://www.mpii.de/yago/resource/Lohja>"); strings.push_back("<http://www.mpii.de/yago/resource/John_Ford>"); strings.push_back("<http://www.mpii.de/yago/resource/Vance_Hartke>"); strings.push_back("<http://www.mpii.de/yago/resource/Leo_Fender>"); strings.push_back("<http://www.mpii.de/yago/resource/Foday_Sankoh>"); strings.push_back("<http://www.mpii.de/yago/resource/Harvey_Samuel_Firestone>"); strings.push_back("<http://www.mpii.de/yago/resource/John_Hunyadi>"); strings.push_back("<http://www.mpii.de/yago/resource/William_Adelin>"); strings.push_back("<http://www.mpii.de/yago/resource/Barfleur>"); strings.push_back("<http://www.mpii.de/yago/resource/Richard_Mulligan>"); strings.push_back("<http://www.mpii.de/yago/resource/H%C3%A9l%C3%A8ne_Dutrieu>"); strings.push_back("<http://www.mpii.de/yago/resource/Wenceslaus_I_of_Bohemia>"); strings.push_back("<http://www.mpii.de/yago/resource/Kr%C3%A1l%C5%AFv_Dv%C5%AFr>"); strings.push_back("<http://www.mpii.de/yago/resource/Orval_Faubus>"); strings.push_back("<http://www.mpii.de/yago/resource/Conway,_Arkansas>"); strings.push_back("<http://www.mpii.de/yago/resource/Max_Wertheimer>"); strings.push_back("<http://www.mpii.de/yago/resource/New_Rochelle,_New_York>"); strings.push_back("<http://www.mpii.de/yago/resource/Levy_Mwanawasa>"); strings.push_back("<http://www.mpii.de/yago/resource/Nathan_Hale>"); strings.push_back("<http://www.mpii.de/yago/resource/Bruno_Hauptmann>"); strings.push_back("<http://www.mpii.de/yago/resource/Al_Bowlly>"); strings.push_back("<http://www.mpii.de/yago/resource/Madame_de_La_Fayette>"); strings.push_back("<http://www.mpii.de/yago/resource/Soraya_Esfandiary-Bakhtiari>"); strings.push_back("<http://www.mpii.de/yago/resource/George_Steinbrenner>"); strings.push_back("<http://www.mpii.de/yago/resource/Tampa,_Florida>"); strings.push_back("<http://www.mpii.de/yago/resource/Mercedes_de_Acosta>"); strings.push_back("<http://www.mpii.de/yago/resource/Elihu_Root>"); strings.push_back("<http://www.mpii.de/yago/resource/Albert_Bierstadt>"); strings.push_back("<http://www.mpii.de/yago/resource/Jagadish_Chandra_Bose>"); strings.push_back("<http://www.mpii.de/yago/resource/Giridih>"); strings.push_back("<http://www.mpii.de/yago/resource/Gideon_Welles>"); strings.push_back("<http://www.mpii.de/yago/resource/Julian_Tuwim>"); strings.push_back("<http://www.mpii.de/yago/resource/Zakopane>"); strings.push_back("<http://www.mpii.de/yago/resource/Woody_Hayes>"); strings.push_back("<http://www.mpii.de/yago/resource/Upper_Arlington,_Ohio>"); strings.push_back("<http://www.mpii.de/yago/resource/Ivar_Kreuger>"); strings.push_back("<http://www.mpii.de/yago/resource/Glenn_Curtiss>"); strings.push_back("<http://www.mpii.de/yago/resource/Mo_Mowlam>"); strings.push_back("<http://www.mpii.de/yago/resource/P._V._Narasimha_Rao>"); strings.push_back("<http://www.mpii.de/yago/resource/Joseph-Ignace_Guillotin>"); strings.push_back("<http://www.mpii.de/yago/resource/Emily_Carr>"); strings.push_back("<http://www.mpii.de/yago/resource/Semyon_Timoshenko>"); strings.push_back("<http://www.mpii.de/yago/resource/Maurice_Ren%C3%A9_Fr%C3%A9chet>"); strings.push_back("<http://www.mpii.de/yago/resource/P._J._Kennedy>"); strings.push_back("<http://www.mpii.de/yago/resource/Herblock>"); strings.push_back("<http://www.mpii.de/yago/resource/Yasunari_Kawabata>"); strings.push_back("<http://www.mpii.de/yago/resource/Thomas_Eagleton>"); strings.push_back("<http://www.mpii.de/yago/resource/Sarvadaman_Chowla>"); strings.push_back("<http://www.mpii.de/yago/resource/Laramie,_Wyoming>"); strings.push_back("<http://www.mpii.de/yago/resource/Allan_MacNab>"); strings.push_back("<http://www.mpii.de/yago/resource/Hamilton,_Ontario>"); strings.push_back("<http://www.mpii.de/yago/resource/Charles_de_Saint-%C3%89vremond>"); strings.push_back("<http://www.mpii.de/yago/resource/Josif_Runjanin>"); strings.push_back("<http://www.mpii.de/yago/resource/Novi_Sad>"); strings.push_back("<http://www.mpii.de/yago/resource/Malcolm_Alexander_MacLean>"); strings.push_back("<http://www.mpii.de/yago/resource/David_Oppenheimer>"); strings.push_back("<http://www.mpii.de/yago/resource/Theo_van_Doesburg>"); strings.push_back("<http://www.mpii.de/yago/resource/Patrick_Cleburne>"); strings.push_back("<http://www.mpii.de/yago/resource/Franklin,_Tennessee>"); strings.push_back("<http://www.mpii.de/yago/resource/Frederick_Henry,_Prince_of_Orange>"); strings.push_back("<http://www.mpii.de/yago/resource/Isaac_Murphy>"); strings.push_back("<http://www.mpii.de/yago/resource/Huntsville,_Arkansas>"); strings.push_back("<http://www.mpii.de/yago/resource/Powell_Clayton>"); strings.push_back("<http://www.mpii.de/yago/resource/William_Tubman>"); strings.push_back("<http://www.mpii.de/yago/resource/Harold_Bennett>"); strings.push_back("<http://www.mpii.de/yago/resource/Winthrop_Rockefeller>"); strings.push_back("<http://www.mpii.de/yago/resource/Herb_Brooks>"); strings.push_back("<http://www.mpii.de/yago/resource/Forest_Lake,_Minnesota>"); strings.push_back("<http://www.mpii.de/yago/resource/John_Edward_Mack>"); strings.push_back("<http://www.mpii.de/yago/resource/Takashi_Shimura>"); strings.push_back("<http://www.mpii.de/yago/resource/Saint_Lucy>"); strings.push_back("<http://www.mpii.de/yago/resource/Langdon_Cheves>"); strings.push_back("<http://www.mpii.de/yago/resource/Michael_Jackson_(writer)>"); strings.push_back("<http://www.mpii.de/yago/resource/Charles_Read_(naval_officer)>"); strings.push_back("<http://www.mpii.de/yago/resource/Meridian,_Mississippi>"); strings.push_back("<http://www.mpii.de/yago/resource/Petr_Beckmann>"); strings.push_back("<http://www.mpii.de/yago/resource/Cao_Xueqin>"); strings.push_back("<http://www.mpii.de/yago/resource/Archduchess_Gisela_of_Austria>"); strings.push_back("<http://www.mpii.de/yago/resource/Ernest_Aldrich_Simpson>"); strings.push_back("<http://www.mpii.de/yago/resource/Earl_Winfield_Spencer,_Jr.>"); strings.push_back("<http://www.mpii.de/yago/resource/Coronado,_California>"); strings.push_back("<http://www.mpii.de/yago/resource/Princess_Ludovika_of_Bavaria>"); strings.push_back("<http://www.mpii.de/yago/resource/Maximilian_I_Joseph_of_Bavaria>"); strings.push_back("<http://www.mpii.de/yago/resource/Li_Zongren>"); strings.push_back("<http://www.mpii.de/yago/resource/Stark_Young>"); strings.push_back("<http://www.mpii.de/yago/resource/Ivan_Goncharov>"); strings.push_back("<http://www.mpii.de/yago/resource/D%C3%A9sir%C3%A9e_Clary>"); strings.push_back("<http://www.mpii.de/yago/resource/Raphael_Semmes>"); strings.push_back("<http://www.mpii.de/yago/resource/Mobile,_Alabama>"); strings.push_back("<http://www.mpii.de/yago/resource/E._Power_Biggs>"); strings.push_back("<http://www.mpii.de/yago/resource/Abdurrahman_Wahid>"); strings.push_back("<http://www.mpii.de/yago/resource/Jonathan_Dayton>"); strings.push_back("<http://www.mpii.de/yago/resource/Hiroshi_Teshigahara>"); strings.push_back("<http://www.mpii.de/yago/resource/Salvatore_Giuliano>"); strings.push_back("<http://www.mpii.de/yago/resource/Castelvetrano>"); strings.push_back("<http://www.mpii.de/yago/resource/Pandurang_Shastri_Athavale>"); strings.push_back("<http://www.mpii.de/yago/resource/Anthony_Wood>"); strings.push_back("<http://www.mpii.de/yago/resource/Donogh_O'Malley>"); strings.push_back("<http://www.mpii.de/yago/resource/William_Blount>"); strings.push_back("<http://www.mpii.de/yago/resource/Knoxville,_Tennessee>"); strings.push_back("<http://www.mpii.de/yago/resource/Allen_Tate>"); strings.push_back("<http://www.mpii.de/yago/resource/Aodh_M%C3%B3r_%C3%93_N%C3%A9ill>"); strings.push_back("<http://www.mpii.de/yago/resource/Hattie_Caraway>"); strings.push_back("<http://www.mpii.de/yago/resource/Georg_Carl_von_D%C3%B6beln>"); strings.push_back("<http://www.mpii.de/yago/resource/Bear_Bryant>"); strings.push_back("<http://www.mpii.de/yago/resource/Tuscaloosa,_Alabama>"); strings.push_back("<http://www.mpii.de/yago/resource/Daniel_Ziegler>"); strings.push_back("<http://www.mpii.de/yago/resource/Yang_Guifei>"); strings.push_back("<http://www.mpii.de/yago/resource/Xianyang>"); strings.push_back("<http://www.mpii.de/yago/resource/Ellen_G._White>"); strings.push_back("<http://www.mpii.de/yago/resource/St._Helena,_California>"); strings.push_back("<http://www.mpii.de/yago/resource/Hamida_Djandoubi>"); strings.push_back("<http://www.mpii.de/yago/resource/Umberto_Saba>"); strings.push_back("<http://www.mpii.de/yago/resource/John_Selden_Roane>"); strings.push_back("<http://www.mpii.de/yago/resource/Pine_Bluff,_Arkansas>"); strings.push_back("<http://www.mpii.de/yago/resource/Vladislav_Ardzinba>"); strings.push_back("<http://www.mpii.de/yago/resource/Pedro_Albizu_Campos>"); strings.push_back("<http://www.mpii.de/yago/resource/Heinrich_L%C3%BCbke>"); strings.push_back("<http://www.mpii.de/yago/resource/Lloyd_Bentsen>"); strings.push_back("<http://www.mpii.de/yago/resource/Karl_Arnold>"); strings.push_back("<http://www.mpii.de/yago/resource/Theodor_Heuss>"); strings.push_back("<http://www.mpii.de/yago/resource/Frank_D._White>"); strings.push_back("<http://www.mpii.de/yago/resource/Giulio_de'_Medici_(d._1600)>"); strings.push_back("<http://www.mpii.de/yago/resource/John_D._Rockefeller,_Jr.>"); strings.push_back("<http://www.mpii.de/yago/resource/William_Dampier>"); strings.push_back("<http://www.mpii.de/yago/resource/Jessie_Royce_Landis>"); strings.push_back("<http://www.mpii.de/yago/resource/Simon_Pollard_Hughes,_Jr.>"); strings.push_back("<http://www.mpii.de/yago/resource/Jeff_Davis_(Arkansas_governor)>"); strings.push_back("<http://www.mpii.de/yago/resource/Zhang_Binglin>"); strings.push_back("<http://www.mpii.de/yago/resource/Suzhou>"); strings.push_back("<http://www.mpii.de/yago/resource/Oskar_Klein>"); strings.push_back("<http://www.mpii.de/yago/resource/Andrey_Vlasov>"); strings.push_back("<http://www.mpii.de/yago/resource/William_F._Buckley,_Jr.>"); strings.push_back("<http://www.mpii.de/yago/resource/Peter_of_Verona>"); strings.push_back("<http://www.mpii.de/yago/resource/Bob_C._Riley>"); strings.push_back("<http://www.mpii.de/yago/resource/Arkadelphia,_Arkansas>"); strings.push_back("<http://www.mpii.de/yago/resource/Joe_Purcell>"); strings.push_back("<http://www.mpii.de/yago/resource/Benton,_Arkansas>"); strings.push_back("<http://www.mpii.de/yago/resource/Friedrich_Paulus>"); strings.push_back("<http://www.mpii.de/yago/resource/Cai_Yuanpei>"); strings.push_back("<http://www.mpii.de/yago/resource/John_Ellis_Martineau>"); strings.push_back("<http://www.mpii.de/yago/resource/Sid_McMath>"); strings.push_back("<http://www.mpii.de/yago/resource/Elizabeth_Alexeievna_(Louise_of_Baden)>"); strings.push_back("<http://www.mpii.de/yago/resource/Belyov>"); strings.push_back("<http://www.mpii.de/yago/resource/Catherine_Dolgorukov>"); strings.push_back("<http://www.mpii.de/yago/resource/Kinji_Fukasaku>"); strings.push_back("<http://www.mpii.de/yago/resource/Soemu_Toyoda>"); strings.push_back("<http://www.mpii.de/yago/resource/Henry_Parkes>"); strings.push_back("<http://www.mpii.de/yago/resource/Hiram_Stevens_Maxim>"); strings.push_back("<http://www.mpii.de/yago/resource/Peter_Camejo>"); strings.push_back("<http://www.mpii.de/yago/resource/Folsom,_California>"); strings.push_back("<http://www.mpii.de/yago/resource/Paul_Douglas>"); strings.push_back("<http://www.mpii.de/yago/resource/Neem_Karoli_Baba>"); strings.push_back("<http://www.mpii.de/yago/resource/Chao_Yuen_Ren>"); strings.push_back("<http://www.mpii.de/yago/resource/Ram%C3%B3n_Mercader>"); strings.push_back("<http://www.mpii.de/yago/resource/Sergey_Mikhalkov>"); strings.push_back("<http://www.mpii.de/yago/resource/William_Lawrence_Bragg>"); strings.push_back("<http://www.mpii.de/yago/resource/Ipswich>"); strings.push_back("<http://www.mpii.de/yago/resource/William_Light>"); strings.push_back("<http://www.mpii.de/yago/resource/Raymond_Poincar%C3%A9>"); strings.push_back("<http://www.mpii.de/yago/resource/Elisha_Baxter>"); strings.push_back("<http://www.mpii.de/yago/resource/Batesville,_Arkansas>"); strings.push_back("<http://www.mpii.de/yago/resource/Claiborne_Pell>"); strings.push_back("<http://www.mpii.de/yago/resource/James_Henderson_Berry>"); strings.push_back("<http://www.mpii.de/yago/resource/Bentonville,_Arkansas>"); strings.push_back("<http://www.mpii.de/yago/resource/Joseph_Taylor_Robinson>"); strings.push_back("<http://www.mpii.de/yago/resource/Happy_Chandler>"); strings.push_back("<http://www.mpii.de/yago/resource/Versailles,_Kentucky>"); strings.push_back("<http://www.mpii.de/yago/resource/Albert_Knight>"); strings.push_back("<http://www.mpii.de/yago/resource/Abdus_Salam>"); strings.push_back("<http://www.mpii.de/yago/resource/Christopher_Polhem>"); strings.push_back("<http://www.mpii.de/yago/resource/James_Paul_Clarke>"); strings.push_back("<http://www.mpii.de/yago/resource/Eliel_Saarinen>"); strings.push_back("<http://www.mpii.de/yago/resource/Bloomfield_Hills,_Michigan>"); strings.push_back("<http://www.mpii.de/yago/resource/Jim_Wacker>"); strings.push_back("<http://www.mpii.de/yago/resource/San_Marcos,_Texas>"); strings.push_back("<http://www.mpii.de/yago/resource/Augustus_Hill_Garland>"); strings.push_back("<http://www.mpii.de/yago/resource/Chris_von_der_Ahe>"); strings.push_back("<http://www.mpii.de/yago/resource/Henry_Massey_Rector>"); strings.push_back("<http://www.mpii.de/yago/resource/Eleftherios_Venizelos>"); strings.push_back("<http://www.mpii.de/yago/resource/Gerard_Philips>"); strings.push_back("<http://www.mpii.de/yago/resource/William_S._Fulton>"); strings.push_back("<http://www.mpii.de/yago/resource/John_Pope_(politician)>"); strings.push_back("<http://www.mpii.de/yago/resource/Springfield,_Kentucky>"); strings.push_back("<http://www.mpii.de/yago/resource/Abraham_Kuyper>"); strings.push_back("<http://www.mpii.de/yago/resource/George_Izard>"); strings.push_back("<http://www.mpii.de/yago/resource/Thomas_Johnson_(Maryland)>"); strings.push_back("<http://www.mpii.de/yago/resource/Keith_Haring>"); strings.push_back("<http://www.mpii.de/yago/resource/Reinaldo_Arenas>"); strings.push_back("<http://www.mpii.de/yago/resource/Nestor_Makhno>"); strings.push_back("<http://www.mpii.de/yago/resource/Nachman_of_Breslov>"); strings.push_back("<http://www.mpii.de/yago/resource/Uman>"); strings.push_back("<http://www.mpii.de/yago/resource/Ambrose_Hundley_Sevier>"); strings.push_back("<http://www.mpii.de/yago/resource/Robert_Ward_Johnson>"); strings.push_back("<http://www.mpii.de/yago/resource/%C3%81ngel_Maturino_Res%C3%A9ndiz>"); strings.push_back("<http://www.mpii.de/yago/resource/Eddie_Guerrero>"); strings.push_back("<http://www.mpii.de/yago/resource/Mohammed_Baqir_al-Hakim>"); strings.push_back("<http://www.mpii.de/yago/resource/Najaf>"); strings.push_back("<http://www.mpii.de/yago/resource/William_E._Miller>"); strings.push_back("<http://www.mpii.de/yago/resource/Wade_Hampton_III>"); strings.push_back("<http://www.mpii.de/yago/resource/Edmund_Muskie>"); strings.push_back("<http://www.mpii.de/yago/resource/Frederik_Ruysch>"); strings.push_back("<http://www.mpii.de/yago/resource/John_W._Bricker>"); strings.push_back("<http://www.mpii.de/yago/resource/John_Sparkman>"); strings.push_back("<http://www.mpii.de/yago/resource/Huntsville,_Alabama>"); strings.push_back("<http://www.mpii.de/yago/resource/W._W._Rouse_Ball>"); strings.push_back("<http://www.mpii.de/yago/resource/Robert_M._La_Follette,_Jr.>"); strings.push_back("<http://www.mpii.de/yago/resource/Govert_Flinck>"); strings.push_back("<http://www.mpii.de/yago/resource/Miguel,_Duke_of_Braganza>"); strings.push_back("<http://www.mpii.de/yago/resource/Seebenstein>"); strings.push_back("<http://www.mpii.de/yago/resource/Mario_Benedetti>"); strings.push_back("<http://www.mpii.de/yago/resource/Montevideo>"); strings.push_back("<http://www.mpii.de/yago/resource/Ziaur_Rahman>"); strings.push_back("<http://www.mpii.de/yago/resource/Chittagong>"); strings.push_back("<http://www.mpii.de/yago/resource/Reed_Smoot>"); strings.push_back("<http://www.mpii.de/yago/resource/David_Lange>"); strings.push_back("<http://www.mpii.de/yago/resource/Murtala_Mohammed>"); strings.push_back("<http://www.mpii.de/yago/resource/Liu_Chih>"); strings.push_back("<http://www.mpii.de/yago/resource/Taichung>"); strings.push_back("<http://www.mpii.de/yago/resource/Chen_Yi_(communist)>"); strings.push_back("<http://www.mpii.de/yago/resource/Nie_Rongzhen>"); strings.push_back("<http://www.mpii.de/yago/resource/Du_Yuming>"); strings.push_back("<http://www.mpii.de/yago/resource/Francis_Osborne,_5th_Duke_of_Leeds>"); strings.push_back("<http://www.mpii.de/yago/resource/Fu_Zuoyi>"); strings.push_back("<http://www.mpii.de/yago/resource/Henry_Bathurst,_3rd_Earl_Bathurst>"); strings.push_back("<http://www.mpii.de/yago/resource/Liu_Bocheng>"); strings.push_back("<http://www.mpii.de/yago/resource/Granville_Leveson-Gower,_2nd_Earl_Granville>"); strings.push_back("<http://www.mpii.de/yago/resource/John_Wodehouse,_1st_Earl_of_Kimberley>"); strings.push_back("<http://www.mpii.de/yago/resource/Stafford_Northcote,_1st_Earl_of_Iddesleigh>"); strings.push_back("<http://www.mpii.de/yago/resource/Arthur_Henderson>"); strings.push_back("<http://www.mpii.de/yago/resource/Lord_Randolph_Churchill>"); strings.push_back("<http://www.mpii.de/yago/resource/William_Jayne>"); strings.push_back("<http://www.mpii.de/yago/resource/Springfield,_Illinois>"); strings.push_back("<http://www.mpii.de/yago/resource/Juv%C3%A9nal_Habyarimana>"); strings.push_back("<http://www.mpii.de/yago/resource/Kigali>"); strings.push_back("<http://www.mpii.de/yago/resource/Cyprien_Ntaryamira>"); strings.push_back("<http://www.mpii.de/yago/resource/Lee_Atwater>"); strings.push_back("<http://www.mpii.de/yago/resource/Benjamin_Silliman>"); strings.push_back("<http://www.mpii.de/yago/resource/Brigitte_Helm>"); strings.push_back("<http://www.mpii.de/yago/resource/Robert_Recorde>"); strings.push_back("<http://www.mpii.de/yago/resource/Red_Auerbach>"); strings.push_back("<http://www.mpii.de/yago/resource/Franz_Joseph_Gall>"); strings.push_back("<http://www.mpii.de/yago/resource/Charles_Spencer,_3rd_Earl_of_Sunderland>"); strings.push_back("<http://www.mpii.de/yago/resource/Louise_de_La_Valli%C3%A8re>"); strings.push_back("<http://www.mpii.de/yago/resource/Paul_Jennings_Hill>"); strings.push_back("<http://www.mpii.de/yago/resource/Starke,_Florida>"); strings.push_back("<http://www.mpii.de/yago/resource/Bob_Stump>"); strings.push_back("<http://www.mpii.de/yago/resource/Victor_Vasarely>"); strings.push_back("<http://www.mpii.de/yago/resource/Arthur_Cayley>"); strings.push_back("<http://www.mpii.de/yago/resource/Georgia_O'Keeffe>"); strings.push_back("<http://www.mpii.de/yago/resource/James_F._Byrnes>"); strings.push_back("<http://www.mpii.de/yago/resource/George_H._Gay,_Jr.>"); strings.push_back("<http://www.mpii.de/yago/resource/Jason_Robards>"); strings.push_back("<http://www.mpii.de/yago/resource/Jacques_Hadamard>"); strings.push_back("<http://www.mpii.de/yago/resource/Antonie_Pannekoek>"); strings.push_back("<http://www.mpii.de/yago/resource/Wageningen>"); strings.push_back("<http://www.mpii.de/yago/resource/Josef_Kammhuber>"); strings.push_back("<http://www.mpii.de/yago/resource/Samuel_P._Bush>"); strings.push_back("<http://www.mpii.de/yago/resource/John_Eaton>"); strings.push_back("<http://www.mpii.de/yago/resource/Howard_Unruh>"); strings.push_back("<http://www.mpii.de/yago/resource/Fukuzawa_Yukichi>"); strings.push_back("<http://www.mpii.de/yago/resource/Francis_Atterbury>"); strings.push_back("<http://www.mpii.de/yago/resource/Enomoto_Takeaki>"); strings.push_back("<http://www.mpii.de/yago/resource/Imagawa_Yoshimoto>"); strings.push_back("<http://www.mpii.de/yago/resource/Toyoake,_Aichi>"); strings.push_back("<http://www.mpii.de/yago/resource/Sebasti%C3%A1n_de_Belalc%C3%A1zar>"); strings.push_back("<http://www.mpii.de/yago/resource/Zygmunt_Florenty_Wr%C3%B3blewski>"); strings.push_back("<http://www.mpii.de/yago/resource/Raoul_Pictet>"); strings.push_back("<http://www.mpii.de/yago/resource/Edward_Law,_1st_Baron_Ellenborough>"); strings.push_back("<http://www.mpii.de/yago/resource/Dost_Mohammad_Khan>"); strings.push_back("<http://www.mpii.de/yago/resource/Herat>"); strings.push_back("<http://www.mpii.de/yago/resource/Charles_Mitchel>"); strings.push_back("<http://www.mpii.de/yago/resource/Juan_Luis_Vives>"); strings.push_back("<http://www.mpii.de/yago/resource/Frederick_Bates>"); strings.push_back("<http://www.mpii.de/yago/resource/Chesterfield,_Missouri>"); strings.push_back("<http://www.mpii.de/yago/resource/Anna_Lindh>"); strings.push_back("<http://www.mpii.de/yago/resource/Mark_Oliphant>"); strings.push_back("<http://www.mpii.de/yago/resource/Joseph_Rotblat>"); strings.push_back("<http://www.mpii.de/yago/resource/S%C3%A9amus_Brennan>"); strings.push_back("<http://www.mpii.de/yago/resource/Miroslav_Krle%C5%BEa>"); strings.push_back("<http://www.mpii.de/yago/resource/%C5%8Cmura_Masujir%C5%8D>"); strings.push_back("<http://www.mpii.de/yago/resource/Saig%C5%8D_Takamori>"); strings.push_back("<http://www.mpii.de/yago/resource/Kagoshima>"); strings.push_back("<http://www.mpii.de/yago/resource/Judas_Maccabeus>"); strings.push_back("<http://www.mpii.de/yago/resource/Ramallah>"); strings.push_back("<http://www.mpii.de/yago/resource/Larry_Hovis>"); strings.push_back("<http://www.mpii.de/yago/resource/Daniel_Govan>"); strings.push_back("<http://www.mpii.de/yago/resource/S._R._Ranganathan>"); strings.push_back("<http://www.mpii.de/yago/resource/Feroze_Gandhi>"); strings.push_back("<http://www.mpii.de/yago/resource/Abraham_Pais>"); strings.push_back("<http://www.mpii.de/yago/resource/J._J._Becher>"); strings.push_back("<http://www.mpii.de/yago/resource/Ralph_Bunche>"); strings.push_back("<http://www.mpii.de/yago/resource/Lex_Barker>"); strings.push_back("<http://www.mpii.de/yago/resource/Sakamoto_Ry%C5%8Dma>"); strings.push_back("<http://www.mpii.de/yago/resource/Sarah_Baartman>"); strings.push_back("<http://www.mpii.de/yago/resource/Gabriel_Bethlen>"); strings.push_back("<http://www.mpii.de/yago/resource/Alba_Iulia>"); strings.push_back("<http://www.mpii.de/yago/resource/Harry_Rawson>"); strings.push_back("<http://www.mpii.de/yago/resource/Victoria_Eugenie_of_Battenberg>"); strings.push_back("<http://www.mpii.de/yago/resource/Ann_Richards>"); strings.push_back("<http://www.mpii.de/yago/resource/John_Randolph_of_Roanoke>"); strings.push_back("<http://www.mpii.de/yago/resource/Thomas_Pinckney>"); strings.push_back("<http://www.mpii.de/yago/resource/Kuroki_Tamemoto>"); strings.push_back("<http://www.mpii.de/yago/resource/Aim%C3%A9_C%C3%A9saire>"); strings.push_back("<http://www.mpii.de/yago/resource/Fort-de-France>"); strings.push_back("<http://www.mpii.de/yago/resource/W%C5%82adys%C5%82aw_Szpilman>"); strings.push_back("<http://www.mpii.de/yago/resource/Hegesippus_(chronicler)>"); strings.push_back("<http://www.mpii.de/yago/resource/Leopold_Kronecker>"); strings.push_back("<http://www.mpii.de/yago/resource/Babe_Zaharias>"); strings.push_back("<http://www.mpii.de/yago/resource/Patty_Berg>"); strings.push_back("<http://www.mpii.de/yago/resource/Fort_Myers,_Florida>"); strings.push_back("<http://www.mpii.de/yago/resource/Harry_Cooper_(golfer)>"); strings.push_back("<http://www.mpii.de/yago/resource/Julius_Boros>"); strings.push_back("<http://www.mpii.de/yago/resource/Bobby_Cruickshank>"); strings.push_back("<http://www.mpii.de/yago/resource/Delray_Beach,_Florida>"); strings.push_back("<http://www.mpii.de/yago/resource/Ed_Dudley>"); strings.push_back("<http://www.mpii.de/yago/resource/Ben_Nicholson>"); strings.push_back("<http://www.mpii.de/yago/resource/Gianni_Versace>"); strings.push_back("<http://www.mpii.de/yago/resource/Henry_Paget,_1st_Marquess_of_Anglesey>"); strings.push_back("<http://www.mpii.de/yago/resource/Ernst_Kummer>"); strings.push_back("<http://www.mpii.de/yago/resource/Ferdinand_Anton_Ernst_Porsche>"); strings.push_back("<http://www.mpii.de/yago/resource/Zell_am_See>"); strings.push_back("<http://www.mpii.de/yago/resource/George_W._Romney>"); strings.push_back("<http://www.mpii.de/yago/resource/Joseph_Aiuppa>"); strings.push_back("<http://www.mpii.de/yago/resource/Joaquim_Maria_Machado_de_Assis>"); strings.push_back("<http://www.mpii.de/yago/resource/Aaron_Bank>"); strings.push_back("<http://www.mpii.de/yago/resource/Dana_Point,_California>"); strings.push_back("<http://www.mpii.de/yago/resource/Kamato_Hongo>"); strings.push_back("<http://www.mpii.de/yago/resource/Hermann_M%C3%BCller_(politician)>"); strings.push_back("<http://www.mpii.de/yago/resource/Georg_Brandt>"); strings.push_back("<http://www.mpii.de/yago/resource/Rudolf_Hilferding>"); strings.push_back("<http://www.mpii.de/yago/resource/Pio_of_Pietrelcina>"); strings.push_back("<http://www.mpii.de/yago/resource/San_Giovanni_Rotondo>"); strings.push_back("<http://www.mpii.de/yago/resource/Robert_Mapplethorpe>"); strings.push_back("<http://www.mpii.de/yago/resource/Merce_Cunningham>"); strings.push_back("<http://www.mpii.de/yago/resource/Hendrik_Verwoerd>"); strings.push_back("<http://www.mpii.de/yago/resource/Donald_DeFreeze>"); strings.push_back("<http://www.mpii.de/yago/resource/Joe_Valachi>"); strings.push_back("<http://www.mpii.de/yago/resource/El_Paso,_Texas>"); strings.push_back("<http://www.mpii.de/yago/resource/Kim_Edward_Beazley>"); strings.push_back("<http://www.mpii.de/yago/resource/Perth,_Western_Australia>"); strings.push_back("<http://www.mpii.de/yago/resource/John_Ross_(Arctic_explorer)>"); strings.push_back("<http://www.mpii.de/yago/resource/James_Gunn_(senator)>"); strings.push_back("<http://www.mpii.de/yago/resource/Louisville,_Georgia>"); strings.push_back("<http://www.mpii.de/yago/resource/Princess_Maud,_Countess_of_Southesk>"); strings.push_back("<http://www.mpii.de/yago/resource/William_Beall>"); strings.push_back("<http://www.mpii.de/yago/resource/McMinnville,_Tennessee>"); strings.push_back("<http://www.mpii.de/yago/resource/H._V._Evatt>"); strings.push_back("<http://www.mpii.de/yago/resource/Zhuo_Lin>"); strings.push_back("<http://www.mpii.de/yago/resource/James_Gunn_(congressman)>"); strings.push_back("<http://www.mpii.de/yago/resource/Boise,_Idaho>"); strings.push_back("<http://www.mpii.de/yago/resource/Thomas_Pleasant_Dockery>"); strings.push_back("<http://www.mpii.de/yago/resource/John_Houseman>"); strings.push_back("<http://www.mpii.de/yago/resource/Dith_Pran>"); strings.push_back("<http://www.mpii.de/yago/resource/New_Brunswick,_New_Jersey>"); strings.push_back("<http://www.mpii.de/yago/resource/Albert_Rust>"); strings.push_back("<http://www.mpii.de/yago/resource/Nikolaj_Frederik_Severin_Grundtvig>"); strings.push_back("<http://www.mpii.de/yago/resource/Wilhelm_Waiblinger>"); strings.push_back("<http://www.mpii.de/yago/resource/Eduard_M%C3%B6rike>"); strings.push_back("<http://www.mpii.de/yago/resource/Charles_James_Napier>"); strings.push_back("<http://www.mpii.de/yago/resource/Portsmouth>"); strings.push_back("<http://www.mpii.de/yago/resource/Cyril_Cusack>"); strings.push_back("<http://www.mpii.de/yago/resource/Bill_Haywood>"); strings.push_back("<http://www.mpii.de/yago/resource/Herbert_York>"); strings.push_back("<http://www.mpii.de/yago/resource/Nicolaus_Copernicus>"); strings.push_back("<http://www.mpii.de/yago/resource/Frombork>"); strings.push_back("<http://www.mpii.de/yago/resource/Adrian_Willaert>"); strings.push_back("<http://www.mpii.de/yago/resource/U_Thant>"); strings.push_back("<http://www.mpii.de/yago/resource/%C5%BDivojin_Mi%C5%A1i%C4%87>"); strings.push_back("<http://www.mpii.de/yago/resource/Joshua_Chamberlain>"); strings.push_back("<http://www.mpii.de/yago/resource/Portland,_Maine>"); strings.push_back("<http://www.mpii.de/yago/resource/William_Henry_Vanderbilt>"); strings.push_back("<http://www.mpii.de/yago/resource/Patrick_Blackett,_Baron_Blackett>"); strings.push_back("<http://www.mpii.de/yago/resource/James_Starley>"); strings.push_back("<http://www.mpii.de/yago/resource/James_L._Farmer,_Jr.>"); strings.push_back("<http://www.mpii.de/yago/resource/Fredericksburg,_Virginia>"); strings.push_back("<http://www.mpii.de/yago/resource/Edward_Howard_(bishop)>"); strings.push_back("<http://www.mpii.de/yago/resource/Beaverton,_Oregon>"); strings.push_back("<http://www.mpii.de/yago/resource/Naim_Frash%C3%ABri>"); strings.push_back("<http://www.mpii.de/yago/resource/Kad%C4%B1k%C3%B6y>"); strings.push_back("<http://www.mpii.de/yago/resource/Gideon_Mantell>"); strings.push_back("<http://www.mpii.de/yago/resource/William_Gannaway_Brownlow>"); strings.push_back("<http://www.mpii.de/yago/resource/Samuel_Griffith>"); strings.push_back("<http://www.mpii.de/yago/resource/Gordon_B._Hinckley>"); strings.push_back("<http://www.mpii.de/yago/resource/Russell_William_Thaw>"); strings.push_back("<http://www.mpii.de/yago/resource/John_L._Hines>"); strings.push_back("<http://www.mpii.de/yago/resource/John_E._Wool>"); strings.push_back("<http://www.mpii.de/yago/resource/Joseph_Cook>"); strings.push_back("<http://www.mpii.de/yago/resource/Fernando_%C3%81lvarez_de_Toledo,_3rd_Duke_of_Alba>"); strings.push_back("<http://www.mpii.de/yago/resource/Aleksandr_Kuprin>"); strings.push_back("<http://www.mpii.de/yago/resource/Maud_of_Wales>"); strings.push_back("<http://www.mpii.de/yago/resource/Maurice_Thatcher>"); strings.push_back("<http://www.mpii.de/yago/resource/Cornelius_Krieghoff>"); strings.push_back("<http://www.mpii.de/yago/resource/Oliver_Reed>"); strings.push_back("<http://www.mpii.de/yago/resource/Valletta>"); strings.push_back("<http://www.mpii.de/yago/resource/Louis-Nicolas_Davout>"); strings.push_back("<http://www.mpii.de/yago/resource/Auguste_de_Marmont>"); strings.push_back("<http://www.mpii.de/yago/resource/Lamar_Hunt>"); strings.push_back("<http://www.mpii.de/yago/resource/Frederic_Leighton,_1st_Baron_Leighton>"); strings.push_back("<http://www.mpii.de/yago/resource/Henry_Irving>"); strings.push_back("<http://www.mpii.de/yago/resource/Bradford>"); strings.push_back("<http://www.mpii.de/yago/resource/Thomas_Bartholin>"); strings.push_back("<http://www.mpii.de/yago/resource/Old_Tom_Parr>"); strings.push_back("<http://www.mpii.de/yago/resource/Juan_Bosch>"); strings.push_back("<http://www.mpii.de/yago/resource/Philip_I,_Landgrave_of_Hesse>"); strings.push_back("<http://www.mpii.de/yago/resource/Kassel>"); strings.push_back("<http://www.mpii.de/yago/resource/Sholem_Aleichem>"); strings.push_back("<http://www.mpii.de/yago/resource/Ferdinand_Foch>"); strings.push_back("<http://www.mpii.de/yago/resource/Wally_Hickel>"); strings.push_back("<http://www.mpii.de/yago/resource/Anchorage,_Alaska>"); strings.push_back("<http://www.mpii.de/yago/resource/Charles_A._Beard>"); strings.push_back("<http://www.mpii.de/yago/resource/Karl_Jaspers>"); strings.push_back("<http://www.mpii.de/yago/resource/Amos_Alonzo_Stagg>"); strings.push_back("<http://www.mpii.de/yago/resource/Stockton,_California>"); strings.push_back("<http://www.mpii.de/yago/resource/Maude_Farris-Luse>"); strings.push_back("<http://www.mpii.de/yago/resource/Coldwater,_Michigan>"); strings.push_back("<http://www.mpii.de/yago/resource/Robert_Brown_(botanist)>"); strings.push_back("<http://www.mpii.de/yago/resource/Joseph_Jenkins_Roberts>"); strings.push_back("<http://www.mpii.de/yago/resource/J._William_Fulbright>"); strings.push_back("<http://www.mpii.de/yago/resource/Th%C3%A9odore_Reinach>"); strings.push_back("<http://www.mpii.de/yago/resource/William_Le_Queux>"); strings.push_back("<http://www.mpii.de/yago/resource/Knokke>"); strings.push_back("<http://www.mpii.de/yago/resource/John_Little_McClellan>"); strings.push_back("<http://www.mpii.de/yago/resource/Michael_Foster_(physiologist)>"); strings.push_back("<http://www.mpii.de/yago/resource/Jayaprakash_Narayan>"); strings.push_back("<http://www.mpii.de/yago/resource/Patna>"); strings.push_back("<http://www.mpii.de/yago/resource/Morarji_Desai>"); strings.push_back("<http://www.mpii.de/yago/resource/Otto_Braun>"); strings.push_back("<http://www.mpii.de/yago/resource/Ashok_Kumar>"); strings.push_back("<http://www.mpii.de/yago/resource/Robert_Helpmann>"); strings.push_back("<http://www.mpii.de/yago/resource/Gavin_Douglas>"); strings.push_back("<http://www.mpii.de/yago/resource/Claude_Simon>"); strings.push_back("<http://www.mpii.de/yago/resource/Nelly_Sachs>"); strings.push_back("<http://www.mpii.de/yago/resource/Ferdinand_von_Lindemann>"); strings.push_back("<http://www.mpii.de/yago/resource/Christian_Friedrich_Sch%C3%B6nbein>"); strings.push_back("<http://www.mpii.de/yago/resource/Thomas_James_Henderson>"); strings.push_back("<http://www.mpii.de/yago/resource/Ivan_Goremykin>"); strings.push_back("<http://www.mpii.de/yago/resource/Sochi>"); strings.push_back("<http://www.mpii.de/yago/resource/Hetty_Green>"); strings.push_back("<http://www.mpii.de/yago/resource/Veronica_Lake>"); strings.push_back("<http://www.mpii.de/yago/resource/Robert_R._Gilruth>"); strings.push_back("<http://www.mpii.de/yago/resource/Stanis%C5%82aw_Maczek>"); strings.push_back("<http://www.mpii.de/yago/resource/James_W._Black>"); strings.push_back("<http://www.mpii.de/yago/resource/Murder_of_Jesse_Dirkhising>"); strings.push_back("<http://www.mpii.de/yago/resource/Rogers,_Arkansas>"); strings.push_back("<http://www.mpii.de/yago/resource/Wilhelm_Pieck>"); strings.push_back("<http://www.mpii.de/yago/resource/East_Berlin>"); strings.push_back("<http://www.mpii.de/yago/resource/Fred_Andrew_Seaton>"); strings.push_back("<http://www.mpii.de/yago/resource/Marvin_Gay,_Sr.>"); strings.push_back("<http://www.mpii.de/yago/resource/William_B._Allison>"); strings.push_back("<http://www.mpii.de/yago/resource/Dubuque,_Iowa>"); strings.push_back("<http://www.mpii.de/yago/resource/Bed%C5%99ich_Hrozn%C3%BD>"); strings.push_back("<http://www.mpii.de/yago/resource/William_Kissam_Vanderbilt>"); strings.push_back("<http://www.mpii.de/yago/resource/Abdul_Rahman_Arif>"); strings.push_back("<http://www.mpii.de/yago/resource/Vitaly_Ginzburg>"); strings.push_back("<http://www.mpii.de/yago/resource/Gilbert_Stuart>"); strings.push_back("<http://www.mpii.de/yago/resource/George_V_of_Hanover>"); strings.push_back("<http://www.mpii.de/yago/resource/Pierre_Charles>"); strings.push_back("<http://www.mpii.de/yago/resource/Roseau>"); strings.push_back("<http://www.mpii.de/yago/resource/Torakusu_Yamaha>"); strings.push_back("<http://www.mpii.de/yago/resource/Alexander_Suvorov>"); strings.push_back("<http://www.mpii.de/yago/resource/John_Hart_(Canadian_politician)>"); strings.push_back("<http://www.mpii.de/yago/resource/Thomas_Dufferin_Pattullo>"); strings.push_back("<http://www.mpii.de/yago/resource/Seishir%C5%8D_Itagaki>"); strings.push_back("<http://www.mpii.de/yago/resource/Kanji_Ishiwara>"); strings.push_back("<http://www.mpii.de/yago/resource/Charles_Marion_Russell>"); strings.push_back("<http://www.mpii.de/yago/resource/Great_Falls,_Montana>"); strings.push_back("<http://www.mpii.de/yago/resource/George_Boolos>"); strings.push_back("<http://www.mpii.de/yago/resource/Hugh_Hoyles>"); strings.push_back("<http://www.mpii.de/yago/resource/Ferdinand_Georg_Frobenius>"); strings.push_back("<http://www.mpii.de/yago/resource/Jos%C3%A9_L%C3%B3pez_Portillo>"); strings.push_back("<http://www.mpii.de/yago/resource/Samuel_Bentham>"); strings.push_back("<http://www.mpii.de/yago/resource/Bertram_Brockhouse>"); strings.push_back("<http://www.mpii.de/yago/resource/Richard_Cobden>"); strings.push_back("<http://www.mpii.de/yago/resource/Xu_Xiangqian>"); strings.push_back("<http://www.mpii.de/yago/resource/Arthur_H._Vandenberg>"); strings.push_back("<http://www.mpii.de/yago/resource/Grand_Rapids,_Michigan>"); strings.push_back("<http://www.mpii.de/yago/resource/Gheorghe_Gheorghiu-Dej>"); strings.push_back("<http://www.mpii.de/yago/resource/Pat_Brown>"); strings.push_back("<http://www.mpii.de/yago/resource/Howard_H._Aiken>"); strings.push_back("<http://www.mpii.de/yago/resource/Fei_Xiaotong>"); strings.push_back("<http://www.mpii.de/yago/resource/William_Bloye>"); strings.push_back("<http://www.mpii.de/yago/resource/Jeane_Dixon>"); strings.push_back("<http://www.mpii.de/yago/resource/Rudolf_Lange>"); strings.push_back("<http://www.mpii.de/yago/resource/Howard_Nemerov>"); strings.push_back("<http://www.mpii.de/yago/resource/University_City,_Missouri>"); strings.push_back("<http://www.mpii.de/yago/resource/Qian_Xuesen>"); strings.push_back("<http://www.mpii.de/yago/resource/Georgy_Malenkov>"); strings.push_back("<http://www.mpii.de/yago/resource/Thomas_Clap>"); strings.push_back("<http://www.mpii.de/yago/resource/Elsie_MacGill>"); strings.push_back("<http://www.mpii.de/yago/resource/Louise_Thaden>"); strings.push_back("<http://www.mpii.de/yago/resource/High_Point,_North_Carolina>"); strings.push_back("<http://www.mpii.de/yago/resource/Janko_Bobetko>"); strings.push_back("<http://www.mpii.de/yago/resource/T%C5%8Dson_Shimazaki>"); strings.push_back("<http://www.mpii.de/yago/resource/Masaoka_Shiki>"); strings.push_back("<http://www.mpii.de/yago/resource/Akiko_Yosano>"); strings.push_back("<http://www.mpii.de/yago/resource/Daniel_Comboni>"); strings.push_back("<http://www.mpii.de/yago/resource/Khartoum>"); strings.push_back("<http://www.mpii.de/yago/resource/Carl_Andrew_Spaatz>"); strings.push_back("<http://www.mpii.de/yago/resource/Ernest_Augustus,_Crown_Prince_of_Hanover>"); strings.push_back("<http://www.mpii.de/yago/resource/Gmunden>"); strings.push_back("<http://www.mpii.de/yago/resource/Pierre-Simon_Laplace>"); strings.push_back("<http://www.mpii.de/yago/resource/Oskari_Tokoi>"); strings.push_back("<http://www.mpii.de/yago/resource/Leominster,_Massachusetts>"); strings.push_back("<http://www.mpii.de/yago/resource/Gustav_Ludwig_Hertz>"); strings.push_back("<http://www.mpii.de/yago/resource/Mary_Todd_Lincoln>"); strings.push_back("<http://www.mpii.de/yago/resource/Giacomo_Balla>"); strings.push_back("<http://www.mpii.de/yago/resource/Imre_Th%C3%B6k%C3%B6ly>"); strings.push_back("<http://www.mpii.de/yago/resource/%C4%B0zmit>"); strings.push_back("<http://www.mpii.de/yago/resource/Vivian_Vance>"); strings.push_back("<http://www.mpii.de/yago/resource/Belvedere,_California>"); strings.push_back("<http://www.mpii.de/yago/resource/Gustavo_D%C3%ADaz_Ordaz>"); strings.push_back("<http://www.mpii.de/yago/resource/Samuel_Brannan>"); strings.push_back("<http://www.mpii.de/yago/resource/Escondido,_California>"); strings.push_back("<http://www.mpii.de/yago/resource/John_P._Hale>"); strings.push_back("<http://www.mpii.de/yago/resource/Dover,_New_Hampshire>"); strings.push_back("<http://www.mpii.de/yago/resource/Crawford_Long>"); strings.push_back("<http://www.mpii.de/yago/resource/Mother_Teresa>"); strings.push_back("<http://www.mpii.de/yago/resource/Kolkata>"); strings.push_back("<http://www.mpii.de/yago/resource/Road_Warrior_Hawk>"); strings.push_back("<http://www.mpii.de/yago/resource/Indian_Rocks_Beach,_Florida>"); strings.push_back("<http://www.mpii.de/yago/resource/%C4%BDudov%C3%ADt_%C5%A0t%C3%BAr>"); strings.push_back("<http://www.mpii.de/yago/resource/Modra>"); strings.push_back("<http://www.mpii.de/yago/resource/Charlie_Soong>"); strings.push_back("<http://www.mpii.de/yago/resource/Shanghai>"); strings.push_back("<http://www.mpii.de/yago/resource/Gustav_Schwarzenegger>"); strings.push_back("<http://www.mpii.de/yago/resource/Weiz>"); strings.push_back("<http://www.mpii.de/yago/resource/John_Millington_Synge>"); strings.push_back("<http://www.mpii.de/yago/resource/William_Ward,_2nd_Earl_of_Dudley>"); strings.push_back("<http://www.mpii.de/yago/resource/Maxwell_Anderson>"); strings.push_back("<http://www.mpii.de/yago/resource/Stanis%C5%82aw_August_Poniatowski>"); strings.push_back("<http://www.mpii.de/yago/resource/Augustus_C._Dodge>"); strings.push_back("<http://www.mpii.de/yago/resource/Burlington,_Iowa>"); strings.push_back("<http://www.mpii.de/yago/resource/George_W._Jones>"); strings.push_back("<http://www.mpii.de/yago/resource/Jean-Paul_Rabaut_Saint-%C3%89tienne>"); strings.push_back("<http://www.mpii.de/yago/resource/Samuel_J._Kirkwood>"); strings.push_back("<http://www.mpii.de/yago/resource/Benjamin_West>"); strings.push_back("<http://www.mpii.de/yago/resource/Lester_Patrick>"); strings.push_back("<http://www.mpii.de/yago/resource/Levi_Woodbury>"); strings.push_back("<http://www.mpii.de/yago/resource/James_Harlan_(senator)>"); strings.push_back("<http://www.mpii.de/yago/resource/Mount_Pleasant,_Iowa>"); strings.push_back("<http://www.mpii.de/yago/resource/Maxwell_D._Taylor>"); strings.push_back("<http://www.mpii.de/yago/resource/Konstantinos_Karamanlis>"); strings.push_back("<http://www.mpii.de/yago/resource/Barbara_Jordan>"); strings.push_back("<http://www.mpii.de/yago/resource/Corneliu_Baba>"); strings.push_back("<http://www.mpii.de/yago/resource/Henry_Forster,_1st_Baron_Forster>"); strings.push_back("<http://www.mpii.de/yago/resource/Eric_Hebborn>"); strings.push_back("<http://www.mpii.de/yago/resource/Walter_Schellenberg>"); strings.push_back("<http://www.mpii.de/yago/resource/Earl_Long>"); strings.push_back("<http://www.mpii.de/yago/resource/Alexandria,_Louisiana>"); strings.push_back("<http://www.mpii.de/yago/resource/Cassie_Chadwick>"); strings.push_back("<http://www.mpii.de/yago/resource/Italo_Balbo>"); strings.push_back("<http://www.mpii.de/yago/resource/Tobruk>"); strings.push_back("<http://www.mpii.de/yago/resource/Stu_Hart>"); strings.push_back("<http://www.mpii.de/yago/resource/Pat_Morita>"); strings.push_back("<http://www.mpii.de/yago/resource/Kazimierz_Fajans>"); strings.push_back("<http://www.mpii.de/yago/resource/John_Cockcroft>"); strings.push_back("<http://www.mpii.de/yago/resource/John_Neumann>"); strings.push_back("<http://www.mpii.de/yago/resource/Jan-Carl_Raspe>"); strings.push_back("<http://www.mpii.de/yago/resource/William_McKell>"); strings.push_back("<http://www.mpii.de/yago/resource/In%C3%AAs_de_Castro>"); strings.push_back("<http://www.mpii.de/yago/resource/Justin_Pierce>"); strings.push_back("<http://www.mpii.de/yago/resource/Anton_Mussert>"); strings.push_back("<http://www.mpii.de/yago/resource/Warren_Austin>"); strings.push_back("<http://www.mpii.de/yago/resource/Krystyna_Skarbek>"); strings.push_back("<http://www.mpii.de/yago/resource/George_Metesky>"); strings.push_back("<http://www.mpii.de/yago/resource/Waterbury,_Connecticut>"); strings.push_back("<http://www.mpii.de/yago/resource/William_Slim,_1st_Viscount_Slim>"); strings.push_back("<http://www.mpii.de/yago/resource/William_Morrison,_1st_Viscount_Dunrossil>"); strings.push_back("<http://www.mpii.de/yago/resource/Juan_Cris%C3%B3stomo_Falc%C3%B3n>"); strings.push_back("<http://www.mpii.de/yago/resource/Alan_Lloyd_Hodgkin>"); strings.push_back("<http://www.mpii.de/yago/resource/Paddy_Chayefsky>"); strings.push_back("<http://www.mpii.de/yago/resource/Hendrikje_van_Andel-Schipper>"); strings.push_back("<http://www.mpii.de/yago/resource/Hoogeveen>"); strings.push_back("<http://www.mpii.de/yago/resource/Harry_Atkinson>"); strings.push_back("<http://www.mpii.de/yago/resource/Wellington>"); strings.push_back("<http://www.mpii.de/yago/resource/Zofia_Kossak-Szczucka>"); strings.push_back("<http://www.mpii.de/yago/resource/Bielsko-Bia%C5%82a>"); strings.push_back("<http://www.mpii.de/yago/resource/William_Tierney_Clark>"); strings.push_back("<http://www.mpii.de/yago/resource/Grover_Cleveland_Alexander>"); strings.push_back("<http://www.mpii.de/yago/resource/St._Paul,_Nebraska>"); strings.push_back("<http://www.mpii.de/yago/resource/Rita_of_Cascia>"); strings.push_back("<http://www.mpii.de/yago/resource/Cascia>"); strings.push_back("<http://www.mpii.de/yago/resource/Lester_Dent>"); strings.push_back("<http://www.mpii.de/yago/resource/La_Plata,_Missouri>"); strings.push_back("<http://www.mpii.de/yago/resource/Rasul_Gamzatov>"); strings.push_back("<http://www.mpii.de/yago/resource/Keiz%C5%8D_Obuchi>"); strings.push_back("<http://www.mpii.de/yago/resource/Oda_Nagamasu>"); strings.push_back("<http://www.mpii.de/yago/resource/Sakae_Osugi>"); strings.push_back("<http://www.mpii.de/yago/resource/Felix_Frankfurter>"); strings.push_back("<http://www.mpii.de/yago/resource/Edwin_Booth>"); strings.push_back("<http://www.mpii.de/yago/resource/Philippa_Plantagenet,_5th_Countess_of_Ulster>"); strings.push_back("<http://www.mpii.de/yago/resource/Cork_(city)>"); strings.push_back("<http://www.mpii.de/yago/resource/Tom_Cribb>"); strings.push_back("<http://www.mpii.de/yago/resource/Maximilian_Voloshin>"); strings.push_back("<http://www.mpii.de/yago/resource/Koktebel>"); strings.push_back("<http://www.mpii.de/yago/resource/Marvin_Camras>"); strings.push_back("<http://www.mpii.de/yago/resource/Washington_Allston>"); strings.push_back("<http://www.mpii.de/yago/resource/Roger_Sherman_Baldwin>"); strings.push_back("<http://www.mpii.de/yago/resource/James_Hillhouse>"); strings.push_back("<http://www.mpii.de/yago/resource/Othniel_Charles_Marsh>"); strings.push_back("<http://www.mpii.de/yago/resource/Ithiel_Town>"); strings.push_back("<http://www.mpii.de/yago/resource/Behram_Kur%C5%9Funo%C4%9Flu>"); strings.push_back("<http://www.mpii.de/yago/resource/George_Leake>"); strings.push_back("<http://www.mpii.de/yago/resource/Alf_Morgans>"); strings.push_back("<http://www.mpii.de/yago/resource/George_Papandreou_(senior)>"); strings.push_back("<http://www.mpii.de/yago/resource/Andreas_Papandreou>"); strings.push_back("<http://www.mpii.de/yago/resource/Joseph_Needham>"); strings.push_back("<http://www.mpii.de/yago/resource/Timothy_Dwight_V>"); strings.push_back("<http://www.mpii.de/yago/resource/John_Bartram>"); strings.push_back("<http://www.mpii.de/yago/resource/Kenneth_E._Hagin>"); strings.push_back("<http://www.mpii.de/yago/resource/Tulsa,_Oklahoma>"); strings.push_back("<http://www.mpii.de/yago/resource/Harlow_Shapley>"); strings.push_back("<http://www.mpii.de/yago/resource/Walther_Bothe>"); strings.push_back("<http://www.mpii.de/yago/resource/Xavier_Cugat>"); strings.push_back("<http://www.mpii.de/yago/resource/Vladimir_Ivashko>"); strings.push_back("<http://www.mpii.de/yago/resource/Julius_Nyerere>"); strings.push_back("<http://www.mpii.de/yago/resource/Walter_James>"); strings.push_back("<http://www.mpii.de/yago/resource/Keith_Joseph>"); strings.push_back("<http://www.mpii.de/yago/resource/Henry_Daglish>"); strings.push_back("<http://www.mpii.de/yago/resource/Robert_Taft>"); strings.push_back("<http://www.mpii.de/yago/resource/Varina_Davis>"); strings.push_back("<http://www.mpii.de/yago/resource/Otto_Grotewohl>"); strings.push_back("<http://www.mpii.de/yago/resource/Robert_Wadlow>"); strings.push_back("<http://www.mpii.de/yago/resource/Manistee,_Michigan>"); strings.push_back("<http://www.mpii.de/yago/resource/Vilho_Petter_Nenonen>"); strings.push_back("<http://www.mpii.de/yago/resource/Slavoljub_Eduard_Penkala>"); strings.push_back("<http://www.mpii.de/yago/resource/Victoriano_Huerta>"); strings.push_back("<http://www.mpii.de/yago/resource/John_Stonehouse>"); strings.push_back("<http://www.mpii.de/yago/resource/Ranasinghe_Premadasa>"); strings.push_back("<http://www.mpii.de/yago/resource/Colombo>"); strings.push_back("<http://www.mpii.de/yago/resource/Georges-Louis_Leclerc,_Comte_de_Buffon>"); strings.push_back("<http://www.mpii.de/yago/resource/Henry_Wager_Halleck>"); strings.push_back("<http://www.mpii.de/yago/resource/Louisville,_Kentucky>"); strings.push_back("<http://www.mpii.de/yago/resource/Karl_Lennart_Oesch>"); strings.push_back("<http://www.mpii.de/yago/resource/Jos%C3%A9_de_San_Mart%C3%ADn>"); strings.push_back("<http://www.mpii.de/yago/resource/Charles_I,_Count_of_Flanders>"); strings.push_back("<http://www.mpii.de/yago/resource/Andrew_H._Longino>"); strings.push_back("<http://www.mpii.de/yago/resource/Kawakami_Gensai>"); strings.push_back("<http://www.mpii.de/yago/resource/Hugh_Lawson_White>"); strings.push_back("<http://www.mpii.de/yago/resource/Otto_Lilienthal>"); strings.push_back("<http://www.mpii.de/yago/resource/Sylvester_Pennoyer>"); strings.push_back("<http://www.mpii.de/yago/resource/Miguel_Primo_de_Rivera,_2nd_Marquis_of_Estella>"); strings.push_back("<http://www.mpii.de/yago/resource/Molly_Ivins>"); strings.push_back("<http://www.mpii.de/yago/resource/George_Brown,_Baron_George-Brown>"); strings.push_back("<http://www.mpii.de/yago/resource/Truro>"); strings.push_back("<http://www.mpii.de/yago/resource/Kurt_Eisner>"); strings.push_back("<http://www.mpii.de/yago/resource/Eduardo_Palomo>"); strings.push_back("<http://www.mpii.de/yago/resource/Alexander_Lippisch>"); strings.push_back("<http://www.mpii.de/yago/resource/Cedar_Rapids,_Iowa>"); strings.push_back("<http://www.mpii.de/yago/resource/Emil_Leon_Post>"); strings.push_back("<http://www.mpii.de/yago/resource/Ernest_Walton>"); strings.push_back("<http://www.mpii.de/yago/resource/Belfast>"); strings.push_back("<http://www.mpii.de/yago/resource/Henri_Cartan>"); strings.push_back("<http://www.mpii.de/yago/resource/Mark_W._Clark>"); strings.push_back("<http://www.mpii.de/yago/resource/Anthony_Crosland>"); strings.push_back("<http://www.mpii.de/yago/resource/George_Smith_(assyriologist)>"); strings.push_back("<http://www.mpii.de/yago/resource/Aleppo>"); strings.push_back("<http://www.mpii.de/yago/resource/Pope_John_XIV>"); strings.push_back("<http://www.mpii.de/yago/resource/Pope_John_XV>"); strings.push_back("<http://www.mpii.de/yago/resource/Pope_John_XII>"); strings.push_back("<http://www.mpii.de/yago/resource/Pope_John_XI>"); strings.push_back("<http://www.mpii.de/yago/resource/Pope_John_XVII>"); strings.push_back("<http://www.mpii.de/yago/resource/Dorian_Leigh>"); strings.push_back("<http://www.mpii.de/yago/resource/Pope_John_XVIII>"); strings.push_back("<http://www.mpii.de/yago/resource/Eduard_Buchner>"); strings.push_back("<http://www.mpii.de/yago/resource/Charles_Wilson_(Texas_politician)>"); strings.push_back("<http://www.mpii.de/yago/resource/Lufkin,_Texas>"); strings.push_back("<http://www.mpii.de/yago/resource/Wu_Sangui>"); strings.push_back("<http://www.mpii.de/yago/resource/Hengyang>"); strings.push_back("<http://www.mpii.de/yago/resource/Hussein_Onn>"); strings.push_back("<http://www.mpii.de/yago/resource/South_San_Francisco,_California>"); strings.push_back("<http://www.mpii.de/yago/resource/Tun_Abdul_Razak>"); strings.push_back("<http://www.mpii.de/yago/resource/Tunku_Abdul_Rahman>"); strings.push_back("<http://www.mpii.de/yago/resource/Kuala_Lumpur>"); strings.push_back("<http://www.mpii.de/yago/resource/Israel_Gelfand>"); strings.push_back("<http://www.mpii.de/yago/resource/Rolf_Dieter_Brinkmann>"); strings.push_back("<http://www.mpii.de/yago/resource/Li_Xiannian>"); strings.push_back("<http://www.mpii.de/yago/resource/Irv_Kupcinet>"); strings.push_back("<http://www.mpii.de/yago/resource/Edward_Abbey>"); strings.push_back("<http://www.mpii.de/yago/resource/Henry_S._Foote>"); strings.push_back("<http://www.mpii.de/yago/resource/William_J._Brennan,_Jr.>"); strings.push_back("<http://www.mpii.de/yago/resource/William_O._Douglas>"); strings.push_back("<http://www.mpii.de/yago/resource/Thaddeus_Stevens>"); strings.push_back("<http://www.mpii.de/yago/resource/Joseph_Proust>"); strings.push_back("<http://www.mpii.de/yago/resource/Claude_Chevalley>"); strings.push_back("<http://www.mpii.de/yago/resource/Newton_Moore>"); strings.push_back("<http://www.mpii.de/yago/resource/William_S._Paley>"); strings.push_back("<http://www.mpii.de/yago/resource/%C3%86thelthryth>"); strings.push_back("<http://www.mpii.de/yago/resource/Ely,_Cambridgeshire>"); strings.push_back("<http://www.mpii.de/yago/resource/Torii_Tadaharu>"); strings.push_back("<http://www.mpii.de/yago/resource/Josep_Trueta>"); strings.push_back("<http://www.mpii.de/yago/resource/Antoine_Houdar_de_la_Motte>"); strings.push_back("<http://www.mpii.de/yago/resource/Charles_Cotesworth_Pinckney>"); strings.push_back("<http://www.mpii.de/yago/resource/Alton_B._Parker>"); strings.push_back("<http://www.mpii.de/yago/resource/Ryutaro_Hashimoto>"); strings.push_back("<http://www.mpii.de/yago/resource/Mumtaz_Mahal>"); strings.push_back("<http://www.mpii.de/yago/resource/Burhanpur>"); strings.push_back("<http://www.mpii.de/yago/resource/Jahandar_Shah>"); strings.push_back("<http://www.mpii.de/yago/resource/Oliver_Winchester>"); strings.push_back("<http://www.mpii.de/yago/resource/George_Frederick_Phillips>"); strings.push_back("<http://www.mpii.de/yago/resource/William_C._Durant>"); strings.push_back("<http://www.mpii.de/yago/resource/Flint,_Michigan>"); strings.push_back("<http://www.mpii.de/yago/resource/Smedley_Butler>"); strings.push_back("<http://www.mpii.de/yago/resource/Lucio_Fulci>"); strings.push_back("<http://www.mpii.de/yago/resource/Clement_Vallandigham>"); strings.push_back("<http://www.mpii.de/yago/resource/Lebanon,_Ohio>"); strings.push_back("<http://www.mpii.de/yago/resource/John_F._Reynolds>"); strings.push_back("<http://www.mpii.de/yago/resource/Gettysburg,_Pennsylvania>"); strings.push_back("<http://www.mpii.de/yago/resource/Przemys%C5%82_II>"); strings.push_back("<http://www.mpii.de/yago/resource/Rogo%C5%BAno>"); strings.push_back("<http://www.mpii.de/yago/resource/Ernst_Udet>"); strings.push_back("<http://www.mpii.de/yago/resource/Don_Carlos_Buell>"); strings.push_back("<http://www.mpii.de/yago/resource/Rockport,_Kentucky>"); strings.push_back("<http://www.mpii.de/yago/resource/Brian_O'Nolan>"); strings.push_back("<http://www.mpii.de/yago/resource/Francis_II_of_the_Two_Sicilies>"); strings.push_back("<http://www.mpii.de/yago/resource/Arco_(TN)>"); strings.push_back("<http://www.mpii.de/yago/resource/Gene_Siskel>"); strings.push_back("<http://www.mpii.de/yago/resource/John_Joseph_Keane>"); strings.push_back("<http://www.mpii.de/yago/resource/Edward_Wightman>"); strings.push_back("<http://www.mpii.de/yago/resource/Lichfield>"); strings.push_back("<http://www.mpii.de/yago/resource/Yuriko_Miyamoto>"); strings.push_back("<http://www.mpii.de/yago/resource/Joseph_Adhemar>"); strings.push_back("<http://www.mpii.de/yago/resource/V._P._Singh>"); strings.push_back("<http://www.mpii.de/yago/resource/Paul_Sauv%C3%A9>"); strings.push_back("<http://www.mpii.de/yago/resource/Saint-Eustache,_Quebec>"); strings.push_back("<http://www.mpii.de/yago/resource/Ad%C3%A9lard_Godbout>"); strings.push_back("<http://www.mpii.de/yago/resource/Eleanor_Powell>"); strings.push_back("<http://www.mpii.de/yago/resource/J._D._Tippit>"); strings.push_back("<http://www.mpii.de/yago/resource/Hugh_MacDiarmid>"); strings.push_back("<http://www.mpii.de/yago/resource/Belle_Boyd>"); strings.push_back("<http://www.mpii.de/yago/resource/Wisconsin_Dells,_Wisconsin>"); strings.push_back("<http://www.mpii.de/yago/resource/Brad_Davis_(actor)>"); strings.push_back("<http://www.mpii.de/yago/resource/Barney_Oldfield>"); strings.push_back("<http://www.mpii.de/yago/resource/Vincent_Astor>"); strings.push_back("<http://www.mpii.de/yago/resource/Edwin_M._Stanton>"); strings.push_back("<http://www.mpii.de/yago/resource/Robert_Stevenson_(civil_engineer)>"); strings.push_back("<http://www.mpii.de/yago/resource/Abel_Gance>"); strings.push_back("<http://www.mpii.de/yago/resource/Andrei_Gromyko>"); strings.push_back("<http://www.mpii.de/yago/resource/John_Philip_Kemble>"); strings.push_back("<http://www.mpii.de/yago/resource/William_Rosecrans>"); strings.push_back("<http://www.mpii.de/yago/resource/Redondo_Beach,_California>"); strings.push_back("<http://www.mpii.de/yago/resource/William_Dowdeswell>"); strings.push_back("<http://www.mpii.de/yago/resource/Lewis_F._Powell,_Jr.>"); strings.push_back("<http://www.mpii.de/yago/resource/Stephen_Kemble>"); strings.push_back("<http://www.mpii.de/yago/resource/Durham>"); strings.push_back("<http://www.mpii.de/yago/resource/George_Romanes>"); strings.push_back("<http://www.mpii.de/yago/resource/Wild_Bill_Hickok>"); strings.push_back("<http://www.mpii.de/yago/resource/Deadwood,_South_Dakota>"); strings.push_back("<http://www.mpii.de/yago/resource/Donald_Swann>"); strings.push_back("<http://www.mpii.de/yago/resource/Tom%C3%A1%C5%A1_Ba%C5%A5a>"); strings.push_back("<http://www.mpii.de/yago/resource/Otrokovice>"); strings.push_back("<http://www.mpii.de/yago/resource/Edmund_Ignatius_Rice>"); strings.push_back("<http://www.mpii.de/yago/resource/Waterford>"); strings.push_back("<http://www.mpii.de/yago/resource/Mieszko_III_the_Old>"); strings.push_back("<http://www.mpii.de/yago/resource/Kalisz>"); strings.push_back("<http://www.mpii.de/yago/resource/Thomas_Jordan>"); strings.push_back("<http://www.mpii.de/yago/resource/Absalom_Jones>"); strings.push_back("<http://www.mpii.de/yago/resource/Wilmer_McLean>"); strings.push_back("<http://www.mpii.de/yago/resource/Lennart_Meri>"); strings.push_back("<http://www.mpii.de/yago/resource/Tallinn>"); strings.push_back("<http://www.mpii.de/yago/resource/Gordon_Drummond>"); strings.push_back("<http://www.mpii.de/yago/resource/Dutch_Schultz>"); strings.push_back("<http://www.mpii.de/yago/resource/Richard_S._Ewell>"); strings.push_back("<http://www.mpii.de/yago/resource/Spring_Hill,_Tennessee>"); strings.push_back("<http://www.mpii.de/yago/resource/Frank_Gotch>"); strings.push_back("<http://www.mpii.de/yago/resource/Humboldt,_Iowa>"); strings.push_back("<http://www.mpii.de/yago/resource/Alexey_Rykov>"); strings.push_back("<http://www.mpii.de/yago/resource/Nathaniel_Bliss>"); strings.push_back("<http://www.mpii.de/yago/resource/Henri-Georges_Clouzot>"); strings.push_back("<http://www.mpii.de/yago/resource/Robert_Anderson_(Civil_War)>"); strings.push_back("<http://www.mpii.de/yago/resource/Turner_Ashby>"); strings.push_back("<http://www.mpii.de/yago/resource/Harrisonburg,_Virginia>"); strings.push_back("<http://www.mpii.de/yago/resource/Raj_Kapoor>"); strings.push_back("<http://www.mpii.de/yago/resource/Edmondo_De_Amicis>"); strings.push_back("<http://www.mpii.de/yago/resource/William_Tryon>"); strings.push_back("<http://www.mpii.de/yago/resource/William_H._Crawford>"); strings.push_back("<http://www.mpii.de/yago/resource/Crawford,_Georgia>"); strings.push_back("<http://www.mpii.de/yago/resource/Sergei_Sobolev>"); strings.push_back("<http://www.mpii.de/yago/resource/James_G._Birney>"); strings.push_back("<http://www.mpii.de/yago/resource/Perth_Amboy,_New_Jersey>"); strings.push_back("<http://www.mpii.de/yago/resource/Frank_Crean>"); strings.push_back("<http://www.mpii.de/yago/resource/John_P._Kennedy>"); strings.push_back("<http://www.mpii.de/yago/resource/Georg_Hackenschmidt>"); strings.push_back("<http://www.mpii.de/yago/resource/Clement_Clarke_Moore>"); strings.push_back("<http://www.mpii.de/yago/resource/Ralph_Yarborough>"); strings.push_back("<http://www.mpii.de/yago/resource/Herbert_C._Brown>"); strings.push_back("<http://www.mpii.de/yago/resource/Lafayette,_Indiana>"); strings.push_back("<http://www.mpii.de/yago/resource/Cleomenes_III>"); strings.push_back("<http://www.mpii.de/yago/resource/Clifford_Berry>"); strings.push_back("<http://www.mpii.de/yago/resource/Diadumenian>"); strings.push_back("<http://www.mpii.de/yago/resource/Kazushige_Ugaki>"); strings.push_back("<http://www.mpii.de/yago/resource/Izunokuni,_Shizuoka>"); strings.push_back("<http://www.mpii.de/yago/resource/Edward_Stafford_(politician)>"); strings.push_back("<http://www.mpii.de/yago/resource/Mitsuo_Fuchida>"); strings.push_back("<http://www.mpii.de/yago/resource/Kashiwara>"); strings.push_back("<http://www.mpii.de/yago/resource/Johannes_Peter_M%C3%BCller>"); strings.push_back("<http://www.mpii.de/yago/resource/Cheddi_Jagan>"); strings.push_back("<http://www.mpii.de/yago/resource/Thurl_Ravenscroft>"); strings.push_back("<http://www.mpii.de/yago/resource/Frank_Hague>"); strings.push_back("<http://www.mpii.de/yago/resource/Asta_Nielsen>"); strings.push_back("<http://www.mpii.de/yago/resource/Frederiksberg>"); strings.push_back("<http://www.mpii.de/yago/resource/John_Henry_Twachtman>"); strings.push_back("<http://www.mpii.de/yago/resource/Lajos_Kossuth>"); strings.push_back("<http://www.mpii.de/yago/resource/Beverly_Robertson>"); strings.push_back("<http://www.mpii.de/yago/resource/John_Alden_Dix>"); strings.push_back("<http://www.mpii.de/yago/resource/Alfred_Drake>"); strings.push_back("<http://www.mpii.de/yago/resource/Kurt_Alder>"); strings.push_back("<http://www.mpii.de/yago/resource/Mary_Livermore>"); strings.push_back("<http://www.mpii.de/yago/resource/Melrose,_Massachusetts>"); strings.push_back("<http://www.mpii.de/yago/resource/Stephen_W._Kearny>"); strings.push_back("<http://www.mpii.de/yago/resource/Daniel_Coit_Gilman>"); strings.push_back("<http://www.mpii.de/yago/resource/Sextus_Afranius_Burrus>"); strings.push_back("<http://www.mpii.de/yago/resource/Clark_Kerr>"); strings.push_back("<http://www.mpii.de/yago/resource/El_Cerrito,_California>"); strings.push_back("<http://www.mpii.de/yago/resource/Samuel_Allyne_Otis>"); strings.push_back("<http://www.mpii.de/yago/resource/Dra%C5%BEa_Mihailovi%C4%87>"); strings.push_back("<http://www.mpii.de/yago/resource/Daws_Butler>"); strings.push_back("<http://www.mpii.de/yago/resource/Emil_Knoevenagel>"); strings.push_back("<http://www.mpii.de/yago/resource/Strother_Martin>"); strings.push_back("<http://www.mpii.de/yago/resource/%C3%89lie_Cartan>"); strings.push_back("<http://www.mpii.de/yago/resource/Daniel_Solander>"); strings.push_back("<http://www.mpii.de/yago/resource/Charles_Buller>"); strings.push_back("<http://www.mpii.de/yago/resource/Erhard_Milch>"); strings.push_back("<http://www.mpii.de/yago/resource/John_S._Mosby>"); strings.push_back("<http://www.mpii.de/yago/resource/Francis_I_of_the_Two_Sicilies>"); strings.push_back("<http://www.mpii.de/yago/resource/John_Copley,_1st_Baron_Lyndhurst>"); strings.push_back("<http://www.mpii.de/yago/resource/Charles_Pepys,_1st_Earl_of_Cottenham>"); strings.push_back("<http://www.mpii.de/yago/resource/Lucca>"); strings.push_back("<http://www.mpii.de/yago/resource/John_Scott,_1st_Earl_of_Eldon>"); strings.push_back("<http://www.mpii.de/yago/resource/Robert_Rolfe,_1st_Baron_Cranworth>"); strings.push_back("<http://www.mpii.de/yago/resource/Alexandre_de_Prouville>"); strings.push_back("<http://www.mpii.de/yago/resource/Tadeus_Reichstein>"); strings.push_back("<http://www.mpii.de/yago/resource/Mikhail_Kalinin>"); strings.push_back("<http://www.mpii.de/yago/resource/Honor%C3%A9_Mercier>"); strings.push_back("<http://www.mpii.de/yago/resource/Taufa'ahau_Tupou_IV>"); strings.push_back("<http://www.mpii.de/yago/resource/Tassos_Papadopoulos>"); strings.push_back("<http://www.mpii.de/yago/resource/Frank_Frazetta>"); strings.push_back("<http://www.mpii.de/yago/resource/David_Hemmings>"); strings.push_back("<http://www.mpii.de/yago/resource/Oscar,_Prince_Bernadotte>"); strings.push_back("<http://www.mpii.de/yago/resource/Brendan_Behan>"); strings.push_back("<http://www.mpii.de/yago/resource/Alexander_Luria>"); strings.push_back("<http://www.mpii.de/yago/resource/J%C3%A2nio_Quadros>"); strings.push_back("<http://www.mpii.de/yago/resource/Adolfo_L%C3%B3pez_Mateos>"); strings.push_back("<http://www.mpii.de/yago/resource/Adolfo_Ruiz_Cortines>"); strings.push_back("<http://www.mpii.de/yago/resource/Hjalmar_Schacht>"); strings.push_back("<http://www.mpii.de/yago/resource/George_W._Randolph>"); strings.push_back("<http://www.mpii.de/yago/resource/Agnes_de_Mille>"); strings.push_back("<http://www.mpii.de/yago/resource/Hiram_Percy_Maxim>"); strings.push_back("<http://www.mpii.de/yago/resource/La_Junta,_Colorado>"); strings.push_back("<http://www.mpii.de/yago/resource/Shiing-Shen_Chern>"); strings.push_back("<http://www.mpii.de/yago/resource/Tianjin>"); strings.push_back("<http://www.mpii.de/yago/resource/Louis_Botha>"); strings.push_back("<http://www.mpii.de/yago/resource/Sani_Abacha>"); strings.push_back("<http://www.mpii.de/yago/resource/Abuja>"); strings.push_back("<http://www.mpii.de/yago/resource/Stephen_Gray_(scientist)>"); strings.push_back("<http://www.mpii.de/yago/resource/Peter_Tomarken>"); strings.push_back("<http://www.mpii.de/yago/resource/Plutarco_El%C3%ADas_Calles>"); strings.push_back("<http://www.mpii.de/yago/resource/Neal_S._Dow>"); strings.push_back("<http://www.mpii.de/yago/resource/Maria_Christina_of_the_Two_Sicilies>"); strings.push_back("<http://www.mpii.de/yago/resource/Le_Havre>"); strings.push_back("<http://www.mpii.de/yago/resource/Omar_Bongo>"); strings.push_back("<http://www.mpii.de/yago/resource/Jan_Matejko>"); strings.push_back("<http://www.mpii.de/yago/resource/Maktoum_bin_Rashid_Al_Maktoum>"); strings.push_back("<http://www.mpii.de/yago/resource/Gold_Coast,_Queensland>"); strings.push_back("<http://www.mpii.de/yago/resource/Learned_Hand>"); strings.push_back("<http://www.mpii.de/yago/resource/Ivica_Ra%C4%8Dan>"); strings.push_back("<http://www.mpii.de/yago/resource/Charlotte_of_Cyprus>"); strings.push_back("<http://www.mpii.de/yago/resource/Blanche_Bruce>"); strings.push_back("<http://www.mpii.de/yago/resource/Peace_Pilgrim>"); strings.push_back("<http://www.mpii.de/yago/resource/Knox,_Indiana>"); strings.push_back("<http://www.mpii.de/yago/resource/Jerry_Goldsmith>"); strings.push_back("<http://www.mpii.de/yago/resource/Cornelis_Tromp>"); strings.push_back("<http://www.mpii.de/yago/resource/Albert_Kahn_(architect)>"); strings.push_back("<http://www.mpii.de/yago/resource/Algirdas_Brazauskas>"); strings.push_back("<http://www.mpii.de/yago/resource/Rafic_Hariri>"); strings.push_back("<http://www.mpii.de/yago/resource/Joan_Mart%C3%AD_i_Alanis>"); strings.push_back("<http://www.mpii.de/yago/resource/Ed_Limato>"); strings.push_back("<http://www.mpii.de/yago/resource/Paul_Simon_(politician)>"); strings.push_back("<http://www.mpii.de/yago/resource/Annie_Oakley>"); strings.push_back("<http://www.mpii.de/yago/resource/Greenville,_Ohio>"); strings.push_back("<http://www.mpii.de/yago/resource/Ma_Lik>"); strings.push_back("<http://www.mpii.de/yago/resource/David_Cox_(artist)>"); strings.push_back("<http://www.mpii.de/yago/resource/Symon_Petliura>"); strings.push_back("<http://www.mpii.de/yago/resource/Charles_Glover_Barkla>"); strings.push_back("<http://www.mpii.de/yago/resource/Victor_Francis_Hess>"); strings.push_back("<http://www.mpii.de/yago/resource/William_Henry_Bragg>"); strings.push_back("<http://www.mpii.de/yago/resource/Carl_David_Anderson>"); strings.push_back("<http://www.mpii.de/yago/resource/Edward_Mills_Purcell>"); strings.push_back("<http://www.mpii.de/yago/resource/Edward_Victor_Appleton>"); strings.push_back("<http://www.mpii.de/yago/resource/J._Hans_D._Jensen>"); strings.push_back("<http://www.mpii.de/yago/resource/Martin_Ryle>"); strings.push_back("<http://www.mpii.de/yago/resource/Max_von_Laue>"); strings.push_back("<http://www.mpii.de/yago/resource/Nevill_Francis_Mott>"); strings.push_back("<http://www.mpii.de/yago/resource/John_Hasbrouck_Van_Vleck>"); strings.push_back("<http://www.mpii.de/yago/resource/Korechika_Anami>"); strings.push_back("<http://www.mpii.de/yago/resource/Alfred_Terry>"); strings.push_back("<http://www.mpii.de/yago/resource/Charles_Crocker>"); strings.push_back("<http://www.mpii.de/yago/resource/Pedro_Lascur%C3%A1in>"); strings.push_back("<http://www.mpii.de/yago/resource/Stephen_Mallory>"); strings.push_back("<http://www.mpii.de/yago/resource/Pensacola,_Florida>"); strings.push_back("<http://www.mpii.de/yago/resource/Christen_K%C3%B8bke>"); strings.push_back("<http://www.mpii.de/yago/resource/Alfred_Richard_Orage>"); strings.push_back("<http://www.mpii.de/yago/resource/Henry_Koster>"); strings.push_back("<http://www.mpii.de/yago/resource/Camarillo,_California>"); strings.push_back("<http://www.mpii.de/yago/resource/James_Wilkinson>"); strings.push_back("<http://www.mpii.de/yago/resource/Robert_Napier,_1st_Baron_Napier_of_Magdala>"); strings.push_back("<http://www.mpii.de/yago/resource/Gerhard_von_Scharnhorst>"); strings.push_back("<http://www.mpii.de/yago/resource/Marguerite_Gardiner,_Countess_of_Blessington>"); strings.push_back("<http://www.mpii.de/yago/resource/Dmitriy_Ustinov>"); strings.push_back("<http://www.mpii.de/yago/resource/Ernie_Harwell>"); strings.push_back("<http://www.mpii.de/yago/resource/Novi,_Michigan>"); strings.push_back("<http://www.mpii.de/yago/resource/Howard_Jarvis>"); strings.push_back("<http://www.mpii.de/yago/resource/H._L._Gold>"); strings.push_back("<http://www.mpii.de/yago/resource/Laguna_Hills,_California>"); strings.push_back("<http://www.mpii.de/yago/resource/Avram_Davidson>"); strings.push_back("<http://www.mpii.de/yago/resource/Bremerton,_Washington>"); strings.push_back("<http://www.mpii.de/yago/resource/Heinrich_Harrer>"); strings.push_back("<http://www.mpii.de/yago/resource/Friesach>"); strings.push_back("<http://www.mpii.de/yago/resource/James_Graham,_1st_Marquess_of_Montrose>"); strings.push_back("<http://www.mpii.de/yago/resource/Wilder_Penfield>"); strings.push_back("<http://www.mpii.de/yago/resource/George_Scarborough>"); strings.push_back("<http://www.mpii.de/yago/resource/Deming,_New_Mexico>"); strings.push_back("<http://www.mpii.de/yago/resource/Kenneth_More>"); strings.push_back("<http://www.mpii.de/yago/resource/Lazar_Kaganovich>"); strings.push_back("<http://www.mpii.de/yago/resource/Thomas_Moran>"); strings.push_back("<http://www.mpii.de/yago/resource/John_Ross_(Cherokee_chief)>"); strings.push_back("<http://www.mpii.de/yago/resource/Willis_C._Hawley>"); strings.push_back("<http://www.mpii.de/yago/resource/Salem,_Oregon>"); strings.push_back("<http://www.mpii.de/yago/resource/Thomas_Gore>"); strings.push_back("<http://www.mpii.de/yago/resource/Hussein-Ali_Montazeri>"); strings.push_back("<http://www.mpii.de/yago/resource/Qom>"); strings.push_back("<http://www.mpii.de/yago/resource/Preston_Sturges>"); strings.push_back("<http://www.mpii.de/yago/resource/Thomas_Pownall>"); strings.push_back("<http://www.mpii.de/yago/resource/William_V._Roth,_Jr.>"); strings.push_back("<http://www.mpii.de/yago/resource/Muhammad_Ali_Jinnah>"); strings.push_back("<http://www.mpii.de/yago/resource/Jos%C3%A9_Antonio_Primo_de_Rivera>"); strings.push_back("<http://www.mpii.de/yago/resource/Kenji_Doihara>"); strings.push_back("<http://www.mpii.de/yago/resource/Peng_Zhen>"); strings.push_back("<http://www.mpii.de/yago/resource/Jacques_H%C3%A9bert>"); strings.push_back("<http://www.mpii.de/yago/resource/Ern%C5%91_Goldfinger>"); strings.push_back("<http://www.mpii.de/yago/resource/Leopold_Gmelin>"); strings.push_back("<http://www.mpii.de/yago/resource/Josep_Tarradellas_i_Joan>"); strings.push_back("<http://www.mpii.de/yago/resource/Ernest_Bevin>"); strings.push_back("<http://www.mpii.de/yago/resource/Herbert_Wehner>"); strings.push_back("<http://www.mpii.de/yago/resource/William_Hamilton_(diplomat)>"); strings.push_back("<http://www.mpii.de/yago/resource/Leo_V,_King_of_Armenia>"); strings.push_back("<http://www.mpii.de/yago/resource/Robert_Heilbroner>"); strings.push_back("<http://www.mpii.de/yago/resource/Joe_Adonis>"); strings.push_back("<http://www.mpii.de/yago/resource/Duchess_Sophie_Charlotte_in_Bavaria>"); strings.push_back("<http://www.mpii.de/yago/resource/Philip_Pendleton_Barbour>"); strings.push_back("<http://www.mpii.de/yago/resource/I._J._Good>"); strings.push_back("<http://www.mpii.de/yago/resource/Radford,_Virginia>"); strings.push_back("<http://www.mpii.de/yago/resource/Abram_Samoilovitch_Besicovitch>"); strings.push_back("<http://www.mpii.de/yago/resource/Abraham_Gottlob_Werner>"); strings.push_back("<http://www.mpii.de/yago/resource/Johnny_Olson>"); strings.push_back("<http://www.mpii.de/yago/resource/Thomas_E._Watson>"); strings.push_back("<http://www.mpii.de/yago/resource/James_FitzGibbon>"); strings.push_back("<http://www.mpii.de/yago/resource/Yumjaagiin_Tsedenbal>"); strings.push_back("<http://www.mpii.de/yago/resource/Noe_Ito>"); strings.push_back("<http://www.mpii.de/yago/resource/Louis_Cyr>"); strings.push_back("<http://www.mpii.de/yago/resource/Thomas_Pelham,_2nd_Earl_of_Chichester>"); strings.push_back("<http://www.mpii.de/yago/resource/Wolfred_Nelson>"); strings.push_back("<http://www.mpii.de/yago/resource/William_Howitt>"); strings.push_back("<http://www.mpii.de/yago/resource/Richard_Bright_(physician)>"); strings.push_back("<http://www.mpii.de/yago/resource/William_Wood,_1st_Baron_Hatherley>"); strings.push_back("<http://www.mpii.de/yago/resource/Ali>"); strings.push_back("<http://www.mpii.de/yago/resource/Kufa>"); strings.push_back("<http://www.mpii.de/yago/resource/Alan_Coren>"); strings.push_back("<http://www.mpii.de/yago/resource/George_Douglas-Hamilton,_1st_Earl_of_Orkney>"); strings.push_back("<http://www.mpii.de/yago/resource/John_Dalrymple,_2nd_Earl_of_Stair>"); strings.push_back("<http://www.mpii.de/yago/resource/Dietrich_von_Choltitz>"); strings.push_back("<http://www.mpii.de/yago/resource/Ruan_Lingyu>"); strings.push_back("<http://www.mpii.de/yago/resource/Sri_Yukteswar_Giri>"); strings.push_back("<http://www.mpii.de/yago/resource/Puri>"); strings.push_back("<http://www.mpii.de/yago/resource/Lahiri_Mahasaya>"); strings.push_back("<http://www.mpii.de/yago/resource/Varanasi>"); strings.push_back("<http://www.mpii.de/yago/resource/Hussein_bin_Ali,_Sharif_of_Mecca>"); strings.push_back("<http://www.mpii.de/yago/resource/Julie_Billiart>"); strings.push_back("<http://www.mpii.de/yago/resource/Namur_(city)>"); strings.push_back("<http://www.mpii.de/yago/resource/Pau_Claris_i_Casademunt>"); strings.push_back("<http://www.mpii.de/yago/resource/Juanita_Millender-McDonald>"); strings.push_back("<http://www.mpii.de/yago/resource/Carson,_California>"); strings.push_back("<http://www.mpii.de/yago/resource/Hughie_Edwards>"); strings.push_back("<http://www.mpii.de/yago/resource/Theodor_Eicke>"); strings.push_back("<http://www.mpii.de/yago/resource/Oryol>"); strings.push_back("<http://www.mpii.de/yago/resource/Dulah_Marie_Evans>"); strings.push_back("<http://www.mpii.de/yago/resource/Siegfried_Kracauer>"); strings.push_back("<http://www.mpii.de/yago/resource/Andr%C3%A9_Citro%C3%ABn>"); strings.push_back("<http://www.mpii.de/yago/resource/Jennifer_Dunn>"); strings.push_back("<http://www.mpii.de/yago/resource/Elisabeth_of_Wied>"); strings.push_back("<http://www.mpii.de/yago/resource/Curtea_de_Arge%C5%9F>"); strings.push_back("<http://www.mpii.de/yago/resource/Sam_Rayburn>"); strings.push_back("<http://www.mpii.de/yago/resource/Bonham,_Texas>"); strings.push_back("<http://www.mpii.de/yago/resource/Constantin_Br%C3%A2ncoveanu>"); strings.push_back("<http://www.mpii.de/yago/resource/Rabah_Bitat>"); strings.push_back("<http://www.mpii.de/yago/resource/Houari_Boumedi%C3%A8ne>"); strings.push_back("<http://www.mpii.de/yago/resource/Mihail_Kog%C4%83lniceanu>"); strings.push_back("<http://www.mpii.de/yago/resource/Seretse_Khama>"); strings.push_back("<http://www.mpii.de/yago/resource/Gaborone>"); strings.push_back("<http://www.mpii.de/yago/resource/Simo_H%C3%A4yh%C3%A4>"); strings.push_back("<http://www.mpii.de/yago/resource/Hamina>"); strings.push_back("<http://www.mpii.de/yago/resource/Mariano_Guadalupe_Vallejo>"); strings.push_back("<http://www.mpii.de/yago/resource/Charlie_Norwood>"); strings.push_back("<http://www.mpii.de/yago/resource/Isa_bin_Salman_Al_Khalifa>"); strings.push_back("<http://www.mpii.de/yago/resource/Manama>"); strings.push_back("<http://www.mpii.de/yago/resource/Henry_Hyde>"); strings.push_back("<http://www.mpii.de/yago/resource/Sandro_Pertini>"); strings.push_back("<http://www.mpii.de/yago/resource/Freddie_Mills>"); strings.push_back("<http://www.mpii.de/yago/resource/Frederick_de_Houtman>"); strings.push_back("<http://www.mpii.de/yago/resource/Alkmaar>"); strings.push_back("<http://www.mpii.de/yago/resource/Nellie_McClung>"); strings.push_back("<http://www.mpii.de/yago/resource/Vilna_Gaon>"); strings.push_back("<http://www.mpii.de/yago/resource/Gabriel_Narutowicz>"); strings.push_back("<http://www.mpii.de/yago/resource/Jacob_Ruppert>"); strings.push_back("<http://www.mpii.de/yago/resource/John_Kendrew>"); strings.push_back("<http://www.mpii.de/yago/resource/Tony_Banks,_Baron_Stratford>"); strings.push_back("<http://www.mpii.de/yago/resource/Erich_von_dem_Bach-Zelewski>"); strings.push_back("<http://www.mpii.de/yago/resource/Nick_Adams_(actor)>"); strings.push_back("<http://www.mpii.de/yago/resource/Samuel_Curtis>"); strings.push_back("<http://www.mpii.de/yago/resource/Council_Bluffs,_Iowa>"); strings.push_back("<http://www.mpii.de/yago/resource/Maximilian_I,_Elector_of_Bavaria>"); strings.push_back("<http://www.mpii.de/yago/resource/Bess_Truman>"); strings.push_back("<http://www.mpii.de/yago/resource/Florence_Harding>"); strings.push_back("<http://www.mpii.de/yago/resource/Marion,_Ohio>"); strings.push_back("<http://www.mpii.de/yago/resource/Mamie_Eisenhower>"); strings.push_back("<http://www.mpii.de/yago/resource/Helen_Herron_Taft>"); strings.push_back("<http://www.mpii.de/yago/resource/Ida_Saxton_McKinley>"); strings.push_back("<http://www.mpii.de/yago/resource/Canton,_Ohio>"); strings.push_back("<http://www.mpii.de/yago/resource/Louisa_Adams>"); strings.push_back("<http://www.mpii.de/yago/resource/B._J._Vorster>"); strings.push_back("<http://www.mpii.de/yago/resource/Itsuo_Tsuda>"); strings.push_back("<http://www.mpii.de/yago/resource/Walter_P._Lane>"); strings.push_back("<http://www.mpii.de/yago/resource/John_Tukey>"); strings.push_back("<http://www.mpii.de/yago/resource/Lucretia_Garfield>"); strings.push_back("<http://www.mpii.de/yago/resource/Caroline_Harrison>"); strings.push_back("<http://www.mpii.de/yago/resource/Letitia_Christian_Tyler>"); strings.push_back("<http://www.mpii.de/yago/resource/Sarah_Childress_Polk>"); strings.push_back("<http://www.mpii.de/yago/resource/Julia_Gardiner_Tyler>"); strings.push_back("<http://www.mpii.de/yago/resource/Margaret_Taylor>"); strings.push_back("<http://www.mpii.de/yago/resource/Pascagoula,_Mississippi>"); strings.push_back("<http://www.mpii.de/yago/resource/Abigail_Fillmore>"); strings.push_back("<http://www.mpii.de/yago/resource/Hal_Ashby>"); strings.push_back("<http://www.mpii.de/yago/resource/Imad_Mughniyah>"); strings.push_back("<http://www.mpii.de/yago/resource/Lu%C3%ADs_Cabral>"); strings.push_back("<http://www.mpii.de/yago/resource/Torres_Vedras>"); strings.push_back("<http://www.mpii.de/yago/resource/Charles_Herbert_Allen>"); strings.push_back("<http://www.mpii.de/yago/resource/Lowell,_Massachusetts>"); strings.push_back("<http://www.mpii.de/yago/resource/August_Neidhardt_von_Gneisenau>"); strings.push_back("<http://www.mpii.de/yago/resource/Betty_Loh>"); strings.push_back("<http://www.mpii.de/yago/resource/Mark_Hopkins,_Jr.>"); strings.push_back("<http://www.mpii.de/yago/resource/Yuma,_Arizona>"); strings.push_back("<http://www.mpii.de/yago/resource/William_A._Paterson>"); strings.push_back("<http://www.mpii.de/yago/resource/Frederic_Thesiger,_1st_Baron_Chelmsford>"); strings.push_back("<http://www.mpii.de/yago/resource/Richard_Bourke,_6th_Earl_of_Mayo>"); strings.push_back("<http://www.mpii.de/yago/resource/Port_Blair>"); strings.push_back("<http://www.mpii.de/yago/resource/Benedict_Arnold>"); strings.push_back("<http://www.mpii.de/yago/resource/Kenny_Guinn>"); strings.push_back("<http://www.mpii.de/yago/resource/Calico_Jack>"); strings.push_back("<http://www.mpii.de/yago/resource/Port_Royal>"); strings.push_back("<http://www.mpii.de/yago/resource/Moses_Alexander>"); strings.push_back("<http://www.mpii.de/yago/resource/Henry_S._Johnston>"); strings.push_back("<http://www.mpii.de/yago/resource/Perry,_Oklahoma>"); strings.push_back("<http://www.mpii.de/yago/resource/Henry_Bellmon>"); strings.push_back("<http://www.mpii.de/yago/resource/Enid,_Oklahoma>"); strings.push_back("<http://www.mpii.de/yago/resource/William_Henry_Bissell>"); strings.push_back("<http://www.mpii.de/yago/resource/Daniel_Carleton_Gajdusek>"); strings.push_back("<http://www.mpii.de/yago/resource/Troms%C3%B8>"); strings.push_back("<http://www.mpii.de/yago/resource/Santo_Trafficante,_Jr.>"); strings.push_back("<http://www.mpii.de/yago/resource/Creighton_Abrams>"); strings.push_back("<http://www.mpii.de/yago/resource/Robert_Stethem>"); strings.push_back("<http://www.mpii.de/yago/resource/John_Peter_Altgeld>"); strings.push_back("<http://www.mpii.de/yago/resource/Joliet,_Illinois>"); strings.push_back("<http://www.mpii.de/yago/resource/Frank_Steunenberg>"); strings.push_back("<http://www.mpii.de/yago/resource/Caldwell,_Idaho>"); strings.push_back("<http://www.mpii.de/yago/resource/Holger_Meins>"); strings.push_back("<http://www.mpii.de/yago/resource/Ernest_Blythe>"); strings.push_back("<http://www.mpii.de/yago/resource/Otto_Hermann_Kahn>"); strings.push_back("<http://www.mpii.de/yago/resource/Arthur_Lismer>"); strings.push_back("<http://www.mpii.de/yago/resource/Lewis_Vernon_Harcourt,_1st_Viscount_Harcourt>"); strings.push_back("<http://www.mpii.de/yago/resource/Arthur_Godfrey>"); strings.push_back("<http://www.mpii.de/yago/resource/Abigail_Scott_Duniway>"); strings.push_back("<http://www.mpii.de/yago/resource/Cecil_H._Underwood>"); strings.push_back("<http://www.mpii.de/yago/resource/Charleston,_West_Virginia>"); strings.push_back("<http://www.mpii.de/yago/resource/James_Stirling_(architect)>"); strings.push_back("<http://www.mpii.de/yago/resource/Alexander_Berkman>"); strings.push_back("<http://www.mpii.de/yago/resource/J._Meade_Falkner>"); strings.push_back("<http://www.mpii.de/yago/resource/Stewart_Granger>"); strings.push_back("<http://www.mpii.de/yago/resource/Ahmadou_Ahidjo>"); strings.push_back("<http://www.mpii.de/yago/resource/Dakar>"); strings.push_back("<http://www.mpii.de/yago/resource/Edmund_FitzAlan,_9th_Earl_of_Arundel>"); strings.push_back("<http://www.mpii.de/yago/resource/David_IV_of_Georgia>"); strings.push_back("<http://www.mpii.de/yago/resource/Tbilisi>"); strings.push_back("<http://www.mpii.de/yago/resource/Jimmie_Davis>"); strings.push_back("<http://www.mpii.de/yago/resource/Haing_S._Ngor>"); strings.push_back("<http://www.mpii.de/yago/resource/Amir_Kabir>"); strings.push_back("<http://www.mpii.de/yago/resource/Kashan>"); strings.push_back("<http://www.mpii.de/yago/resource/Wayne_Morse>"); strings.push_back("<http://www.mpii.de/yago/resource/Norbert_Elias>"); strings.push_back("<http://www.mpii.de/yago/resource/Jorge_Amado>"); strings.push_back("<http://www.mpii.de/yago/resource/Salvador,_Bahia>"); strings.push_back("<http://www.mpii.de/yago/resource/David_Strickland>"); strings.push_back("<http://www.mpii.de/yago/resource/Kamisese_Mara>"); strings.push_back("<http://www.mpii.de/yago/resource/Suva>"); strings.push_back("<http://www.mpii.de/yago/resource/Stanis%C5%82aw_Le%C5%9Bniewski>"); strings.push_back("<http://www.mpii.de/yago/resource/Edward_Arthur_Milne>"); strings.push_back("<http://www.mpii.de/yago/resource/Francesco_Scavullo>"); strings.push_back("<http://www.mpii.de/yago/resource/Terry_Sanford>"); strings.push_back("<http://www.mpii.de/yago/resource/Earl_Hindman>"); strings.push_back("<http://www.mpii.de/yago/resource/Sylvester_%22Pat%22_Weaver>"); strings.push_back("<http://www.mpii.de/yago/resource/Johannes_Gerhardus_Strijdom>"); strings.push_back("<http://www.mpii.de/yago/resource/Countess_Palatine_Hedwig_Elisabeth_of_Neuburg>"); strings.push_back("<http://www.mpii.de/yago/resource/Henry_Huttleston_Rogers>"); strings.push_back("<http://www.mpii.de/yago/resource/Sun_Li-jen>"); strings.push_back("<http://www.mpii.de/yago/resource/William_Mulholland>"); strings.push_back("<http://www.mpii.de/yago/resource/Tom_Hurndall>"); strings.push_back("<http://www.mpii.de/yago/resource/Angelica_Singleton_Van_Buren>"); strings.push_back("<http://www.mpii.de/yago/resource/Lawton_Chiles>"); strings.push_back("<http://www.mpii.de/yago/resource/Richard_O'Kane>"); strings.push_back("<http://www.mpii.de/yago/resource/Petaluma,_California>"); strings.push_back("<http://www.mpii.de/yago/resource/John_Wentworth_(governor)>"); strings.push_back("<http://www.mpii.de/yago/resource/Benning_Wentworth>"); strings.push_back("<http://www.mpii.de/yago/resource/Paul_Lazarsfeld>"); strings.push_back("<http://www.mpii.de/yago/resource/Harry_Chauvel>"); strings.push_back("<http://www.mpii.de/yago/resource/John_Moore_(Scottish_physician)>"); strings.push_back("<http://www.mpii.de/yago/resource/William_Stafford_(poet)>"); strings.push_back("<http://www.mpii.de/yago/resource/Lake_Oswego,_Oregon>"); strings.push_back("<http://www.mpii.de/yago/resource/Josephus_Daniels>"); strings.push_back("<http://www.mpii.de/yago/resource/John_Frederic_Daniell>"); strings.push_back("<http://www.mpii.de/yago/resource/Sophie,_Duchess_of_Hohenberg>"); strings.push_back("<http://www.mpii.de/yago/resource/Willi_Stoph>"); strings.push_back("<http://www.mpii.de/yago/resource/Henry_III,_Duke_of_Brabant>"); strings.push_back("<http://www.mpii.de/yago/resource/Henry_II,_Duke_of_Brabant>"); strings.push_back("<http://www.mpii.de/yago/resource/Charles_Kuralt>"); strings.push_back("<http://www.mpii.de/yago/resource/Marc_Mitscher>"); strings.push_back("<http://www.mpii.de/yago/resource/Nicole_Brown_Simpson>"); strings.push_back("<http://www.mpii.de/yago/resource/George_Habash>"); strings.push_back("<http://www.mpii.de/yago/resource/Candido_Portinari>"); strings.push_back("<http://www.mpii.de/yago/resource/Duane_Hanson>"); strings.push_back("<http://www.mpii.de/yago/resource/Boca_Raton,_Florida>"); strings.push_back("<http://www.mpii.de/yago/resource/G._D._H._Cole>"); strings.push_back("<http://www.mpii.de/yago/resource/Percy_Lavon_Julian>"); strings.push_back("<http://www.mpii.de/yago/resource/Waukegan,_Illinois>"); strings.push_back("<http://www.mpii.de/yago/resource/Hans_Luther>"); strings.push_back("<http://www.mpii.de/yago/resource/Bernhard_von_B%C3%BClow>"); strings.push_back("<http://www.mpii.de/yago/resource/Elijah_Abel>"); strings.push_back("<http://www.mpii.de/yago/resource/Itzik_Kol>"); strings.push_back("<http://www.mpii.de/yago/resource/Kfar_Saba>"); strings.push_back("<http://www.mpii.de/yago/resource/Paul_Harvey>"); strings.push_back("<http://www.mpii.de/yago/resource/Alexander_Lebed>"); strings.push_back("<http://www.mpii.de/yago/resource/Abakan>"); strings.push_back("<http://www.mpii.de/yago/resource/Thomas_Hopkins_Gallaudet>"); strings.push_back("<http://www.mpii.de/yago/resource/Botho_zu_Eulenburg>"); strings.push_back("<http://www.mpii.de/yago/resource/Albrecht_von_Roon>"); strings.push_back("<http://www.mpii.de/yago/resource/Francis_Lovelace>"); strings.push_back("<http://www.mpii.de/yago/resource/Charles_Nelson_Reilly>"); strings.push_back("<http://www.mpii.de/yago/resource/Elizabeth_George_Speare>"); strings.push_back("<http://www.mpii.de/yago/resource/John_FitzAlan,_14th_Earl_of_Arundel>"); strings.push_back("<http://www.mpii.de/yago/resource/Beauvais>"); strings.push_back("<http://www.mpii.de/yago/resource/Daniel_Duncan_McKenzie>"); strings.push_back("<http://www.mpii.de/yago/resource/J._B._M._Hertzog>"); strings.push_back("<http://www.mpii.de/yago/resource/Neil_Bartlett_(chemist)>"); strings.push_back("<http://www.mpii.de/yago/resource/Walnut_Creek,_California>"); strings.push_back("<http://www.mpii.de/yago/resource/Morrison_Waite>"); strings.push_back("<http://www.mpii.de/yago/resource/Edmund_Crouchback>"); strings.push_back("<http://www.mpii.de/yago/resource/Bayonne>"); strings.push_back("<http://www.mpii.de/yago/resource/Thomas_Beckington>"); strings.push_back("<http://www.mpii.de/yago/resource/Wells>"); strings.push_back("<http://www.mpii.de/yago/resource/William_Hopkins>"); strings.push_back("<http://www.mpii.de/yago/resource/Clarence_Irving_Lewis>"); strings.push_back("<http://www.mpii.de/yago/resource/Ram%C3%B3n_Rivero>"); strings.push_back("<http://www.mpii.de/yago/resource/Tom_Bradley_(politician)>"); strings.push_back("<http://www.mpii.de/yago/resource/Tiburcio_V%C3%A1squez>"); strings.push_back("<http://www.mpii.de/yago/resource/San_Jose,_California>"); strings.push_back("<http://www.mpii.de/yago/resource/William_B._Umstead>"); strings.push_back("<http://www.mpii.de/yago/resource/Richard_Caswell>"); strings.push_back("<http://www.mpii.de/yago/resource/Fayetteville,_North_Carolina>"); strings.push_back("<http://www.mpii.de/yago/resource/W._Kerr_Scott>"); strings.push_back("<http://www.mpii.de/yago/resource/Abner_Nash>"); strings.push_back("<http://www.mpii.de/yago/resource/Paul_Gleason>"); strings.push_back("<http://www.mpii.de/yago/resource/Bobby_Jones_(golfer)>"); strings.push_back("<http://www.mpii.de/yago/resource/Atlanta>"); strings.push_back("<http://www.mpii.de/yago/resource/John_Boyd_Dunlop>"); strings.push_back("<http://www.mpii.de/yago/resource/John_David_McWilliam>"); strings.push_back("<http://www.mpii.de/yago/resource/Jim_Marshall_(UK_politician)>"); strings.push_back("<http://www.mpii.de/yago/resource/Hiram_Rhodes_Revels>"); strings.push_back("<http://www.mpii.de/yago/resource/Aberdeen,_Mississippi>"); strings.push_back("<http://www.mpii.de/yago/resource/Clifford_Milburn_Holland>"); strings.push_back("<http://www.mpii.de/yago/resource/Battle_Creek,_Michigan>"); strings.push_back("<http://www.mpii.de/yago/resource/Rafael_Cordero_Santiago>"); strings.push_back("<http://www.mpii.de/yago/resource/Gulzarilal_Nanda>"); strings.push_back("<http://www.mpii.de/yago/resource/Rudolf_Wanderone>"); strings.push_back("<http://www.mpii.de/yago/resource/Francisco_S._Carvajal>"); strings.push_back("<http://www.mpii.de/yago/resource/Miguel_Alem%C3%A1n_Vald%C3%A9s>"); strings.push_back("<http://www.mpii.de/yago/resource/Sirimavo_Bandaranaike>"); strings.push_back("<http://www.mpii.de/yago/resource/Allard_K._Lowenstein>"); strings.push_back("<http://www.mpii.de/yago/resource/Sidney_Reilly>"); strings.push_back("<http://www.mpii.de/yago/resource/Pope_Conon>"); strings.push_back("<http://www.mpii.de/yago/resource/Grand_Duchess_Maria_Alexandrovna_of_Russia>"); strings.push_back("<http://www.mpii.de/yago/resource/Napoleon_B._Broward>"); strings.push_back("<http://www.mpii.de/yago/resource/John_Augustine_Collins>"); strings.push_back("<http://www.mpii.de/yago/resource/Ben_Johnson_(actor)>"); strings.push_back("<http://www.mpii.de/yago/resource/Mesa,_Arizona>"); strings.push_back("<http://www.mpii.de/yago/resource/Ram%C3%B3n_Vald%C3%A9s>"); strings.push_back("<http://www.mpii.de/yago/resource/George_Herbert_Walker>"); strings.push_back("<http://www.mpii.de/yago/resource/Pope_Adeodatus_II>"); strings.push_back("<http://www.mpii.de/yago/resource/Pope_Donus>"); strings.push_back("<http://www.mpii.de/yago/resource/Pope_Sisinnius>"); strings.push_back("<http://www.mpii.de/yago/resource/Eddie_Mabo>"); strings.push_back("<http://www.mpii.de/yago/resource/Rufus_Choate>"); strings.push_back("<http://www.mpii.de/yago/resource/Edward_F._Arn>"); strings.push_back("<http://www.mpii.de/yago/resource/Wichita,_Kansas>"); strings.push_back("<http://www.mpii.de/yago/resource/Lawrence_Pazder>"); strings.push_back("<http://www.mpii.de/yago/resource/Wolfgang_Harich>"); strings.push_back("<http://www.mpii.de/yago/resource/Francis_P._Fleming>"); strings.push_back("<http://www.mpii.de/yago/resource/Angelines_Fern%C3%A1ndez>"); strings.push_back("<http://www.mpii.de/yago/resource/William_Jones_(statesman)>"); strings.push_back("<http://www.mpii.de/yago/resource/Mathew_Brady>"); strings.push_back("<http://www.mpii.de/yago/resource/Prince_Carl,_Duke_of_V%C3%A4sterg%C3%B6tland>"); strings.push_back("<http://www.mpii.de/yago/resource/Princess_Margaretha_of_Sweden>"); strings.push_back("<http://www.mpii.de/yago/resource/Faxe>"); strings.push_back("<http://www.mpii.de/yago/resource/John_Bell_Hood>"); strings.push_back("<http://www.mpii.de/yago/resource/Charles_Algernon_Parsons>"); strings.push_back("<http://www.mpii.de/yago/resource/Richard_J._Hughes>"); strings.push_back("<http://www.mpii.de/yago/resource/Walter_Evans_Edge>"); strings.push_back("<http://www.mpii.de/yago/resource/Robert_Woodward_Barnwell>"); strings.push_back("<http://www.mpii.de/yago/resource/Andrija_%C5%A0tampar>"); strings.push_back("<http://www.mpii.de/yago/resource/Harold_G._Hoffman>"); strings.push_back("<http://www.mpii.de/yago/resource/Rudolph_I_of_Bohemia>"); strings.push_back("<http://www.mpii.de/yago/resource/Hora%C5%BE%C4%8Fovice>"); strings.push_back("<http://www.mpii.de/yago/resource/Peljidiin_Genden>"); strings.push_back("<http://www.mpii.de/yago/resource/Claude_Perrault>"); strings.push_back("<http://www.mpii.de/yago/resource/Simon_Snyder>"); strings.push_back("<http://www.mpii.de/yago/resource/William_Findlay_(governor)>"); strings.push_back("<http://www.mpii.de/yago/resource/Joseph_Hiester>"); strings.push_back("<http://www.mpii.de/yago/resource/John_W._Geary>"); strings.push_back("<http://www.mpii.de/yago/resource/Archibald_Campbell,_1st_Marquess_of_Argyll>"); strings.push_back("<http://www.mpii.de/yago/resource/David_Davis_(Supreme_Court_justice)>"); strings.push_back("<http://www.mpii.de/yago/resource/Bloomington,_Illinois>"); strings.push_back("<http://www.mpii.de/yago/resource/Hjalmar_Johansen>"); strings.push_back("<http://www.mpii.de/yago/resource/D._W._Davis>"); strings.push_back("<http://www.mpii.de/yago/resource/Sergey_Prokudin-Gorsky>"); strings.push_back("<http://www.mpii.de/yago/resource/J._Hugo_Aronson>"); strings.push_back("<http://www.mpii.de/yago/resource/Columbia_Falls,_Montana>"); strings.push_back("<http://www.mpii.de/yago/resource/James_Hamilton_Peabody>"); strings.push_back("<http://www.mpii.de/yago/resource/Ca%C3%B1on_City,_Colorado>"); strings.push_back("<http://www.mpii.de/yago/resource/Agostinho_Neto>"); strings.push_back("<http://www.mpii.de/yago/resource/Ted_Fujita>"); strings.push_back("<http://www.mpii.de/yago/resource/Sh%C5%8Dhei_%C5%8Coka>"); strings.push_back("<http://www.mpii.de/yago/resource/Don_Messick>"); strings.push_back("<http://www.mpii.de/yago/resource/Salinas,_California>"); strings.push_back("<http://www.mpii.de/yago/resource/Rikki_Fulton>"); strings.push_back("<http://www.mpii.de/yago/resource/Ted_Nebbeling>"); strings.push_back("<http://www.mpii.de/yago/resource/Paul_Tsongas>"); strings.push_back("<http://www.mpii.de/yago/resource/David_Ervine>"); strings.push_back("<http://www.mpii.de/yago/resource/George_Woodbridge>"); strings.push_back("<http://www.mpii.de/yago/resource/John_Ponsonby,_4th_Earl_of_Bessborough>"); strings.push_back("<http://www.mpii.de/yago/resource/Johnny_Farrell>"); strings.push_back("<http://www.mpii.de/yago/resource/Boynton_Beach,_Florida>"); strings.push_back("<http://www.mpii.de/yago/resource/Robert_Smith_(mathematician)>"); strings.push_back("<http://www.mpii.de/yago/resource/Fanni_Kaplan>"); strings.push_back("<http://www.mpii.de/yago/resource/G%C3%A9rard_Brach>"); strings.push_back("<http://www.mpii.de/yago/resource/Lloyd_Kenyon,_1st_Baron_Kenyon>"); strings.push_back("<http://www.mpii.de/yago/resource/Suraiya>"); strings.push_back("<http://www.mpii.de/yago/resource/Usama_ibn_Munqidh>"); strings.push_back("<http://www.mpii.de/yago/resource/Kawai_Gyokud%C5%8D>"); strings.push_back("<http://www.mpii.de/yago/resource/John_I_Albert_of_Poland>"); strings.push_back("<http://www.mpii.de/yago/resource/Toru%C5%84>"); strings.push_back("<http://www.mpii.de/yago/resource/Max_Robinson>"); strings.push_back("<http://www.mpii.de/yago/resource/Ingrid_Thulin>"); strings.push_back("<http://www.mpii.de/yago/resource/Gust%C3%A1v_Hus%C3%A1k>"); strings.push_back("<http://www.mpii.de/yago/resource/Lobsang_Rampa>"); strings.push_back("<http://www.mpii.de/yago/resource/Ian_Stevenson>"); strings.push_back("<http://www.mpii.de/yago/resource/Ferdinand_Schichau>"); strings.push_back("<http://www.mpii.de/yago/resource/Elbl%C4%85g>"); strings.push_back("<http://www.mpii.de/yago/resource/Johannes_Itten>"); strings.push_back("<http://www.mpii.de/yago/resource/Fred_Hollows>"); strings.push_back("<http://www.mpii.de/yago/resource/Vernon_Malone>"); strings.push_back("<http://www.mpii.de/yago/resource/Fritz_Julius_Kuhn>"); strings.push_back("<http://www.mpii.de/yago/resource/Andrija_Maurovi%C4%87>"); strings.push_back("<http://www.mpii.de/yago/resource/Hans_Jonas>"); strings.push_back("<http://www.mpii.de/yago/resource/Bona_Sforza>"); strings.push_back("<http://www.mpii.de/yago/resource/Ralph_Nelson>"); strings.push_back("<http://www.mpii.de/yago/resource/Thoralf_Skolem>"); strings.push_back("<http://www.mpii.de/yago/resource/L._Patrick_Gray>"); strings.push_back("<http://www.mpii.de/yago/resource/Atlantic_Beach,_Florida>"); strings.push_back("<http://www.mpii.de/yago/resource/Charles_Alvin_Beckwith>"); strings.push_back("<http://www.mpii.de/yago/resource/Iskander_Mirza>"); strings.push_back("<http://www.mpii.de/yago/resource/George_Murdoch>"); strings.push_back("<http://www.mpii.de/yago/resource/James_Benton_Grant>"); strings.push_back("<http://www.mpii.de/yago/resource/Excelsior_Springs,_Missouri>"); strings.push_back("<http://www.mpii.de/yago/resource/Elpidio_Quirino>"); strings.push_back("<http://www.mpii.de/yago/resource/Ralf_Dahrendorf>"); strings.push_back("<http://www.mpii.de/yago/resource/William_Fargo>"); strings.push_back("<http://www.mpii.de/yago/resource/Joseph_Black>"); strings.push_back("<http://www.mpii.de/yago/resource/Nicolas_Desmarest>"); strings.push_back("<http://www.mpii.de/yago/resource/Heinrich_Louis_d'Arrest>"); strings.push_back("<http://www.mpii.de/yago/resource/Sh%C5%8Dhei_Imamura>"); strings.push_back("<http://www.mpii.de/yago/resource/Gordon_MacRae>"); strings.push_back("<http://www.mpii.de/yago/resource/Lincoln,_Nebraska>"); strings.push_back("<http://www.mpii.de/yago/resource/Kate_Sheppard>"); strings.push_back("<http://www.mpii.de/yago/resource/William_H._Murray>"); strings.push_back("<http://www.mpii.de/yago/resource/Tishomingo,_Oklahoma>"); strings.push_back("<http://www.mpii.de/yago/resource/Donald_Maclean_(British_politician)>"); strings.push_back("<http://www.mpii.de/yago/resource/Carl-Gustaf_Rossby>"); strings.push_back("<http://www.mpii.de/yago/resource/Miriam_Waddington>"); strings.push_back("<http://www.mpii.de/yago/resource/Murder_of_Polly_Klaas>"); strings.push_back("<http://www.mpii.de/yago/resource/Nadezhda_Krupskaya>"); strings.push_back("<http://www.mpii.de/yago/resource/Lewis_H._Morgan>"); strings.push_back("<http://www.mpii.de/yago/resource/Trugernanner>"); strings.push_back("<http://www.mpii.de/yago/resource/Hobart>"); strings.push_back("<http://www.mpii.de/yago/resource/Stephen_Toma%C5%A1evi%C4%87_of_Bosnia>"); strings.push_back("<http://www.mpii.de/yago/resource/Jajce>"); strings.push_back("<http://www.mpii.de/yago/resource/Christian_Leopold_von_Buch>"); strings.push_back("<http://www.mpii.de/yago/resource/Mak_Dizdar>"); strings.push_back("<http://www.mpii.de/yago/resource/Fernando_Sor>"); strings.push_back("<http://www.mpii.de/yago/resource/George_Frisbie_Hoar>"); strings.push_back("<http://www.mpii.de/yago/resource/Worcester,_Massachusetts>"); strings.push_back("<http://www.mpii.de/yago/resource/Xu_Zhimo>"); strings.push_back("<http://www.mpii.de/yago/resource/Jinan>"); strings.push_back("<http://www.mpii.de/yago/resource/E._B._Ford>"); strings.push_back("<http://www.mpii.de/yago/resource/Johnny_Leartice_Robinson>"); strings.push_back("<http://www.mpii.de/yago/resource/John_Wesley_Hardin>"); strings.push_back("<http://www.mpii.de/yago/resource/Timothy_Pickering>"); strings.push_back("<http://www.mpii.de/yago/resource/Salem,_Massachusetts>"); strings.push_back("<http://www.mpii.de/yago/resource/John_Langdon>"); strings.push_back("<http://www.mpii.de/yago/resource/Georgios_Rallis>"); strings.push_back("<http://www.mpii.de/yago/resource/Corfu>"); strings.push_back("<http://www.mpii.de/yago/resource/C%C3%A9sar-Fran%C3%A7ois_Cassini_de_Thury>"); strings.push_back("<http://www.mpii.de/yago/resource/Luigi_Malerba>"); strings.push_back("<http://www.mpii.de/yago/resource/Moe_Howard>"); strings.push_back("<http://www.mpii.de/yago/resource/Champ_Clark>"); strings.push_back("<http://www.mpii.de/yago/resource/Leander_Starr_Jameson>"); strings.push_back("<http://www.mpii.de/yago/resource/Robert_Adrain>"); strings.push_back("<http://www.mpii.de/yago/resource/F%C3%A9lix_d'Herelle>"); strings.push_back("<http://www.mpii.de/yago/resource/Vlaho_Bukovac>"); strings.push_back("<http://www.mpii.de/yago/resource/George_S._Mickelson>"); strings.push_back("<http://www.mpii.de/yago/resource/Alexander_Kielland>"); strings.push_back("<http://www.mpii.de/yago/resource/Bergen>"); strings.push_back("<http://www.mpii.de/yago/resource/J%C5%ABz%C5%8D_Itami>"); strings.push_back("<http://www.mpii.de/yago/resource/Curt_Hennig>"); strings.push_back("<http://www.mpii.de/yago/resource/John_Tower>"); strings.push_back("<http://www.mpii.de/yago/resource/Brunswick,_Georgia>"); strings.push_back("<http://www.mpii.de/yago/resource/U._G._Krishnamurti>"); strings.push_back("<http://www.mpii.de/yago/resource/Vallecrosia>"); strings.push_back("<http://www.mpii.de/yago/resource/Constantin_Carath%C3%A9odory>"); strings.push_back("<http://www.mpii.de/yago/resource/Mulk_Raj_Anand>"); strings.push_back("<http://www.mpii.de/yago/resource/Miep_Gies>"); strings.push_back("<http://www.mpii.de/yago/resource/Hoorn>"); strings.push_back("<http://www.mpii.de/yago/resource/Vladimir_Prelog>"); strings.push_back("<http://www.mpii.de/yago/resource/Xenophon_Zolotas>"); strings.push_back("<http://www.mpii.de/yago/resource/M._G._Ramachandran>"); strings.push_back("<http://www.mpii.de/yago/resource/Hiroshi_Inagaki>"); strings.push_back("<http://www.mpii.de/yago/resource/N%C3%A2z%C4%B1m_Hikmet>"); strings.push_back("<http://www.mpii.de/yago/resource/John_Biffen>"); strings.push_back("<http://www.mpii.de/yago/resource/Zuo_Zongtang>"); strings.push_back("<http://www.mpii.de/yago/resource/Fuzhou>"); strings.push_back("<http://www.mpii.de/yago/resource/Greyfriars_Bobby>"); strings.push_back("<http://www.mpii.de/yago/resource/Nikolai_Bulganin>"); strings.push_back("<http://www.mpii.de/yago/resource/Bella_Abzug>"); strings.push_back("<http://www.mpii.de/yago/resource/Johnny_Torrio>"); strings.push_back("<http://www.mpii.de/yago/resource/Yonatan_Netanyahu>"); strings.push_back("<http://www.mpii.de/yago/resource/Entebbe>"); strings.push_back("<http://www.mpii.de/yago/resource/Tetsur%C5%8D_Tamba>"); strings.push_back("<http://www.mpii.de/yago/resource/Honor%C3%A9_Beaugrand>"); strings.push_back("<http://www.mpii.de/yago/resource/Robinson_Jeffers>"); strings.push_back("<http://www.mpii.de/yago/resource/Nizar_Qabbani>"); strings.push_back("<http://www.mpii.de/yago/resource/Tzannis_Tzannetakis>"); strings.push_back("<http://www.mpii.de/yago/resource/Robert_F._Furchgott>"); strings.push_back("<http://www.mpii.de/yago/resource/Otto_Fritz_Meyerhof>"); strings.push_back("<http://www.mpii.de/yago/resource/Heinrich_Gustav_Magnus>"); strings.push_back("<http://www.mpii.de/yago/resource/Louis_Jacques_Th%C3%A9nard>"); strings.push_back("<http://www.mpii.de/yago/resource/Jean-Antoine_Chaptal>"); strings.push_back("<http://www.mpii.de/yago/resource/William_Quantrill>"); strings.push_back("<http://www.mpii.de/yago/resource/Taylorsville,_Kentucky>"); strings.push_back("<http://www.mpii.de/yago/resource/Ralph_Canine>"); strings.push_back("<http://www.mpii.de/yago/resource/C._H._D._Buys_Ballot>"); strings.push_back("<http://www.mpii.de/yago/resource/Maria_Mandel>"); strings.push_back("<http://www.mpii.de/yago/resource/Nina_Wang>"); strings.push_back("<http://www.mpii.de/yago/resource/Joseph_Rochefort>"); strings.push_back("<http://www.mpii.de/yago/resource/Ba_Jin>"); strings.push_back("<http://www.mpii.de/yago/resource/Du%C5%A1an_D%C5%BEamonja>"); strings.push_back("<http://www.mpii.de/yago/resource/Harvey_Pekar>"); strings.push_back("<http://www.mpii.de/yago/resource/Cleveland_Heights,_Ohio>"); strings.push_back("<http://www.mpii.de/yago/resource/Howard_Ashman>"); strings.push_back("<http://www.mpii.de/yago/resource/Marko_Maruli%C4%87>"); strings.push_back("<http://www.mpii.de/yago/resource/Split_(city)>"); strings.push_back("<http://www.mpii.de/yago/resource/Saint_Barbara>"); strings.push_back("<http://www.mpii.de/yago/resource/Sebasti%C3%A1n_Lerdo_de_Tejada>"); strings.push_back("<http://www.mpii.de/yago/resource/Alexander_Herzen>"); strings.push_back("<http://www.mpii.de/yago/resource/James_B._McPherson>"); strings.push_back("<http://www.mpii.de/yago/resource/K._B._Hedgewar>"); strings.push_back("<http://www.mpii.de/yago/resource/Nagpur>"); strings.push_back("<http://www.mpii.de/yago/resource/Jean_de_Lattre_de_Tassigny>"); strings.push_back("<http://www.mpii.de/yago/resource/John_Sharp_Williams>"); strings.push_back("<http://www.mpii.de/yago/resource/Yazoo_City,_Mississippi>"); strings.push_back("<http://www.mpii.de/yago/resource/John_Gresham_Machen>"); strings.push_back("<http://www.mpii.de/yago/resource/Bismarck,_North_Dakota>"); strings.push_back("<http://www.mpii.de/yago/resource/Suzanne_Bianchetti>"); strings.push_back("<http://www.mpii.de/yago/resource/E._Fay_Jones>"); strings.push_back("<http://www.mpii.de/yago/resource/Fayetteville,_Arkansas>"); strings.push_back("<http://www.mpii.de/yago/resource/Chester_Lauck>"); strings.push_back("<http://www.mpii.de/yago/resource/Seal_Beach,_California>"); strings.push_back("<http://www.mpii.de/yago/resource/Dale_Alford>"); strings.push_back("<http://www.mpii.de/yago/resource/Dominique_Laffin>"); strings.push_back("<http://www.mpii.de/yago/resource/Leo_Amery>"); strings.push_back("<http://www.mpii.de/yago/resource/Barbu_Catargiu>"); strings.push_back("<http://www.mpii.de/yago/resource/Rembrandt_Peale>"); strings.push_back("<http://www.mpii.de/yago/resource/Alu%C3%ADsio_Azevedo>"); strings.push_back("<http://www.mpii.de/yago/resource/La_Plata>"); strings.push_back("<http://www.mpii.de/yago/resource/Tom%C3%A1s_Mac_Giolla>"); strings.push_back("<http://www.mpii.de/yago/resource/Nicholas_Longworth>"); strings.push_back("<http://www.mpii.de/yago/resource/Nicholas_Culpeper>"); strings.push_back("<http://www.mpii.de/yago/resource/Valery_Chkalov>"); strings.push_back("<http://www.mpii.de/yago/resource/Iwane_Matsui>"); strings.push_back("<http://www.mpii.de/yago/resource/Claudia_Cohen>"); strings.push_back("<http://www.mpii.de/yago/resource/John_G._Carlisle>"); strings.push_back("<http://www.mpii.de/yago/resource/Woodrow_Stanley_Lloyd>"); strings.push_back("<http://www.mpii.de/yago/resource/Padmarajan>"); strings.push_back("<http://www.mpii.de/yago/resource/Kozhikode>"); strings.push_back("<http://www.mpii.de/yago/resource/Yevgeny_Polivanov>"); strings.push_back("<http://www.mpii.de/yago/resource/William_Hull>"); strings.push_back("<http://www.mpii.de/yago/resource/Wladimir_K%C3%B6ppen>"); strings.push_back("<http://www.mpii.de/yago/resource/Tim_Russert>"); strings.push_back("<http://www.mpii.de/yago/resource/Jim_Bacon>"); strings.push_back("<http://www.mpii.de/yago/resource/Vijay_Anand>"); strings.push_back("<http://www.mpii.de/yago/resource/Maria_Schell>"); strings.push_back("<http://www.mpii.de/yago/resource/Preitenegg>"); strings.push_back("<http://www.mpii.de/yago/resource/C._L._Schmitt>"); strings.push_back("<http://www.mpii.de/yago/resource/New_Kensington,_Pennsylvania>"); strings.push_back("<http://www.mpii.de/yago/resource/Norman_Birkett,_1st_Baron_Birkett>"); strings.push_back("<http://www.mpii.de/yago/resource/Bill_Oakley_(artist)>"); strings.push_back("<http://www.mpii.de/yago/resource/Eliezer_Ben-Yehuda>"); strings.push_back("<http://www.mpii.de/yago/resource/Anastas_Mikoyan>"); strings.push_back("<http://www.mpii.de/yago/resource/Ernst_Curtius>"); strings.push_back("<http://www.mpii.de/yago/resource/Annette_Vadim>"); strings.push_back("<http://www.mpii.de/yago/resource/Chad_of_Mercia>"); strings.push_back("<http://www.mpii.de/yago/resource/Kalki_Krishnamurthy>"); strings.push_back("<http://www.mpii.de/yago/resource/Ransom_E._Olds>"); strings.push_back("<http://www.mpii.de/yago/resource/Lansing,_Michigan>"); strings.push_back("<http://www.mpii.de/yago/resource/Elizabeth_Monroe>"); strings.push_back("<http://www.mpii.de/yago/resource/Juan_Manuel_de_Rosas>"); strings.push_back("<http://www.mpii.de/yago/resource/John_Harvey_Kellogg>"); strings.push_back("<http://www.mpii.de/yago/resource/Levi_Boone>"); strings.push_back("<http://www.mpii.de/yago/resource/Edward_Dunlop>"); strings.push_back("<http://www.mpii.de/yago/resource/John_Proctor>"); strings.push_back("<http://www.mpii.de/yago/resource/James_Moore_Wayne>"); strings.push_back("<http://www.mpii.de/yago/resource/Winnifred_Eaton>"); strings.push_back("<http://www.mpii.de/yago/resource/Butte,_Montana>"); strings.push_back("<http://www.mpii.de/yago/resource/Ted_Briggs>"); strings.push_back("<http://www.mpii.de/yago/resource/Arthur_Greiser>"); strings.push_back("<http://www.mpii.de/yago/resource/Roy_Stryker>"); strings.push_back("<http://www.mpii.de/yago/resource/Grand_Junction,_Colorado>"); strings.push_back("<http://www.mpii.de/yago/resource/Christen_S%C3%B8rensen_Longomontanus>"); strings.push_back("<http://www.mpii.de/yago/resource/Terence_Cooper>"); strings.push_back("<http://www.mpii.de/yago/resource/Cairns,_Queensland>"); strings.push_back("<http://www.mpii.de/yago/resource/Ernesto_Geisel>"); strings.push_back("<http://www.mpii.de/yago/resource/John_Marshall_Harlan>"); strings.push_back("<http://www.mpii.de/yago/resource/Kamehameha_II>"); strings.push_back("<http://www.mpii.de/yago/resource/Hans_Vaihinger>"); strings.push_back("<http://www.mpii.de/yago/resource/Willy_Millowitsch>"); strings.push_back("<http://www.mpii.de/yago/resource/Josiah_Royce>"); strings.push_back("<http://www.mpii.de/yago/resource/Joe_Viterelli>"); strings.push_back("<http://www.mpii.de/yago/resource/Oliver_Phelps>"); strings.push_back("<http://www.mpii.de/yago/resource/Canandaigua_(city),_New_York>"); strings.push_back("<http://www.mpii.de/yago/resource/Genrikh_Yagoda>"); strings.push_back("<http://www.mpii.de/yago/resource/Kay_Yow>"); strings.push_back("<http://www.mpii.de/yago/resource/Cary,_North_Carolina>"); strings.push_back("<http://www.mpii.de/yago/resource/Nikolai_Yezhov>"); strings.push_back("<http://www.mpii.de/yago/resource/Susan_Atkins>"); strings.push_back("<http://www.mpii.de/yago/resource/Chowchilla,_California>"); strings.push_back("<http://www.mpii.de/yago/resource/Anthony_Joseph_Drexel_Biddle,_Sr.>"); strings.push_back("<http://www.mpii.de/yago/resource/Edward_Needles_Hallowell>"); strings.push_back("<http://www.mpii.de/yago/resource/William_Ralph_Meredith>"); strings.push_back("<http://www.mpii.de/yago/resource/Joseph_Cahill>"); strings.push_back("<http://www.mpii.de/yago/resource/Claude_Berri>"); strings.push_back("<http://www.mpii.de/yago/resource/Cliff_Arquette>"); strings.push_back("<http://www.mpii.de/yago/resource/Patrick_Gordon_Walker>"); strings.push_back("<http://www.mpii.de/yago/resource/Alberts_Kviesis>"); strings.push_back("<http://www.mpii.de/yago/resource/Riga>"); strings.push_back("<http://www.mpii.de/yago/resource/Richard_F._Kneip>"); strings.push_back("<http://www.mpii.de/yago/resource/William_Cheselden>"); strings.push_back("<http://www.mpii.de/yago/resource/Otto_Liman_von_Sanders>"); strings.push_back("<http://www.mpii.de/yago/resource/Rose_O'Neill>"); strings.push_back("<http://www.mpii.de/yago/resource/Anthony_Minghella>"); strings.push_back("<http://www.mpii.de/yago/resource/Bob_Ross>"); strings.push_back("<http://www.mpii.de/yago/resource/New_Smyrna_Beach,_Florida>"); strings.push_back("<http://www.mpii.de/yago/resource/Boss_Johnson>"); strings.push_back("<http://www.mpii.de/yago/resource/Lev_Kopelev>"); strings.push_back("<http://www.mpii.de/yago/resource/Will_H._Hays>"); strings.push_back("<http://www.mpii.de/yago/resource/Sullivan,_Indiana>"); strings.push_back("<http://www.mpii.de/yago/resource/Wojciech_Frykowski>"); strings.push_back("<http://www.mpii.de/yago/resource/Peter_Rice>"); strings.push_back("<http://www.mpii.de/yago/resource/Mahadevi_Varma>"); strings.push_back("<http://www.mpii.de/yago/resource/Suryakant_Tripathi_'Nirala'>"); strings.push_back("<http://www.mpii.de/yago/resource/Michael_Wilding_(actor)>"); strings.push_back("<http://www.mpii.de/yago/resource/Conrad_Hilton,_Jr.>"); strings.push_back("<http://www.mpii.de/yago/resource/Warren_Winslow>"); strings.push_back("<http://www.mpii.de/yago/resource/Alfred_Moore_Scales>"); strings.push_back("<http://www.mpii.de/yago/resource/Greensboro,_North_Carolina>"); strings.push_back("<http://www.mpii.de/yago/resource/Thomas_Bragg>"); strings.push_back("<http://www.mpii.de/yago/resource/David_Settle_Reid>"); strings.push_back("<http://www.mpii.de/yago/resource/Reidsville,_North_Carolina>"); strings.push_back("<http://www.mpii.de/yago/resource/Richard_Dobbs_Spaight,_Jr.>"); strings.push_back("<http://www.mpii.de/yago/resource/New_Bern,_North_Carolina>"); strings.push_back("<http://www.mpii.de/yago/resource/William_Alexander_Graham>"); strings.push_back("<http://www.mpii.de/yago/resource/Saratoga_Springs,_New_York>"); strings.push_back("<http://www.mpii.de/yago/resource/Edward_Bishop_Dudley>"); strings.push_back("<http://www.mpii.de/yago/resource/Benjamin_Smith_(North_Carolina)>"); strings.push_back("<http://www.mpii.de/yago/resource/Southport,_North_Carolina>"); strings.push_back("<http://www.mpii.de/yago/resource/David_Stone>"); strings.push_back("<http://www.mpii.de/yago/resource/Richard_Dobbs_Spaight>"); strings.push_back("<http://www.mpii.de/yago/resource/Armand_C%C4%83linescu>"); strings.push_back("<http://www.mpii.de/yago/resource/Bruce_McCandless>"); strings.push_back("<http://www.mpii.de/yago/resource/Thomas_Jordan_Jarvis>"); strings.push_back("<http://www.mpii.de/yago/resource/Greenville,_North_Carolina>"); strings.push_back("<http://www.mpii.de/yago/resource/Titu_Maiorescu>"); strings.push_back("<http://www.mpii.de/yago/resource/Charles_Galton_Darwin>"); strings.push_back("<http://www.mpii.de/yago/resource/Alexandru_Averescu>"); strings.push_back("<http://www.mpii.de/yago/resource/John_List>"); strings.push_back("<http://www.mpii.de/yago/resource/Germain_of_Paris>"); strings.push_back("<http://www.mpii.de/yago/resource/Eric_I_of_Denmark>"); strings.push_back("<http://www.mpii.de/yago/resource/Sergio_Osme%C3%B1a>"); strings.push_back("<http://www.mpii.de/yago/resource/Robert_Ridgway>"); strings.push_back("<http://www.mpii.de/yago/resource/Olney,_Illinois>"); strings.push_back("<http://www.mpii.de/yago/resource/Nicholas_Metropolis>"); strings.push_back("<http://www.mpii.de/yago/resource/Los_Alamos,_New_Mexico>"); strings.push_back("<http://www.mpii.de/yago/resource/F._E._Smith,_1st_Earl_of_Birkenhead>"); strings.push_back("<http://www.mpii.de/yago/resource/H._Richard_Hornberger>"); strings.push_back("<http://www.mpii.de/yago/resource/Waterville,_Maine>"); strings.push_back("<http://www.mpii.de/yago/resource/Frank_Knox>"); strings.push_back("<http://www.mpii.de/yago/resource/Byron_Nelson>"); strings.push_back("<http://www.mpii.de/yago/resource/Roanoke,_Texas>"); strings.push_back("<http://www.mpii.de/yago/resource/John_Wooden>"); strings.push_back("<http://www.mpii.de/yago/resource/Frank_Murphy>"); strings.push_back("<http://www.mpii.de/yago/resource/E._J._Harrison_(golfer)>"); strings.push_back("<http://www.mpii.de/yago/resource/Jack_Adams_(ice_hockey_b._1895)>"); strings.push_back("<http://www.mpii.de/yago/resource/Georges_V%C3%A9zina>"); strings.push_back("<http://www.mpii.de/yago/resource/Chicoutimi>"); strings.push_back("<http://www.mpii.de/yago/resource/Louis_Slotin>"); strings.push_back("<http://www.mpii.de/yago/resource/Per_Jacobsson>"); strings.push_back("<http://www.mpii.de/yago/resource/Pierre-Paul_Schweitzer>"); strings.push_back("<http://www.mpii.de/yago/resource/E._C._Segar>"); strings.push_back("<http://www.mpii.de/yago/resource/Henry_Vivian,_1st_Baron_Swansea>"); strings.push_back("<http://www.mpii.de/yago/resource/Swansea>"); strings.push_back("<http://www.mpii.de/yago/resource/Petru_Groza>"); strings.push_back("<http://www.mpii.de/yago/resource/Ernst_Busch_(actor)>"); strings.push_back("<http://www.mpii.de/yago/resource/Sanjeev_Kumar>"); strings.push_back("<http://www.mpii.de/yago/resource/Abbott_Lawrence_Lowell>"); strings.push_back("<http://www.mpii.de/yago/resource/Alfred_Mond,_1st_Baron_Melchett>"); strings.push_back("<http://www.mpii.de/yago/resource/Prince_Nashimoto_Morimasa>"); strings.push_back("<http://www.mpii.de/yago/resource/Margaret_of_Provence>"); strings.push_back("<http://www.mpii.de/yago/resource/Jos%C3%A9_Batlle_y_Ord%C3%B3%C3%B1ez>"); strings.push_back("<http://www.mpii.de/yago/resource/Petronila_of_Aragon>"); strings.push_back("<http://www.mpii.de/yago/resource/Henry_Dodge>"); strings.push_back("<http://www.mpii.de/yago/resource/Taras_Shevchenko>"); strings.push_back("<http://www.mpii.de/yago/resource/James_F._Wilson>"); strings.push_back("<http://www.mpii.de/yago/resource/Fairfield,_Iowa>"); strings.push_back("<http://www.mpii.de/yago/resource/James_Wilson_(U.S._politician)>"); strings.push_back("<http://www.mpii.de/yago/resource/Traer,_Iowa>"); strings.push_back("<http://www.mpii.de/yago/resource/Constantin_Hansen>"); strings.push_back("<http://www.mpii.de/yago/resource/Alan_Berg>"); strings.push_back("<http://www.mpii.de/yago/resource/Emma_Verona_Johnston>"); strings.push_back("<http://www.mpii.de/yago/resource/Worthington,_Ohio>"); strings.push_back("<http://www.mpii.de/yago/resource/James_Henry_Thomas>"); strings.push_back("<http://www.mpii.de/yago/resource/Betty_Ong>"); strings.push_back("<http://www.mpii.de/yago/resource/Tayeb_Salih>"); strings.push_back("<http://www.mpii.de/yago/resource/Pappy_Boyington>"); strings.push_back("<http://www.mpii.de/yago/resource/Richard_Hofstadter>"); strings.push_back("<http://www.mpii.de/yago/resource/Christoffer_Wilhelm_Eckersberg>"); strings.push_back("<http://www.mpii.de/yago/resource/David_Murray_Anderson>"); strings.push_back("<http://www.mpii.de/yago/resource/Hans_Hermann_Gro%C3%ABr>"); strings.push_back("<http://www.mpii.de/yago/resource/Sankt_P%C3%B6lten>"); strings.push_back("<http://www.mpii.de/yago/resource/I._A._L._Diamond>"); strings.push_back("<http://www.mpii.de/yago/resource/George_Edmund_Badger>"); strings.push_back("<http://www.mpii.de/yago/resource/Thomas_Lanier_Clingman>"); strings.push_back("<http://www.mpii.de/yago/resource/Morganton,_North_Carolina>"); strings.push_back("<http://www.mpii.de/yago/resource/Marion_Butler>"); strings.push_back("<http://www.mpii.de/yago/resource/Takoma_Park,_Maryland>"); strings.push_back("<http://www.mpii.de/yago/resource/Josiah_Bailey>"); strings.push_back("<http://www.mpii.de/yago/resource/Alton_Lennon>"); strings.push_back("<http://www.mpii.de/yago/resource/Lee_Slater_Overman>"); strings.push_back("<http://www.mpii.de/yago/resource/Robert_Rice_Reynolds>"); strings.push_back("<http://www.mpii.de/yago/resource/Sam_Ervin>"); strings.push_back("<http://www.mpii.de/yago/resource/Winston-Salem,_North_Carolina>"); strings.push_back("<http://www.mpii.de/yago/resource/Simon-Napol%C3%A9on_Parent>"); strings.push_back("<http://www.mpii.de/yago/resource/Jerome_Lawrence>"); strings.push_back("<http://www.mpii.de/yago/resource/John_Porter_East>"); strings.push_back("<http://www.mpii.de/yago/resource/Scott_Walker_(boxer)>"); strings.push_back("<http://www.mpii.de/yago/resource/Apache_Junction,_Arizona>"); strings.push_back("<http://www.mpii.de/yago/resource/Mary-Ellis_Bunim>"); strings.push_back("<http://www.mpii.de/yago/resource/Camillien_Houde>"); strings.push_back("<http://www.mpii.de/yago/resource/Charles_Boucher_de_Boucherville>"); strings.push_back("<http://www.mpii.de/yago/resource/Joseph-Alfred_Mousseau>"); strings.push_back("<http://www.mpii.de/yago/resource/G%C3%A9d%C3%A9on_Ouimet>"); strings.push_back("<http://www.mpii.de/yago/resource/Mont-Saint-Hilaire,_Quebec>"); strings.push_back("<http://www.mpii.de/yago/resource/Joseph-Adolphe_Chapleau>"); strings.push_back("<http://www.mpii.de/yago/resource/Oliver_Wendell_Holmes,_Sr.>"); strings.push_back("<http://www.mpii.de/yago/resource/Vsevolod_Pudovkin>"); strings.push_back("<http://www.mpii.de/yago/resource/Ken_Clark_(actor)>"); strings.push_back("<http://www.mpii.de/yago/resource/Brian_Gibson_(director)>"); strings.push_back("<http://www.mpii.de/yago/resource/Norbert_of_Xanten>"); strings.push_back("<http://www.mpii.de/yago/resource/Magdeburg>"); strings.push_back("<http://www.mpii.de/yago/resource/Juan_Cris%C3%B3stomo_Arriaga>"); strings.push_back("<http://www.mpii.de/yago/resource/Galusha_A._Grow>"); strings.push_back("<http://www.mpii.de/yago/resource/Scranton,_Pennsylvania>"); strings.push_back("<http://www.mpii.de/yago/resource/Guru_Gobind_Singh>"); strings.push_back("<http://www.mpii.de/yago/resource/Nanded>"); strings.push_back("<http://www.mpii.de/yago/resource/Tulsidas>"); strings.push_back("<http://www.mpii.de/yago/resource/Moshe_Mordechai_Epstein>"); strings.push_back("<http://www.mpii.de/yago/resource/Robert_Beatty>"); strings.push_back("<http://www.mpii.de/yago/resource/Warith_Deen_Mohammed>"); strings.push_back("<http://www.mpii.de/yago/resource/James_H._Wilson>"); strings.push_back("<http://www.mpii.de/yago/resource/Wilmington,_Delaware>"); strings.push_back("<http://www.mpii.de/yago/resource/John_Dickinson_(delegate)>"); strings.push_back("<http://www.mpii.de/yago/resource/J._R._Clynes>"); strings.push_back("<http://www.mpii.de/yago/resource/Frank_O'Connor>"); strings.push_back("<http://www.mpii.de/yago/resource/Bruno_Rossi>"); strings.push_back("<http://www.mpii.de/yago/resource/Alexander_Mitchell_Palmer>"); strings.push_back("<http://www.mpii.de/yago/resource/Ann_Sothern>"); strings.push_back("<http://www.mpii.de/yago/resource/Charles_Avery_Dunning>"); strings.push_back("<http://www.mpii.de/yago/resource/Martin_Caidin>"); strings.push_back("<http://www.mpii.de/yago/resource/Thomas_Dudley>"); strings.push_back("<http://www.mpii.de/yago/resource/Roxbury,_Boston>"); strings.push_back("<http://www.mpii.de/yago/resource/Harry_Kalas>"); strings.push_back("<http://www.mpii.de/yago/resource/Harry_Hopkins>"); strings.push_back("<http://www.mpii.de/yago/resource/Werner_Sombart>"); strings.push_back("<http://www.mpii.de/yago/resource/Wilhelm_Marstrand>"); strings.push_back("<http://www.mpii.de/yago/resource/Clifford_Shull>"); strings.push_back("<http://www.mpii.de/yago/resource/Mike_O'Callaghan>"); strings.push_back("<http://www.mpii.de/yago/resource/John_Haynes>"); strings.push_back("<http://www.mpii.de/yago/resource/Charles_Robberts_Swart>"); strings.push_back("<http://www.mpii.de/yago/resource/Bloemfontein>"); strings.push_back("<http://www.mpii.de/yago/resource/Eleonora_Duse>"); strings.push_back("<http://www.mpii.de/yago/resource/Michael_LeMoyne_Kennedy>"); strings.push_back("<http://www.mpii.de/yago/resource/Aspen,_Colorado>"); strings.push_back("<http://www.mpii.de/yago/resource/Nigel_Bruce>"); strings.push_back("<http://www.mpii.de/yago/resource/Kemal_Sunal>"); strings.push_back("<http://www.mpii.de/yago/resource/John_Gunnell>"); strings.push_back("<http://www.mpii.de/yago/resource/Wakefield>"); strings.push_back("<http://www.mpii.de/yago/resource/Harry_Strom>"); strings.push_back("<http://www.mpii.de/yago/resource/Ernst_Abbe>"); strings.push_back("<http://www.mpii.de/yago/resource/Oliver_Wendell_Holmes,_Jr.>"); strings.push_back("<http://www.mpii.de/yago/resource/Michael_O'Donoghue>"); strings.push_back("<http://www.mpii.de/yago/resource/Me%C5%A1a_Selimovi%C4%87>"); strings.push_back("<http://www.mpii.de/yago/resource/J%C3%B3zef_Kostrzewski>"); strings.push_back("<http://www.mpii.de/yago/resource/Joseph_Auslander>"); strings.push_back("<http://www.mpii.de/yago/resource/Nicholas_Ray>"); strings.push_back("<http://www.mpii.de/yago/resource/Frank_W._Hunt>"); strings.push_back("<http://www.mpii.de/yago/resource/Era%C3%B1o_Manalo>"); strings.push_back("<http://www.mpii.de/yago/resource/George_C._Homans>"); strings.push_back("<http://www.mpii.de/yago/resource/Madhubala>"); strings.push_back("<http://www.mpii.de/yago/resource/Palmiro_Togliatti>"); strings.push_back("<http://www.mpii.de/yago/resource/Yalta>"); strings.push_back("<http://www.mpii.de/yago/resource/Fritz_London>"); strings.push_back("<http://www.mpii.de/yago/resource/James_Anthony_Bailey>"); strings.push_back("<http://www.mpii.de/yago/resource/Maria_Pia_de_Saxe-Coburgo_e_Bragan%C3%A7a>"); strings.push_back("<http://www.mpii.de/yago/resource/Charles_Wilson_(Canadian_politician)>"); strings.push_back("<http://www.mpii.de/yago/resource/Ahmad_Shamlou>"); strings.push_back("<http://www.mpii.de/yago/resource/Karaj>"); strings.push_back("<http://www.mpii.de/yago/resource/Peter_McGill>"); strings.push_back("<http://www.mpii.de/yago/resource/Augustus_Seymour_Porter>"); strings.push_back("<http://www.mpii.de/yago/resource/Niagara_Falls,_New_York>"); strings.push_back("<http://www.mpii.de/yago/resource/Akiyama_Saneyuki>"); strings.push_back("<http://www.mpii.de/yago/resource/Odawara,_Kanagawa>"); strings.push_back("<http://www.mpii.de/yago/resource/Max_Streibl>"); strings.push_back("<http://www.mpii.de/yago/resource/Edward_Morris,_1st_Baron_Morris>"); strings.push_back("<http://www.mpii.de/yago/resource/Ben_Weider>"); strings.push_back("<http://www.mpii.de/yago/resource/Carl_Vinson>"); strings.push_back("<http://www.mpii.de/yago/resource/Milledgeville,_Georgia>"); strings.push_back("<http://www.mpii.de/yago/resource/James_Francis_McIntyre>"); strings.push_back("<http://www.mpii.de/yago/resource/Billy_Laughlin>"); strings.push_back("<http://www.mpii.de/yago/resource/La_Puente,_California>"); strings.push_back("<http://www.mpii.de/yago/resource/John_J._Crittenden>"); strings.push_back("<http://www.mpii.de/yago/resource/Tahmasp_I>"); strings.push_back("<http://www.mpii.de/yago/resource/Qazvin>"); strings.push_back("<http://www.mpii.de/yago/resource/Arthur_Goldberg>"); strings.push_back("<http://www.mpii.de/yago/resource/Benjamin_Bonneville>"); strings.push_back("<http://www.mpii.de/yago/resource/Fort_Smith,_Arkansas>"); strings.push_back("<http://www.mpii.de/yago/resource/Saint_Hyacinth>"); strings.push_back("<http://www.mpii.de/yago/resource/Stanislaus_of_Szczepan%C3%B3w>"); strings.push_back("<http://www.mpii.de/yago/resource/Leslie_Orgel>"); strings.push_back("<http://www.mpii.de/yago/resource/Stefan_%C5%BBeromski>"); strings.push_back("<http://www.mpii.de/yago/resource/Zhang_Zuolin>"); strings.push_back("<http://www.mpii.de/yago/resource/Shenyang>"); strings.push_back("<http://www.mpii.de/yago/resource/Bankim_Chandra_Chattopadhyay>"); strings.push_back("<http://www.mpii.de/yago/resource/Henry_Herbert_Stevens>"); strings.push_back("<http://www.mpii.de/yago/resource/Marjorie_Kinnan_Rawlings>"); strings.push_back("<http://www.mpii.de/yago/resource/St._Augustine,_Florida>"); strings.push_back("<http://www.mpii.de/yago/resource/Per_Wahl%C3%B6%C3%B6>"); strings.push_back("<http://www.mpii.de/yago/resource/Leigh_Bowery>"); strings.push_back("<http://www.mpii.de/yago/resource/Alessia_di_Matteo>"); strings.push_back("<http://www.mpii.de/yago/resource/Raaj_Kumar>"); strings.push_back("<http://www.mpii.de/yago/resource/Stanis%C5%82aw_Miko%C5%82ajczyk>"); strings.push_back("<http://www.mpii.de/yago/resource/Albert_R._Broccoli>"); strings.push_back("<http://www.mpii.de/yago/resource/Elyesa_Bazna>"); strings.push_back("<http://www.mpii.de/yago/resource/John_Easton_Mills>"); strings.push_back("<http://www.mpii.de/yago/resource/George_Grant_(philosopher)>"); strings.push_back("<http://www.mpii.de/yago/resource/George_FitzGerald>"); strings.push_back("<http://www.mpii.de/yago/resource/Gale_Gordon>"); strings.push_back("<http://www.mpii.de/yago/resource/Georg_von_K%C3%BCchler>"); strings.push_back("<http://www.mpii.de/yago/resource/Garmisch-Partenkirchen>"); strings.push_back("<http://www.mpii.de/yago/resource/Sholom_Dovber_Schneersohn>"); strings.push_back("<http://www.mpii.de/yago/resource/Rostov-on-Don>"); strings.push_back("<http://www.mpii.de/yago/resource/Jean-Robert_Argand>"); strings.push_back("<http://www.mpii.de/yago/resource/John_Sherman_Cooper>"); strings.push_back("<http://www.mpii.de/yago/resource/Eugenio_Beltrami>"); strings.push_back("<http://www.mpii.de/yago/resource/Charles_Kingston>"); strings.push_back("<http://www.mpii.de/yago/resource/Ludwig_Boltzmann>"); strings.push_back("<http://www.mpii.de/yago/resource/Duino>"); strings.push_back("<http://www.mpii.de/yago/resource/Roy_Thomson,_1st_Baron_Thomson_of_Fleet>"); strings.push_back("<http://www.mpii.de/yago/resource/Ismail_I>"); strings.push_back("<http://www.mpii.de/yago/resource/Tabriz>"); strings.push_back("<http://www.mpii.de/yago/resource/John_Cadbury>"); strings.push_back("<http://www.mpii.de/yago/resource/James_B._Sumner>"); strings.push_back("<http://www.mpii.de/yago/resource/Edgar_Allen>"); strings.push_back("<http://www.mpii.de/yago/resource/Eliza_Poe>"); strings.push_back("<http://www.mpii.de/yago/resource/Samuel_Bronfman>"); strings.push_back("<http://www.mpii.de/yago/resource/Goodwin_Knight>"); strings.push_back("<http://www.mpii.de/yago/resource/Dom_DeLuise>"); strings.push_back("<http://www.mpii.de/yago/resource/Rodmond_Roblin>"); strings.push_back("<http://www.mpii.de/yago/resource/Hot_Springs,_Arkansas>"); strings.push_back("<http://www.mpii.de/yago/resource/Paolo_Ruffini>"); strings.push_back("<http://www.mpii.de/yago/resource/David_Howard_Harrison>"); strings.push_back("<http://www.mpii.de/yago/resource/Marcelo_Caetano>"); strings.push_back("<http://www.mpii.de/yago/resource/Robert_Atkinson_Davis>"); strings.push_back("<http://www.mpii.de/yago/resource/Nicholas_Gilman>"); strings.push_back("<http://www.mpii.de/yago/resource/Jared_Ingersoll>"); strings.push_back("<http://www.mpii.de/yago/resource/Prince_Leopold_of_Bavaria>"); strings.push_back("<http://www.mpii.de/yago/resource/Robert_Ritter_von_Greim>"); strings.push_back("<http://www.mpii.de/yago/resource/G%C3%A9rard_Philipe>"); strings.push_back("<http://www.mpii.de/yago/resource/Emil_H%C3%A1cha>"); strings.push_back("<http://www.mpii.de/yago/resource/Maximilian_von_Weichs>"); strings.push_back("<http://www.mpii.de/yago/resource/Wolfram_Freiherr_von_Richthofen>"); strings.push_back("<http://www.mpii.de/yago/resource/Bad_Ischl>"); strings.push_back("<http://www.mpii.de/yago/resource/Harold_Hitz_Burton>"); strings.push_back("<http://www.mpii.de/yago/resource/Cecilia_Gallerani>"); strings.push_back("<http://www.mpii.de/yago/resource/Alois_Hitler>"); strings.push_back("<http://www.mpii.de/yago/resource/Jakob_Roggeveen>"); strings.push_back("<http://www.mpii.de/yago/resource/Cadwallader_C._Washburn>"); strings.push_back("<http://www.mpii.de/yago/resource/Eureka_Springs,_Arkansas>"); strings.push_back("<http://www.mpii.de/yago/resource/Heinrich_M%C3%BCller_(Gestapo)>"); strings.push_back("<http://www.mpii.de/yago/resource/Paul_Hymans>"); strings.push_back("<http://www.mpii.de/yago/resource/Spyros_Kyprianou>"); strings.push_back("<http://www.mpii.de/yago/resource/James_Gascoyne-Cecil,_4th_Marquess_of_Salisbury>"); strings.push_back("<http://www.mpii.de/yago/resource/Jack_Cornwell>"); strings.push_back("<http://www.mpii.de/yago/resource/Grimsby>"); strings.push_back("<http://www.mpii.de/yago/resource/Thomas_Corwin>"); strings.push_back("<http://www.mpii.de/yago/resource/Arthur_Askey>"); strings.push_back("<http://www.mpii.de/yago/resource/Helen_Suzman>"); strings.push_back("<http://www.mpii.de/yago/resource/John_of_Nepomuk>"); strings.push_back("<http://www.mpii.de/yago/resource/Juan_Jos%C3%A9_de_Am%C3%A9zaga>"); strings.push_back("<http://www.mpii.de/yago/resource/Charles_Lane_(actor)>"); strings.push_back("<http://www.mpii.de/yago/resource/Odilo_Globocnik>"); strings.push_back("<http://www.mpii.de/yago/resource/Paternion>"); strings.push_back("<http://www.mpii.de/yago/resource/Kenneth_Arnold>"); strings.push_back("<http://www.mpii.de/yago/resource/Bellevue,_Washington>"); strings.push_back("<http://www.mpii.de/yago/resource/S._J._Perelman>"); strings.push_back("<http://www.mpii.de/yago/resource/Paul_Pierre_L%C3%A9vy>"); strings.push_back("<http://www.mpii.de/yago/resource/Angus_Lewis_Macdonald>"); strings.push_back("<http://www.mpii.de/yago/resource/Guy_Burgess>"); strings.push_back("<http://www.mpii.de/yago/resource/Paul_Richard_Heinrich_Blasius>"); strings.push_back("<http://www.mpii.de/yago/resource/James_Pinckney_Henderson>"); strings.push_back("<http://www.mpii.de/yago/resource/Sir_George_Arthur,_1st_Baronet>"); strings.push_back("<http://www.mpii.de/yago/resource/Yixin,_1st_Prince_Gong>"); strings.push_back("<http://www.mpii.de/yago/resource/Carl_Theodor_Zahle>"); strings.push_back("<http://www.mpii.de/yago/resource/Anton%C3%ADn_Z%C3%A1potock%C3%BD>"); strings.push_back("<http://www.mpii.de/yago/resource/John_Z%C3%A1polya>"); strings.push_back("<http://www.mpii.de/yago/resource/Sebe%C5%9F>"); strings.push_back("<http://www.mpii.de/yago/resource/Alfredo_Zayas_y_Alfonso>"); strings.push_back("<http://www.mpii.de/yago/resource/Jacob_Zeilin>"); strings.push_back("<http://www.mpii.de/yago/resource/Henry_Rinnan>"); strings.push_back("<http://www.mpii.de/yago/resource/Richard_Hurndall>"); strings.push_back("<http://www.mpii.de/yago/resource/Nicolae_R%C4%83descu>"); strings.push_back("<http://www.mpii.de/yago/resource/William_Young_(politician)>"); strings.push_back("<http://www.mpii.de/yago/resource/Karl_Ziegler>"); strings.push_back("<http://www.mpii.de/yago/resource/M%C3%BClheim>"); strings.push_back("<http://www.mpii.de/yago/resource/Francis_Lubbock>"); strings.push_back("<http://www.mpii.de/yago/resource/Aleksandras_Stulginskis>"); strings.push_back("<http://www.mpii.de/yago/resource/Kaunas>"); strings.push_back("<http://www.mpii.de/yago/resource/Gunning_Bedford,_Jr.>"); strings.push_back("<http://www.mpii.de/yago/resource/William_Few>"); strings.push_back("<http://www.mpii.de/yago/resource/Beacon,_New_York>"); strings.push_back("<http://www.mpii.de/yago/resource/Salahuddin_of_Selangor>"); strings.push_back("<http://www.mpii.de/yago/resource/Muriel_Duckworth>"); strings.push_back("<http://www.mpii.de/yago/resource/Magog,_Quebec>"); strings.push_back("<http://www.mpii.de/yago/resource/Ferdinand_von_Schill>"); strings.push_back("<http://www.mpii.de/yago/resource/Stralsund>"); strings.push_back("<http://www.mpii.de/yago/resource/John_Blair,_Jr.>"); strings.push_back("<http://www.mpii.de/yago/resource/Edgar_Guest>"); strings.push_back("<http://www.mpii.de/yago/resource/George_Anthony_Walkem>"); strings.push_back("<http://www.mpii.de/yago/resource/Zenna_Henderson>"); strings.push_back("<http://www.mpii.de/yago/resource/Alexander_Keith>"); strings.push_back("<http://www.mpii.de/yago/resource/Rashid_bin_Saeed_Al_Maktoum>"); strings.push_back("<http://www.mpii.de/yago/resource/Dubai>"); strings.push_back("<http://www.mpii.de/yago/resource/Sidney_Souers>"); strings.push_back("<http://www.mpii.de/yago/resource/Lou_Blonger>"); strings.push_back("<http://www.mpii.de/yago/resource/Alexander_Edmund_Batson_Davie>"); strings.push_back("<http://www.mpii.de/yago/resource/Sanjay_Gandhi>"); strings.push_back("<http://www.mpii.de/yago/resource/Albert_B._Fall>"); strings.push_back("<http://www.mpii.de/yago/resource/Henry_Alexander_Scammell_Dearborn>"); strings.push_back("<http://www.mpii.de/yago/resource/William_Gibbs_McAdoo>"); strings.push_back("<http://www.mpii.de/yago/resource/Ulrich_Salchow>"); strings.push_back("<http://www.mpii.de/yago/resource/Morgan_Lewis_(governor)>"); strings.push_back("<http://www.mpii.de/yago/resource/Paul_Emil_von_Lettow-Vorbeck>"); strings.push_back("<http://www.mpii.de/yago/resource/Luigj_Gurakuqi>"); strings.push_back("<http://www.mpii.de/yago/resource/James_Watson_(New_York)>"); strings.push_back("<http://www.mpii.de/yago/resource/Hugh_Samuel_Johnson>"); strings.push_back("<http://www.mpii.de/yago/resource/Robert_Woodhouse>"); strings.push_back("<http://www.mpii.de/yago/resource/Prince_Paul_of_Yugoslavia>"); strings.push_back("<http://www.mpii.de/yago/resource/James_Eli_Watson>"); strings.push_back("<http://www.mpii.de/yago/resource/Buffalo_Bob_Smith>"); strings.push_back("<http://www.mpii.de/yago/resource/Hendersonville,_North_Carolina>"); strings.push_back("<http://www.mpii.de/yago/resource/Theodore_Davie>"); strings.push_back("<http://www.mpii.de/yago/resource/Mihailo_Obrenovi%C4%87_III,_Prince_of_Serbia>"); strings.push_back("<http://www.mpii.de/yago/resource/Diosdado_Macapagal>"); strings.push_back("<http://www.mpii.de/yago/resource/Robert_Beaven>"); strings.push_back("<http://www.mpii.de/yago/resource/Jakob_Steiner>"); strings.push_back("<http://www.mpii.de/yago/resource/Salim_Ali>"); strings.push_back("<http://www.mpii.de/yago/resource/Spessard_Holland>"); strings.push_back("<http://www.mpii.de/yago/resource/Bartow,_Florida>"); strings.push_back("<http://www.mpii.de/yago/resource/Edward_Platt>"); strings.push_back("<http://www.mpii.de/yago/resource/William_Smithe>"); strings.push_back("<http://www.mpii.de/yago/resource/Jigme_Dorji_Wangchuck>"); strings.push_back("<http://www.mpii.de/yago/resource/John_Robson>"); strings.push_back("<http://www.mpii.de/yago/resource/Erika_Mann>"); strings.push_back("<http://www.mpii.de/yago/resource/Lin_Zexu>"); strings.push_back("<http://www.mpii.de/yago/resource/Puning>"); strings.push_back("<http://www.mpii.de/yago/resource/Caran_d'Ache>"); strings.push_back("<http://www.mpii.de/yago/resource/Kim_Gu>"); strings.push_back("<http://www.mpii.de/yago/resource/Lee_Strasberg>"); strings.push_back("<http://www.mpii.de/yago/resource/Joseph_Warren>"); strings.push_back("<http://www.mpii.de/yago/resource/Robert_Drinan>"); strings.push_back("<http://www.mpii.de/yago/resource/Karen_Silkwood>"); strings.push_back("<http://www.mpii.de/yago/resource/Crescent,_Oklahoma>"); strings.push_back("<http://www.mpii.de/yago/resource/Joost_van_den_Vondel>"); strings.push_back("<http://www.mpii.de/yago/resource/James_Van_Fleet>"); strings.push_back("<http://www.mpii.de/yago/resource/Polk_City,_Florida>"); strings.push_back("<http://www.mpii.de/yago/resource/Manne_Siegbahn>"); strings.push_back("<http://www.mpii.de/yago/resource/Jean_Baptiste_Perrin>"); strings.push_back("<http://www.mpii.de/yago/resource/William_Spottiswoode>"); strings.push_back("<http://www.mpii.de/yago/resource/Tiradentes>"); strings.push_back("<http://www.mpii.de/yago/resource/Fred_M._Vinson>"); strings.push_back("<http://www.mpii.de/yago/resource/Ron_Brown_(U.S._politician)>"); strings.push_back("<http://www.mpii.de/yago/resource/Dubrovnik>"); strings.push_back("<http://www.mpii.de/yago/resource/Hans_Conried>"); strings.push_back("<http://www.mpii.de/yago/resource/Max_Schreck>"); strings.push_back("<http://www.mpii.de/yago/resource/Dorothy_Kilgallen>"); strings.push_back("<http://www.mpii.de/yago/resource/Alphonso_Taft>"); strings.push_back("<http://www.mpii.de/yago/resource/Nikolai_Luzin>"); strings.push_back("<http://www.mpii.de/yago/resource/Lucian_Blaga>"); strings.push_back("<http://www.mpii.de/yago/resource/Cluj-Napoca>"); strings.push_back("<http://www.mpii.de/yago/resource/Milton_Caniff>"); strings.push_back("<http://www.mpii.de/yago/resource/Frithjof_Schuon>"); strings.push_back("<http://www.mpii.de/yago/resource/Charles_Thomson_Rees_Wilson>"); strings.push_back("<http://www.mpii.de/yago/resource/William_Alfred_Fowler>"); strings.push_back("<http://www.mpii.de/yago/resource/Robert_Hobart,_4th_Earl_of_Buckinghamshire>"); strings.push_back("<http://www.mpii.de/yago/resource/Wally_Wood>"); strings.push_back("<http://www.mpii.de/yago/resource/Carl_Hayden>"); strings.push_back("<http://www.mpii.de/yago/resource/Dolph_Briscoe>"); strings.push_back("<http://www.mpii.de/yago/resource/Ludwig_Cr%C3%BCwell>"); strings.push_back("<http://www.mpii.de/yago/resource/Siaka_Stevens>"); strings.push_back("<http://www.mpii.de/yago/resource/Vasily_Chuikov>"); strings.push_back("<http://www.mpii.de/yago/resource/Clifford_William_Robinson>"); strings.push_back("<http://www.mpii.de/yago/resource/James_Murray_(lexicographer)>"); strings.push_back("<http://www.mpii.de/yago/resource/James_Henry_Craig>"); strings.push_back("<http://www.mpii.de/yago/resource/George_Pr%C3%A9vost>"); strings.push_back("<http://www.mpii.de/yago/resource/Art_James>"); strings.push_back("<http://www.mpii.de/yago/resource/Pier_Gerlofs_Donia>"); strings.push_back("<http://www.mpii.de/yago/resource/Sneek>"); strings.push_back("<http://www.mpii.de/yago/resource/Thomas_Edward_Campbell>"); strings.push_back("<http://www.mpii.de/yago/resource/Evan_Mecham>"); strings.push_back("<http://www.mpii.de/yago/resource/Maria_Montez>"); strings.push_back("<http://www.mpii.de/yago/resource/Joseph_Force_Crater>"); strings.push_back("<http://www.mpii.de/yago/resource/Ismail_Nasiruddin_of_Terengganu>"); strings.push_back("<http://www.mpii.de/yago/resource/Kuala_Terengganu>"); strings.push_back("<http://www.mpii.de/yago/resource/Putra_of_Perlis>"); strings.push_back("<http://www.mpii.de/yago/resource/Yahya_Petra_of_Kelantan>"); strings.push_back("<http://www.mpii.de/yago/resource/Mwambutsa_IV_Bangiriceng_of_Burundi>"); strings.push_back("<http://www.mpii.de/yago/resource/Abu_Mansur_Maturidi>"); strings.push_back("<http://www.mpii.de/yago/resource/Samarkand>"); strings.push_back("<http://www.mpii.de/yago/resource/Max_Wolf>"); strings.push_back("<http://www.mpii.de/yago/resource/Mary_Sue_Hubbard>"); strings.push_back("<http://www.mpii.de/yago/resource/Lee_Krasner>"); strings.push_back("<http://www.mpii.de/yago/resource/George_W._P._Hunt>"); strings.push_back("<http://www.mpii.de/yago/resource/Pierre_B%C3%A9r%C3%A9govoy>"); strings.push_back("<http://www.mpii.de/yago/resource/Pierre_Pflimlin>"); strings.push_back("<http://www.mpii.de/yago/resource/F%C3%A9lix_Gouin>"); return strings; } BOOST_AUTO_TEST_CASE(testWithLongStringsAndNodeSplit) { std::vector<std::string> const &strings = getLongStrings(); testValues(hot::testhelpers::stdStringsToCStrings(strings)); } BOOST_AUTO_TEST_CASE(testBoundsWithLongStringsAndIterate) { std::vector<std::string> const &strings = getLongStrings(); std::set<std::string> sortedStrings { strings.begin(), strings.end() }; std::vector<std::string> valuesToInsert; std::vector<std::string> valuesToLeaveOut; std::string valueBeforeAll; std::string valueAfterAll; size_t index = 0; for(auto value : sortedStrings) { if(index == 0) { valueBeforeAll = value; } else if(index == (sortedStrings.size() - 1)) { valueAfterAll = value; } else if((index%2) == 1) { valuesToInsert.push_back(value); } else { valuesToLeaveOut.push_back(value); } ++index; } std::vector<char const *> cStrings = hot::testhelpers::stdStringsToCStrings(valuesToInsert); std::vector<char const *> cStringsToLeaveOut = hot::testhelpers::stdStringsToCStrings(valuesToLeaveOut); std::shared_ptr<CStringTrieType> trie = testValues(cStrings); std::set<char const *, typename idx::contenthelpers::KeyComparator<char const *>::type> redBlackTree(cStrings.begin(), cStrings.end()); const CStringTrieType::const_iterator &lowerBound = trie->lower_bound(valueAfterAll.c_str()); BOOST_REQUIRE_MESSAGE(lowerBound == trie->end(), "Lower bound for value which is after all values is the end"); BOOST_REQUIRE_MESSAGE(trie->upper_bound(valueAfterAll.c_str()) == trie->end(), "Upper bound for a value which is after all values is the end"); BOOST_REQUIRE_MESSAGE(*trie->lower_bound(valueBeforeAll.c_str()) == cStrings[0], "Lower bound for value which is before all values is the first value"); BOOST_REQUIRE_MESSAGE(*trie->upper_bound(valueBeforeAll.c_str()) == cStrings[0], "Upper bound for a value which is before all values is the first value"); BOOST_REQUIRE_EQUAL(*trie->lower_bound(valueBeforeAll.c_str()), *redBlackTree.lower_bound(valueBeforeAll.c_str())); BOOST_REQUIRE_MESSAGE(redBlackTree.lower_bound(valueAfterAll.c_str()) == redBlackTree.end(), "Defined behavior for lower bound if value after all is searched"); BOOST_REQUIRE_EQUAL(*trie->upper_bound(valueBeforeAll.c_str()), *redBlackTree.upper_bound(valueBeforeAll.c_str())); BOOST_REQUIRE_MESSAGE(redBlackTree.upper_bound(valueAfterAll.c_str()) == redBlackTree.end(), "Defined behavior for upper bound if value after all is searched"); for(size_t i=2; i < (valuesToLeaveOut.size() - 2); ++i) { BOOST_REQUIRE_EQUAL(*trie->lower_bound(cStringsToLeaveOut[i]), *redBlackTree.lower_bound(cStringsToLeaveOut[i])); BOOST_REQUIRE_EQUAL(*trie->upper_bound(cStringsToLeaveOut[i]), *redBlackTree.upper_bound(cStringsToLeaveOut[i])); } BOOST_REQUIRE_EQUAL_COLLECTIONS( trie->lower_bound(cStringsToLeaveOut[4]), trie->upper_bound(cStringsToLeaveOut[cStringsToLeaveOut.size() - 2]), redBlackTree.lower_bound(cStringsToLeaveOut[4]), redBlackTree.upper_bound(cStringsToLeaveOut[cStringsToLeaveOut.size() - 2]) ); } BOOST_AUTO_TEST_CASE(testStringPrefixes) { std::vector<std::string> strings = { "fernando@terras.com.bt", "fernando@terras.com" }; testValues(hot::testhelpers::stdStringsToCStrings(strings)); } BOOST_AUTO_TEST_CASE(testEmptyIterator) { HOTSingleThreadedUint64 hotSingleThreaded; BOOST_REQUIRE(hotSingleThreaded.begin() == hotSingleThreaded.end()); } BOOST_AUTO_TEST_CASE(testSingleElementIterator) { HOTSingleThreadedUint64 hotSingleThreaded; hotSingleThreaded.insert(42u); std::array<uint64_t, 1> expectedValues = { 42u }; BOOST_REQUIRE_EQUAL_COLLECTIONS(hotSingleThreaded.begin(), hotSingleThreaded.end(), expectedValues.begin(), expectedValues.end()); } BOOST_AUTO_TEST_CASE(testFindOnEmptyTrie) { HOTSingleThreadedUint64 hotSingleThreaded; BOOST_REQUIRE_MESSAGE(hotSingleThreaded.find(42u) == hotSingleThreaded.end(), "Find on empty trie must return the end iterator"); } BOOST_AUTO_TEST_CASE(testFindElementNotInTrie) { HOTSingleThreadedUint64 hotSingleThreaded; hotSingleThreaded.insert(41u); hotSingleThreaded.insert(43u); BOOST_REQUIRE_MESSAGE(hotSingleThreaded.find(40u) == hotSingleThreaded.end(), "Cannot lookup element which is not contained."); BOOST_REQUIRE_MESSAGE(hotSingleThreaded.find(42u) == hotSingleThreaded.end(), "Cannot lookup element which is not contained."); BOOST_REQUIRE_MESSAGE(hotSingleThreaded.find(44u) == hotSingleThreaded.end(), "Cannot lookup element which is not contained."); } BOOST_AUTO_TEST_CASE(testUpsert) { hot::singlethreaded::HOTSingleThreaded<std::pair<uint64_t, uint64_t>*, idx::contenthelpers::PairPointerKeyExtractor> hotSingleThreaded; std::vector<std::pair<uint64_t, uint64_t>> initialValues { { 41u, 3u }, { 43u, 5u }, { 55u, 9u }, { 59u, 13u }, { 62u, 2u }, { 69u, 7u }, { 105u, 44u }, { 120u, 1200u }, { 257u, 33u }, }; std::vector<std::pair<uint64_t , uint64_t>*> pointerValues; for(std::pair<uint64_t, uint64_t> & value : initialValues) { pointerValues.push_back(&value); hotSingleThreaded.insert(&value); } std::pair<uint64_t, uint64_t> newValue { 120u, 42u }; BOOST_REQUIRE_EQUAL_COLLECTIONS(hotSingleThreaded.begin(), hotSingleThreaded.end(), pointerValues.begin(), pointerValues.end()); const idx::contenthelpers::OptionalValue<std::pair<uint64_t, uint64_t> *> &previousValue = hotSingleThreaded.upsert(&newValue); pointerValues[7] = &newValue; BOOST_REQUIRE_EQUAL_COLLECTIONS(hotSingleThreaded.begin(), hotSingleThreaded.end(), pointerValues.begin(), pointerValues.end()); BOOST_REQUIRE(previousValue.compliesWith({ true, &initialValues[7] })); } BOOST_AUTO_TEST_SUITE_END() } }
71.915971
247
0.753879
[ "vector" ]
f5ec274bcfb22ff93d715d32aba2117f13f9227a
2,499
cpp
C++
src/tests/tests-boundary-conditions.cpp
gnikit/md-sim
95d426fe1be084e89d81a199c407d6724c39b240
[ "MIT" ]
1
2020-03-24T14:45:33.000Z
2020-03-24T14:45:33.000Z
src/tests/tests-boundary-conditions.cpp
gnikit/md-sim
95d426fe1be084e89d81a199c407d6724c39b240
[ "MIT" ]
12
2019-12-01T16:39:11.000Z
2020-05-25T11:02:06.000Z
src/tests/tests-boundary-conditions.cpp
GNikit/md-sim
95d426fe1be084e89d81a199c407d6724c39b240
[ "MIT" ]
1
2017-05-01T23:17:13.000Z
2017-05-01T23:17:13.000Z
#pragma once #include <catch.hpp> #define protected public #include "MD.h" SCENARIO("Boundary conditions", "[bcs]") { GIVEN("Periodic boundaries") { MD obj; obj.options.Lx = obj.options.Ly = obj.options.Lz = 1.0; obj.options.N = 1; WHEN("x, y, z are smaller than 0") { vector_3d<double> r({-0.1}, {-0.2}, {-0.3}); REQUIRE(r.size() == obj.options.N); INFO("vector before applying BCs: " << r); obj.periodic_boundary_conditions(r); INFO("vector after applying BCs: " << r); THEN("the positions are moved to the right side of the box") { REQUIRE(r.x[0] == Approx(0.9)); REQUIRE(r.y[0] == Approx(0.8)); REQUIRE(r.z[0] == Approx(0.7)); } } WHEN("x, y, z are greater than the box length") { vector_3d<double> r({1.1}, {1.2}, {1.3}); REQUIRE(r.size() == obj.options.N); INFO("vector before applying BCs: " << r); obj.periodic_boundary_conditions(r); INFO("vector after applying BCs: " << r); THEN("the positions are moved to the left side of the box") { REQUIRE(r.x[0] == Approx(0.1)); REQUIRE(r.y[0] == Approx(0.2)); REQUIRE(r.z[0] == Approx(0.3)); } } } GIVEN("Reflective boundaries") { MD obj; obj.options.Lx = obj.options.Ly = obj.options.Lz = 1.0; obj.options.N = 1; WHEN("x, y, z are smaller than 0") { vector_3d<double> r({-0.1}, {-0.2}, {-0.3}); vector_3d<double> v({-1}, {-1}, {-1}); REQUIRE(r.size() == obj.options.N); REQUIRE(v.size() == r.size()); INFO("vector before applying BCs: " << v); obj.reflective_boundary_conditions(r, v); INFO("vector after applying BCs: " << v); THEN("the positions are moved to the right side of the box") { REQUIRE(v.x[0] == Approx(1)); REQUIRE(v.y[0] == Approx(1)); REQUIRE(v.z[0] == Approx(1)); } } WHEN("x, y, z are greater than the box length") { vector_3d<double> r({1.1}, {1.2}, {1.3}); vector_3d<double> v({-1}, {-1}, {-1}); REQUIRE(r.size() == obj.options.N); REQUIRE(v.size() == r.size()); INFO("vector before applying BCs: " << v); obj.reflective_boundary_conditions(r, v); INFO("vector after applying BCs: " << v); THEN("the positions are moved to the left side of the box") { REQUIRE(v.x[0] == Approx(1)); REQUIRE(v.y[0] == Approx(1)); REQUIRE(v.z[0] == Approx(1)); } } } }
26.585106
68
0.540616
[ "vector" ]
f5ef8c0666cab12288cc12c2fc72cf44a09ee85a
20,099
cpp
C++
Templates/DirectX12App/Common/DeviceResources.cpp
dsrour/DSX2
e3489ff4bc3d49ed00480b4a6eb14ac08f6f98e7
[ "MIT" ]
3
2017-08-15T06:57:39.000Z
2021-05-03T10:04:01.000Z
Templates/DirectX12App/Common/DeviceResources.cpp
dsrour/DSX2
e3489ff4bc3d49ed00480b4a6eb14ac08f6f98e7
[ "MIT" ]
null
null
null
Templates/DirectX12App/Common/DeviceResources.cpp
dsrour/DSX2
e3489ff4bc3d49ed00480b4a6eb14ac08f6f98e7
[ "MIT" ]
1
2018-11-29T15:39:56.000Z
2018-11-29T15:39:56.000Z
#include "pch.h" #include "DeviceResources.h" #include "DirectXHelper.h" using namespace DirectX; using namespace Microsoft::WRL; using namespace Windows::Foundation; using namespace Windows::Graphics::Display; using namespace Windows::UI::Core; using namespace Windows::UI::Xaml::Controls; using namespace Platform; namespace DisplayMetrics { // High resolution displays can require a lot of GPU and battery power to render. // High resolution phones, for example, may suffer from poor battery life if // games attempt to render at 60 frames per second at full fidelity. // The decision to render at full fidelity across all platforms and form factors // should be deliberate. static const bool SupportHighResolutions = false; // The default thresholds that define a "high resolution" display. If the thresholds // are exceeded and SupportHighResolutions is false, the dimensions will be scaled // by 50%. static const float DpiThreshold = 192.0f; // 200% of standard desktop display. static const float WidthThreshold = 1920.0f; // 1080p width. static const float HeightThreshold = 1080.0f; // 1080p height. }; // Constants used to calculate screen rotations. namespace ScreenRotation { // 0-degree Z-rotation static const XMFLOAT4X4 Rotation0( 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f ); // 90-degree Z-rotation static const XMFLOAT4X4 Rotation90( 0.0f, 1.0f, 0.0f, 0.0f, -1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f ); // 180-degree Z-rotation static const XMFLOAT4X4 Rotation180( -1.0f, 0.0f, 0.0f, 0.0f, 0.0f, -1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f ); // 270-degree Z-rotation static const XMFLOAT4X4 Rotation270( 0.0f, -1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f ); }; // Constructor for DeviceResources. DX::DeviceResources::DeviceResources(DXGI_FORMAT backBufferFormat, DXGI_FORMAT depthBufferFormat) : m_currentFrame(0), m_screenViewport(), m_rtvDescriptorSize(0), m_fenceEvent(0), m_backBufferFormat(backBufferFormat), m_depthBufferFormat(depthBufferFormat), m_fenceValues{}, m_d3dRenderTargetSize(), m_outputSize(), m_logicalSize(), m_nativeOrientation(DisplayOrientations::None), m_currentOrientation(DisplayOrientations::None), m_dpi(-1.0f), m_effectiveDpi(-1.0f), m_deviceRemoved(false) { CreateDeviceIndependentResources(); CreateDeviceResources(); } // Configures resources that don't depend on the Direct3D device. void DX::DeviceResources::CreateDeviceIndependentResources() { } // Configures the Direct3D device, and stores handles to it and the device context. void DX::DeviceResources::CreateDeviceResources() { #if defined(_DEBUG) // If the project is in a debug build, enable debugging via SDK Layers. { ComPtr<ID3D12Debug> debugController; if (SUCCEEDED(D3D12GetDebugInterface(IID_PPV_ARGS(&debugController)))) { debugController->EnableDebugLayer(); } } #endif DX::ThrowIfFailed(CreateDXGIFactory1(IID_PPV_ARGS(&m_dxgiFactory))); ComPtr<IDXGIAdapter1> adapter; GetHardwareAdapter(&adapter); // Create the Direct3D 12 API device object HRESULT hr = D3D12CreateDevice( adapter.Get(), // The hardware adapter. D3D_FEATURE_LEVEL_11_0, // Minimum feature level this app can support. IID_PPV_ARGS(&m_d3dDevice) // Returns the Direct3D device created. ); #if defined(_DEBUG) if (FAILED(hr)) { // If the initialization fails, fall back to the WARP device. // For more information on WARP, see: // http://go.microsoft.com/fwlink/?LinkId=286690 ComPtr<IDXGIAdapter> warpAdapter; DX::ThrowIfFailed(m_dxgiFactory->EnumWarpAdapter(IID_PPV_ARGS(&warpAdapter))); hr = D3D12CreateDevice(warpAdapter.Get(), D3D_FEATURE_LEVEL_11_0, IID_PPV_ARGS(&m_d3dDevice)); } #endif DX::ThrowIfFailed(hr); // Create the command queue. D3D12_COMMAND_QUEUE_DESC queueDesc = {}; queueDesc.Flags = D3D12_COMMAND_QUEUE_FLAG_NONE; queueDesc.Type = D3D12_COMMAND_LIST_TYPE_DIRECT; DX::ThrowIfFailed(m_d3dDevice->CreateCommandQueue(&queueDesc, IID_PPV_ARGS(&m_commandQueue))); NAME_D3D12_OBJECT(m_commandQueue); // Create descriptor heaps for render target views and depth stencil views. D3D12_DESCRIPTOR_HEAP_DESC rtvHeapDesc = {}; rtvHeapDesc.NumDescriptors = c_frameCount; rtvHeapDesc.Type = D3D12_DESCRIPTOR_HEAP_TYPE_RTV; rtvHeapDesc.Flags = D3D12_DESCRIPTOR_HEAP_FLAG_NONE; DX::ThrowIfFailed(m_d3dDevice->CreateDescriptorHeap(&rtvHeapDesc, IID_PPV_ARGS(&m_rtvHeap))); NAME_D3D12_OBJECT(m_rtvHeap); m_rtvDescriptorSize = m_d3dDevice->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_RTV); D3D12_DESCRIPTOR_HEAP_DESC dsvHeapDesc = {}; dsvHeapDesc.NumDescriptors = 1; dsvHeapDesc.Type = D3D12_DESCRIPTOR_HEAP_TYPE_DSV; dsvHeapDesc.Flags = D3D12_DESCRIPTOR_HEAP_FLAG_NONE; ThrowIfFailed(m_d3dDevice->CreateDescriptorHeap(&dsvHeapDesc, IID_PPV_ARGS(&m_dsvHeap))); NAME_D3D12_OBJECT(m_dsvHeap); for (UINT n = 0; n < c_frameCount; n++) { DX::ThrowIfFailed( m_d3dDevice->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&m_commandAllocators[n])) ); } // Create synchronization objects. DX::ThrowIfFailed(m_d3dDevice->CreateFence(m_fenceValues[m_currentFrame], D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&m_fence))); m_fenceValues[m_currentFrame]++; m_fenceEvent = CreateEventEx(nullptr, FALSE, FALSE, EVENT_ALL_ACCESS); } // These resources need to be recreated every time the window size is changed. void DX::DeviceResources::CreateWindowSizeDependentResources() { // Wait until all previous GPU work is complete. WaitForGpu(); // Clear the previous window size specific content and update the tracked fence values. for (UINT n = 0; n < c_frameCount; n++) { m_renderTargets[n] = nullptr; m_fenceValues[n] = m_fenceValues[m_currentFrame]; } UpdateRenderTargetSize(); // The width and height of the swap chain must be based on the window's // natively-oriented width and height. If the window is not in the native // orientation, the dimensions must be reversed. DXGI_MODE_ROTATION displayRotation = ComputeDisplayRotation(); bool swapDimensions = displayRotation == DXGI_MODE_ROTATION_ROTATE90 || displayRotation == DXGI_MODE_ROTATION_ROTATE270; m_d3dRenderTargetSize.Width = swapDimensions ? m_outputSize.Height : m_outputSize.Width; m_d3dRenderTargetSize.Height = swapDimensions ? m_outputSize.Width : m_outputSize.Height; UINT backBufferWidth = lround(m_d3dRenderTargetSize.Width); UINT backBufferHeight = lround(m_d3dRenderTargetSize.Height); if (m_swapChain != nullptr) { // If the swap chain already exists, resize it. HRESULT hr = m_swapChain->ResizeBuffers(c_frameCount, backBufferWidth, backBufferHeight, m_backBufferFormat, 0); if (hr == DXGI_ERROR_DEVICE_REMOVED || hr == DXGI_ERROR_DEVICE_RESET) { // If the device was removed for any reason, a new device and swap chain will need to be created. m_deviceRemoved = true; // Do not continue execution of this method. DeviceResources will be destroyed and re-created. return; } else { DX::ThrowIfFailed(hr); } } else { // Otherwise, create a new one using the same adapter as the existing Direct3D device. DXGI_SCALING scaling = DisplayMetrics::SupportHighResolutions ? DXGI_SCALING_NONE : DXGI_SCALING_STRETCH; DXGI_SWAP_CHAIN_DESC1 swapChainDesc = {}; swapChainDesc.Width = backBufferWidth; // Match the size of the window. swapChainDesc.Height = backBufferHeight; swapChainDesc.Format = m_backBufferFormat; swapChainDesc.Stereo = false; swapChainDesc.SampleDesc.Count = 1; // Don't use multi-sampling. swapChainDesc.SampleDesc.Quality = 0; swapChainDesc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT; swapChainDesc.BufferCount = c_frameCount; // Use triple-buffering to minimize latency. swapChainDesc.SwapEffect = DXGI_SWAP_EFFECT_FLIP_DISCARD; // All Windows Universal apps must use _FLIP_ SwapEffects. swapChainDesc.Flags = 0; swapChainDesc.Scaling = scaling; swapChainDesc.AlphaMode = DXGI_ALPHA_MODE_IGNORE; ComPtr<IDXGISwapChain1> swapChain; DX::ThrowIfFailed( m_dxgiFactory->CreateSwapChainForCoreWindow( m_commandQueue.Get(), // Swap chains need a reference to the command queue in DirectX 12. reinterpret_cast<IUnknown*>(m_window.Get()), &swapChainDesc, nullptr, &swapChain ) ); DX::ThrowIfFailed(swapChain.As(&m_swapChain)); } // Set the proper orientation for the swap chain, and generate // 3D matrix transformations for rendering to the rotated swap chain. // The 3D matrix is specified explicitly to avoid rounding errors. switch (displayRotation) { case DXGI_MODE_ROTATION_IDENTITY: m_orientationTransform3D = ScreenRotation::Rotation0; break; case DXGI_MODE_ROTATION_ROTATE90: m_orientationTransform3D = ScreenRotation::Rotation270; break; case DXGI_MODE_ROTATION_ROTATE180: m_orientationTransform3D = ScreenRotation::Rotation180; break; case DXGI_MODE_ROTATION_ROTATE270: m_orientationTransform3D = ScreenRotation::Rotation90; break; default: throw ref new FailureException(); } DX::ThrowIfFailed( m_swapChain->SetRotation(displayRotation) ); // Create render target views of the swap chain back buffer. { m_currentFrame = m_swapChain->GetCurrentBackBufferIndex(); CD3DX12_CPU_DESCRIPTOR_HANDLE rtvDescriptor(m_rtvHeap->GetCPUDescriptorHandleForHeapStart()); for (UINT n = 0; n < c_frameCount; n++) { DX::ThrowIfFailed(m_swapChain->GetBuffer(n, IID_PPV_ARGS(&m_renderTargets[n]))); m_d3dDevice->CreateRenderTargetView(m_renderTargets[n].Get(), nullptr, rtvDescriptor); rtvDescriptor.Offset(m_rtvDescriptorSize); WCHAR name[25]; if (swprintf_s(name, L"m_renderTargets[%u]", n) > 0) { DX::SetName(m_renderTargets[n].Get(), name); } } } // Create a depth stencil and view. { D3D12_HEAP_PROPERTIES depthHeapProperties = CD3DX12_HEAP_PROPERTIES(D3D12_HEAP_TYPE_DEFAULT); D3D12_RESOURCE_DESC depthResourceDesc = CD3DX12_RESOURCE_DESC::Tex2D(m_depthBufferFormat, backBufferWidth, backBufferHeight); depthResourceDesc.Flags |= D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL; CD3DX12_CLEAR_VALUE depthOptimizedClearValue(m_depthBufferFormat, 1.0f, 0); ThrowIfFailed(m_d3dDevice->CreateCommittedResource( &depthHeapProperties, D3D12_HEAP_FLAG_NONE, &depthResourceDesc, D3D12_RESOURCE_STATE_DEPTH_WRITE, &depthOptimizedClearValue, IID_PPV_ARGS(&m_depthStencil) )); NAME_D3D12_OBJECT(m_depthStencil); D3D12_DEPTH_STENCIL_VIEW_DESC dsvDesc = {}; dsvDesc.Format = m_depthBufferFormat; dsvDesc.ViewDimension = D3D12_DSV_DIMENSION_TEXTURE2D; dsvDesc.Flags = D3D12_DSV_FLAG_NONE; m_d3dDevice->CreateDepthStencilView(m_depthStencil.Get(), &dsvDesc, m_dsvHeap->GetCPUDescriptorHandleForHeapStart()); } // Set the 3D rendering viewport to target the entire window. m_screenViewport = { 0.0f, 0.0f, m_d3dRenderTargetSize.Width, m_d3dRenderTargetSize.Height, 0.0f, 1.0f }; } // Determine the dimensions of the render target and whether it will be scaled down. void DX::DeviceResources::UpdateRenderTargetSize() { m_effectiveDpi = m_dpi; // To improve battery life on high resolution devices, render to a smaller render target // and allow the GPU to scale the output when it is presented. if (!DisplayMetrics::SupportHighResolutions && m_dpi > DisplayMetrics::DpiThreshold) { float width = DX::ConvertDipsToPixels(m_logicalSize.Width, m_dpi); float height = DX::ConvertDipsToPixels(m_logicalSize.Height, m_dpi); // When the device is in portrait orientation, height > width. Compare the // larger dimension against the width threshold and the smaller dimension // against the height threshold. if (max(width, height) > DisplayMetrics::WidthThreshold && min(width, height) > DisplayMetrics::HeightThreshold) { // To scale the app we change the effective DPI. Logical size does not change. m_effectiveDpi /= 2.0f; } } // Calculate the necessary render target size in pixels. m_outputSize.Width = DX::ConvertDipsToPixels(m_logicalSize.Width, m_effectiveDpi); m_outputSize.Height = DX::ConvertDipsToPixels(m_logicalSize.Height, m_effectiveDpi); // Prevent zero size DirectX content from being created. m_outputSize.Width = max(m_outputSize.Width, 1); m_outputSize.Height = max(m_outputSize.Height, 1); } // This method is called when the CoreWindow is created (or re-created). void DX::DeviceResources::SetWindow(CoreWindow^ window) { DisplayInformation^ currentDisplayInformation = DisplayInformation::GetForCurrentView(); m_window = window; m_logicalSize = Windows::Foundation::Size(window->Bounds.Width, window->Bounds.Height); m_nativeOrientation = currentDisplayInformation->NativeOrientation; m_currentOrientation = currentDisplayInformation->CurrentOrientation; m_dpi = currentDisplayInformation->LogicalDpi; CreateWindowSizeDependentResources(); } // This method is called in the event handler for the SizeChanged event. void DX::DeviceResources::SetLogicalSize(Windows::Foundation::Size logicalSize) { if (m_logicalSize != logicalSize) { m_logicalSize = logicalSize; CreateWindowSizeDependentResources(); } } // This method is called in the event handler for the DpiChanged event. void DX::DeviceResources::SetDpi(float dpi) { if (dpi != m_dpi) { m_dpi = dpi; // When the display DPI changes, the logical size of the window (measured in Dips) also changes and needs to be updated. m_logicalSize = Windows::Foundation::Size(m_window->Bounds.Width, m_window->Bounds.Height); CreateWindowSizeDependentResources(); } } // This method is called in the event handler for the OrientationChanged event. void DX::DeviceResources::SetCurrentOrientation(DisplayOrientations currentOrientation) { if (m_currentOrientation != currentOrientation) { m_currentOrientation = currentOrientation; CreateWindowSizeDependentResources(); } } // This method is called in the event handler for the DisplayContentsInvalidated event. void DX::DeviceResources::ValidateDevice() { // The D3D Device is no longer valid if the default adapter changed since the device // was created or if the device has been removed. // First, get the LUID for the default adapter from when the device was created. DXGI_ADAPTER_DESC previousDesc; { ComPtr<IDXGIAdapter1> previousDefaultAdapter; DX::ThrowIfFailed(m_dxgiFactory->EnumAdapters1(0, &previousDefaultAdapter)); DX::ThrowIfFailed(previousDefaultAdapter->GetDesc(&previousDesc)); } // Next, get the information for the current default adapter. DXGI_ADAPTER_DESC currentDesc; { ComPtr<IDXGIFactory4> currentDxgiFactory; DX::ThrowIfFailed(CreateDXGIFactory1(IID_PPV_ARGS(&currentDxgiFactory))); ComPtr<IDXGIAdapter1> currentDefaultAdapter; DX::ThrowIfFailed(currentDxgiFactory->EnumAdapters1(0, &currentDefaultAdapter)); DX::ThrowIfFailed(currentDefaultAdapter->GetDesc(&currentDesc)); } // If the adapter LUIDs don't match, or if the device reports that it has been removed, // a new D3D device must be created. if (previousDesc.AdapterLuid.LowPart != currentDesc.AdapterLuid.LowPart || previousDesc.AdapterLuid.HighPart != currentDesc.AdapterLuid.HighPart || FAILED(m_d3dDevice->GetDeviceRemovedReason())) { m_deviceRemoved = true; } } // Present the contents of the swap chain to the screen. void DX::DeviceResources::Present() { // The first argument instructs DXGI to block until VSync, putting the application // to sleep until the next VSync. This ensures we don't waste any cycles rendering // frames that will never be displayed to the screen. HRESULT hr = m_swapChain->Present(1, 0); // If the device was removed either by a disconnection or a driver upgrade, we // must recreate all device resources. if (hr == DXGI_ERROR_DEVICE_REMOVED || hr == DXGI_ERROR_DEVICE_RESET) { m_deviceRemoved = true; } else { DX::ThrowIfFailed(hr); MoveToNextFrame(); } } // Wait for pending GPU work to complete. void DX::DeviceResources::WaitForGpu() { // Schedule a Signal command in the queue. DX::ThrowIfFailed(m_commandQueue->Signal(m_fence.Get(), m_fenceValues[m_currentFrame])); // Wait until the fence has been crossed. DX::ThrowIfFailed(m_fence->SetEventOnCompletion(m_fenceValues[m_currentFrame], m_fenceEvent)); WaitForSingleObjectEx(m_fenceEvent, INFINITE, FALSE); // Increment the fence value for the current frame. m_fenceValues[m_currentFrame]++; } // Prepare to render the next frame. void DX::DeviceResources::MoveToNextFrame() { // Schedule a Signal command in the queue. const UINT64 currentFenceValue = m_fenceValues[m_currentFrame]; DX::ThrowIfFailed(m_commandQueue->Signal(m_fence.Get(), currentFenceValue)); // Advance the frame index. m_currentFrame = m_swapChain->GetCurrentBackBufferIndex(); // Check to see if the next frame is ready to start. if (m_fence->GetCompletedValue() < m_fenceValues[m_currentFrame]) { DX::ThrowIfFailed(m_fence->SetEventOnCompletion(m_fenceValues[m_currentFrame], m_fenceEvent)); WaitForSingleObjectEx(m_fenceEvent, INFINITE, FALSE); } // Set the fence value for the next frame. m_fenceValues[m_currentFrame] = currentFenceValue + 1; } // This method determines the rotation between the display device's native Orientation and the // current display orientation. DXGI_MODE_ROTATION DX::DeviceResources::ComputeDisplayRotation() { DXGI_MODE_ROTATION rotation = DXGI_MODE_ROTATION_UNSPECIFIED; // Note: NativeOrientation can only be Landscape or Portrait even though // the DisplayOrientations enum has other values. switch (m_nativeOrientation) { case DisplayOrientations::Landscape: switch (m_currentOrientation) { case DisplayOrientations::Landscape: rotation = DXGI_MODE_ROTATION_IDENTITY; break; case DisplayOrientations::Portrait: rotation = DXGI_MODE_ROTATION_ROTATE270; break; case DisplayOrientations::LandscapeFlipped: rotation = DXGI_MODE_ROTATION_ROTATE180; break; case DisplayOrientations::PortraitFlipped: rotation = DXGI_MODE_ROTATION_ROTATE90; break; } break; case DisplayOrientations::Portrait: switch (m_currentOrientation) { case DisplayOrientations::Landscape: rotation = DXGI_MODE_ROTATION_ROTATE90; break; case DisplayOrientations::Portrait: rotation = DXGI_MODE_ROTATION_IDENTITY; break; case DisplayOrientations::LandscapeFlipped: rotation = DXGI_MODE_ROTATION_ROTATE270; break; case DisplayOrientations::PortraitFlipped: rotation = DXGI_MODE_ROTATION_ROTATE180; break; } break; } return rotation; } // This method acquires the first available hardware adapter that supports Direct3D 12. // If no such adapter can be found, *ppAdapter will be set to nullptr. void DX::DeviceResources::GetHardwareAdapter(IDXGIAdapter1** ppAdapter) { ComPtr<IDXGIAdapter1> adapter; *ppAdapter = nullptr; for (UINT adapterIndex = 0; DXGI_ERROR_NOT_FOUND != m_dxgiFactory->EnumAdapters1(adapterIndex, &adapter); adapterIndex++) { DXGI_ADAPTER_DESC1 desc; adapter->GetDesc1(&desc); if (desc.Flags & DXGI_ADAPTER_FLAG_SOFTWARE) { // Don't select the Basic Render Driver adapter. continue; } // Check to see if the adapter supports Direct3D 12, but don't create the // actual device yet. if (SUCCEEDED(D3D12CreateDevice(adapter.Get(), D3D_FEATURE_LEVEL_11_0, _uuidof(ID3D12Device), nullptr))) { break; } } *ppAdapter = adapter.Detach(); }
34.00846
128
0.743967
[ "render", "object", "3d" ]
f5f0b7a565015b147e6cce9fa32b7012166c8d31
17,587
cc
C++
src/devices/board/drivers/x86/acpi-dev/dev-ec.cc
wwjiang007/fuchsia-1
0db66b52b5bcd3e27c8b8c2163925309e8522f94
[ "BSD-2-Clause" ]
210
2019-02-05T12:45:09.000Z
2022-03-28T07:59:06.000Z
src/devices/board/drivers/x86/acpi-dev/dev-ec.cc
wwjiang007/fuchsia-1
0db66b52b5bcd3e27c8b8c2163925309e8522f94
[ "BSD-2-Clause" ]
56
2021-06-03T03:16:25.000Z
2022-03-20T01:07:44.000Z
src/devices/board/drivers/x86/acpi-dev/dev-ec.cc
wwjiang007/fuchsia-1
0db66b52b5bcd3e27c8b8c2163925309e8522f94
[ "BSD-2-Clause" ]
73
2019-03-06T18:55:23.000Z
2022-03-26T12:04:51.000Z
// Copyright 2017 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include <lib/ddk/debug.h> #include <lib/ddk/driver.h> #include <lib/ddk/hw/inout.h> #include <lib/fit/defer.h> #include <stdio.h> #include <threads.h> #include <zircon/syscalls.h> #include <zircon/types.h> #include "acpi-private.h" #include "dev.h" #include "errors.h" #define xprintf(fmt...) zxlogf(TRACE, fmt) /* EC commands */ #define EC_CMD_READ 0x80 #define EC_CMD_WRITE 0x81 #define EC_CMD_QUERY 0x84 /* EC status register bits */ #define EC_SC_SCI_EVT (1 << 5) #define EC_SC_IBF (1 << 1) #define EC_SC_OBF (1 << 0) /* Thread signals */ #define IRQ_RECEIVED ZX_EVENT_SIGNALED #define EC_THREAD_SHUTDOWN ZX_USER_SIGNAL_0 #define EC_THREAD_SHUTDOWN_DONE ZX_USER_SIGNAL_1 typedef struct acpi_ec_device { zx_device_t* zxdev; ACPI_HANDLE acpi_handle; // PIO addresses for EC device uint16_t cmd_port; uint16_t data_port; // GPE for EC events ACPI_HANDLE gpe_block; UINT32 gpe; // thread for processing events from the EC thrd_t evt_thread; zx_handle_t interrupt_event; bool gpe_setup : 1; bool thread_setup : 1; bool ec_space_setup : 1; } acpi_ec_device_t; static ACPI_STATUS get_ec_handle(ACPI_HANDLE, UINT32, void*, void**); static ACPI_STATUS get_ec_gpe_info(ACPI_HANDLE, ACPI_HANDLE*, UINT32*); static ACPI_STATUS get_ec_ports(ACPI_HANDLE, uint16_t*, uint16_t*); static ACPI_STATUS ec_space_setup_handler(ACPI_HANDLE Region, UINT32 Function, void* HandlerContext, void** ReturnContext); static ACPI_STATUS ec_space_request_handler(UINT32 Function, ACPI_PHYSICAL_ADDRESS Address, UINT32 BitWidth, UINT64* Value, void* HandlerContext, void* RegionContext); static zx_status_t wait_for_interrupt(acpi_ec_device_t* dev); static zx_status_t execute_read_op(acpi_ec_device_t* dev, uint8_t addr, uint8_t* val); static zx_status_t execute_write_op(acpi_ec_device_t* dev, uint8_t addr, uint8_t val); static zx_status_t execute_query_op(acpi_ec_device_t* dev, uint8_t* val); // Execute the EC_CMD_READ operation. Requires the ACPI global lock be held. static zx_status_t execute_read_op(acpi_ec_device_t* dev, uint8_t addr, uint8_t* val) { // Issue EC command outp(dev->cmd_port, EC_CMD_READ); // Wait for EC to read the command so we can write the address while (inp(dev->cmd_port) & EC_SC_IBF) { zx_status_t status = wait_for_interrupt(dev); if (status != ZX_OK) { return status; } } // Specify the address outp(dev->data_port, addr); // Wait for EC to read the address and write a response while ((inp(dev->cmd_port) & (EC_SC_OBF | EC_SC_IBF)) != EC_SC_OBF) { zx_status_t status = wait_for_interrupt(dev); if (status != ZX_OK) { return status; } } // Read the response *val = inp(dev->data_port); return ZX_OK; } // Execute the EC_CMD_WRITE operation. Requires the ACPI global lock be held. static zx_status_t execute_write_op(acpi_ec_device_t* dev, uint8_t addr, uint8_t val) { // Issue EC command outp(dev->cmd_port, EC_CMD_WRITE); // Wait for EC to read the command so we can write the address while (inp(dev->cmd_port) & EC_SC_IBF) { zx_status_t status = wait_for_interrupt(dev); if (status != ZX_OK) { return status; } } // Specify the address outp(dev->data_port, addr); // Wait for EC to read the address while (inp(dev->cmd_port) & EC_SC_IBF) { zx_status_t status = wait_for_interrupt(dev); if (status != ZX_OK) { return status; } } // Write the data outp(dev->data_port, val); // Wait for EC to read the data while (inp(dev->cmd_port) & EC_SC_IBF) { zx_status_t status = wait_for_interrupt(dev); if (status != ZX_OK) { return status; } } return ZX_OK; } // Execute the EC_CMD_QUERY operation. Requires the ACPI global lock be held. static zx_status_t execute_query_op(acpi_ec_device_t* dev, uint8_t* event) { // Query EC command outp(dev->cmd_port, EC_CMD_QUERY); // Wait for EC to respond while ((inp(dev->cmd_port) & (EC_SC_OBF | EC_SC_IBF)) != EC_SC_OBF) { zx_status_t status = wait_for_interrupt(dev); if (status != ZX_OK) { return status; } } *event = inp(dev->data_port); return ZX_OK; } static ACPI_STATUS ec_space_setup_handler(ACPI_HANDLE Region, UINT32 Function, void* HandlerContext, void** ReturnContext) { acpi_ec_device_t* dev = static_cast<acpi_ec_device_t*>(HandlerContext); *ReturnContext = dev; if (Function == ACPI_REGION_ACTIVATE) { xprintf("acpi-ec: Setting up EC region"); return AE_OK; } else if (Function == ACPI_REGION_DEACTIVATE) { xprintf("acpi-ec: Tearing down EC region"); return AE_OK; } else { return AE_SUPPORT; } } static ACPI_STATUS ec_space_request_handler(UINT32 Function, ACPI_PHYSICAL_ADDRESS Address, UINT32 BitWidth, UINT64* Value, void* HandlerContext, void* RegionContext) { acpi_ec_device_t* dev = static_cast<acpi_ec_device_t*>(HandlerContext); if (BitWidth != 8 && BitWidth != 16 && BitWidth != 32 && BitWidth != 64) { return AE_BAD_PARAMETER; } if (Address > UINT8_MAX || Address - 1 + BitWidth / 8 > UINT8_MAX) { return AE_BAD_PARAMETER; } UINT32 global_lock; while (AcpiAcquireGlobalLock(0xFFFF, &global_lock) != AE_OK) ; // NB: The processing of the read/write ops below will generate interrupts, // which will unfortunately cause spurious wakeups on the event thread. One // design that would avoid this is to have that thread responsible for // processing these EC address space requests, but an attempt at an // implementation failed due to apparent deadlocks against the Global Lock. const size_t bytes = BitWidth / 8; ACPI_STATUS status = AE_OK; uint8_t* value_bytes = (uint8_t*)Value; if (Function == ACPI_WRITE) { for (size_t i = 0; i < bytes; ++i) { zx_status_t zx_status = execute_write_op(dev, static_cast<uint8_t>(Address + i), value_bytes[i]); if (zx_status != ZX_OK) { status = AE_ERROR; goto finish; } } } else { *Value = 0; for (size_t i = 0; i < bytes; ++i) { zx_status_t zx_status = execute_read_op(dev, static_cast<uint8_t>(Address + i), value_bytes + i); if (zx_status != ZX_OK) { status = AE_ERROR; goto finish; } } } finish: AcpiReleaseGlobalLock(global_lock); return status; } static zx_status_t wait_for_interrupt(acpi_ec_device_t* dev) { uint32_t pending; zx_status_t status = zx_object_wait_one(dev->interrupt_event, IRQ_RECEIVED | EC_THREAD_SHUTDOWN, ZX_TIME_INFINITE, &pending); if (status != ZX_OK) { printf("acpi-ec: thread wait failed: %d\n", status); zx_object_signal(dev->interrupt_event, 0, EC_THREAD_SHUTDOWN_DONE); return status; } if (pending & EC_THREAD_SHUTDOWN) { zx_object_signal(dev->interrupt_event, 0, EC_THREAD_SHUTDOWN_DONE); return ZX_ERR_STOP; } /* Clear interrupt */ zx_object_signal(dev->interrupt_event, IRQ_RECEIVED, 0); return ZX_OK; } static int acpi_ec_thread(void* arg) { acpi_ec_device_t* dev = static_cast<acpi_ec_device_t*>(arg); UINT32 global_lock; while (1) { zx_status_t zx_status = wait_for_interrupt(dev); if (zx_status != ZX_OK) { goto exiting_without_lock; } while (AcpiAcquireGlobalLock(0xFFFF, &global_lock) != AE_OK) ; uint8_t status; bool processed_evt = false; while ((status = inp(dev->cmd_port)) & EC_SC_SCI_EVT) { uint8_t event_code; zx_status_t zx_status = execute_query_op(dev, &event_code); if (zx_status != ZX_OK) { goto exiting_with_lock; } if (event_code != 0) { char method[5] = {0}; snprintf(method, sizeof(method), "_Q%02x", event_code); xprintf("acpi-ec: Invoking method %s", method); AcpiEvaluateObject(dev->acpi_handle, method, NULL, NULL); xprintf("acpi-ec: Invoked method %s", method); } else { xprintf("acpi-ec: Spurious event?"); } processed_evt = true; /* Clear interrupt before we check EVT again, to prevent a spurious * interrupt later. There could be two sources of that spurious * wakeup: Either we handled two events back-to-back, or we didn't * wait for the OBF interrupt above. */ zx_object_signal(dev->interrupt_event, IRQ_RECEIVED, 0); } if (!processed_evt) { xprintf("acpi-ec: Spurious wakeup, no evt: %#x", status); } AcpiReleaseGlobalLock(global_lock); } exiting_with_lock: AcpiReleaseGlobalLock(global_lock); exiting_without_lock: xprintf("acpi-ec: thread terminated"); return 0; } static uint32_t raw_ec_event_gpe_handler(ACPI_HANDLE gpe_dev, uint32_t gpe_num, void* ctx) { acpi_ec_device_t* dev = static_cast<acpi_ec_device_t*>(ctx); zx_object_signal(dev->interrupt_event, 0, IRQ_RECEIVED); return ACPI_REENABLE_GPE; } __UNUSED static ACPI_STATUS get_ec_handle(ACPI_HANDLE object, UINT32 nesting_level, void* context, void** ret) { *(ACPI_HANDLE*)context = object; return AE_OK; } static ACPI_STATUS get_ec_gpe_info(ACPI_HANDLE ec_handle, ACPI_HANDLE* gpe_block, UINT32* gpe) { acpi::UniquePtr<ACPI_OBJECT> gpe_obj; { ACPI_BUFFER buffer = { .Length = ACPI_ALLOCATE_BUFFER, .Pointer = NULL, }; ACPI_STATUS status = AcpiEvaluateObject(ec_handle, (char*)"_GPE", NULL, &buffer); gpe_obj.reset(static_cast<ACPI_OBJECT*>(buffer.Pointer)); if (status != AE_OK) { return status; } } auto cleanup = fit::defer([]() { xprintf("Failed to intepret EC GPE number"); }); /* According to section 12.11 of ACPI v6.1, a _GPE object on this device * evaluates to either an integer specifying bit in the GPEx_STS blocks * to use, or a package specifying which GPE block and which bit inside * that block to use. */ if (gpe_obj->Type == ACPI_TYPE_INTEGER) { *gpe_block = NULL; *gpe = static_cast<uint32_t>(gpe_obj->Integer.Value); } else if (gpe_obj->Type == ACPI_TYPE_PACKAGE) { if (gpe_obj->Package.Count != 2) { return AE_BAD_DATA; } ACPI_OBJECT* block_obj = &gpe_obj->Package.Elements[0]; ACPI_OBJECT* gpe_num_obj = &gpe_obj->Package.Elements[1]; if (block_obj->Type != ACPI_TYPE_LOCAL_REFERENCE) { return AE_BAD_DATA; } if (gpe_num_obj->Type != ACPI_TYPE_INTEGER) { return AE_BAD_DATA; } *gpe_block = block_obj->Reference.Handle; *gpe = static_cast<uint32_t>(gpe_num_obj->Integer.Value); } else { return AE_BAD_DATA; } cleanup.cancel(); return AE_OK; } struct ec_ports_callback_ctx { uint16_t* data_port; uint16_t* cmd_port; unsigned int resource_num; }; static ACPI_STATUS get_ec_ports_callback(ACPI_RESOURCE* Resource, void* Context) { struct ec_ports_callback_ctx* ctx = static_cast<ec_ports_callback_ctx*>(Context); if (Resource->Type == ACPI_RESOURCE_TYPE_END_TAG) { return AE_OK; } /* The spec says there will be at most 3 resources */ if (ctx->resource_num >= 3) { return AE_BAD_DATA; } /* The third resource only exists on HW-Reduced platforms, which we don't * support at the moment. */ if (ctx->resource_num == 2) { xprintf("RESOURCE TYPE %d", Resource->Type); return AE_NOT_IMPLEMENTED; } /* The two resources we're expecting are both address regions. First the * data one, then the command one. We assume they're single IO ports. */ if (Resource->Type != ACPI_RESOURCE_TYPE_IO) { return AE_SUPPORT; } if (Resource->Data.Io.Maximum != Resource->Data.Io.Minimum) { return AE_SUPPORT; } uint16_t port = Resource->Data.Io.Minimum; if (ctx->resource_num == 0) { *ctx->data_port = port; } else { *ctx->cmd_port = port; } ctx->resource_num++; return AE_OK; } static ACPI_STATUS get_ec_ports(ACPI_HANDLE ec_handle, uint16_t* data_port, uint16_t* cmd_port) { struct ec_ports_callback_ctx ctx = { .data_port = data_port, .cmd_port = cmd_port, .resource_num = 0, }; return AcpiWalkResources(ec_handle, (char*)"_CRS", get_ec_ports_callback, &ctx); } static void acpi_ec_release(void* ctx) { acpi_ec_device_t* dev = static_cast<acpi_ec_device_t*>(ctx); if (dev->ec_space_setup) { AcpiRemoveAddressSpaceHandler(ACPI_ROOT_OBJECT, ACPI_ADR_SPACE_EC, ec_space_request_handler); } if (dev->gpe_setup) { AcpiDisableGpe(dev->gpe_block, dev->gpe); AcpiRemoveGpeHandler(dev->gpe_block, dev->gpe, raw_ec_event_gpe_handler); } if (dev->interrupt_event != ZX_HANDLE_INVALID) { if (dev->thread_setup) { /* Shutdown the EC thread */ zx_object_signal(dev->interrupt_event, 0, EC_THREAD_SHUTDOWN); zx_object_wait_one(dev->interrupt_event, EC_THREAD_SHUTDOWN_DONE, ZX_TIME_INFINITE, NULL); thrd_join(dev->evt_thread, NULL); } zx_handle_close(dev->interrupt_event); } free(dev); } static void acpi_ec_suspend(void* ctx, uint8_t requested_state, bool enable_wake, uint8_t suspend_reason) { acpi_ec_device_t* dev = static_cast<acpi_ec_device_t*>(ctx); if (suspend_reason != DEVICE_SUSPEND_REASON_MEXEC) { device_suspend_reply(dev->zxdev, ZX_OK, requested_state); return; } AcpiRemoveAddressSpaceHandler(ACPI_ROOT_OBJECT, ACPI_ADR_SPACE_EC, ec_space_request_handler); dev->ec_space_setup = false; AcpiDisableGpe(dev->gpe_block, dev->gpe); AcpiRemoveGpeHandler(dev->gpe_block, dev->gpe, raw_ec_event_gpe_handler); dev->gpe_setup = false; zx_object_signal(dev->interrupt_event, 0, EC_THREAD_SHUTDOWN); zx_object_wait_one(dev->interrupt_event, EC_THREAD_SHUTDOWN_DONE, ZX_TIME_INFINITE, NULL); thrd_join(dev->evt_thread, NULL); zx_handle_close(dev->interrupt_event); dev->interrupt_event = ZX_HANDLE_INVALID; device_suspend_reply(dev->zxdev, ZX_OK, requested_state); } static zx_protocol_device_t acpi_ec_device_proto = [] { zx_protocol_device_t ops = {}; ops.version = DEVICE_OPS_VERSION; ops.release = acpi_ec_release; ops.suspend = acpi_ec_suspend; return ops; }(); zx_status_t ec_init(zx_device_t* parent, ACPI_HANDLE acpi_handle) { xprintf("acpi-ec: init"); acpi_ec_device_t* dev = static_cast<acpi_ec_device_t*>(calloc(1, sizeof(acpi_ec_device_t))); if (!dev) { return ZX_ERR_NO_MEMORY; } dev->acpi_handle = acpi_handle; zx_status_t err = zx_event_create(0, &dev->interrupt_event); if (err != ZX_OK) { xprintf("acpi-ec: Failed to create event: %d", err); acpi_ec_release(dev); return err; } int ret; ACPI_STATUS status = get_ec_gpe_info(acpi_handle, &dev->gpe_block, &dev->gpe); if (status != AE_OK) { xprintf("acpi-ec: Failed to decode GPE info: %d", status); goto acpi_error; } status = get_ec_ports(acpi_handle, &dev->data_port, &dev->cmd_port); if (status != AE_OK) { xprintf("acpi-ec: Failed to decode comm info: %d", status); goto acpi_error; } // Please do not use get_root_resource() in new code. See fxbug.dev/31358. status = zx_ioports_request(get_root_resource(), dev->data_port, 1); if (status != ZX_OK) { xprintf("acpi-ec: Failed to map ec data port: %d", status); goto acpi_error; } status = zx_ioports_request(get_root_resource(), dev->cmd_port, 1); if (status != ZX_OK) { xprintf("acpi-ec: Failed to map ec cmd port: %d", status); goto acpi_error; } /* Setup GPE handling */ status = AcpiInstallGpeHandler(dev->gpe_block, dev->gpe, ACPI_GPE_EDGE_TRIGGERED, raw_ec_event_gpe_handler, dev); if (status != AE_OK) { xprintf("acpi-ec: Failed to install GPE %d: %x", dev->gpe, status); goto acpi_error; } status = AcpiEnableGpe(dev->gpe_block, dev->gpe); if (status != AE_OK) { xprintf("acpi-ec: Failed to enable GPE %d: %x", dev->gpe, status); AcpiRemoveGpeHandler(dev->gpe_block, dev->gpe, raw_ec_event_gpe_handler); goto acpi_error; } dev->gpe_setup = true; /* TODO(teisenbe): This thread should ideally be at a high priority, since it takes the ACPI global lock which is shared with SMM. */ ret = thrd_create_with_name(&dev->evt_thread, acpi_ec_thread, dev, "acpi-ec-evt"); if (ret != thrd_success) { xprintf("acpi-ec: Failed to create thread"); acpi_ec_release(dev); return ZX_ERR_INTERNAL; } dev->thread_setup = true; status = AcpiInstallAddressSpaceHandler(ACPI_ROOT_OBJECT, ACPI_ADR_SPACE_EC, ec_space_request_handler, ec_space_setup_handler, dev); if (status != AE_OK) { xprintf("acpi-ec: Failed to install ec space handler"); acpi_ec_release(dev); return acpi_to_zx_status(status); } dev->ec_space_setup = true; { device_add_args_t args = {}; args.version = DEVICE_ADD_ARGS_VERSION; args.name = "acpi-ec"; args.ctx = dev; args.ops = &acpi_ec_device_proto; args.proto_id = ZX_PROTOCOL_MISC; status = device_add(parent, &args, &dev->zxdev); } if (status != ZX_OK) { xprintf("acpi-ec: could not add device! err=%d", status); acpi_ec_release(dev); return status; } printf("acpi-ec: initialized\n"); return ZX_OK; acpi_error: acpi_ec_release(dev); return acpi_to_zx_status(status); }
30.963028
100
0.683573
[ "object" ]
f5f4ac7847fcea263797b1d9dbf39b430063bdb3
4,302
cpp
C++
fib/ass/writer.cpp
keitaroskmt/cpuex2020_1
33cdc033a6184286232f4ce7729030708213b6f8
[ "BSD-3-Clause-Attribution", "FSFAP" ]
null
null
null
fib/ass/writer.cpp
keitaroskmt/cpuex2020_1
33cdc033a6184286232f4ce7729030708213b6f8
[ "BSD-3-Clause-Attribution", "FSFAP" ]
null
null
null
fib/ass/writer.cpp
keitaroskmt/cpuex2020_1
33cdc033a6184286232f4ce7729030708213b6f8
[ "BSD-3-Clause-Attribution", "FSFAP" ]
3
2020-10-08T04:16:58.000Z
2021-10-11T13:19:30.000Z
#include "parser.hpp" #include "writer.hpp" Writer::Writer(const char *fname, Parser *p) { file_name = fname; parser = p; current_num = 0; } void Writer::assemble() { fstream f; f.open(file_name, ios::out); if (!f.is_open()) { cerr << "cannot open output file" << endl; } for (auto v : parser->code_map) { current_num = v.first; f << static_cast<bitset<32>>(encode(v.second)) << endl; } f.close(); } unsigned int Writer::encode(vector<string> &v) { // R形式 // opcode 31-26, rs 25-21, rt 20-16, rd 15-11, shamt 10-6, funct 5-0 // add, jr, sll, slt if (v[0] == "R") { unsigned int op, rs, rt, rd, shamt, funct; if (v[1] == "add") { op = 0x0; rd = reg_name.at(v[2]); rs = reg_name.at(v[3]); rt = reg_name.at(v[4]); shamt = 0x0; funct = 0x20; } else if (v[1] == "sll") { op = 0x0; rd = reg_name.at(v[2]); rt = reg_name.at(v[3]); shamt = reg_name.at(v[4]); rs = 0x0; funct = 0x0; } else if (v[1] == "slt") { op = 0x0; rd = reg_name.at(v[2]); rs = reg_name.at(v[3]); rt = reg_name.at(v[4]); shamt = 0x0; funct = 0x2a; } else if (v[1] == "jr") { op = 0x0; rs = reg_name.at(v[2]); rt = 0x0; rd = reg_name.at(v[2]); shamt = 0x0; funct = 0x8; } op &= 0b111111; rs &= 0b11111; rt &= 0b11111; rd &= 0b11111; shamt &= 0b11111; funct &= 0b111111; return (op << 26) | (rs << 21) | (rt << 16) | (rd << 11) | (shamt << 6) | funct; } // I形式 // opcode 31-26, rs 25-21, rt 20-16, imm 15-0 // addi, bne, lw, sw else if (v[0] == "I") { unsigned int op, rs, rt, imm; if (v[1] == "addi") { op = 0x8; rt = reg_name.at(v[2]); rs = reg_name.at(v[3]); imm = stoi(v[4]); } else if (v[1] == "bne") { op = 0x5; rt = reg_name.at(v[2]); rs = reg_name.at(v[3]); // 相対アドレス imm = parser->label_map.at(v[4]) - (current_num + 1); } else if (v[1] == "lw") { op = 0x23; rt = reg_name.at(v[2]); imm = stoi(v[3]); rs = reg_name.at(v[4]); } else if (v[1] == "sw") { op = 0x2b; rt = reg_name.at(v[2]); imm = stoi(v[3]); rs = reg_name.at(v[4]); } op &= 0b111111; rs &= 0b11111; rt &= 0b11111; imm &= 0xffff; return (op << 26) | (rs << 21) | (rt << 16) | imm; } // J形式 // opcode 31-26, addr 25-0 // j, jal else if (v[0] == "J") { unsigned int op, addr; if (v[1] == "j") { op = 0x2; addr = parser->label_map.at(v[2]); } else if (v[1] == "jal") { op = 0x3; // print_intをとりあえずnopに //if (v[2] == "min_caml_print_int") { //op = 0x0; //addr = 0x0; //} else { addr = parser->label_map.at(v[2]); //} } op &= 0b111111; addr &= 0x3ffffff; return (op << 26) | addr; } // ret デバッグ用にaddi $v0 $v0 0とする. else if (v[0] == "ret") { return 0b00100000010000100000000000000000; } // nop 0うめ else if (v[0] == "nop") { return 0; } else { cerr << "Error has occured in encoding" << endl; exit(1); } return 0; } void Writer::debug() { parser->print_label(); cout << endl; for (auto v : parser->code_map) { cout << "L." << v.first << " "; for (auto x : v.second) { cout << x << " "; } cout << endl; current_num = v.first; unsigned int bit = encode(v.second); for (int i = 31; i >= 0; --i) { if (bit & (1<<i)) cout << 1; else cout << 0; if (i == 26 || i == 21 || i == 16 || i == 11 || i == 6) cout << " "; } cout << endl; } }
24.03352
88
0.39656
[ "vector" ]
f5f6ec146c3dd9bd9394b5a682783f309e91a8dc
340
hpp
C++
am/linear/matrix.hpp
komiga/am
4ce4cc5539c3fd5b1ff1ccf5bf843e6c484e94aa
[ "MIT" ]
1
2015-01-16T18:56:01.000Z
2015-01-16T18:56:01.000Z
am/linear/matrix.hpp
komiga/am
4ce4cc5539c3fd5b1ff1ccf5bf843e6c484e94aa
[ "MIT" ]
null
null
null
am/linear/matrix.hpp
komiga/am
4ce4cc5539c3fd5b1ff1ccf5bf843e6c484e94aa
[ "MIT" ]
null
null
null
/** @copyright MIT license; see @ref index or the accompanying LICENSE file. @file @brief Include matrix types, interfaces, and operations. */ #pragma once #include "../config.hpp" #include "./vector.hpp" #include "./matrix_types.hpp" #include "./matrix_interface.hpp" #include "./matrix_operations.hpp" namespace am {} // namespace am
20
72
0.726471
[ "vector" ]
f5f84f2bbe8d9db9b5286e5b842041b5c259f174
6,410
cpp
C++
openstudiocore/src/radiance/AnnualIlluminanceMap.cpp
Acidburn0zzz/OpenStudio
8d7aa85fe5df7987cb6983984d4ce8698f1bd0bd
[ "MIT" ]
null
null
null
openstudiocore/src/radiance/AnnualIlluminanceMap.cpp
Acidburn0zzz/OpenStudio
8d7aa85fe5df7987cb6983984d4ce8698f1bd0bd
[ "MIT" ]
null
null
null
openstudiocore/src/radiance/AnnualIlluminanceMap.cpp
Acidburn0zzz/OpenStudio
8d7aa85fe5df7987cb6983984d4ce8698f1bd0bd
[ "MIT" ]
null
null
null
/*********************************************************************************************************************** * OpenStudio(R), Copyright (c) 2008-2018, Alliance for Sustainable Energy, LLC. All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the * following conditions are met: * * (1) Redistributions of source code must retain the above copyright notice, this list of conditions and the following * disclaimer. * * (2) Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided with the distribution. * * (3) Neither the name of the copyright holder nor the names of any contributors may be used to endorse or promote products * derived from this software without specific prior written permission from the respective party. * * (4) Other than as required in clauses (1) and (2), distributions in any form of modifications or other derivative works * may not use the "OpenStudio" trademark, "OS", "os", or any other confusingly similar designation without specific prior * written permission from Alliance for Sustainable Energy, LLC. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER(S) AND ANY CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER(S), ANY CONTRIBUTORS, THE UNITED STATES GOVERNMENT, OR THE UNITED * STATES DEPARTMENT OF ENERGY, NOR ANY OF THEIR EMPLOYEES, BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ***********************************************************************************************************************/ #include "AnnualIlluminanceMap.hpp" #include "HeaderInfo.hpp" #include <iostream> #include <fstream> #include <vector> #include <boost/lexical_cast.hpp> #include <boost/regex.hpp> #include <boost/algorithm/string.hpp> #include <boost/tokenizer.hpp> using namespace std; using namespace boost; using namespace openstudio; namespace openstudio{ namespace radiance{ /// default constructor AnnualIlluminanceMap::AnnualIlluminanceMap() {} /// constructor with path AnnualIlluminanceMap::AnnualIlluminanceMap(const openstudio::path& path) { init(path); } void AnnualIlluminanceMap::init(const openstudio::path& path) { // file must exist if (!exists( path )){ LOG(Fatal, "File does not exist: '" << toString(path) << "'" ); return; } // open file openstudio::filesystem::ifstream file(path); // keep track of line number unsigned lineNum = 0; // keep track of matrix size unsigned M=0; unsigned N=0; // temp string to read file string line; // lines 1 and 2 are the header lines string line1, line2; // this will contain matches to regular expressions smatch matches; // matches a single number followed by either tabs or spaces const regex singleNumber("([-+]?[0-9]*\\.?[0-9]+)[\\s\\t]*"); // conversion from footcandles to lux const double footcandlesToLux(10.76); // read the rest of the file line by line while(getline(file, line)){ ++lineNum; if (lineNum == 1){ // save line 1 line1 = line; }else if (lineNum == 2){ // save line 2 line2 = line; // create the header info HeaderInfo headerInfo(line1, line2); // we can now initialize x and y vectors m_xVector = headerInfo.xVector(); m_yVector = headerInfo.yVector(); M = m_xVector.size(); N = m_yVector.size(); }else{ // each line contains the month, day, time (in hours), // Solar Azimuth(degrees from south), Solar Altitude(degrees), Global Horizontal Illuminance (fc) // followed by M*N illuminance points // break the line up by spaces vector<string> lineVector; tokenizer<char_separator<char>, std::string::const_iterator, std::string > tk(line, char_separator<char>(" ")); for (tokenizer<char_separator<char>, std::string::const_iterator, std::string >::iterator it(tk.begin()); it!=tk.end(); ++it) { lineVector.push_back(*it); } // total number minus 6 standard header items unsigned numValues = lineVector.size() - 6; if (numValues != M*N){ LOG(Fatal, "Incorrect number of illuminance values read " << numValues << ", expecting " << M*N << "."); return; }else{ MonthOfYear month = monthOfYear(lexical_cast<unsigned>(lineVector[0])); unsigned day = lexical_cast<unsigned>(lineVector[1]); double fracDays = lexical_cast<double>(lineVector[2]) / 24.0; // ignore solar angles and global horizontal for now // make the date time DateTime dateTime(Date(month, day), Time(fracDays)); // matrix we are going to read in Matrix illuminanceMap(M,N); // read in the values unsigned index = 6; for (unsigned j = 0; j < N; ++j){ for (unsigned i = 0; i < M; ++i){ illuminanceMap(i,j) = footcandlesToLux*lexical_cast<double>(lineVector[index]); ++index; } } m_dateTimes.push_back(dateTime); m_dateTimeIlluminanceMap[dateTime] = illuminanceMap; } } } // close file file.close(); } /// get the illuminance map in lux corresponding to date and time openstudio::Matrix AnnualIlluminanceMap::illuminanceMap(const openstudio::DateTime& dateTime) const { auto it = m_dateTimeIlluminanceMap.find(dateTime); if (it != m_dateTimeIlluminanceMap.end()){ return it->second; } return m_nullIlluminanceMap; } } // radiance } // openstudio
34.648649
133
0.64493
[ "vector" ]
f5f969ff0da3d7a2def9718adf6b382ffa6443df
5,272
hpp
C++
obs-studio/UI/window-basic-auto-config.hpp
noelemahcz/libobspp
029472b973e5a1985f883242f249848385df83a3
[ "MIT" ]
null
null
null
obs-studio/UI/window-basic-auto-config.hpp
noelemahcz/libobspp
029472b973e5a1985f883242f249848385df83a3
[ "MIT" ]
null
null
null
obs-studio/UI/window-basic-auto-config.hpp
noelemahcz/libobspp
029472b973e5a1985f883242f249848385df83a3
[ "MIT" ]
null
null
null
#pragma once #include <QWizard> #include <QPointer> #include <QFormLayout> #include <QWizardPage> #include <condition_variable> #include <utility> #include <thread> #include <memory> #include <vector> #include <string> #include <mutex> class Ui_AutoConfigStartPage; class Ui_AutoConfigVideoPage; class Ui_AutoConfigStreamPage; class Ui_AutoConfigTestPage; class AutoConfigStreamPage; class Auth; class AutoConfig : public QWizard { Q_OBJECT friend class AutoConfigStartPage; friend class AutoConfigVideoPage; friend class AutoConfigStreamPage; friend class AutoConfigTestPage; enum class Type { Invalid, Streaming, Recording, VirtualCam, }; enum class Service { Twitch, YouTube, Other, }; enum class Encoder { x264, NVENC, QSV, AMD, Stream, }; enum class Quality { Stream, High, }; enum class FPSType : int { PreferHighFPS, PreferHighRes, UseCurrent, fps30, fps60, }; static inline const char *GetEncoderId(Encoder enc); AutoConfigStreamPage *streamPage = nullptr; Service service = Service::Other; Quality recordingQuality = Quality::Stream; Encoder recordingEncoder = Encoder::Stream; Encoder streamingEncoder = Encoder::x264; Type type = Type::Streaming; FPSType fpsType = FPSType::PreferHighFPS; int idealBitrate = 2500; int baseResolutionCX = 1920; int baseResolutionCY = 1080; int idealResolutionCX = 1280; int idealResolutionCY = 720; int idealFPSNum = 60; int idealFPSDen = 1; std::string serviceName; std::string serverName; std::string server; std::string key; bool hardwareEncodingAvailable = false; bool nvencAvailable = false; bool qsvAvailable = false; bool vceAvailable = false; int startingBitrate = 2500; bool customServer = false; bool bandwidthTest = false; bool testRegions = true; bool twitchAuto = false; bool regionUS = true; bool regionEU = true; bool regionAsia = true; bool regionOther = true; bool preferHighFPS = false; bool preferHardware = false; int specificFPSNum = 0; int specificFPSDen = 0; void TestHardwareEncoding(); bool CanTestServer(const char *server); virtual void done(int result) override; void SaveStreamSettings(); void SaveSettings(); public: AutoConfig(QWidget *parent); ~AutoConfig(); enum Page { StartPage, VideoPage, StreamPage, TestPage, }; }; class AutoConfigStartPage : public QWizardPage { Q_OBJECT friend class AutoConfig; Ui_AutoConfigStartPage *ui; public: AutoConfigStartPage(QWidget *parent = nullptr); ~AutoConfigStartPage(); virtual int nextId() const override; public slots: void on_prioritizeStreaming_clicked(); void on_prioritizeRecording_clicked(); void PrioritizeVCam(); }; class AutoConfigVideoPage : public QWizardPage { Q_OBJECT friend class AutoConfig; Ui_AutoConfigVideoPage *ui; public: AutoConfigVideoPage(QWidget *parent = nullptr); ~AutoConfigVideoPage(); virtual int nextId() const override; virtual bool validatePage() override; }; class AutoConfigStreamPage : public QWizardPage { Q_OBJECT friend class AutoConfig; enum class Section : int { Connect, StreamKey, }; std::shared_ptr<Auth> auth; Ui_AutoConfigStreamPage *ui; QString lastService; bool ready = false; void LoadServices(bool showAll); inline bool IsCustomService() const; public: AutoConfigStreamPage(QWidget *parent = nullptr); ~AutoConfigStreamPage(); virtual bool isComplete() const override; virtual int nextId() const override; virtual bool validatePage() override; void OnAuthConnected(); void OnOAuthStreamKeyConnected(); public slots: void on_show_clicked(); void on_connectAccount_clicked(); void on_disconnectAccount_clicked(); void on_useStreamKey_clicked(); void ServiceChanged(); void UpdateKeyLink(); void UpdateMoreInfoLink(); void UpdateServerList(); void UpdateCompleted(); void reset_service_ui_fields(std::string &service); }; class AutoConfigTestPage : public QWizardPage { Q_OBJECT friend class AutoConfig; QPointer<QFormLayout> results; Ui_AutoConfigTestPage *ui; std::thread testThread; std::condition_variable cv; std::mutex m; bool cancel = false; bool started = false; enum class Stage { Starting, BandwidthTest, StreamEncoder, RecordingEncoder, Finished, }; Stage stage = Stage::Starting; bool softwareTested = false; void StartBandwidthStage(); void StartStreamEncoderStage(); void StartRecordingEncoderStage(); void FindIdealHardwareResolution(); bool TestSoftwareEncoding(); void TestBandwidthThread(); void TestStreamEncoderThread(); void TestRecordingEncoderThread(); void FinalizeResults(); struct ServerInfo { std::string name; std::string address; int bitrate = 0; int ms = -1; inline ServerInfo() {} inline ServerInfo(const char *name_, const char *address_) : name(name_), address(address_) { } }; void GetServers(std::vector<ServerInfo> &servers); public: AutoConfigTestPage(QWidget *parent = nullptr); ~AutoConfigTestPage(); virtual void initializePage() override; virtual void cleanupPage() override; virtual bool isComplete() const override; virtual int nextId() const override; public slots: void NextStage(); void UpdateMessage(QString message); void Failure(QString message); void Progress(int percentage); };
19.240876
60
0.752086
[ "vector" ]
f5f9ab3c76f763d311ae09c69e84e74b02dcea02
19,509
cpp
C++
arangod/IResearch/IResearchViewCoordinator.cpp
wiltonlazary/arangodb
e1706e34fad8685f5a4dda6a95ed38f1fb7439db
[ "Apache-2.0" ]
null
null
null
arangod/IResearch/IResearchViewCoordinator.cpp
wiltonlazary/arangodb
e1706e34fad8685f5a4dda6a95ed38f1fb7439db
[ "Apache-2.0" ]
null
null
null
arangod/IResearch/IResearchViewCoordinator.cpp
wiltonlazary/arangodb
e1706e34fad8685f5a4dda6a95ed38f1fb7439db
[ "Apache-2.0" ]
null
null
null
//////////////////////////////////////////////////////////////////////////////// /// DISCLAIMER /// /// Copyright 2014-2022 ArangoDB GmbH, Cologne, Germany /// Copyright 2004-2014 triAGENS GmbH, Cologne, Germany /// /// Licensed under the Apache License, Version 2.0 (the "License"); /// you may not use this file except in compliance with the License. /// You may obtain a copy of the License at /// /// http://www.apache.org/licenses/LICENSE-2.0 /// /// Unless required by applicable law or agreed to in writing, software /// distributed under the License is distributed on an "AS IS" BASIS, /// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. /// See the License for the specific language governing permissions and /// limitations under the License. /// /// Copyright holder is ArangoDB GmbH, Cologne, Germany /// /// @author Andrey Abramov /// @author Vasiliy Nabatchikov //////////////////////////////////////////////////////////////////////////////// #include "IResearchViewCoordinator.h" #include "IResearchCommon.h" #include "IResearchLinkHelper.h" #include <velocypack/Builder.h> #include <velocypack/Collection.h> #include <velocypack/Parser.h> #include "ApplicationFeatures/ApplicationServer.h" #include "Basics/StaticStrings.h" #include "Basics/StringUtils.h" #include "Cluster/ClusterFeature.h" #include "Cluster/ClusterInfo.h" #include "Cluster/ClusterMethods.h" #include "Cluster/ServerState.h" #include "IResearch/IResearchFeature.h" #include "IResearch/IResearchLink.h" #include "IResearch/VelocyPackHelper.h" #include "RestServer/ViewTypesFeature.h" #include "Transaction/Methods.h" #include "Transaction/StandaloneContext.h" #include "Utils/ExecContext.h" #include "VocBase/LogicalCollection.h" #include "VocBase/Methods/Indexes.h" namespace { void ensureImmutableProperties( arangodb::iresearch::IResearchViewMeta& dst, arangodb::iresearch::IResearchViewMeta const& src) { dst._version = src._version; dst._writebufferActive = src._writebufferActive; dst._writebufferIdle = src._writebufferIdle; dst._writebufferSizeMax = src._writebufferSizeMax; dst._primarySort = src._primarySort; dst._storedValues = src._storedValues; dst._primarySortCompression = src._primarySortCompression; } } // namespace namespace arangodb { namespace iresearch { //////////////////////////////////////////////////////////////////////////////// /// @brief IResearchView-specific implementation of a ViewFactory //////////////////////////////////////////////////////////////////////////////// struct IResearchViewCoordinator::ViewFactory : public arangodb::ViewFactory { virtual Result create(LogicalView::ptr& view, TRI_vocbase_t& vocbase, VPackSlice definition, bool isUserRequest) const override { if (!vocbase.server().hasFeature<ClusterFeature>()) { return Result( TRI_ERROR_INTERNAL, std::string("failure to find 'ClusterInfo' instance while creating " "arangosearch View in database '") + vocbase.name() + "'"); } auto& ci = vocbase.server().getFeature<ClusterFeature>().clusterInfo(); auto properties = definition.isObject() ? definition : velocypack::Slice::emptyObjectSlice(); // if no 'info' then // assume defaults auto links = properties.hasKey(StaticStrings::LinksField) ? properties.get(StaticStrings::LinksField) : velocypack::Slice::emptyObjectSlice(); auto res = IResearchLinkHelper::validateLinks(vocbase, links); if (!res.ok()) { return res; } LogicalView::ptr impl; res = LogicalViewHelperClusterInfo::construct(impl, vocbase, definition); if (!res.ok()) { return res; } // create links on a best-effor basis // link creation failure does not cause view creation failure try { std::unordered_set<DataSourceId> collections; res = IResearchLinkHelper::updateLinks(collections, *impl, links, getDefaultVersion(isUserRequest)); if (!res.ok()) { LOG_TOPIC("39d88", WARN, iresearch::TOPIC) << "failed to create links while creating arangosearch view '" << impl->name() << "': " << res.errorNumber() << " " << res.errorMessage(); } } catch (basics::Exception const& e) { LOG_TOPIC("09bb9", WARN, iresearch::TOPIC) << "caught exception while creating links while creating " "arangosearch view '" << impl->name() << "': " << e.code() << " " << e.what(); } catch (std::exception const& e) { LOG_TOPIC("6b99b", WARN, iresearch::TOPIC) << "caught exception while creating links while creating " "arangosearch view '" << impl->name() << "': " << e.what(); } catch (...) { LOG_TOPIC("61ae6", WARN, iresearch::TOPIC) << "caught exception while creating links while creating " "arangosearch view '" << impl->name() << "'"; } view = ci.getView( vocbase.name(), std::to_string(impl->id().id())); // refresh view from Agency if (view) { view->open(); // open view to match the behavior in // StorageEngine::openExistingDatabase(...) and original // behavior of TRI_vocbase_t::createView(...) } return Result(); } virtual Result instantiate(LogicalView::ptr& view, TRI_vocbase_t& vocbase, VPackSlice definition) const override { std::string error; auto impl = std::shared_ptr<IResearchViewCoordinator>( new IResearchViewCoordinator(vocbase, definition)); if (!impl->_meta.init(definition, error)) { return Result( TRI_ERROR_BAD_PARAMETER, error.empty() ? (std::string("failed to initialize arangosearch View '") + impl->name() + "' from definition: " + definition.toString()) : (std::string("failed to initialize arangosearch View '") + impl->name() + "' from definition, error in attribute '" + error + "': " + definition.toString())); } view = impl; return Result(); } }; Result IResearchViewCoordinator::appendVelocyPackImpl( velocypack::Builder& builder, Serialization context) const { if (Serialization::List == context) { // nothing more to output return {}; } std::function<bool(irs::string_ref)> const propertiesAcceptor = [](irs::string_ref key) -> bool { return std::string_view{key} != StaticStrings::VersionField; }; std::function<bool(irs::string_ref)> const persistenceAcceptor = [](irs::string_ref) -> bool { return true; }; const std::function<bool(irs::string_ref)> linkPropertiesAcceptor = [](std::string_view key) -> bool { return key != iresearch::StaticStrings::AnalyzerDefinitionsField && key != iresearch::StaticStrings::PrimarySortField && key != iresearch::StaticStrings::PrimarySortCompressionField && key != iresearch::StaticStrings::StoredValuesField && key != iresearch::StaticStrings::VersionField && key != iresearch::StaticStrings::CollectionNameField; }; auto* acceptor = &propertiesAcceptor; if (context == Serialization::Persistence || context == Serialization::PersistenceWithInProgress) { auto res = LogicalViewHelperClusterInfo::properties(builder, *this); if (!res.ok()) { return res; } acceptor = &persistenceAcceptor; } if (context == Serialization::Properties || context == Serialization::Inventory) { // verify that the current user has access on all linked collections ExecContext const& exec = ExecContext::current(); if (!exec.isSuperuser()) { for (auto& entry : _collections) { if (!exec.canUseCollection(vocbase().name(), entry.second.first, auth::Level::RO)) { return Result(TRI_ERROR_FORBIDDEN); } } } VPackBuilder tmp; // '_collections' can be asynchronously modified auto lock = irs::make_shared_lock(_mutex); builder.add(StaticStrings::LinksField, VPackValue(VPackValueType::Object)); for (auto& entry : _collections) { auto linkSlice = entry.second.second.slice(); if (context == Serialization::Properties) { tmp.clear(); tmp.openObject(); if (!mergeSliceSkipKeys(tmp, linkSlice, linkPropertiesAcceptor)) { return {TRI_ERROR_INTERNAL, "failed to generate externally visible link definition for " "arangosearch View '" + name() + "'"}; } linkSlice = tmp.close().slice(); } builder.add(entry.second.first, linkSlice); } builder.close(); } if (!builder.isOpenObject()) { return {TRI_ERROR_BAD_PARAMETER, "invalid builder provided for " "IResearchViewCoordinator definition"}; } VPackBuilder sanitizedBuilder; sanitizedBuilder.openObject(); IResearchViewMeta::Mask mask(true); if (!_meta.json(sanitizedBuilder, nullptr, &mask) || !mergeSliceSkipKeys(builder, sanitizedBuilder.close().slice(), *acceptor)) { return {TRI_ERROR_INTERNAL, std::string("failure to generate definition while generating " "properties jSON for IResearch View in database '") .append(vocbase().name()) .append("'")}; } return {}; } /*static*/ ViewFactory const& IResearchViewCoordinator::factory() { static const ViewFactory factory; return factory; } Result IResearchViewCoordinator::link(IResearchLink const& link) { if (!ClusterMethods::includeHiddenCollectionInLink( link.collection().name())) { return TRI_ERROR_NO_ERROR; } std::function<bool(irs::string_ref key)> const acceptor = [](std::string_view key) -> bool { return key != arangodb::StaticStrings::IndexId && key != arangodb::StaticStrings::IndexType && key != StaticStrings::ViewIdField; }; velocypack::Builder builder; builder.openObject(); // generate user-visible definition, agency will not see links auto res = link.properties(builder, true); if (!res.ok()) { return res; } builder.close(); auto cid = link.collection().id(); velocypack::Builder sanitizedBuilder; sanitizedBuilder.openObject(); // strip internal keys (added in IResearchLink::properties(...)) from // externally visible link definition if (!mergeSliceSkipKeys(sanitizedBuilder, builder.slice(), acceptor)) { return Result( // result TRI_ERROR_INTERNAL, // code std::string("failed to generate externally visible link definition " "while emplacing collection '") + std::to_string(cid.id()) + "' into arangosearch View '" + name() + "'"); } sanitizedBuilder.close(); // '_collections' can be asynchronously read auto lock = irs::make_lock_guard(_mutex); auto [it, emplaced] = _collections.try_emplace(cid, link.collection().name(), std::move(sanitizedBuilder)); UNUSED(it); if (!emplaced) { return {TRI_ERROR_ARANGO_DUPLICATE_IDENTIFIER, "duplicate entry while emplacing collection '" + std::to_string(cid.id()) + "' into arangosearch View '" + name() + "'"}; } return Result(); } Result IResearchViewCoordinator::renameImpl(std::string const& oldName) { return LogicalViewHelperClusterInfo::rename(*this, oldName); } Result IResearchViewCoordinator::unlink(DataSourceId) noexcept { return Result(); // NOOP since no internal store } IResearchViewCoordinator::IResearchViewCoordinator(TRI_vocbase_t& vocbase, velocypack::Slice info) : LogicalView(vocbase, info) { TRI_ASSERT(ServerState::instance()->isCoordinator()); } bool IResearchViewCoordinator::visitCollections( CollectionVisitor const& visitor) const { // '_collections' can be asynchronously modified auto lock = irs::make_shared_lock(_mutex); for (auto& entry : _collections) { if (!visitor(entry.first)) { return false; } } return true; } Result IResearchViewCoordinator::properties(velocypack::Slice slice, bool isUserRequest, bool partialUpdate) { if (!vocbase().server().hasFeature<ClusterFeature>()) { return {TRI_ERROR_INTERNAL, std::string("failure to get storage engine while " "updating arangosearch view '") + name() + "'"}; } auto& engine = vocbase().server().getFeature<ClusterFeature>().clusterInfo(); try { auto links = slice.hasKey(StaticStrings::LinksField) ? slice.get(StaticStrings::LinksField) : velocypack::Slice::emptyObjectSlice(); auto res = IResearchLinkHelper::validateLinks(vocbase(), links); if (!res.ok()) { return res; } // check link auth as per https://github.com/arangodb/backlog/issues/459 ExecContext const& exe = ExecContext::current(); if (!exe.isSuperuser()) { // check existing links for (auto& entry : _collections) { auto collection = engine.getCollection( vocbase().name(), std::to_string(entry.first.id())); if (collection && !exe.canUseCollection(vocbase().name(), collection->name(), auth::Level::RO)) { return Result( TRI_ERROR_FORBIDDEN, std::string("while updating arangosearch definition, error: " "collection '") + collection->name() + "' not authorized for read access"); } } } std::string error; IResearchViewMeta meta; auto const& defaults = partialUpdate ? _meta : IResearchViewMeta::DEFAULT(); if (!meta.init(slice, error, defaults)) { return Result(TRI_ERROR_BAD_PARAMETER, error.empty() ? (std::string("failed to update arangosearch view '") + name() + "' from definition: " + slice.toString()) : (std::string("failed to update arangosearch view '") + name() + "' from definition, error in attribute '" + error + "': " + slice.toString())); } // reset non-updatable values to match current meta ensureImmutableProperties(meta, _meta); // only trigger persisting of properties if they have changed if (_meta != meta) { auto oldMeta = std::move(_meta); _meta = std::move(meta); // update meta for persistence auto result = LogicalViewHelperClusterInfo::properties(*this); _meta = std::move(oldMeta); // restore meta if (!result.ok()) { return result; } } if (links.isEmptyObject() && partialUpdate) { return {}; // nothing more to do } // ........................................................................... // update links if requested (on a best-effort basis) // indexing of collections is done in different threads so no locks can be // held and rollback is not possible as a result it's also possible for // links to be simultaneously modified via a different callflow (e.g. from // collections) // ........................................................................... velocypack::Builder currentLinks; std::unordered_set<DataSourceId> currentCids; { // '_collections' can be asynchronously modified auto lock = irs::make_shared_lock(_mutex); currentLinks.openObject(); for (auto& entry : _collections) { currentCids.emplace(entry.first); currentLinks.add(entry.second.first, entry.second.second.slice()); } currentLinks.close(); } std::unordered_set<DataSourceId> collections; if (partialUpdate) { return IResearchLinkHelper::updateLinks(collections, *this, links, getDefaultVersion(isUserRequest)); } return IResearchLinkHelper::updateLinks(collections, *this, links, getDefaultVersion(isUserRequest), currentCids); } catch (basics::Exception& e) { LOG_TOPIC("714b3", WARN, iresearch::TOPIC) << "caught exception while updating properties for arangosearch view '" << name() << "': " << e.code() << " " << e.what(); return {e.code(), std::string("error updating properties for arangosearch view '") + name() + "'"}; } catch (std::exception const& e) { LOG_TOPIC("86a5c", WARN, iresearch::TOPIC) << "caught exception while updating properties for arangosearch view '" << name() << "': " << e.what(); return {TRI_ERROR_BAD_PARAMETER, std::string("error updating properties for arangosearch view '") + name() + "'"}; } catch (...) { LOG_TOPIC("17b66", WARN, iresearch::TOPIC) << "caught exception while updating properties for arangosearch view '" << name() << "'"; return {TRI_ERROR_BAD_PARAMETER, std::string("error updating properties for arangosearch view '") + name() + "'"}; } } Result IResearchViewCoordinator::dropImpl() { if (!vocbase().server().hasFeature<ClusterFeature>()) { return Result(TRI_ERROR_INTERNAL, std::string("failure to get storage engine while " "dropping arangosearch view '") + name() + "'"); } auto& engine = vocbase().server().getFeature<ClusterFeature>().clusterInfo(); // drop links first { std::unordered_set<DataSourceId> currentCids; visitCollections([&currentCids](DataSourceId cid) -> bool { currentCids.emplace(cid); return true; }); // check link auth as per https://github.com/arangodb/backlog/issues/459 ExecContext const& exe = ExecContext::current(); if (!exe.isSuperuser()) { for (auto& entry : currentCids) { auto collection = engine.getCollection(vocbase().name(), std::to_string(entry.id())); if (collection && !exe.canUseCollection(vocbase().name(), collection->name(), auth::Level::RO)) { return Result(TRI_ERROR_FORBIDDEN); } } } std::unordered_set<DataSourceId> collections; auto res = IResearchLinkHelper::updateLinks( collections, *this, velocypack::Slice::emptyObjectSlice(), LinkVersion::MAX, // we don't care of link version due to removal only // request currentCids); if (!res.ok()) { return {res.errorNumber(), basics::StringUtils::concatT( "failed to remove links while removing arangosearch view '", name(), "': ", res.errorMessage())}; } } return LogicalViewHelperClusterInfo::drop(*this); } } // namespace iresearch } // namespace arangodb
34.962366
82
0.599723
[ "object" ]
f5fb427a1d9b45f0b4a48fbe330277fcf793a88c
7,797
cc
C++
chrome/browser/extensions/extension_special_storage_policy.cc
junmin-zhu/chromium-rivertrail
eb1a57aca71fe68d96e48af8998dcfbe45171ee1
[ "BSD-3-Clause" ]
5
2018-03-10T13:08:42.000Z
2021-07-26T15:02:11.000Z
chrome/browser/extensions/extension_special_storage_policy.cc
quisquous/chromium
b25660e05cddc9d0c3053b3514f07037acc69a10
[ "BSD-3-Clause" ]
1
2015-07-21T08:02:01.000Z
2015-07-21T08:02:01.000Z
chrome/browser/extensions/extension_special_storage_policy.cc
jianglong0156/chromium.src
d496dfeebb0f282468827654c2b3769b3378c087
[ "BSD-3-Clause" ]
6
2016-11-14T10:13:35.000Z
2021-01-23T15:29:53.000Z
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/extensions/extension_special_storage_policy.h" #include "base/bind.h" #include "base/logging.h" #include "base/stl_util.h" #include "base/utf_string_conversions.h" #include "chrome/browser/content_settings/cookie_settings.h" #include "chrome/browser/intents/web_intents_util.h" #include "chrome/common/content_settings.h" #include "chrome/common/content_settings_types.h" #include "chrome/common/extensions/extension.h" #include "chrome/common/url_constants.h" #include "content/public/browser/browser_thread.h" #include "webkit/glue/web_intent_service_data.h" using content::BrowserThread; using extensions::APIPermission; namespace { // Does the specified extension support the passed Web Intent, |action|? bool ExtensionSupportsIntentAction( const extensions::Extension* extension, const std::string& action) { for (std::vector<webkit_glue::WebIntentServiceData>::const_iterator i = extension->intents_services().begin(); i != extension->intents_services().end(); ++i) { if (UTF16ToUTF8(i->action) == action) return true; } return false; } } // namespace ExtensionSpecialStoragePolicy::ExtensionSpecialStoragePolicy( CookieSettings* cookie_settings) : cookie_settings_(cookie_settings) {} ExtensionSpecialStoragePolicy::~ExtensionSpecialStoragePolicy() {} bool ExtensionSpecialStoragePolicy::IsStorageProtected(const GURL& origin) { if (origin.SchemeIs(chrome::kExtensionScheme)) return true; base::AutoLock locker(lock_); return protected_apps_.Contains(origin); } bool ExtensionSpecialStoragePolicy::IsStorageUnlimited(const GURL& origin) { base::AutoLock locker(lock_); return unlimited_extensions_.Contains(origin); } bool ExtensionSpecialStoragePolicy::IsStorageSessionOnly(const GURL& origin) { if (cookie_settings_ == NULL) return false; return cookie_settings_->IsCookieSessionOnly(origin); } bool ExtensionSpecialStoragePolicy::IsInstalledApp(const GURL& origin) { return installed_apps_.Contains(origin); } bool ExtensionSpecialStoragePolicy::HasSessionOnlyOrigins() { if (cookie_settings_ == NULL) return false; if (cookie_settings_->GetDefaultCookieSetting(NULL) == CONTENT_SETTING_SESSION_ONLY) return true; ContentSettingsForOneType entries; cookie_settings_->GetCookieSettings(&entries); for (size_t i = 0; i < entries.size(); ++i) { if (entries[i].setting == CONTENT_SETTING_SESSION_ONLY) return true; } return false; } bool ExtensionSpecialStoragePolicy::IsFileHandler( const std::string& extension_id) { base::AutoLock locker(lock_); return web_intent_extensions_.ContainsExtension(extension_id) || file_handler_extensions_.ContainsExtension(extension_id); } bool ExtensionSpecialStoragePolicy::NeedsProtection( const extensions::Extension* extension) { return extension->is_hosted_app() && !extension->from_bookmark(); } const ExtensionSet* ExtensionSpecialStoragePolicy::ExtensionsProtectingOrigin( const GURL& origin) { base::AutoLock locker(lock_); return protected_apps_.ExtensionsContaining(origin); } void ExtensionSpecialStoragePolicy::GrantRightsForExtension( const extensions::Extension* extension) { DCHECK(extension); const bool supports_intent_view = ExtensionSupportsIntentAction( extension, web_intents::kActionView); if (!NeedsProtection(extension) && !extension->HasAPIPermission( APIPermission::kUnlimitedStorage) && !extension->HasAPIPermission( APIPermission::kFileBrowserHandler) && !supports_intent_view) { return; } { base::AutoLock locker(lock_); if (NeedsProtection(extension)) protected_apps_.Add(extension); // FIXME: Does GrantRightsForExtension imply |extension| is installed? if (extension->is_app()) installed_apps_.Add(extension); if (extension->HasAPIPermission(APIPermission::kUnlimitedStorage)) unlimited_extensions_.Add(extension); if (extension->HasAPIPermission( APIPermission::kFileBrowserHandler)) file_handler_extensions_.Add(extension); if (supports_intent_view) web_intent_extensions_.Add(extension); } NotifyChanged(); } void ExtensionSpecialStoragePolicy::RevokeRightsForExtension( const extensions::Extension* extension) { DCHECK(extension); const bool supports_intent_view = ExtensionSupportsIntentAction( extension, web_intents::kActionView); if (!NeedsProtection(extension) && !extension->HasAPIPermission( APIPermission::kUnlimitedStorage) && !extension->HasAPIPermission( APIPermission::kFileBrowserHandler) && !supports_intent_view) { return; } { base::AutoLock locker(lock_); if (NeedsProtection(extension)) protected_apps_.Remove(extension); if (extension->is_app()) installed_apps_.Remove(extension); if (extension->HasAPIPermission(APIPermission::kUnlimitedStorage)) unlimited_extensions_.Remove(extension); if (extension->HasAPIPermission(APIPermission::kFileBrowserHandler)) file_handler_extensions_.Remove(extension); if (supports_intent_view) web_intent_extensions_.Remove(extension); } NotifyChanged(); } void ExtensionSpecialStoragePolicy::RevokeRightsForAllExtensions() { { base::AutoLock locker(lock_); protected_apps_.Clear(); installed_apps_.Clear(); unlimited_extensions_.Clear(); file_handler_extensions_.Clear(); web_intent_extensions_.Clear(); } NotifyChanged(); } void ExtensionSpecialStoragePolicy::NotifyChanged() { if (!BrowserThread::CurrentlyOn(BrowserThread::IO)) { BrowserThread::PostTask(BrowserThread::IO, FROM_HERE, base::Bind(&ExtensionSpecialStoragePolicy::NotifyChanged, this)); return; } SpecialStoragePolicy::NotifyObservers(); } //----------------------------------------------------------------------------- // SpecialCollection helper class //----------------------------------------------------------------------------- ExtensionSpecialStoragePolicy::SpecialCollection::SpecialCollection() {} ExtensionSpecialStoragePolicy::SpecialCollection::~SpecialCollection() { STLDeleteValues(&cached_results_); } bool ExtensionSpecialStoragePolicy::SpecialCollection::Contains( const GURL& origin) { return !ExtensionsContaining(origin)->is_empty(); } const ExtensionSet* ExtensionSpecialStoragePolicy::SpecialCollection::ExtensionsContaining( const GURL& origin) { CachedResults::const_iterator found = cached_results_.find(origin); if (found != cached_results_.end()) return found->second; ExtensionSet* result = new ExtensionSet(); for (ExtensionSet::const_iterator iter = extensions_.begin(); iter != extensions_.end(); ++iter) { if ((*iter)->OverlapsWithOrigin(origin)) result->Insert(*iter); } cached_results_[origin] = result; return result; } bool ExtensionSpecialStoragePolicy::SpecialCollection::ContainsExtension( const std::string& extension_id) { return extensions_.Contains(extension_id); } void ExtensionSpecialStoragePolicy::SpecialCollection::Add( const extensions::Extension* extension) { ClearCache(); extensions_.Insert(extension); } void ExtensionSpecialStoragePolicy::SpecialCollection::Remove( const extensions::Extension* extension) { ClearCache(); extensions_.Remove(extension->id()); } void ExtensionSpecialStoragePolicy::SpecialCollection::Clear() { ClearCache(); extensions_.Clear(); } void ExtensionSpecialStoragePolicy::SpecialCollection::ClearCache() { STLDeleteValues(&cached_results_); cached_results_.clear(); }
32.4875
79
0.739643
[ "vector" ]
f5fd6f9dd4332d77f31d1705d5055923c5ae214e
3,084
hpp
C++
include/Tools/Display/Statistics/Statistics.hpp
FredrikBlomgren/aff3ct
fa616bd923b2dcf03a4cf119cceca51cf810d483
[ "MIT" ]
315
2016-06-21T13:32:14.000Z
2022-03-28T09:33:59.000Z
include/Tools/Display/Statistics/Statistics.hpp
a-panella/aff3ct
61509eb756ae3725b8a67c2d26a5af5ba95186fb
[ "MIT" ]
153
2017-01-17T03:51:06.000Z
2022-03-24T15:39:26.000Z
include/Tools/Display/Statistics/Statistics.hpp
a-panella/aff3ct
61509eb756ae3725b8a67c2d26a5af5ba95186fb
[ "MIT" ]
119
2017-01-04T14:31:58.000Z
2022-03-21T08:34:16.000Z
/*! * \file * \brief Class tools::Statistics. */ #ifndef STATISTICS_HPP_ #define STATISTICS_HPP_ #include <iostream> #include <cstdint> #include <cstddef> #include <vector> #include <chrono> #include <string> #include "Module/Module.hpp" #include "Module/Task.hpp" namespace aff3ct { namespace tools { class Statistics { protected: Statistics() = default; public: virtual ~Statistics() = default; template <class MODULE_OR_TASK> static void show(std::vector<MODULE_OR_TASK*> modules_or_tasks, const bool ordered = false, std::ostream &stream = std::cout); template <class MODULE_OR_TASK> static void show(std::vector<std::vector<MODULE_OR_TASK*>> modules_or_tasks, const bool ordered = false, std::ostream &stream = std::cout); private: template <class MODULE = const module::Module> static void show_modules(std::vector<MODULE*> modules, const bool ordered = false, std::ostream &stream = std::cout); template <class TASK = const module::Task> static void show_tasks(std::vector<TASK*> tasks, const bool ordered = false, std::ostream &stream = std::cout); template <class MODULE = const module::Module> static void show_modules(std::vector<std::vector<MODULE*>> modules, const bool ordered = false, std::ostream &stream = std::cout); template <class TASK = const module::Task> static void show_tasks(std::vector<std::vector<TASK*>> tasks, const bool ordered = false, std::ostream &stream = std::cout); static void separation1(std::ostream &stream = std::cout); static void separation2(std::ostream &stream = std::cout); static void show_header(std::ostream &stream = std::cout); static void show_task(const float total_sec, const std::string& module_sname, const std::string& task_name, const size_t task_n_elmts, const uint32_t task_n_calls, const std::chrono::nanoseconds task_tot_duration, const std::chrono::nanoseconds task_min_duration, const std::chrono::nanoseconds task_max_duration, std::ostream &stream = std::cout); static void show_timer(const float total_sec, const uint32_t task_n_calls, const size_t timer_n_elmts, const std::string& timer_name, const uint32_t timer_n_calls, const std::chrono::nanoseconds timer_tot_duration, const std::chrono::nanoseconds timer_min_duration, const std::chrono::nanoseconds timer_max_duration, std::ostream &stream = std::cout); }; using Stats = Statistics; } } #endif /* STATISTICS_HPP_ */
37.156627
105
0.583333
[ "vector" ]