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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
effbb78d1b482ac51f09564be2d44b4f43186217 | 11,359 | cc | C++ | src/E2AP-c/subscription/subscription_handler.cc | o-ran-sc/ric-app-admin | 0a168f272a81ac4c3afe42e014f8032f2a159d97 | [
"Apache-2.0"
] | null | null | null | src/E2AP-c/subscription/subscription_handler.cc | o-ran-sc/ric-app-admin | 0a168f272a81ac4c3afe42e014f8032f2a159d97 | [
"Apache-2.0"
] | null | null | null | src/E2AP-c/subscription/subscription_handler.cc | o-ran-sc/ric-app-admin | 0a168f272a81ac4c3afe42e014f8032f2a159d97 | [
"Apache-2.0"
] | null | null | null | /*
==================================================================================
Copyright (c) 2018-2019 AT&T Intellectual Property.
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.
==================================================================================
*/
/* Author : Ashwin Sridharan
Date : Feb 2019
*/
#include <subscription_handler.hpp>
#include <errno.h>
subscription_handler::subscription_handler(unsigned int timeout_seconds, unsigned int num_tries):_time_out(std::chrono::seconds(timeout_seconds)), _num_retries(num_tries){
init();
};
void subscription_handler::init(void){
_data_lock = std::make_unique<std::mutex>();
_cv = std::make_unique<std::condition_variable>();
}
void subscription_handler::clear(void){
{
std::lock_guard<std::mutex> lock(*(_data_lock).get());
requests_table.clear();
subscription_responses.clear();
}
};
size_t subscription_handler::num_pending(void) const {
return requests_table.size();
}
size_t subscription_handler::num_complete(void) const {
return subscription_responses.size();
}
void subscription_handler::set_timeout(unsigned int timeout_seconds){
_time_out = std::chrono::seconds(timeout_seconds);
}
void subscription_handler::set_num_retries(unsigned int num_tries){
_num_retries = num_tries;
};
bool subscription_handler::add_request_entry(subscription_identifier id, int status){
// add entry in hash table if it does not exist
auto search = requests_table.find(id);
if(search != requests_table.end()){
return false;
}
requests_table[id] = status;
return true;
};
bool subscription_handler::set_request_status(subscription_identifier id, int status){
// change status of a request only if it exists.
auto search = requests_table.find(id);
if(search != requests_table.end()){
requests_table[id] = status;
return true;
}
return false;
};
bool subscription_handler::delete_request_entry(subscription_identifier id){
auto search = requests_table.find(id);
if (search != requests_table.end()){
requests_table.erase(search);
return true;
}
return false;
};
bool subscription_handler::add_subscription_entry(subscription_identifier id, subscription_response_helper &he){
auto search = subscription_responses.find(id);
if (search == subscription_responses.end()){
subscription_responses[id] = he;
return true;
}
return false;
}
bool subscription_handler::delete_subscription_entry(subscription_identifier id){
auto search = subscription_responses.find(id);
if(search == subscription_responses.end()){
return false;
}
else{
subscription_responses.erase(search);
return true;
}
}
subscription_response_helper * const subscription_handler::get_subscription(subscription_identifier id){
auto search = subscription_responses.find(id);
if(search == subscription_responses.end()){
return NULL;
}
else{
return &(subscription_responses[id]);
}
};
// Handles responses from RMR
void subscription_handler::Response(int message_type, unsigned char *payload, int payload_length, const char * node_id){
bool res;
std::string node(node_id);
int type;
int procedureCode;
bool valid_response =false;
E2N_E2AP_PDU_t * e2ap_recv;
asn_dec_rval_t retval;
subscription_response sub_resp;
subscription_delete_response sub_del_resp;
subscription_response_helper he_response;
e2ap_recv = 0;
retval = asn_decode(0, ATS_ALIGNED_BASIC_PER, &asn_DEF_E2N_E2AP_PDU, (void**)&(e2ap_recv), payload, payload_length);
if(retval.code != RC_OK){
mdclog_write(MDCLOG_ERR, "%s, %d: Error decoding E2AP PDU of RMR type %d. Bytes decoded = %lu out of %d\n", __FILE__, __LINE__, message_type, retval.consumed, payload_length);
ASN_STRUCT_FREE(asn_DEF_E2N_E2AP_PDU, e2ap_recv);
return ;
}
type = e2ap_recv->present;
mdclog_write(MDCLOG_INFO, "Received RMR message of type = %d", type);
if(type == E2N_E2AP_PDU_PR_successfulOutcome){
procedureCode = e2ap_recv->choice.successfulOutcome->procedureCode;
mdclog_write(MDCLOG_INFO, "Received E2N_E2AP PDU successful outcome message with procedureCode = %d", procedureCode);
if( procedureCode == E2N_ProcedureCode_id_ricSubscription){
// subscription response
// decode the message
sub_resp.get_fields(e2ap_recv->choice.successfulOutcome, he_response);
{
std::lock_guard<std::mutex> lock(*(_data_lock.get()));
// get the id
subscription_identifier id = std::make_tuple (node, he_response.get_request_id());
// get status of id
int req_status = get_request_status(id);
if (req_status == request_pending ){
res = add_subscription_entry(id, he_response);
if(res)
set_request_status(id, request_success);
else{
set_request_status(id, request_duplicate);
mdclog_write(MDCLOG_ERR, "Error:: %s, %d: Request %s, %d seems to be a duplicate. Subscription already present in subscription table\n", __FILE__, __LINE__, std::get<0>(id).c_str(), std::get<1>(id));
}
valid_response = true;
}
else if (req_status > 0){
// we don't change status of response since it was not in pending
// we simply fail
mdclog_write(MDCLOG_ERR, "Error:: %s, %d: Request %s,%d is not in request_pending state, is in State = %d\n", __FILE__, __LINE__, std::get<0>(id).c_str(), std::get<1>(id), req_status);
}
else{
mdclog_write(MDCLOG_ERR, "%s, %d: Could not find id %s, %d in request queue for subscription", __FILE__, __LINE__, std::get<0>(id).c_str(), std::get<1>(id));
}
}
}
else if( procedureCode == E2N_ProcedureCode_id_ricSubscriptionDelete){
res = sub_del_resp.get_fields(e2ap_recv->choice.successfulOutcome, he_response);
{
std::lock_guard<std::mutex> lock(*(_data_lock.get()));
// get the id
subscription_identifier id = std::make_tuple (node, he_response.get_request_id());
int req_status = get_request_status(id);
if (req_status == delete_request_pending ){
// Remove the subscription from the table
res = delete_subscription_entry(id);
if(res){
set_request_status(id, delete_request_success);
valid_response = true;
}
else{
set_request_status(id, delete_request_failed);
mdclog_write(MDCLOG_ERR, "%s, %d: Error deleting subscription entry for %s, %d", __FILE__, __LINE__, std::get<0>(id).c_str(), std::get<1>(id));
valid_response = true;
}
}
else if (req_status > 0){
// we don't change status since it was not in pending
// we simply fail
mdclog_write(MDCLOG_ERR, "Error:: %s, %d: Request %s, %d for deletion is not in delete_pending state, is in State = %d\n", __FILE__, __LINE__, id, std::get<0>(id).c_str(), std::get<1>(id));
}
else{
mdclog_write(MDCLOG_ERR, "%s, %d: Could not find request id %s, %d in request queue for deletion ", __FILE__, __LINE__, std::get<0>(id).c_str(), std::get<1>(id));
}
}
}
else{
mdclog_write(MDCLOG_ERR, "%s, %d: Subscription Handler Response received E2AP PDU success response with an non-subscription response related type %d", __FILE__, __LINE__, procedureCode);
}
}
else if(type == E2N_E2AP_PDU_PR_unsuccessfulOutcome){
procedureCode = e2ap_recv->choice.unsuccessfulOutcome->procedureCode;
mdclog_write(MDCLOG_INFO, "Received E2AP PDU unsuccessful outcome message with procedureCode = %d", procedureCode);
if(procedureCode == E2N_ProcedureCode_id_ricSubscription){
sub_resp.get_fields(e2ap_recv->choice.unsuccessfulOutcome, he_response);
{
std::lock_guard<std::mutex> lock(*(_data_lock.get()));
// get the id
subscription_identifier id = std::make_tuple (node, he_response.get_request_id());
int req_status = get_request_status(id);
if(req_status == request_pending){
set_request_status(id, request_failed);
valid_response = true;
mdclog_write(MDCLOG_ERR, "Subscription request %d failed", id);
}
else if (req_status > 0){
// we don't changet status since it was not in pending
// we simply fail
mdclog_write(MDCLOG_ERR, "Error:: %s, %d: Request %s, %d is not in request_pending state, is in State = %d\n", __FILE__, __LINE__, std::get<0>(id).c_str(), std::get<1>(id), req_status);
}
else{
mdclog_write(MDCLOG_ERR, "%s, %d: Could not find id %s, %d in request queue for subscription ", __FILE__, __LINE__, std::get<0>(id).c_str(), std::get<1>(id));
}
}
}
else if(procedureCode == E2N_ProcedureCode_id_ricSubscriptionDelete){
res = sub_del_resp.get_fields(e2ap_recv->choice.unsuccessfulOutcome, he_response);
{
std::lock_guard<std::mutex> lock(*(_data_lock.get()));
// get the id
subscription_identifier id = std::make_tuple (node, he_response.get_request_id());
int req_status = get_request_status(id);
if(req_status == delete_request_pending){
set_request_status(id, delete_request_failed);
mdclog_write(MDCLOG_INFO, "Subscription delete request %s,%d failed", std::get<0>(id).c_str(), std::get<1>(id));
valid_response = true;
}
else if (req_status > 0){
mdclog_write(MDCLOG_ERR, "Error:: %s, %d: Request %s,%d for deletion is not in delete_pending state, is in State = %d\n", __FILE__, __LINE__, std::get<0>(id).c_str(), std::get<1>(id), req_status);
}
else{
mdclog_write(MDCLOG_ERR, "%s, %d: Could not find id %s,%d in request queue for deletion ", __FILE__, __LINE__, std::get<0>(id).c_str(), std::get<1>(id));
}
}
}
else{
mdclog_write(MDCLOG_ERR, "%s, %d: Susbcription Handler Response received E2AP PDU failure response with a non-subscription response related type %d", __FILE__, __LINE__, procedureCode);
}
}
else{
mdclog_write(MDCLOG_ERR, "%s, %d: Susbcription Handler Response received E2AP PDU with non response type %d", __FILE__, __LINE__, type);
}
ASN_STRUCT_FREE(asn_DEF_E2N_E2AP_PDU, e2ap_recv);
// wake up all waiting users ...
if(valid_response){
_cv.get()->notify_all();
}
}
int const subscription_handler::get_request_status(subscription_identifier id){
auto search = requests_table.find(id);
if (search == requests_table.end()){
return -1;
}
return search->second;
}
bool subscription_handler::is_subscription_entry(subscription_identifier id){
auto search = subscription_responses.find(id);
if (search != subscription_responses.end())
return true;
else
return false;
}
bool subscription_handler::is_request_entry(subscription_identifier id){
auto search = requests_table.find(id);
if (search != requests_table.end())
return true;
else
return false;
}
void subscription_handler::get_subscription_keys(std::vector<subscription_identifier> & key_list){
for(auto & e: subscription_responses){
key_list.push_back(e.first);
}
}
| 31.640669 | 204 | 0.697421 | [
"vector"
] |
560d98a09ccdd795f109c15cb354c003ffdad83d | 7,785 | cpp | C++ | bazaar/Map/MapView.cpp | dreamsxin/ultimatepp | 41d295d999f9ff1339b34b43c99ce279b9b3991c | [
"BSD-2-Clause"
] | 2 | 2016-04-07T07:54:26.000Z | 2020-04-14T12:37:34.000Z | bazaar/Map/MapView.cpp | dreamsxin/ultimatepp | 41d295d999f9ff1339b34b43c99ce279b9b3991c | [
"BSD-2-Clause"
] | null | null | null | bazaar/Map/MapView.cpp | dreamsxin/ultimatepp | 41d295d999f9ff1339b34b43c99ce279b9b3991c | [
"BSD-2-Clause"
] | null | null | null | #include "MapView.h"
#define IMAGECLASS MapViewImg
#define IMAGEFILE <Map/MapView.iml>
#include <Draw/iml_source.h>
#define SetButtonStyle(but,im1,im2) \
static Button::Style but##_style = Button::StyleNormal(); \
but##_style.look[0] = MapViewImg::im1(); \
but##_style.look[1] = MapViewImg::im1(); \
but##_style.look[2] = MapViewImg::im2(); \
but##_style.look[3] = MapViewImg::im2(); \
but.SetStyle(but##_style);
MapView::MapView()
{
CtrlLayout(*this, t_("MapCtrl View"));
MinimizeBox().MinimizeBox().Sizeable();
// init values
_mousePos = Point(0, 0);
_drag = false;
_move = false;
_level = -1;
HideZoomSlider();
HideSearch();
// init layout
ZoomInBtn .NoWantFocus();
ZoomOutBtn .NoWantFocus();
MoveUpBtn .NoWantFocus();
MoveDownBtn .NoWantFocus();
MoveLeftBtn .NoWantFocus();
MoveRightBtn.NoWantFocus();
LevelUpBtn .NoWantFocus();
LevelDownBtn.NoWantFocus();
MoveUpBtn .WhenPush = MoveUpBtn .WhenRepeat = THISBACK(OnMoveUp);
MoveDownBtn .WhenPush = MoveDownBtn .WhenRepeat = THISBACK(OnMoveDown);
MoveLeftBtn .WhenPush = MoveLeftBtn .WhenRepeat = THISBACK(OnMoveLeft);
MoveRightBtn.WhenPush = MoveRightBtn.WhenRepeat = THISBACK(OnMoveRight);
ZoomInBtn .WhenPush = ZoomInBtn .WhenRepeat = THISBACK(OnZoomIn);
ZoomOutBtn.WhenPush = ZoomOutBtn.WhenRepeat = THISBACK(OnZoomOut);
ZoomSlider.WhenAction = THISBACK(OnZoomSlide);
LevelUpBtn .WhenPush = THISBACK(OnLevelUp);
LevelDownBtn.WhenPush = THISBACK(OnLevelDown);
Search.WhenAction = THISBACK(OnSearch);
Search.WhenEnter = THISBACK(OnSearch);
ClearSearchBtn <<= THISBACK(OnSearchClear);
SetButtonStyle(MoveUpBtn, map_button_up_1, map_button_up_2);
SetButtonStyle(MoveDownBtn, map_button_down_1, map_button_down_2);
SetButtonStyle(MoveLeftBtn, map_button_left_1, map_button_left_2);
SetButtonStyle(MoveRightBtn, map_button_right_1, map_button_right_2);
SetButtonStyle(ZoomInBtn, map_button_zoom_in_1, map_button_zoom_in_2);
SetButtonStyle(ZoomOutBtn, map_button_zoom_out_1, map_button_zoom_out_2);
SetButtonStyle(LevelUpBtn, map_button_zoom_in_1, map_button_zoom_in_2);
SetButtonStyle(LevelDownBtn, map_button_zoom_out_1, map_button_zoom_out_2);
}
void MapView::OnLevelUp()
{
_level++;
SetCurrentLevel(_level);
UpdateButtons();
}
void MapView::OnLevelDown()
{
_level--;
SetCurrentLevel(_level);
UpdateButtons();
}
void MapView::OnMoveUp()
{
if (GetCurrentLevel())
GetCurrentLevel()->MoveBy(Point(0, -100));
}
void MapView::OnMoveDown()
{
if (GetCurrentLevel())
GetCurrentLevel()->MoveBy(Point(0, 100));
}
void MapView::OnMoveLeft()
{
if (GetCurrentLevel())
GetCurrentLevel()->MoveBy(Point(-100, 0));
}
void MapView::OnMoveRight()
{
if (GetCurrentLevel())
GetCurrentLevel()->MoveBy(Point( 100, 0));
}
void MapView::OnZoomIn()
{
MapLevel* level = GetCurrentLevel();
if (!level) return;
level->ZoomIn();
UpdateButtons();
ZoomSlider <<= level->GetCurrentZoom();
}
void MapView::OnZoomOut()
{
MapLevel* level = GetCurrentLevel();
if (!level) return;
level->ZoomOut();
UpdateButtons();
ZoomSlider <<= level->GetCurrentZoom();
}
void MapView::OnZoomSlide()
{
MapLevel* level = GetCurrentLevel();
if (!level) return;
int zoom = ~ZoomSlider;
level->ZoomTo(zoom);
UpdateButtons();
}
void MapView::UpdateButtons()
{
MapLevel* level = GetCurrentLevel();
if (!level)
{
ZoomInBtn .Disable();
ZoomOutBtn .Disable();
LevelUpBtn .Disable();
LevelDownBtn.Disable();
MoveUpBtn .Disable();
MoveDownBtn .Disable();
MoveLeftBtn .Disable();
MoveRightBtn.Disable();
return;
}
int total = level->GetZoomCount();
int zoom = level->GetCurrentZoom();
ZoomInBtn .Enable(zoom >= 0 && zoom < total - 1);
ZoomOutBtn.Enable(zoom >= 1 && zoom < total);
LevelUpBtn .Enable(_level < _levels.GetCount() - 1);
LevelDownBtn.Enable(_level > 0);
}
void MapView::ShowZoomSlider(bool flag)
{
ZoomSlider.Show(flag);
}
void MapView::ShowNavButtons(bool flag)
{
MoveUpBtn .Show(flag);
MoveDownBtn .Show(flag);
MoveLeftBtn .Show(flag);
MoveRightBtn.Show(flag);
}
void MapView::ShowLevelsCtrl(bool flag)
{
LevelName .Show(flag);
LevelUpBtn .Show(flag);
LevelDownBtn.Show(flag);
}
void MapView::ShowSearch(bool flag)
{
Search .Show(flag);
ClearSearchBtn.Show(flag);
}
void MapView::SetCurrentLevel(int level)
{
MapLevel* p = GetLevel(level);
if (!p)
{
_level = -1;
return;
}
_level = level;
for (int i = 0; i < _levels.GetCount(); ++i)
_levels[i].Hide();
p->Show();
ZoomSlider.Range(p->GetZoomCount() - 1).Step(1);
ZoomSlider <<= p->GetCurrentZoom();
LevelName.SetLabel(p->GetLevelName());
UpdateButtons();
}
bool MapView::LoadMap(Map& map, bool editMode)
{
for (int i = 0; i < _levels.GetCount(); ++i)
RemoveChild(&_levels[i]);
_levels.Clear();
for (int i = 0; i < map.GetLevels().GetCount(); ++i)
{
MapLevel& level = _levels.Add();
AddChildBefore(&level.SizePos(), GetFirstChild());
level.IgnoreMouse();
level.Hide();
String fp = AppendFileName(
AppendFileName( GetFileDirectory(GetExeFilePath()), "Mipmaps"),
NFormat("%s-%d.xml", map.GetName(), i + 1)
);
level.SetLevelName(map.GetLevels()[i].GetName());
level.SetLevelDesc(map.GetLevels()[i].GetDesc());
level.LoadMap(fp);
level.EditMode(editMode);
for (int j = 0; j < map.GetLevels()[i].GetLayers().GetCount(); ++j)
{
Ptr<IMapRender> layer = level.AddItem<IMapRender>();
/* Array<Room>& rooms = map.GetLevels()[i].GetLayers()[j].GetRooms();
for (int r = 0; r < rooms.GetCount(); ++r)
{
Ptr<PolygonItem> room = layer->AddItem<PolygonItem>();
for (int v = 0; v < rooms[r].GetVertices().GetCount(); ++v)
room->AddVertice(rooms[r].GetVertices()[v]);
room->SetRoom(rooms[r]);
if (editMode)
room->StateOn(STATE_EDIT);
}*/
for (int rx = 0; rx < 10; ++rx)
for (int ry = 0; ry < 10; ++ry)
{
Ptr<PolygonItem> room = layer->AddItem<PolygonItem>();
room->AddVertice( 0 * rx, 0 * ry);
room->AddVertice(40 * rx, 0 * ry);
room->AddVertice(40 * rx, 40 * ry);
room->AddVertice( 0 * rx, 40 * ry);
room->SetRoom(rooms[r]);
if (editMode)
room->StateOn(STATE_EDIT);
}
}
}
SetCurrentLevel(_levels.GetCount() ? 0 : -1);
return true;
}
bool MapView::LoadMap(const char* fp, bool editMode)
{
Map map;
if (!LoadFromXMLFile(map, fp))
return false;
return LoadMap(map, editMode);
}
bool MapView::UpdateLevel(Level& level, int pos, bool editMode)
{
if (pos < 0 || pos >= _levels.GetCount())
return false;
MapLevel& mapLevel = _levels[pos];
mapLevel.EditMode(editMode);
if (mapLevel.GetItems().GetCount() != level.GetLayers().GetCount())
mapLevel.Clear();
Vector<Ptr<IMapItem> >& mapLayers = mapLevel.GetItems();
for (int j = 0; j < level.GetLayers().GetCount(); ++j)
{
IMapRender* mapLayer =
(j < mapLayers.GetCount())
? dynamic_cast<IMapRender*>(~mapLayers[j])
: ~mapLevel.AddItem<IMapRender>();
Vector<Ptr<IMapItem> >& mapRooms = mapLayer->GetItems();
Array<Room>& rooms = level.GetLayers()[j].GetRooms();
mapLayer->Clear();
for (int r = 0; r < rooms.GetCount(); ++r)
{
Ptr<PolygonItem> mapRoom =
mapLayer->AddItem<PolygonItem>();
mapRoom->GetVertices().Clear();
for (int v = 0; v < rooms[r].GetVertices().GetCount(); ++v)
mapRoom->AddVertice(rooms[r].GetVertices()[v]);
mapRoom->SetRoom(rooms[r]);
if (editMode)
mapRoom->StateOn(STATE_EDIT);
}
}
Refresh();
}
| 24.55836 | 77 | 0.649326 | [
"vector"
] |
560f7ec0362fb7b8e89695714592f8fba933759b | 1,588 | hpp | C++ | src/foreign_if/server/exrpc_pca.hpp | wmeddie/frovedis | c134e5e64114799cc7c265c72525ff98d06b49c1 | [
"BSD-2-Clause"
] | null | null | null | src/foreign_if/server/exrpc_pca.hpp | wmeddie/frovedis | c134e5e64114799cc7c265c72525ff98d06b49c1 | [
"BSD-2-Clause"
] | null | null | null | src/foreign_if/server/exrpc_pca.hpp | wmeddie/frovedis | c134e5e64114799cc7c265c72525ff98d06b49c1 | [
"BSD-2-Clause"
] | null | null | null | #ifndef _EXRPC_PCA_HPP_
#define _EXRPC_PCA_HPP_
#include "frovedis.hpp"
#include "frovedis/matrix/pca.hpp"
#include "../exrpc/exrpc_expose.hpp"
#include "pca_result.hpp"
using namespace frovedis;
template <class MATRIX, class T>
pca_result frovedis_pca(exrpc_ptr_t& data_ptr, int& k,
bool& isMovableInput=false) {
MATRIX& mat = *reinterpret_cast<MATRIX*>(data_ptr);
auto pca_directions = new colmajor_matrix<T>();
auto explained_variance_ratio = new std::vector<T>();
colmajor_matrix<T> pca_scores;
std::vector<T> eigen_values, singular_values;
pca(mat,*pca_directions,pca_scores,
eigen_values,*explained_variance_ratio,
singular_values,k);
#ifdef _EXRPC_DEBUG_
std::cout << "components: \n"; pca_directions->debug_print();
std::cout << "ratio: \n"; pca_scores.debug_print();
std::cout << "eigen values: \n";
for(auto e: eigen_values) std::cout << e << " "; std::cout << std::endl;
std::cout << "variance ratio: \n";
for(auto e: *explained_variance_ratio) std::cout << e << " "; std::cout << std::endl;
std::cout << "singular values: \n";
for(auto e: singular_values) std::cout << e << " "; std::cout << std::endl;
#endif
// if input is movable, destroying Frovedis side data after computation is done.
if (isMovableInput) mat.clear();
auto mptr = reinterpret_cast<exrpc_ptr_t>(pca_directions);
auto vptr = reinterpret_cast<exrpc_ptr_t>(explained_variance_ratio);
auto nrows = pca_directions->num_row;
auto ncols = pca_directions->num_col;
return pca_result(mptr,nrows,ncols,vptr,k);
}
#endif
| 37.809524 | 87 | 0.698992 | [
"vector"
] |
56115fa1bb596dc35d7938ce26eb20c37a204b1e | 6,057 | cpp | C++ | src/utils.cpp | mozman/ezdxf.cpp | 09295f7dafe2a76253807fccd92560fd45eb97a5 | [
"MIT"
] | 2 | 2021-02-10T08:14:59.000Z | 2021-12-09T08:55:01.000Z | src/utils.cpp | mozman/ezdxf.cpp | 09295f7dafe2a76253807fccd92560fd45eb97a5 | [
"MIT"
] | null | null | null | src/utils.cpp | mozman/ezdxf.cpp | 09295f7dafe2a76253807fccd92560fd45eb97a5 | [
"MIT"
] | 1 | 2021-02-10T08:25:20.000Z | 2021-02-10T08:25:20.000Z | // Copyright (c) 2020, Manfred Moitzi
// License: MIT License
//
#include "ezdxf/utils.hpp"
#include "ezdxf/tag/tag.hpp"
#include <stdexcept>
using namespace ezdxf::tag;
namespace ezdxf::utils {
// Source: https://stackoverflow.com/questions/216823/whats-the-best-way-to-trim-stdstring
void ltrim(std::string &s) {
// trim from start (in place)
s.erase(s.begin(),
std::find_if(s.begin(), s.end(), [](unsigned char ch) {
return !std::isspace(ch);
}));
}
void rtrim(std::string &s) {
// trim from end (in place)
s.erase(std::find_if(s.rbegin(), s.rend(), [](unsigned char ch) {
return !std::isspace(ch);
}).base(), s.end());
}
void trim(std::string &s) {
// trim from both ends (in place)
ltrim(s);
rtrim(s);
}
void rtrim_endl(std::string &s) {
// trim <CR><LF> from end (in place)
s.erase(std::find_if(s.rbegin(), s.rend(), [](unsigned char ch) {
return ch != 10 && ch != 13;
}).base(), s.end());
}
std::optional<Real> safe_str_to_real(const String &s) {
try {
return stod(s);
}
catch (...) {
return {};
}
}
std::optional<int64_t> safe_str_to_int64(const String &s) {
try {
return stoll(s);
}
catch (...) {
return {};
}
}
int safe_group_code(const String &s) {
// Returns kError for invalid group codes.
// valid group codes are in the range [0 .. 1071]
try {
auto code = stoi(s);
return is_valid_group_code(code) ? code : GroupCode::kError;
}
catch (...) {
return GroupCode::kError;
}
}
inline static unsigned char _nibble_to_char(const unsigned char nibble) {
// Convert a nibble (0-15) into a char '0'-'9', 'A'-'F'
return nibble + (nibble < 10 ? 0x30 : 0x37); // '0' : 'A' - 10
}
String hexlify(const Bytes &data) {
// Convert Binary data into a continuous hex string
// e.g. {0xfe, 0xfe, ...} to "FEFE..."
//
// Returns uppercase hex chars.
auto buffer = String();
buffer.reserve(data.size() * 2);
for (const unsigned char byte: data) {
buffer.push_back(_nibble_to_char(byte >> 4));
buffer.push_back(_nibble_to_char(byte & 0x0f));
}
return buffer;
}
inline static char _char_to_nibble(const char c) {
// Convert an ascii hex char into a number e.g. 'A' -> 10.
// Valid chars '0'-'9', 'A'-'F', 'a'-'f'
//
// Returns -1 for invalid chars.
if (c >= '0' && c <= '9')
return c - 0x30;
if (c >= 'A' && c <= 'F')
return c - 0x37;
if (c >= 'a' && c <= 'f')
return c - 0x57;
return -1; // error
}
std::optional<Bytes> unhexlify(String s) {
// Convert a continuous hex string into binary data
// e.g. "FEFE..." to {0xfe, 0xfe, ...}.
//
// If argument `s` contains an uneven count of chars, the last char is
// ignored!
trim(s); // trim white space on both sides inplace
Bytes bytes{};
bytes.reserve(s.size() >> 1);
bool high_nibble = true;
unsigned char byte;
signed char nibble;
for (const char c : s) {
nibble = _char_to_nibble(c);
if (nibble < 0) return {}; // string contains invalid chars
if (high_nibble) {
byte = nibble << 4;
} else {
bytes.push_back(byte | nibble);
}
high_nibble = !high_nibble;
}
return bytes;
}
Bytes concatenate_bytes(const std::vector<Bytes> &data) {
Bytes merged = Bytes{};
if (!data.empty()) {
std::size_t sum = 0;
for (const auto &bytes : data) {
sum += bytes.size();
}
merged.reserve(sum);
for (const auto &bytes : data) {
merged.insert(merged.end(), bytes.begin(), bytes.end());
}
}
return merged;
}
String dxf_version_to_str(Version v) {
switch (v) {
case Version::R9:
return "AC1004";
case Version::R10:
return "AC1006";
case Version::R12:
return "AC1009";
case Version::R13:
return "AC1012";
case Version::R14:
return "AC1014";
case Version::R2000:
return "AC1015";
case Version::R2004:
return "AC1018";
case Version::R2007:
return "AC1021";
case Version::R2010:
return "AC1024";
case Version::R2013:
return "AC1027";
case Version::R2018:
return "AC1032";
default:
return "AC1009";
}
}
Version str_to_dxf_version(const String s) { // NOLINT(performance-unnecessary-value-param)
if (s == "AC1004") return Version::R9;
if (s == "AC1006") return Version::R10;
if (s == "AC1009") return Version::R12;
if (s == "AC1012") return Version::R13;
if (s == "AC1014") return Version::R14;
if (s == "AC1015") return Version::R2000;
if (s == "AC1018") return Version::R2004;
if (s == "AC1021") return Version::R2007;
if (s == "AC1024") return Version::R2010;
if (s == "AC1027") return Version::R2013;
if (s == "AC1032") return Version::R2018;
return Version::R12; // Default
}
const SimpleSet<Version> DXFExportVersions{
Version::R12,
Version::R2000,
Version::R2004,
Version::R2007,
Version::R2010,
Version::R2013,
Version::R2018,
};
}
| 29.837438 | 95 | 0.489681 | [
"vector"
] |
5618e12186b0b6a95cdb8ce4e548c34a42a87611 | 1,349 | cpp | C++ | third_party/WebKit/Source/platform/geometry/FloatQuadTest.cpp | metux/chromium-deb | 3c08e9b89a1b6f95f103a61ff4f528dbcd57fc42 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | third_party/WebKit/Source/platform/geometry/FloatQuadTest.cpp | metux/chromium-deb | 3c08e9b89a1b6f95f103a61ff4f528dbcd57fc42 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | third_party/WebKit/Source/platform/geometry/FloatQuadTest.cpp | metux/chromium-deb | 3c08e9b89a1b6f95f103a61ff4f528dbcd57fc42 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | // Copyright 2016 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 "platform/geometry/FloatQuad.h"
#include <limits>
#include "platform/wtf/text/WTFString.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace blink {
TEST(FloatQuadTest, ToString) {
FloatQuad quad(FloatPoint(2, 3), FloatPoint(5, 7), FloatPoint(11, 13),
FloatPoint(17, 19));
EXPECT_EQ("2,3; 5,7; 11,13; 17,19", quad.ToString());
}
TEST(FloatQuadTest, BoundingBox) {
FloatQuad quad(FloatPoint(2, 3), FloatPoint(5, 7), FloatPoint(11, 13),
FloatPoint(17, 19));
FloatRect rect = quad.BoundingBox();
EXPECT_EQ(rect.X(), 2);
EXPECT_EQ(rect.Y(), 3);
EXPECT_EQ(rect.Width(), 17 - 2);
EXPECT_EQ(rect.Height(), 19 - 3);
}
TEST(FloatQuadTest, BoundingBoxSaturateInf) {
double inf = std::numeric_limits<double>::infinity();
FloatQuad quad(FloatPoint(-inf, 3), FloatPoint(5, inf), FloatPoint(11, 13),
FloatPoint(17, 19));
FloatRect rect = quad.BoundingBox();
EXPECT_EQ(rect.X(), std::numeric_limits<int>::min());
EXPECT_EQ(rect.Y(), 3.0f);
EXPECT_EQ(rect.Width(), 17.0f - std::numeric_limits<int>::min());
EXPECT_EQ(rect.Height(), std::numeric_limits<int>::max() - 3.0f);
}
} // namespace blink
| 33.725 | 77 | 0.670867 | [
"geometry"
] |
5622a55c735aea1826a8c95c9b5ed541329bd679 | 7,269 | cpp | C++ | ace/tao/orbsvcs/orbsvcs/Time/tao_tio.cpp | tharindusathis/sourcecodes-of-CodeReadingTheOpenSourcePerspective | 1b0172cdb78757fd17898503aaf6ce03d940ef28 | [
"Apache-1.1"
] | 46 | 2015-12-04T17:12:58.000Z | 2022-03-11T04:30:49.000Z | ace/tao/orbsvcs/orbsvcs/Time/tao_tio.cpp | tharindusathis/sourcecodes-of-CodeReadingTheOpenSourcePerspective | 1b0172cdb78757fd17898503aaf6ce03d940ef28 | [
"Apache-1.1"
] | null | null | null | ace/tao/orbsvcs/orbsvcs/Time/tao_tio.cpp | tharindusathis/sourcecodes-of-CodeReadingTheOpenSourcePerspective | 1b0172cdb78757fd17898503aaf6ce03d940ef28 | [
"Apache-1.1"
] | 23 | 2016-10-24T09:18:14.000Z | 2022-02-25T02:11:35.000Z | // -*- C++ -*-
// TAO_TIO.cpp,v 1.16 2001/03/28 23:49:14 bala Exp
#include "TAO_TIO.h"
// Constructor.
TAO_TIO::TAO_TIO (TimeBase::TimeT lower,
TimeBase::TimeT upper)
{
this->attr_time_interval.lower_bound = lower;
this->attr_time_interval.upper_bound = upper;
}
// Destructor.
TAO_TIO::~TAO_TIO (void)
{
}
// This is the get method for the attribute time interval.
TimeBase::IntervalT
TAO_TIO::time_interval (CORBA::Environment &)
ACE_THROW_SPEC ((CORBA::SystemException))
{
return attr_time_interval;
}
// This operation returns a value of type OverlapType depending on how
// the interval in the object and the time range represented by the
// parameter UTO overlap. If OverlapType is not OTNoOverlap, then the
// out parameter overlap contains the overlap interval, otherwise the
// out parameter contains the gap between the two intervals.
CosTime::OverlapType
TAO_TIO::spans (CosTime::UTO_ptr uto,
CosTime::TIO_out overlap,
CORBA::Environment &ACE_TRY_ENV)
ACE_THROW_SPEC ((CORBA::SystemException))
{
TAO_TIO *tio = 0;
ACE_TRY
{
TimeBase::TimeT lb1 =
this->time_interval ().lower_bound;
TimeBase::TimeT up1 =
this->time_interval ().upper_bound;
TimeBase::TimeT tmp1 = uto->time (ACE_TRY_ENV);
ACE_TRY_CHECK;
TimeBase::TimeT tmp2 = uto->inaccuracy (ACE_TRY_ENV);
ACE_TRY_CHECK;
TimeBase::TimeT lb2 = tmp1 - tmp2;
tmp1 = uto->time (ACE_TRY_ENV);
ACE_TRY_CHECK;
tmp2 = uto->inaccuracy (ACE_TRY_ENV);
ACE_TRY_CHECK;
TimeBase::TimeT up2 = tmp1 + tmp2;
if (lb1 == lb2 && up1 == up2)
{
ACE_NEW_RETURN (tio,
TAO_TIO (lb1, up1),
CosTime::OTNoOverlap);
overlap = tio->_this ();
return CosTime::OTOverlap;
}
else if (lb1 > lb2 && up1 < up2)
{
ACE_NEW_RETURN (tio,
TAO_TIO (lb1, up1),
CosTime::OTNoOverlap);
overlap = tio->_this ();
return CosTime::OTContained;
}
else if (lb1 < lb2 && up1 > up2)
{
ACE_NEW_RETURN (tio,
TAO_TIO (lb2, up2),
CosTime::OTNoOverlap);
overlap = tio->_this ();
return CosTime::OTContained;
}
else if (lb1 < lb2)
{
if (up1 < lb2)
{
ACE_NEW_RETURN (tio,
TAO_TIO (0, 0),
CosTime::OTNoOverlap);
overlap = tio->_this ();
return CosTime::OTNoOverlap;
}
else
{
ACE_NEW_RETURN (tio,
TAO_TIO (lb2, up1),
CosTime::OTNoOverlap);
overlap = tio->_this ();
return CosTime::OTOverlap;
}
}
else if (up2 < lb1)
{
ACE_NEW_RETURN (tio,
TAO_TIO (0, 0),
CosTime::OTNoOverlap);
overlap = tio->_this ();
return CosTime::OTNoOverlap;
}
else
{
ACE_NEW_RETURN (tio,
TAO_TIO (lb1, up2),
CosTime::OTNoOverlap);
overlap = tio->_this ();
}
}
ACE_CATCHANY
{
ACE_PRINT_EXCEPTION (ACE_ANY_EXCEPTION, "Exception:");
}
ACE_ENDTRY;
ACE_CHECK_RETURN (CosTime::OTNoOverlap);
return CosTime::OTNoOverlap;
}
// This operation returns a value of type OverlapType depending on how
// the interval in the object and interval in the parameter TIO
// overlap. If OverlapType is not OTNoOverlap, then the out parameter
// overlap contains the overlap interval, otherwise the out parameter
// contains the gap between the two intervals.
CosTime::OverlapType
TAO_TIO::overlaps (CosTime::TIO_ptr tio,
CosTime::TIO_out overlap,
CORBA::Environment & ACE_TRY_ENV)
ACE_THROW_SPEC ((CORBA::SystemException))
{
TAO_TIO *tio_i = 0;
TimeBase::TimeT lb1 =
this->time_interval ().lower_bound;
TimeBase::TimeT up1 =
this->time_interval ().upper_bound;
TimeBase::TimeT lb2 =
tio->time_interval ().lower_bound;
TimeBase::TimeT up2 =
tio->time_interval ().upper_bound;
if (lb1 == lb2 && up1 == up2)
{
ACE_NEW_THROW_EX (tio_i,
TAO_TIO (lb1, up1),
CORBA::NO_MEMORY ());
ACE_CHECK_RETURN (CosTime::OTNoOverlap);
overlap = tio_i->_this ();
return CosTime::OTOverlap;
}
else if (lb1 > lb2 && up1 < up2)
{
ACE_NEW_THROW_EX (tio_i,
TAO_TIO (lb1, up1),
CORBA::NO_MEMORY ());
ACE_CHECK_RETURN (CosTime::OTNoOverlap);
overlap = tio_i->_this ();
return CosTime::OTContained;
}
else if (lb1 < lb2 && up1 > up2)
{
ACE_NEW_THROW_EX (tio_i,
TAO_TIO (lb2, up2),
CORBA::NO_MEMORY ());
ACE_CHECK_RETURN (CosTime::OTNoOverlap);
overlap = tio_i->_this ();
return CosTime::OTContained;
}
else if (lb1 < lb2)
{
if (up1 < lb2)
{
ACE_NEW_THROW_EX (tio_i,
TAO_TIO (0, 0),
CORBA::NO_MEMORY ());
ACE_CHECK_RETURN (CosTime::OTNoOverlap);
overlap = tio_i->_this ();
return CosTime::OTNoOverlap;
}
else
{
ACE_NEW_THROW_EX (tio_i,
TAO_TIO (lb2, up1),
CORBA::NO_MEMORY ());
ACE_CHECK_RETURN (CosTime::OTNoOverlap);
overlap = tio_i->_this ();
return CosTime::OTOverlap;
}
}
else if (up2 < lb1)
{
ACE_NEW_THROW_EX (tio_i,
TAO_TIO (0, 0),
CORBA::NO_MEMORY ());
ACE_CHECK_RETURN (CosTime::OTNoOverlap);
overlap = tio_i->_this ();
return CosTime::OTNoOverlap;
}
else
{
ACE_NEW_THROW_EX (tio_i,
TAO_TIO (lb1, up2),
CORBA::NO_MEMORY ());
ACE_CHECK_RETURN (CosTime::OTNoOverlap);
overlap = tio_i->_this ();
}
return CosTime::OTNoOverlap;
}
CosTime::UTO_ptr
TAO_TIO::time (CORBA::Environment &ACE_TRY_ENV)
ACE_THROW_SPEC ((CORBA::SystemException))
{
TAO_UTO *uto = 0;
ACE_NEW_THROW_EX (uto,
TAO_UTO ((this->time_interval ().upper_bound -
this->time_interval ().lower_bound) / 2,
this->time_interval ().upper_bound -
this->time_interval ().lower_bound,
0),
CORBA::NO_MEMORY ());
ACE_CHECK_RETURN (CosTime::UTO::_nil ());
return uto->_this ();
}
| 26.529197 | 71 | 0.508873 | [
"object"
] |
562636f3a977bb1b4b5f32a2625fe34784fa0cd8 | 3,496 | cpp | C++ | ydb/ydb_lock_test.cpp | allenporter/thebends | 5e35c7e654e5260b37218e59b02fb0b1a5cb2eca | [
"Apache-2.0"
] | 4 | 2015-07-27T04:05:50.000Z | 2021-01-28T21:56:09.000Z | ydb/ydb_lock_test.cpp | allenporter/thebends | 5e35c7e654e5260b37218e59b02fb0b1a5cb2eca | [
"Apache-2.0"
] | null | null | null | ydb/ydb_lock_test.cpp | allenporter/thebends | 5e35c7e654e5260b37218e59b02fb0b1a5cb2eca | [
"Apache-2.0"
] | null | null | null | // ydb_trans_test.cpp
// Author: Allen Porter <allen@thebends.org>
//
// Test basic functionality of the lock table.
#include <iostream>
#include <string>
#include "ydb_lock.h"
#include "ydb_trans.h"
using namespace std;
class Ydb_Lock_Test {
public:
static void test1();
static void test2();
static void test3();
};
// Object to let tests create fake transactions.
class TestTrans : public Ydb_Trans {
public:
TestTrans() : Ydb_Trans(NULL) { }
};
void Ydb_Lock_Test::test1() {
// read and write locks for the same key by different transactions that
// don't overloap.
Ydb_LockTable table;
Ydb_Trans* trans1 = new TestTrans();
Ydb_Trans* trans2 = new TestTrans();
assert(table.ReadLock(trans1, "key"));
assert(table.Unlock(trans1, "key"));
assert(table.ReadLock(trans2, "key"));
assert(table.Unlock(trans2, "key"));
assert(table.WriteLock(trans1, "key"));
assert(table.Unlock(trans1, "key"));
assert(table.WriteLock(trans2, "key"));
assert(table.Unlock(trans2, "key"));
assert(table.ReadLock(trans1, "key"));
assert(table.Unlock(trans1, "key"));
}
void Ydb_Lock_Test::test2() {
// test lock upgrading from read to write
Ydb_LockTable table;
Ydb_Trans* trans1 = new TestTrans();
Ydb_Trans* trans2 = new TestTrans();
// no locks are held
assert(!table.Unlock(trans1, "key"));
assert(table.GetLockHolders("key") == NULL);
// upgrade read lock to a write lock
assert(table.ReadLock(trans1, "key"));
assert(table.WriteLock(trans1, "key"));
assert(table.ReadLock(trans1, "key"));
// trans1 holds a write lock
assert(!table.ReadLock(trans2, "key"));
const TransList* list1 = table.GetLockHolders("key");
assert(list1->size() == 1);
assert(list1->at(0) == trans1);
assert(table.Unlock(trans1, "key"));
// Unlock only needs to be called once per transaction
assert(!table.Unlock(trans1, "key"));
// test that all locks were removed
assert(table.ReadLock(trans2, "key"));
assert(table.Unlock(trans2, "key"));
// unable to get a write lock because a read lock is held
assert(table.ReadLock(trans1, "key"));
assert(!table.WriteLock(trans2, "key"));
const TransList* list2 = table.GetLockHolders("key");
assert(list2->size() == 1);
assert(list2->at(0) == trans1);
assert(table.Unlock(trans1, "key"));
// unable to upgrade because there are multiple readers
assert(table.ReadLock(trans1, "key"));
assert(table.ReadLock(trans2, "key"));
assert(!table.WriteLock(trans2, "key"));
const TransList* list3 = table.GetLockHolders("key");
assert(list3->size() == 2);
assert(table.Unlock(trans1, "key"));
assert(table.Unlock(trans2, "key"));
}
void Ydb_Lock_Test::test3() {
// test a shared read and exclusive write
Ydb_LockTable table;
Ydb_Trans* trans1 = new TestTrans();
Ydb_Trans* trans2 = new TestTrans();
// shared read
assert(table.ReadLock(trans1, "key"));
assert(table.ReadLock(trans2, "key"));
assert(table.Unlock(trans1, "key"));
assert(table.Unlock(trans2, "key"));
assert(table.ReadLock(trans1, "key"));
assert(!table.Unlock(trans2, "key"));
assert(table.Unlock(trans1, "key"));
// write is exclusive
assert(table.WriteLock(trans1, "key"));
assert(!table.ReadLock(trans2, "key"));
assert(!table.WriteLock(trans2, "key"));
assert(!table.Unlock(trans2, "key"));
assert(table.Unlock(trans1, "key"));
}
int main(int argc, char* argv[]) {
Ydb_Lock_Test test;
test.test1();
test.test2();
test.test3();
cout << "OK" << endl;
}
| 26.892308 | 73 | 0.678204 | [
"object"
] |
562af3ace4bfc2841dec214aa5485dfddad43dce | 5,097 | cpp | C++ | KoopaTroopa.cpp | zacharytay1994/NotSoSuperMario | e0828f4cb2231f2e5993a71a492a25892744e129 | [
"CC-BY-3.0"
] | 2 | 2019-11-22T06:04:43.000Z | 2019-12-05T13:29:17.000Z | KoopaTroopa.cpp | zacharytay1994/NotSoSuperMario | e0828f4cb2231f2e5993a71a492a25892744e129 | [
"CC-BY-3.0"
] | null | null | null | KoopaTroopa.cpp | zacharytay1994/NotSoSuperMario | e0828f4cb2231f2e5993a71a492a25892744e129 | [
"CC-BY-3.0"
] | null | null | null | #include "KoopaTroopa.h"
#include "PhysicsComponent.h"
#include "CollisionDetectionComponent.h"
#include <cstdlib>
#include <iostream>
#include <sstream>
KoopaTroopa::KoopaTroopa(ColliderManager& cm, const Vec2<float>& position)
:
GameObject("pictures\\" + theme + "\\testsquare.png", 64, 64, 1, D3DXVECTOR2(position.x_, position.y_), "Koopa"),
walking_sprite_(new Sprite("pictures\\" + theme + "\\kooparunsheet.png", 64, 64, 8)),
shellmoving_sprite_(new Sprite("pictures\\" + theme + "\\koopashellmovingsheet.png", 54, 64, 4)),
shellidle_sprite_(new Sprite("pictures\\" + theme + "\\koopashellidle.png", 54, 64, 1))
{
walking_sprite_->InitializeAnimation(0, 7, 0.25f);
shellmoving_sprite_->InitializeAnimation(0, 3, 0.125f);
PhysicsComponent* temp = new PhysicsComponent(*this);
random = rand() % 5+10;
timer = random;
phy_ = temp;
AddComponent(temp);
AddComponent(new CollisionDetectionComponent<AABBCollider>(*this, new AABBCollider(position_, this, sprite_->GetWidth() - 10.0f, sprite_->GetHeight() - 3.0f, false, true), cm));
sprite_ = walking_sprite_;
}
KoopaTroopa::~KoopaTroopa()
{
}
void KoopaTroopa::Update(const float& frametime)
{
GameObject::Update(frametime);
if (!shellState) {
timer = timer - frametime;
if (timer <= 0) {
std::stringstream test;
if (direction_.x_ == 1)
{
direction_.x_ = -1;
sprite_->GetImage().flipHorizontal(false);
looking_left_ = false;
}
else {
direction_.x_ = 1;
sprite_->GetImage().flipHorizontal(true);
looking_left_ = false;
}
timer = random;
}
// temp
if (touch_.touch_left_) {
direction_.x_ = -1;
sprite_->GetImage().flipHorizontal(false);
looking_left_ = true;
}
else if (touch_.touch_right_) {
direction_.x_ = 1;
sprite_->GetImage().flipHorizontal(true);
looking_left_ = false;
}
if (touch_.touch_top_)
{
if (touch_obj_.touch_obj_top_->owner_->type_ == "Mario")
shellState = true;
}
// walk
phy_->AddVelocity(direction_ * speed_);
}
else {
//dynamic_cast<CollisionDetectionComponent<AABBCollider>*>(GetComponent("CollisionDetectionComponent"));
;
// temp
if (touch_.touch_left_) {
looking_left_ = true;
shellMoving = true;
if (touch_obj_.touch_obj_left_->owner_->type_ == "Goomba")
{
touch_obj_.touch_obj_left_->owner_->removed_ = true;
//AddGoombaSprite();
}
else {
direction_.x_ = -1;
sprite_->GetImage().flipHorizontal(false);
}
}
else if (touch_.touch_right_) {
looking_left_ = false;
shellMoving = true;
if (touch_obj_.touch_obj_right_->owner_->type_ == "Goomba")
{
touch_obj_.touch_obj_right_->owner_->removed_ = true;
//AddGoombaSprite();
}
else {
direction_.x_ = 1;
sprite_->GetImage().flipHorizontal(true);
}
}
if (touch_.touch_top_) {
//sprite_->GetImage().flipVertical(!looking_left_);
shellMoving = false;
}
if (!shellMoving) {
ChangeSprite(shellidle_sprite_);
phy_->AddVelocity(direction_ * 0); }
else {
ChangeSprite(shellmoving_sprite_);
phy_->AddVelocity(direction_ * shellSpeed_); }
}
UpdateGoombaSprites(frametime);
}
void KoopaTroopa::Render()
{
//DrawGoombaSprites();
GameObject::Render();
}
void KoopaTroopa::ChildInitialize(Graphics& gfx)
{
shellidle_sprite_->Initialize(gfx);
shellidle_sprite_->GetImage().setScale(CAMERA_ZOOM);
shellmoving_sprite_->Initialize(gfx);
shellmoving_sprite_->GetImage().setScale(CAMERA_ZOOM);
walking_sprite_->Initialize(gfx);
walking_sprite_->GetImage().setScale(CAMERA_ZOOM);
gfx_ = &gfx;
}
bool KoopaTroopa::GetShellState()
{
return shellState;
}
bool KoopaTroopa::GetShellMovingState()
{
return shellMoving;
}
void KoopaTroopa::AddGoombaSprite()
{
Sprite* temp = new Sprite("pictures\\goombawalksheet.png", 64, 64, 4);
temp->Initialize(*gfx_);
temp->GetImage().setX(position_.x);
temp->GetImage().setY(position_.y);
temp->GetImage().setScale(CAMERA_ZOOM);
goomba_sprites_.push_back(*temp);
}
void KoopaTroopa::UpdateGoombaSprites(const float& frametime)
{
// loop through goombas
for (int i = 0; i < goomba_sprites_.size(); i++) {
// fly it up
if (goomba_sprites_[i].GetImage().getRadians() < 1.571f) {
goomba_sprites_[i].GetImage().setY(goomba_sprites_[i].GetImage().getY() - drop_speed_ * frametime);
}
else {
drop_speed_ += 500.0f * frametime;
goomba_sprites_[i].GetImage().setY(goomba_sprites_[i].GetImage().getY() + drop_speed_ * frametime);
}
// check if goomba rotation > certain amount, 270 degrees
if (goomba_sprites_[i].GetImage().getRadians() > 15.652f) {
// remove sprite
Sprite* temp = &goomba_sprites_[i];
goomba_sprites_.erase(goomba_sprites_.begin() + i);
delete temp;
}
else {
// spin it
goomba_sprites_[i].GetImage().setRadians(goomba_sprites_[i].GetImage().getRadians() + 10.0f * frametime);
}
}
}
void KoopaTroopa::DrawGoombaSprites()
{
for (int i = 0; i < goomba_sprites_.size(); i++) {
goomba_sprites_[i].Draw();
}
}
| 24.985294 | 178 | 0.672356 | [
"render"
] |
5635dc9fc7e70e90aefc8c3f8c809ac3d8877547 | 2,815 | cxx | C++ | Testing/Code/Review/itkQuadEdgeMeshDeleteEdgeTest.cxx | kiranhs/ITKv4FEM-Kiran | 0e4ab3b61b5fc4c736f04a73dd19e41390f20152 | [
"BSD-3-Clause"
] | 1 | 2018-04-15T13:32:43.000Z | 2018-04-15T13:32:43.000Z | Testing/Code/Review/itkQuadEdgeMeshDeleteEdgeTest.cxx | kiranhs/ITKv4FEM-Kiran | 0e4ab3b61b5fc4c736f04a73dd19e41390f20152 | [
"BSD-3-Clause"
] | null | null | null | Testing/Code/Review/itkQuadEdgeMeshDeleteEdgeTest.cxx | kiranhs/ITKv4FEM-Kiran | 0e4ab3b61b5fc4c736f04a73dd19e41390f20152 | [
"BSD-3-Clause"
] | null | null | null | /*=========================================================================
Program: Insight Segmentation & Registration Toolkit
Module: itkQuadEdgeMeshDeleteEdgeTest.cxx
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) Insight Software Consortium. All rights reserved.
See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#if defined(_MSC_VER)
#pragma warning ( disable : 4786 )
#endif
#include "itkQuadEdgeMesh.h"
int itkQuadEdgeMeshDeleteEdgeTest( int , char* [] )
{
typedef double PixelType;
typedef itk::QuadEdgeMesh< PixelType, 3 > MeshType;
std::string indent = " ";
MeshType::Pointer mesh = MeshType::New( );
// Points
MeshType::PointType p0, p1, p2, p3, p4, p5;
p0[ 0 ] = 0.00000000000000; p0[ 1 ] = 0.00000000000000; p0[ 2 ] = 5.0;
p1[ 0 ] = 0.00000000000000; p1[ 1 ] = 10.00000000000000; p1[ 2 ] = 0.0;
p2[ 0 ] = -9.51056516295153; p2[ 1 ] = 3.09016994374947; p2[ 2 ] = 0.0;
p3[ 0 ] = -5.87785252292473; p3[ 1 ] = -8.09016994374947; p3[ 2 ] = 0.0;
p4[ 0 ] = 5.87785252292473; p4[ 1 ] = -8.09016994374948; p4[ 2 ] = 0.0;
p5[ 0 ] = 9.51056516295154; p5[ 1 ] = 3.09016994374947; p5[ 2 ] = 0.0;
MeshType::PointIdentifier pid0 = mesh->AddPoint( p0 );
MeshType::PointIdentifier pid1 = mesh->AddPoint( p1 );
MeshType::PointIdentifier pid2 = mesh->AddPoint( p2 );
MeshType::PointIdentifier pid3 = mesh->AddPoint( p3 );
MeshType::PointIdentifier pid4 = mesh->AddPoint( p4 );
MeshType::PointIdentifier pid5 = mesh->AddPoint( p5 );
// Cells in a proper way
mesh->AddEdge( pid3, pid4 );
mesh->AddEdge( pid4, pid0 );
mesh->AddEdge( pid0, pid3 );
mesh->AddFaceTriangle( pid3, pid4, pid0 );
mesh->AddEdge( pid4, pid5 );
mesh->AddEdge( pid5, pid0 );
mesh->AddFaceTriangle( pid4, pid5, pid0 );
mesh->AddEdge( pid5, pid1 );
mesh->AddEdge( pid1, pid0 );
mesh->AddFaceTriangle( pid5, pid1, pid0 );
mesh->AddEdge( pid1, pid2 );
mesh->AddEdge( pid2, pid0 );
mesh->AddEdge( pid2, pid3 );
int EdgesBefore = mesh->ComputeNumberOfEdges();
// Deleting two arbitrary edges:
mesh->DeleteEdge( pid3, pid4 );
mesh->DeleteEdge( pid0, pid5 );
std::cout << indent << "Trying to remove only two edges...";
if ( EdgesBefore - mesh->ComputeNumberOfEdges() == 2 )
{
std::cout << "OK." << std::endl;
return( EXIT_SUCCESS );
}
else
{
std::cout << "FAILED." << std::endl;
return( EXIT_FAILURE );
}
return( EXIT_SUCCESS );
}
| 33.117647 | 76 | 0.607815 | [
"mesh"
] |
5636c208bb198246715c1c80db0db0973b3696cf | 6,128 | cpp | C++ | realm/realm-library/src/main/cpp/io_realm_internal_OsObjectStore.cpp | schmalliso/realm-java | 5c270e7a11191e6f7246c9d6c4c37fa892aa0b37 | [
"Apache-2.0"
] | 1 | 2021-12-16T13:09:38.000Z | 2021-12-16T13:09:38.000Z | realm/realm-library/src/main/cpp/io_realm_internal_OsObjectStore.cpp | schmalliso/realm-java | 5c270e7a11191e6f7246c9d6c4c37fa892aa0b37 | [
"Apache-2.0"
] | null | null | null | realm/realm-library/src/main/cpp/io_realm_internal_OsObjectStore.cpp | schmalliso/realm-java | 5c270e7a11191e6f7246c9d6c4c37fa892aa0b37 | [
"Apache-2.0"
] | 1 | 2021-12-16T13:08:41.000Z | 2021-12-16T13:08:41.000Z | /*
* Copyright 2017 Realm 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.
*/
#include "io_realm_internal_OsObjectStore.h"
#include <realm/object-store/object_store.hpp>
#include <realm/object-store/shared_realm.hpp>
#include "util.hpp"
#include "jni_util/java_method.hpp"
#include "jni_util/java_exception_thrower.hpp"
#include "jni_util/java_exception_thrower.hpp"
using namespace realm;
using namespace realm::jni_util;
using namespace realm::util;
using namespace realm::_impl;
static_assert(io_realm_internal_OsObjectStore_SCHEMA_NOT_VERSIONED == static_cast<jlong>(ObjectStore::NotVersioned),
"");
JNIEXPORT void JNICALL Java_io_realm_internal_OsObjectStore_nativeSetPrimaryKeyForObject(JNIEnv* env, jclass,
jlong shared_realm_ptr,
jstring j_class_name,
jstring j_pk_field_name)
{
try {
auto& shared_realm = *(reinterpret_cast<SharedRealm*>(shared_realm_ptr));
JStringAccessor class_name(env, j_class_name);
JStringAccessor primary_key_field_name(env, j_pk_field_name);
auto& group = shared_realm->read_group();
if (!group.has_table(class_name)) {
std::string name_str = class_name;
if (name_str.find(TABLE_PREFIX) == 0) {
name_str = name_str.substr(TABLE_PREFIX.length());
}
THROW_JAVA_EXCEPTION(env, JavaExceptionDef::IllegalArgument,
util::format("The class '%1' doesn't exist in this Realm.", name_str));
}
TableRef table = group.get_table(class_name);
shared_realm->verify_in_write();
table->set_primary_key_column(table->get_column_key(primary_key_field_name));
}
CATCH_STD()
}
JNIEXPORT jstring JNICALL Java_io_realm_internal_OsObjectStore_nativeGetPrimaryKeyForObject(JNIEnv* env, jclass,
jlong shared_realm_ptr,
jstring j_class_name)
{
try {
auto& shared_realm = *(reinterpret_cast<SharedRealm*>(shared_realm_ptr));
JStringAccessor class_name(env, j_class_name);
TableRef table = shared_realm->read_group().get_table(class_name);
auto col = table->get_primary_key_column();
std::string primary_key_field_name = (col) ? table->get_column_name(col) : "";
return primary_key_field_name.size() == 0 ? nullptr : to_jstring(env, primary_key_field_name);
}
CATCH_STD()
return nullptr;
}
JNIEXPORT void JNICALL Java_io_realm_internal_OsObjectStore_nativeSetSchemaVersion(JNIEnv* env, jclass,
jlong shared_realm_ptr,
jlong schema_version)
{
try {
auto& shared_realm = *(reinterpret_cast<SharedRealm*>(shared_realm_ptr));
shared_realm->verify_in_write();
ObjectStore::set_schema_version(shared_realm->read_group(), schema_version);
}
CATCH_STD()
}
JNIEXPORT jlong JNICALL Java_io_realm_internal_OsObjectStore_nativeGetSchemaVersion(JNIEnv* env, jclass,
jlong shared_realm_ptr)
{
try {
auto& shared_realm = *(reinterpret_cast<SharedRealm*>(shared_realm_ptr));
return ObjectStore::get_schema_version(shared_realm->read_group());
}
CATCH_STD()
return ObjectStore::NotVersioned;
}
JNIEXPORT jboolean JNICALL Java_io_realm_internal_OsObjectStore_nativeDeleteTableForObject(JNIEnv* env, jclass,
jlong shared_realm_ptr,
jstring j_class_name)
{
try {
auto& shared_realm = *(reinterpret_cast<SharedRealm*>(shared_realm_ptr));
JStringAccessor class_name_accessor(env, j_class_name);
shared_realm->verify_in_write();
if (!ObjectStore::table_for_object_type(shared_realm->read_group(), class_name_accessor)) {
return JNI_FALSE;
}
ObjectStore::delete_data_for_object(shared_realm->read_group(), class_name_accessor);
return JNI_TRUE;
}
CATCH_STD()
return JNI_FALSE;
}
JNIEXPORT jboolean JNICALL Java_io_realm_internal_OsObjectStore_nativeCallWithLock(JNIEnv* env, jclass,
jstring j_realm_path,
jobject j_runnable)
{
try {
JStringAccessor path_accessor(env, j_realm_path);
std::string realm_path(path_accessor);
static JavaClass runnable_class(env, "java/lang/Runnable");
static JavaMethod run_method(env, runnable_class, "run", "()V");
bool result = DB::call_with_lock(realm_path, [&](std::string path) {
REALM_ASSERT_RELEASE_EX(realm_path.compare(path) == 0, realm_path.c_str(), path.c_str());
env->CallVoidMethod(j_runnable, run_method);
TERMINATE_JNI_IF_JAVA_EXCEPTION_OCCURRED(env, nullptr);
});
return result;
}
CATCH_STD()
return false;
}
| 44.729927 | 116 | 0.598074 | [
"object"
] |
56399322589f557c65e8e1497646e37a4170a7a3 | 3,876 | hpp | C++ | src/main/mapmaker/calculator.hpp | PatrickLindemann/warzone-osm-processor | 16cbc956723f79d07dd1c1dcfd11ac7842a63312 | [
"MIT"
] | null | null | null | src/main/mapmaker/calculator.hpp | PatrickLindemann/warzone-osm-processor | 16cbc956723f79d07dd1c1dcfd11ac7842a63312 | [
"MIT"
] | null | null | null | src/main/mapmaker/calculator.hpp | PatrickLindemann/warzone-osm-processor | 16cbc956723f79d07dd1c1dcfd11ac7842a63312 | [
"MIT"
] | null | null | null | #pragma once
#include "model/geometry/point.hpp"
#include "model/geometry/rectangle.hpp"
#include "handler/bounds_handler.hpp"
#include "functions/center.hpp"
using namespace model;
namespace mapmaker
{
template <typename T>
class BoundsCalculator
{
public:
/* Constructors */
BoundsCalculator() {}
/* Methods */
geometry::Rectangle<T> run(const osmium::memory::Buffer& buffer) const
{
// Prepare the bounds handler that calculates the minimum bounding
// box over all nodes in the buffer
handler::BoundsHandler bounds_handler{};
osmium::apply(buffer, bounds_handler);
// Retrieve the calculated bounds and convert them to a rectangle
// geometry
osmium::Box bounds = bounds_handler.bounds();
return geometry::Rectangle<T>{
T(bounds.bottom_left().lon()),
T(bounds.bottom_left().lat()),
T(bounds.top_right().lon()),
T(bounds.top_right().lat())
};
}
};
template <typename T>
class CenterCalculator
{
public:
/* Constructors */
CenterCalculator() {}
/* Methods */
void run(std::map<object_id_type, Boundary<T>>& boundaries)
{
for (auto& [id, boundary] : boundaries)
{
boundary.center = functions::center(boundary.geometry);
}
}
};
//class ArmyCalculator
//{
//protected:
// /* Members */
// /**
// * The minimum number of armies for a bonus.
// */
// int m_min = 1;
// /**
// * The maximum number of armies for a bonus.
// */
// int m_max = 10;
// /**
// * The territory count weight.
// */
// double m_tw = 0.5;
// /**
// * The outer connection count weight.
// */
// double m_ow = 0.5;
//public:
// /* Constructors */
// ArmyCalculator() {}
// ArmyCalculator(int min, int max) : m_min(min), m_max(max) {}
// ArmyCalculator(int min, int max, std::vector<double> weights)
// : m_min(min), m_max(max), m_tw(weights.at(0)), m_ow(weights.at(1)) {}
//protected:
// /* Helper Methods */
// std::set<object_id_type> outer_connections(const warzone::Map& map, const warzone::Bonus& bonus)
// {
// std::set<object_id_type> connections = {};
// // Retrieve the neighbors of all territories contained in the bonus
// for (const object_id_type& child : bonus.children)
// {
// const warzone::Territory& territory = map.territories.at(child);
// for (const object_id_type& neighbor : territory.neighbors)
// {
// connections.insert(neighbor);
// }
// }
// // Filter the neighbors that are territories in the bonus
// for (const object_id_type& child : bonus.children)
// {
// connections.erase(child);
// }
// return connections;
// }
//public:
// /* Methods */
// void run(warzone::Map& map)
// {
// // Retrieve the total number of territories
// std::size_t t_total = map.territories.size();
// // Calculate the number of each outer connections for each bonus
// std::size_t o_total = 0;
// std::vector<std::set<object_id_type>> bonus_connections;
// for (warzone::Bonus& bonus : map.bonuses)
// {
// bonus_connections.push_back(outer_connections(map, bonus));
// }
// m_tw* (t / t_total) + m_ow * (o / o_total);
// }
//};
} | 25.5 | 106 | 0.514964 | [
"geometry",
"vector",
"model"
] |
563f0892e825d3f9ad6a70029e9192d28987a619 | 24,762 | cpp | C++ | applications/popart/transformer_transducer/custom_ops/rnnt_loss/rnnt_utils.cpp | payoto/graphcore_examples | 46d2b7687b829778369fc6328170a7b14761e5c6 | [
"MIT"
] | 260 | 2019-11-18T01:50:00.000Z | 2022-03-28T23:08:53.000Z | applications/popart/transformer_transducer/custom_ops/rnnt_loss/rnnt_utils.cpp | payoto/graphcore_examples | 46d2b7687b829778369fc6328170a7b14761e5c6 | [
"MIT"
] | 27 | 2020-01-28T23:07:50.000Z | 2022-02-14T15:37:06.000Z | applications/popart/transformer_transducer/custom_ops/rnnt_loss/rnnt_utils.cpp | payoto/graphcore_examples | 46d2b7687b829778369fc6328170a7b14761e5c6 | [
"MIT"
] | 56 | 2019-11-18T02:13:12.000Z | 2022-02-28T14:36:09.000Z | // Copyright (c) 2021 Graphcore Ltd. All rights reserved.
#include "rnnt_utils.hpp"
#include "ipu_utils.hpp"
#include "poplar/Program.hpp"
#include <popnn/Loss.hpp>
#include <popops/ElementWise.hpp>
#include <popops/Reduce.hpp>
#include <poputil/TileMapping.hpp>
#include <poputil/Util.hpp>
#include <poputil/VertexTemplates.hpp>
#include <tuple>
#include <unordered_map>
poplar::Tensor initBatchIndices(poplar::Graph &graph, uint32_t batchSize,
uint32_t T, uint32_t U) {
std::vector<uint16_t> bsRange;
for (size_t i = 0; i < batchSize; ++i)
bsRange.push_back(i);
poplar::ArrayRef<uint16_t> bsArrayRef(bsRange);
poplar::Tensor batchIndices = graph.addConstant(
poplar::UNSIGNED_SHORT, {batchSize, 1}, bsArrayRef, "BatchSizeIndices");
poplar::Tensor result =
batchIndices.broadcast(T * U, 1).reshape({batchSize, T, U});
return result;
}
poplar::Tensor initTIndices(poplar::Graph &graph, uint32_t batchSize,
uint32_t T, uint32_t U) {
std::vector<uint16_t> sliceRange;
for (size_t i = 0; i < T; ++i)
sliceRange.push_back(i);
poplar::ArrayRef<uint16_t> sliceArrayRef(sliceRange);
poplar::Tensor sliceIndices = graph.addConstant(
poplar::UNSIGNED_SHORT, {1, T, 1}, sliceArrayRef, "TIndices");
poplar::Tensor result = sliceIndices.broadcast(batchSize, 0).broadcast(U, 2);
return result;
}
poplar::Tensor initUIndices(poplar::Graph &graph, uint32_t batchSize,
uint32_t T, uint32_t U) {
std::vector<uint16_t> sliceRange;
for (size_t i = 0; i < U; ++i)
sliceRange.push_back(i);
poplar::ArrayRef<uint16_t> sliceArrayRef(sliceRange);
poplar::Tensor sliceIndices = graph.addConstant(
poplar::UNSIGNED_SHORT, {1, 1, U}, sliceArrayRef, "TIndices");
poplar::Tensor result = sliceIndices.broadcast(batchSize, 0).broadcast(T, 1);
return result;
}
void mapTileVertex(
poplar::Graph &graph,
const std::unordered_map<std::string, poplar::Tensor> &flat,
const std::unordered_map<std::string, poplar::Tensor> &full,
const std::unordered_map<std::string, poplar::Tensor> &indices,
const std::unordered_map<std::string, poplar::Tensor> &tiles,
const std::unordered_map<std::string, poplar::Tensor> &workers,
poplar::ComputeSet &computeSet, const std::string &vertexName,
const std::vector<poplar::Interval> ®ions, uint16_t index,
uint32_t tileNumber, uint32_t splitSize) {
auto vertexRegions =
poputil::splitRegionsBetweenWorkers(graph.getTarget(), regions, 1, 1);
size_t j = 0;
for (auto &r : vertexRegions) {
poplar::VertexRef vtx = graph.addVertex(computeSet, vertexName);
for (auto &p : flat) {
graph.connect(vtx[p.first], poplar::concat(p.second.slices(r)));
}
for (auto &p : full) {
graph.connect(vtx[p.first], p.second);
}
for (auto &p : indices) {
graph.connect(vtx[p.first], p.second[index]);
}
for (auto &p : tiles) {
if (r.size() > 1) {
std::cerr << "Debug " << tileNumber << ":" << regions.size() << " "
<< r.size() << " ";
for (const auto &t : r) {
std::cerr << "(" << t.begin() << "," << t.end() << ") ";
}
std::cerr << std::endl;
}
const size_t dim0 = p.second.dim(0);
if (r.size() > 1) {
std::vector<poplar::Tensor> tensors;
for (const auto &t : r) {
tensors.emplace_back(p.second.slice({0, t.begin()}, {dim0, t.end()}));
}
graph.connect(vtx[p.first], poplar::concat(tensors));
} else {
const auto &interval = *r.begin();
poplar::Tensor dest =
p.second.slice({0, interval.begin()}, {dim0, interval.end()});
graph.connect(vtx[p.first], dest);
}
}
for (auto &p : workers) {
graph.connect(vtx[p.first], p.second[index][j]);
}
graph.setPerfEstimate(vtx, r.size()); // wrong ...
graph.setTileMapping(vtx, tileNumber);
++j;
}
}
void mapVertex(poplar::Graph &graph,
const std::unordered_map<std::string, poplar::Tensor> &flat,
const std::unordered_map<std::string, poplar::Tensor> &full,
const std::unordered_map<std::string, poplar::Tensor> &indices,
const std::unordered_map<std::string, poplar::Tensor> &tiles,
const std::unordered_map<std::string, poplar::Tensor> &workers,
poplar::Type elementType, poplar::ComputeSet &computeSet,
const std::string &vertexName,
const std::vector<std::vector<poplar::Interval>> &mapping) {
std::unordered_map<std::string, poplar::Tensor> flatten;
for (auto &p : flat) {
flatten.insert({p.first, p.second.flatten()});
}
const auto &target = graph.getTarget();
const auto vectorWidth = target.getVectorWidth(elementType);
const auto splitSize =
std::max<uint32_t>(vectorWidth, target.getAtomicStoreGranularity());
const auto numTiles = target.getTilesPerIPU();
size_t index = 0;
for (size_t i = 0; i < numTiles; ++i) {
auto ®ions = mapping[i];
if (regions.size() > 0)
mapTileVertex(graph, flatten, full, indices, tiles, workers, computeSet,
vertexName, regions, index++, i, splitSize);
}
}
void maplosses(poplar::Graph &graph, poplar::program::Sequence &program,
const poplar::Tensor &log_probs, const poplar::Tensor &log_alpha,
const poplar::Tensor &input_lengths,
const poplar::Tensor &label_lengths, poplar::Tensor &losses) {
size_t batch_size = log_probs.dim(0);
size_t U = log_probs.dim(2);
auto probs = log_probs.dimShuffle({3, 0, 2, 1})[0];
auto alpha = log_alpha.dimShuffle({0, 2, 1});
auto losses_ =
graph.addVariable(log_alpha.elementType(), {batch_size, U}, "map_losses");
poputil::mapTensorLinearly(graph, losses_, 1, 1);
poplar::ComputeSet computeSet = graph.addComputeSet("alphaLoss");
for (size_t i = 0; i < batch_size; ++i) {
for (int u = 0; u < static_cast<int>(U); ++u) {
poplar::Tensor uT =
graph.addConstant(poplar::INT, {}, poplar::ArrayRef<int>({u}));
graph.setTileMapping(uT, 0);
poplar::VertexRef vtx = graph.addVertex(
computeSet,
poputil::templateVertex("MapLossVertex", probs.elementType()));
graph.connect(vtx["input_len"], input_lengths[i]);
graph.connect(vtx["label_len"], label_lengths[i]);
graph.connect(vtx["alphas"], alpha[i][u]);
graph.connect(vtx["probs"], probs[i][u]);
graph.connect(vtx["out"], losses_[i][u]);
graph.connect(vtx["u"], uT);
graph.setPerfEstimate(vtx, 1);
graph.setTileMapping(vtx, getTile(graph, losses_[i][u]));
}
}
program.add(poplar::program::Execute(computeSet));
popops::ReduceParams params{popops::Operation::MAX};
popops::reduceWithOutput(graph, losses_, losses, {1}, params, program);
}
poplar::Tensor losses(poplar::Graph &graph, poplar::program::Sequence &program,
const poplar::Tensor &log_beta) {
return popops::neg(graph, log_beta.dimShuffle({1, 2, 0})[0][0], program,
"NegLoss");
}
void initializeTensor(poplar::Graph &graph, poplar::program::Sequence &program,
poplar::Tensor &t, float value) {
poplar::Tensor v =
graph.addConstant(t.elementType(), {1}, poplar::ArrayRef<float>({value}));
graph.setTileMapping(v, 1);
program.add(poplar::program::Copy(
v.broadcast(t.numElements(), 0).reshape(t.shape()), t));
}
void grads(poplar::Graph &graph, poplar::program::Sequence &program,
const poplar::Tensor &log_probs, const poplar::Tensor &input_lengths,
const poplar::Tensor &label_lengths, const poplar::Tensor &alphas,
const poplar::Tensor &betas, const poplar::Tensor &losses,
poplar::Tensor &compactedGrads) {
size_t batch_size = log_probs.dim(0);
size_t maxT = log_probs.dim(1);
size_t maxU = log_probs.dim(2);
initializeTensor(graph, program, compactedGrads, 0.0f);
poplar::ComputeSet computeSet = graph.addComputeSet("gradients");
for (size_t t = 0; t < maxT; t++) {
for (size_t u = 0; u < maxU; u++) {
for (size_t i = 0; i < batch_size; ++i) {
if (t < maxT - 1) {
auto vtx =
connectVertex(graph, computeSet,
poputil::templateVertex("GradientsTVertex",
log_probs.elementType()),
{{"out", compactedGrads[i][t][u][0]},
{"prob", log_probs[i][t][u][0]},
{"loss", losses[i]},
{"alpha_T_U", alphas[i][t][u]},
{"beta_T1_U", betas[i][t + 1][u]},
{"label_len", label_lengths[i]},
{"input_len", input_lengths[i]}},
getTile(graph, compactedGrads[i][t][u][0]));
graph.setInitialValue(vtx["u"], u);
graph.setInitialValue(vtx["t"], t);
} else {
auto vtx =
connectVertex(graph, computeSet,
poputil::templateVertex("Gradients0Vertex",
log_probs.elementType()),
{{"out", compactedGrads[i][t][u][0]},
{"prob", log_probs[i][t][u][0]},
{"loss", losses[i]},
{"alpha_T_U", alphas[i][t][u]},
{"label_len", label_lengths[i]},
{"input_len", input_lengths[i]}},
getTile(graph, compactedGrads[i][t][u][0]));
graph.setInitialValue(vtx["u"], u);
graph.setInitialValue(vtx["t"], t);
}
if (u < maxU - 1) {
auto vtx =
connectVertex(graph, computeSet,
poputil::templateVertex("GradientsUVertexCompact",
log_probs.elementType()),
{{"out", compactedGrads[i][t][u][1]},
{"prob", log_probs[i][t][u][1]},
{"loss", losses[i]},
{"alpha_T_U", alphas[i][t][u]},
{"beta_T_U1", betas[i][t][u + 1]},
{"label_len", label_lengths[i]},
{"input_len", input_lengths[i]}},
getTile(graph, compactedGrads[i][t][u][1]));
graph.setInitialValue(vtx["u"], u);
graph.setInitialValue(vtx["t"], t);
}
}
}
}
program.add(poplar::program::Execute(computeSet));
}
void computeBetaSlice(poplar::Graph &graph, size_t start, size_t end, size_t tp,
size_t batch_size, size_t U, size_t T,
const poplar::Tensor &log_probs,
const poplar::Tensor &input_lengths,
const poplar::Tensor &label_lengths,
poplar::Tensor &log_beta,
poplar::ComputeSet &computeSet) {
for (size_t z = start; z <= end; z++) { // this loop is parallel
size_t u = z;
size_t t = tp - z;
if (t == T - 1) {
if (u == U - 1) {
for (size_t i = 0; i < batch_size; ++i) {
auto out = log_beta[i][t][u];
size_t tile = getTile(graph, out);
auto vtx = connectVertex(
graph, computeSet,
poputil::templateVertex("BetaTUVertex", log_probs.elementType()),
{{"out", out},
{"label_len", label_lengths[i]},
{"input_len", input_lengths[i]},
{"prob_0", log_probs[i][t][u][0]}},
tile);
graph.setInitialValue(vtx["u"], u);
graph.setInitialValue(vtx["t"], t);
}
} else {
for (size_t i = 0; i < batch_size; ++i) {
auto out = log_beta[i][t][u];
size_t tile = getTile(graph, out);
auto vtx =
connectVertex(graph, computeSet,
poputil::templateVertex("BetaTVertexCompact",
log_probs.elementType()),
{{"out", out},
{"label_len", label_lengths[i]},
{"input_len", input_lengths[i]},
{"beta_T_U1", log_beta[i][t][u + 1]},
{"probs_T_U", log_probs[i][t][u]}},
tile);
graph.setInitialValue(vtx["u"], u);
graph.setInitialValue(vtx["t"], t);
}
}
} else {
if (u == U - 1) {
for (size_t i = 0; i < batch_size; ++i) {
auto out = log_beta[i][t][u];
size_t tile = getTile(graph, out);
auto vtx = connectVertex(
graph, computeSet,
poputil::templateVertex("BetaUVertex", log_probs.elementType()),
{{"out", out},
{"label_len", label_lengths[i]},
{"input_len", input_lengths[i]},
{"beta_T1_U", log_beta[i][t + 1][u]},
{"prob_0", log_probs[i][t][u][0]}},
tile);
graph.setInitialValue(vtx["u"], u);
graph.setInitialValue(vtx["t"], t);
}
} else {
for (size_t i = 0; i < batch_size; ++i) {
auto out = log_beta[i][t][u];
size_t tile = getTile(graph, out);
auto vtx =
connectVertex(graph, computeSet,
poputil::templateVertex("BetaVertexCompact",
log_probs.elementType()),
{{"out", out},
{"label_len", label_lengths[i]},
{"input_len", input_lengths[i]},
{"beta_T1_U", log_beta[i][t + 1][u]},
{"beta_T_U1", log_beta[i][t][u + 1]},
{"probs_T_U", log_probs[i][t][u]}},
tile);
graph.setInitialValue(vtx["u"], u);
graph.setInitialValue(vtx["t"], t);
}
}
}
}
}
float infinity(poplar::Type t) {
if (t == poplar::FLOAT)
return -std::numeric_limits<float>::infinity();
return -65504.0f;
}
void beta(poplar::Graph &graph, poplar::program::Sequence &program,
const poplar::Tensor &log_probs, const poplar::Tensor &input_lengths,
const poplar::Tensor &label_lengths, poplar::Tensor &log_beta) {
size_t batch_size = log_probs.dim(0);
size_t maxT = log_probs.dim(1);
size_t maxU = log_probs.dim(2);
size_t U = maxU;
size_t T = maxT;
auto probs_0 = log_probs.dimShuffle({3, 0, 1, 2})[0];
initializeTensor(graph, program, log_beta, infinity(log_beta.elementType()));
for (int tp = T + U - 2; tp >= 0; --tp) {
poplar::ComputeSet computeSet =
graph.addComputeSet("beta" + std::to_string(tp));
size_t start = size_t(std::max(tp - int(T) + 1, 0));
size_t end = std::min(U - 1, size_t(tp)); // inclusive end
computeBetaSlice(graph, start, end, tp, batch_size, U, T, log_probs,
input_lengths, label_lengths, log_beta, computeSet);
program.add(poplar::program::Execute(computeSet));
}
}
void computeAlphaSlice(poplar::Graph &graph, size_t start, size_t end,
size_t tp, size_t batch_size,
const poplar::Tensor &log_probs,
const poplar::Tensor &input_lengths,
const poplar::Tensor &label_lengths,
poplar::Tensor &log_alpha,
poplar::ComputeSet &computeSet) {
for (size_t z = start; z <= end; z++) { // this loop is parallel
size_t u = z;
size_t t = tp - z;
for (size_t i = 0; i < batch_size; ++i) {
auto out = log_alpha[i][t][u];
size_t tile = getTile(graph, out);
if (t == 0) {
if (u == 0) {
connectVertex(
graph, computeSet,
poputil::templateVertex("AlphaZeroVertex", out.elementType()),
{{"out", out}}, tile);
} else {
auto alpha = log_alpha[i][0][u - 1];
auto p = log_probs[i][0][u - 1][1];
auto vtx = connectVertex(
graph, computeSet,
poputil::templateVertex("AlphaUVertex", p.elementType()),
{{"out", out},
{"alpha", alpha},
{"prob", p},
{"label_len", label_lengths[i]}},
tile);
graph.setInitialValue(vtx["u"], u);
}
} else {
if (u == 0) {
auto alpha = log_alpha[i][t - 1][0];
auto p = log_probs[i][t - 1][0][0];
auto vtx = connectVertex(
graph, computeSet,
poputil::templateVertex("AlphaT0Vertex", p.elementType()),
{{"out", out},
{"alpha", alpha},
{"prob", p},
{"input_len", input_lengths[i]}},
tile);
graph.setInitialValue(vtx["t"], t);
} else {
auto alpha1 = log_alpha[i][t - 1][u];
auto p1 = log_probs[i][t - 1][u][0];
auto alpha2 = log_alpha[i][t][u - 1];
auto p2 = log_probs[i][t][u - 1][1]; // vector[label]
connectVertex(
graph, computeSet,
// should check that u <=
// label_len and t < input_len
poputil::templateVertex("AlphaVertexCompact", p1.elementType()),
{{"out", out},
{"alpha_1", alpha1},
{"alpha_2", alpha2},
{"prob_1", p1},
{"prob_2", p2}},
tile);
}
}
}
}
}
void alpha(poplar::Graph &graph, poplar::program::Sequence &program,
const poplar::Tensor &log_probs, const poplar::Tensor &input_lengths,
const poplar::Tensor &label_lengths, poplar::Tensor &log_alpha) {
size_t batch_size = log_probs.dim(0);
size_t maxT = log_probs.dim(1);
size_t maxU = log_probs.dim(2);
size_t U = maxU;
size_t T = maxT;
initializeTensor(graph, program, log_alpha,
infinity(log_alpha.elementType()));
for (size_t tp = 0; tp < T + U - 1; tp++) {
size_t start = size_t(std::max(int(tp) - int(T) + 1, 0));
size_t end = std::min(U - 1, tp); // inclusive end
poplar::ComputeSet computeSet =
graph.addComputeSet("alpha" + std::to_string(tp));
computeAlphaSlice(graph, start, end, tp, batch_size, log_probs,
input_lengths, label_lengths, log_alpha, computeSet);
program.add(poplar::program::Execute(computeSet));
}
}
void alpha_beta(poplar::Graph &graph, poplar::program::Sequence &program,
const poplar::Tensor &log_probs,
const poplar::Tensor &input_lengths,
const poplar::Tensor &label_lengths, poplar::Tensor &log_alpha,
poplar::Tensor &log_beta) {
size_t batch_size = log_probs.dim(0);
size_t maxT = log_probs.dim(1);
size_t maxU = log_probs.dim(2);
size_t U = maxU;
size_t T = maxT;
initializeTensor(graph, program, log_alpha,
infinity(log_alpha.elementType()));
initializeTensor(graph, program, log_beta, infinity(log_beta.elementType()));
auto probs_0 = log_probs.dimShuffle({3, 0, 1, 2})[0];
for (size_t tpA = 0; tpA < T + U - 1; tpA++) {
size_t tpB = T + U - 2 - tpA;
size_t startA = size_t(std::max(int(tpA) - int(T) + 1, 0));
size_t endA = std::min(U - 1, tpA); // inclusive end
poplar::ComputeSet computeSet =
graph.addComputeSet("alpha_beta" + std::to_string(tpA));
size_t startB = size_t(std::max(int(tpB) - int(T) + 1, 0));
size_t endB = std::min(U - 1, tpB); // inclusive end
computeBetaSlice(graph, startB, endB, tpB, batch_size, U, T, log_probs,
input_lengths, label_lengths, log_beta, computeSet);
computeAlphaSlice(graph, startA, endA, tpA, batch_size, log_probs,
input_lengths, label_lengths, log_alpha, computeSet);
program.add(poplar::program::Execute(computeSet));
}
}
void compactProbs(poplar::Graph &graph, poplar::program::Sequence &program,
const poplar::Tensor &log_probs,
poplar::Tensor &compacted_probs, const poplar::Tensor &labels,
const poplar::Tensor &label_lengths) {
size_t batch_size = log_probs.dim(0);
size_t maxT = log_probs.dim(1);
size_t maxU = log_probs.dim(2);
initializeTensor(graph, program, compacted_probs,
infinity(compacted_probs.elementType()));
poplar::ComputeSet computeSet = graph.addComputeSet("compaction");
for (size_t t = 0; t < maxT; ++t) {
for (size_t u = 0; u < maxU; ++u) {
for (size_t i = 0; i < batch_size; ++i) {
const size_t tile = getTile(graph, log_probs[i][t][u]);
connectVertex(graph, computeSet,
poputil::templateVertex("CopyVertex",
log_probs.elementType(),
compacted_probs.elementType()),
{{"out", compacted_probs[i][t][u][0]},
{"in", log_probs[i][t][u][0]}},
tile);
if (u < maxU - 1) {
auto vtx =
connectVertex(graph, computeSet,
poputil::templateVertex("CopyIndexVertex",
log_probs.elementType()),
{{"out", compacted_probs[i][t][u][1]},
{"in", log_probs[i][t][u]},
{"label_len", label_lengths[i]},
{"label", labels[i][u]}},
tile);
graph.setInitialValue(vtx["u"], u);
}
}
}
}
program.add(poplar::program::Execute(computeSet));
}
poplar::Tensor expandGradients(poplar::Graph &graph,
poplar::program::Sequence &program,
const poplar::Tensor &compacted_gradients,
const poplar::Tensor &log_probs,
const poplar::Tensor &labels,
const poplar::Tensor &label_lengths) {
size_t batch_size = log_probs.dim(0);
size_t maxT = log_probs.dim(1);
size_t maxU = log_probs.dim(2);
size_t alphabet = log_probs.dim(3);
poplar::Tensor gradients = graph.addVariable(
log_probs.elementType(), {batch_size, maxT, maxU, alphabet}, "Gradients");
poputil::mapTensorLinearly(graph, gradients, 1, alphabet);
poplar::Tensor compactedGradientsFinal =
graph.addVariable(compacted_gradients.elementType(),
{batch_size, maxT, maxU, 2}, "compactedGradients_");
poputil::mapTensorLinearly(graph, compactedGradientsFinal, 1, 2);
program.add(
poplar::program::Copy(compacted_gradients, compactedGradientsFinal));
program.add(poplar::program::WriteUndef(compacted_gradients));
initializeTensor(graph, program, gradients, 0.0f);
poplar::ComputeSet computeSet = graph.addComputeSet("expansion");
for (size_t t = 0; t < maxT; ++t) {
for (size_t u = 0; u < maxU; ++u) {
poplar::Tensor uT =
graph.addConstant(poplar::UNSIGNED_INT, {},
poplar::ArrayRef<unsigned int>({(unsigned int)u}));
graph.setTileMapping(uT, 1);
for (size_t i = 0; i < batch_size; ++i) {
const size_t tile = getTile(graph, log_probs[i][t][u]);
connectVertex(graph, computeSet,
poputil::templateVertex(
"CopyVertex", compactedGradientsFinal.elementType(),
gradients.elementType()),
{{"out", gradients[i][t][u][0]},
{"in", compactedGradientsFinal[i][t][u][0]}},
tile);
if (u < maxU - 1) {
auto vtx = connectVertex(
graph, computeSet,
poputil::templateVertex("CopyExpandVertex",
compactedGradientsFinal.elementType(),
gradients.elementType()),
{{"out", gradients[i][t][u].slice({1, alphabet})},
{"in", compactedGradientsFinal[i][t][u][1]},
{"label_len", label_lengths[i]},
{"label", labels[i][u]}},
tile);
graph.setInitialValue(vtx["u"], u);
}
}
}
}
program.add(poplar::program::Execute(computeSet));
return gradients;
}
| 42.915078 | 80 | 0.541434 | [
"shape",
"vector"
] |
56451805c2b3c75cb27ff4e5a5593e0a1d1f79f8 | 8,382 | cpp | C++ | src/pke/lib/bfvrns-poly-impl.cpp | tony-blake/Pallisade | b7764a4f9f836fe9adefb7bb0ee4825b38c72398 | [
"BSD-2-Clause"
] | null | null | null | src/pke/lib/bfvrns-poly-impl.cpp | tony-blake/Pallisade | b7764a4f9f836fe9adefb7bb0ee4825b38c72398 | [
"BSD-2-Clause"
] | null | null | null | src/pke/lib/bfvrns-poly-impl.cpp | tony-blake/Pallisade | b7764a4f9f836fe9adefb7bb0ee4825b38c72398 | [
"BSD-2-Clause"
] | null | null | null | /*
* @file bfvrns-poly-impl.cpp - poly implementation for the BFVrns scheme.
* @author TPOC: palisade@njit.edu
*
* @copyright Copyright (c) 2017, New Jersey Institute of Technology (NJIT)
* 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.
* 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.
*
*/
#include "cryptocontext.h"
#include "bfvrns.cpp"
namespace lbcrypto {
#define NOPOLY \
std::string errMsg = "BFVrns does not support Poly. Use DCRTPoly instead."; \
throw std::runtime_error(errMsg);
#define NONATIVEPOLY \
std::string errMsg = "BFVrns does not support NativePoly. Use DCRTPoly instead."; \
throw std::runtime_error(errMsg);
template <>
LPCryptoParametersBFVrns<Poly>::LPCryptoParametersBFVrns(){
NOPOLY
}
template <>
LPCryptoParametersBFVrns<NativePoly>::LPCryptoParametersBFVrns(){
NONATIVEPOLY
}
template <>
LPCryptoParametersBFVrns<Poly>::LPCryptoParametersBFVrns(const LPCryptoParametersBFVrns &rhs){
NOPOLY
}
template <>
LPCryptoParametersBFVrns<NativePoly>::LPCryptoParametersBFVrns(const LPCryptoParametersBFVrns &rhs){
NONATIVEPOLY
}
template <>
LPCryptoParametersBFVrns<Poly>::LPCryptoParametersBFVrns(shared_ptr<typename Poly::Params> params,
const PlaintextModulus &plaintextModulus,
float distributionParameter,
float assuranceMeasure,
float securityLevel,
usint relinWindow,
MODE mode,
int depth,
int maxDepth){
NOPOLY
}
template <>
LPCryptoParametersBFVrns<NativePoly>::LPCryptoParametersBFVrns(shared_ptr<typename NativePoly::Params> params,
const PlaintextModulus &plaintextModulus,
float distributionParameter,
float assuranceMeasure,
float securityLevel,
usint relinWindow,
MODE mode,
int depth,
int maxDepth){
NONATIVEPOLY
}
template <>
LPCryptoParametersBFVrns<Poly>::LPCryptoParametersBFVrns(shared_ptr<typename Poly::Params> params,
EncodingParams encodingParams,
float distributionParameter,
float assuranceMeasure,
float securityLevel,
usint relinWindow,
MODE mode,
int depth,
int maxDepth){
NOPOLY
}
template <>
LPCryptoParametersBFVrns<NativePoly>::LPCryptoParametersBFVrns(shared_ptr<typename NativePoly::Params> params,
EncodingParams encodingParams,
float distributionParameter,
float assuranceMeasure,
float securityLevel,
usint relinWindow,
MODE mode,
int depth,
int maxDepth){
NONATIVEPOLY
}
// Parameter generation for BFV-RNS
template <>
bool LPCryptoParametersBFVrns<Poly>::PrecomputeCRTTables(){
NOPOLY
}
template <>
bool LPCryptoParametersBFVrns<NativePoly>::PrecomputeCRTTables(){
NONATIVEPOLY
}
template <>
LPPublicKeyEncryptionSchemeBFVrns<Poly>::LPPublicKeyEncryptionSchemeBFVrns(){
NOPOLY
}
template <>
LPPublicKeyEncryptionSchemeBFVrns<NativePoly>::LPPublicKeyEncryptionSchemeBFVrns(){
NONATIVEPOLY
}
template <>
bool LPAlgorithmParamsGenBFVrns<Poly>::ParamsGen(shared_ptr<LPCryptoParameters<Poly>> cryptoParams, int32_t evalAddCount,
int32_t evalMultCount, int32_t keySwitchCount) const
{
NOPOLY
}
template <>
bool LPAlgorithmParamsGenBFVrns<NativePoly>::ParamsGen(shared_ptr<LPCryptoParameters<NativePoly>> cryptoParams, int32_t evalAddCount,
int32_t evalMultCount, int32_t keySwitchCount) const
{
NONATIVEPOLY
}
template <>
Ciphertext<Poly> LPAlgorithmBFVrns<Poly>::Encrypt(const LPPublicKey<Poly> publicKey,
Poly ptxt) const
{
NOPOLY
}
template <>
Ciphertext<NativePoly> LPAlgorithmBFVrns<NativePoly>::Encrypt(const LPPublicKey<NativePoly> publicKey,
NativePoly ptxt) const
{
NONATIVEPOLY
}
template <>
DecryptResult LPAlgorithmBFVrns<Poly>::Decrypt(const LPPrivateKey<Poly> privateKey,
const Ciphertext<Poly> ciphertext,
NativePoly *plaintext) const
{
NOPOLY
}
template <>
DecryptResult LPAlgorithmBFVrns<NativePoly>::Decrypt(const LPPrivateKey<NativePoly> privateKey,
const Ciphertext<NativePoly> ciphertext,
NativePoly *plaintext) const
{
NONATIVEPOLY
}
template <>
Ciphertext<Poly> LPAlgorithmBFVrns<Poly>::Encrypt(const LPPrivateKey<Poly> privateKey,
Poly ptxt) const
{
NOPOLY
}
template <>
Ciphertext<NativePoly> LPAlgorithmBFVrns<NativePoly>::Encrypt(const LPPrivateKey<NativePoly> privateKey,
NativePoly ptxt) const
{
NONATIVEPOLY
}
template <>
Ciphertext<Poly> LPAlgorithmSHEBFVrns<Poly>::EvalMult(const Ciphertext<Poly> ciphertext1,
const Ciphertext<Poly> ciphertext2) const {
NOPOLY
}
template <>
Ciphertext<NativePoly> LPAlgorithmSHEBFVrns<NativePoly>::EvalMult(const Ciphertext<NativePoly> ciphertext1,
const Ciphertext<NativePoly> ciphertext2) const {
NONATIVEPOLY
}
template <>
Ciphertext<Poly> LPAlgorithmSHEBFVrns<Poly>::EvalAdd(const Ciphertext<Poly> ct,
const Plaintext pt) const{
NOPOLY
}
template <>
Ciphertext<NativePoly> LPAlgorithmSHEBFVrns<NativePoly>::EvalAdd(const Ciphertext<NativePoly> ct,
const Plaintext pt) const{
NONATIVEPOLY
}
template <>
Ciphertext<Poly> LPAlgorithmSHEBFVrns<Poly>::EvalSub(const Ciphertext<Poly> ct,
const Plaintext pt) const{
NOPOLY
}
template <>
Ciphertext<NativePoly> LPAlgorithmSHEBFVrns<NativePoly>::EvalSub(const Ciphertext<NativePoly> ct,
const Plaintext pt) const{
NONATIVEPOLY
}
template <>
LPEvalKey<Poly> LPAlgorithmSHEBFVrns<Poly>::KeySwitchGen(const LPPrivateKey<Poly> originalPrivateKey,
const LPPrivateKey<Poly> newPrivateKey) const {
NOPOLY
}
template <>
LPEvalKey<NativePoly> LPAlgorithmSHEBFVrns<NativePoly>::KeySwitchGen(const LPPrivateKey<NativePoly> originalPrivateKey,
const LPPrivateKey<NativePoly> newPrivateKey) const {
NONATIVEPOLY
}
template <>
Ciphertext<Poly> LPAlgorithmSHEBFVrns<Poly>::KeySwitch(const LPEvalKey<Poly> keySwitchHint,
const Ciphertext<Poly> cipherText) const{
NOPOLY
}
template <>
Ciphertext<NativePoly> LPAlgorithmSHEBFVrns<NativePoly>::KeySwitch(const LPEvalKey<NativePoly> keySwitchHint,
const Ciphertext<NativePoly> cipherText) const{
NONATIVEPOLY
}
template <>
Ciphertext<Poly> LPAlgorithmSHEBFVrns<Poly>::EvalMultAndRelinearize(const Ciphertext<Poly> ct1,
const Ciphertext<Poly> ct, const vector<LPEvalKey<Poly>> &ek) const{
NOPOLY
}
template <>
Ciphertext<NativePoly> LPAlgorithmSHEBFVrns<NativePoly>::EvalMultAndRelinearize(const Ciphertext<NativePoly> ct1,
const Ciphertext<NativePoly> ct, const vector<LPEvalKey<NativePoly>> &ek) const{
NONATIVEPOLY
}
template <>
DecryptResult LPAlgorithmMultipartyBFVrns<Poly>::MultipartyDecryptFusion(const vector<Ciphertext<Poly>>& ciphertextVec,
NativePoly *plaintext) const {
NOPOLY
}
template <>
DecryptResult LPAlgorithmMultipartyBFVrns<NativePoly>::MultipartyDecryptFusion(const vector<Ciphertext<NativePoly>>& ciphertextVec,
NativePoly *plaintext) const {
NONATIVEPOLY
}
template class LPCryptoParametersBFVrns<Poly>;
template class LPPublicKeyEncryptionSchemeBFVrns<Poly>;
template class LPAlgorithmBFVrns<Poly>;
template class LPAlgorithmSHEBFVrns<Poly>;
template class LPAlgorithmMultipartyBFVrns<Poly>;
template class LPAlgorithmParamsGenBFVrns<Poly>;
template class LPCryptoParametersBFVrns<NativePoly>;
template class LPPublicKeyEncryptionSchemeBFVrns<NativePoly>;
template class LPAlgorithmBFVrns<NativePoly>;
template class LPAlgorithmSHEBFVrns<NativePoly>;
template class LPAlgorithmMultipartyBFVrns<NativePoly>;
template class LPAlgorithmParamsGenBFVrns<NativePoly>;
}
| 28.903448 | 133 | 0.802911 | [
"vector"
] |
871f4a6c63707866daa12ffd019e2e15125c86a3 | 1,237 | hpp | C++ | src/NeuralNetworks.hpp | alpylmz/ML-Models | 04bf40f7b81e76b58f6bc8c491292a67f9c0df49 | [
"MIT"
] | 2 | 2020-06-04T16:25:53.000Z | 2020-06-04T20:27:59.000Z | src/NeuralNetworks.hpp | alpylmz/ML-Models | 04bf40f7b81e76b58f6bc8c491292a67f9c0df49 | [
"MIT"
] | null | null | null | src/NeuralNetworks.hpp | alpylmz/ML-Models | 04bf40f7b81e76b58f6bc8c491292a67f9c0df49 | [
"MIT"
] | 1 | 2020-06-04T09:00:07.000Z | 2020-06-04T09:00:07.000Z | #include "Matrix.hpp"
#include "Models.hpp"
#include <math.h>
/*TO DO:
* Stronger tests
* Much cleaner implementation with Matrix class
* Manipulation of epoch number
* = operator overloading
*/
class Neural_Networks{
private:
//holds how many unit are there in each corresponding layer
//starts from input layer to output layer
std::vector<long> layer_info;
//the first vector separates the weights according to their layers
//weights[0] consists of first layer weights
//weights[0][0] consists of first layer first neuron's weights
//be careful that output layer will have no weight
std::vector<std::vector<std::vector<double>>> weights;
double learning_rate;
std::vector<std::vector<double>> forward_propagate(std::vector<double> inputn);
void back_propagate(std::vector<double> output_deltas, std::vector<std::vector<double>> activation);
public:
//This constructor takes the number of layers
Neural_Networks(std::vector<long> layers,double learningrate);
std::vector<double> Predict(std::vector<double> input);
void Fit(std::vector<std::vector<double>> data,std::vector<double> ans);
}; | 29.452381 | 108 | 0.683104 | [
"vector"
] |
87328170126fcee552b4287d4f24b75474aed9b3 | 12,994 | cpp | C++ | LDPC.cpp | mtahernia/Non-Binary-GF-q-LDPC | a85f71830d295ab177f23be900ea8f51d4ae0cf7 | [
"BSD-3-Clause"
] | 1 | 2021-11-08T08:02:11.000Z | 2021-11-08T08:02:11.000Z | LDPC.cpp | mtahernia/Non-Binary-GF-q-LDPC | a85f71830d295ab177f23be900ea8f51d4ae0cf7 | [
"BSD-3-Clause"
] | null | null | null | LDPC.cpp | mtahernia/Non-Binary-GF-q-LDPC | a85f71830d295ab177f23be900ea8f51d4ae0cf7 | [
"BSD-3-Clause"
] | null | null | null | /*
* LDPC.cpp
*
* Created on: 22 Dec, 2014
* Author: Mehrdad Tahernia
* User: mehrdad
*/
#include <cstdlib>
#include "Report.h"
#include "Channel.h"
#include "Encoding.h"
#include "Utils_2.h" // vector, array
#include "Variable_Node.h"
#include "Check_Node.h"
#include "Edge.h"
#include "LDPC.h"
/**************************************************************
*
* LDPC Constructors
*
**************************************************************/
void LDPC_Code::GetFromFile(std::ifstream &file) {
char dummy_buffer[10000];
int rhos_index, lambdas_index;
rhos_index = lambdas_index = 0;
bool GotMapInUse = false;
//----------------------------------------------
// Go over file
//----------------------------------------------
while (!file.eof()) {
switch (file.peek()) {
case 'r': // Read Rhos from file
if (rhos_index >= MAX_RHOS) {
cout << "LDPC_Code::GetFromFile: MAX_RHOS exceeded\n";
exit(1);
}
file >> rho_degs[rhos_index] >> rho_wts[rhos_index];
file.getline(dummy_buffer, sizeof(dummy_buffer)); // reach EoL
rhos_index++;
break;
case 'l': // Read Lambdas From File
if (lambdas_index >= MAX_LAMBDAS) {
cout << "LDPC_Code::GetFromFile: MAX_LAMBDAS exceeded\n";
exit(1);
}
file >> lambda_degs[lambdas_index] >> lambda_wts[lambdas_index];
lambdas_index++;
file.getline(dummy_buffer, sizeof(dummy_buffer)); // reach EoL
break;
case 'm': // Read mapping from file
GotMapInUse = true;
MapInUse.GetFromFile(file);
// Initialize GF(q)
GFq::Initialize(MapInUse.GetQ());
break;
default:
file.getline(dummy_buffer, sizeof(dummy_buffer)); // Skip line and go to beginning of the next line if nothing matches r l m
}
}
if (!GotMapInUse) {
cout << "mapping not defined\n";
exit(1);
}
rho_degs[rhos_index] = -1;
rho_wts[rhos_index] = -1;
lambda_degs[lambdas_index] = -1;
lambda_wts[lambdas_index] = -1;
}
// Main Constructor of LDPC_Code class
LDPC_Code::LDPC_Code(std::ifstream &File, int p_BlockLength, channel *p_Channel) :
BlockLength(p_BlockLength), Channel(p_Channel) {
GetFromFile(File);
}
/*************************************************************************
*
* Calc rate
*
*************************************************************************/
double LDPC_Code::sigma_lambda() {
double n;
n = 0;
for (int i = 0; lambda_degs[i] != -1; i++)
n += lambda_wts[i] / lambda_degs[i];
return n;
}
double LDPC_Code::sigma_rho() {
double m;
m = 0;
for (int i = 0; rho_degs[i] != -1; i++)
m += rho_wts[i] / rho_degs[i];
return m;
}
double LDPC_Code::Calc_Symbol_Rate() {
double SigmaLambda = sigma_lambda();
double SigmaRho = sigma_rho();
return 1 - SigmaRho / SigmaLambda;
}
/************************************************************************
*
* LDPC code
*
************************************************************************/
/**
* Initialize Variable nodes with channel output
*/
void LDPC_Code::Init_Messages(vector &ChannelOutput) {
if (ChannelOutput.GetSize() != Variables.GetLength()) {
cout << "LDPC_Code::Init_Messages: Incompatible sizes\n";
exit(1);
}
for (int i = 0; i < Variables.GetLength(); i++)
Variables[i].Initialize(*Channel, ChannelOutput[i]);
}
void LDPC_Code::GetZeroCodeword(vector &Codeword) {
Codeword.Allocate(Variables.GetLength());
for (int i = 0; i < Variables.GetLength(); i++)
Codeword[i] = Variables[i].GetZeroSignal();
}
void LDPC_Code::GetCodeword(vector &Codeword) {
Codeword.Allocate(Variables.GetLength());
for (int i = 0; i < Variables.GetLength(); i++)
Codeword[i] = Variables[i].GetSignal();
}
void LDPC_Code::Leftbound_Iteration() {
for (int i = 0; i < Checks.GetLength(); i++)
Checks[i].CalcAllLeftboundMessages();
}
void LDPC_Code::Rightbound_Iteration() {
for (int i = 0; i < Variables.GetLength(); i++)
Variables[i].CalcAllRightboundMessages();
}
void LDPC_Code::FinalIteration() {
for (int i = 0; i < Variables.GetLength(); i++)
Variables[i].CalcFinalMessage();
}
double LDPC_Code::Calc_Symbol_Error_Rate() {
double acc_correct = 0;
for (int i = 0; i < Variables.GetLength(); i++)
// acc_correct += Variables[i].FinalEstimate.Decision().IsZero();
acc_correct += Variables[i].DecSymbol == Variables[i].Symbol;
return 1.0 - acc_correct / (double) Variables.GetLength();
}
double LDPC_Code::Calc_Rightbound_Symbol_Error_Rate() {
double acc_correct = 0;
for (int i = 0; i < Graph.E; i++)
acc_correct += Graph.edges[i].RightBoundMessage.Decision().IsZero();
return 1.0 - acc_correct / Graph.E;
}
double LDPC_Code::Belief_Propagation_Decoder(int Count_Iterations) {
static char buffer[500];
double Func_RC = 0; //=0 is for initialization of the variable so the compiler won't give warnings
double LastMin = INF;
int CountIncreaseIterations = 0;
cout << "Initial symbol error rate = " << Calc_Symbol_Error_Rate() << "\n";
for (int i = 0; i < Count_Iterations; i++) {
Leftbound_Iteration();
Rightbound_Iteration();
// Func_RC = Calc_Rightbound_Symbol_Error_Rate(); //FIXME: Not modified for PNC yet
// sprintf(buffer, "%d: Rightbound SER = %1.10f, %s", i + 1, Func_RC,CharTime());
Func_RC = Calc_Symbol_Error_Rate();
// sprintf(buffer, "%d: SER = %1.10f, %s", i + 1, Func_RC,CharTime());
// cout << buffer;
cout << ".";
// Stop when Func_RC doesn't fall for some consecutive iterations
if (Func_RC < LastMin) {
LastMin = Func_RC;
CountIncreaseIterations = 0;
} else {
CountIncreaseIterations++;
if (CountIncreaseIterations > 50){
sprintf(buffer, "\n%d: SER = %1.10f, %s\n", i + 1, Func_RC,CharTime());
cout << buffer;
break;
}
}
if (Func_RC < 1e-7){
sprintf(buffer, "\n%d: SER = %1.10f, %s\n", i + 1, Func_RC,CharTime());
cout << buffer;
break;
}
}
return Func_RC;
}
/*********************************************************************************
*
* Encoder
*
*********************************************************************************/
void LDPC_Code::GenerateRandomSystematic() {
//------------------------------------------------------
// Randomly select values for systematic digits
//------------------------------------------------------
// for (int i = 0; i < Systematic; i++)
// cout << "Var Nodes: " << Variables.GetLength() << "\n";
for (int i = 0; i < Variables.GetLength(); i++)
Variables[i].Symbol.val = uniform_random(GFq::q);
}
void LDPC_Code::Get_Symbols(GFq *Symbols)
{
for (int i = 0; i < Variables.GetLength(); i++)
*(Symbols+i) = Variables[i].Symbol;
}
void LDPC_Code::Set_Symbols(GFq *Symbols)
{
for (int i = 0; i < Variables.GetLength(); i++)
Variables[i].Symbol = *(Symbols+i);
}
void LDPC_Code::Encode() {
int FirstVarOfTriangle = Systematic + Gap;
//------------------------------------------------------
// Determine gap symbols
//------------------------------------------------------
if (Gap > 0) {
// Multiply systematic vector multiplied by GapMatrix
matrix Vals(Gap); // a column vector for results
for (int i = 0; i < Gap; i++) {
Vals[i] = 0;
for (int j = 0; j < Systematic; j++)
Vals[i] += Variables[j].Symbol * GapMatrix.Element(i, j);
}
matrix GapVars(Gap);
GapVars = MinusPhiInverse * Vals;
// place vals
for (int i = 0; i < Gap; i++)
Variables[Systematic + i].Symbol = GapVars[i];
}
//------------------------------------------------------
// Determine all the rest
//------------------------------------------------------
for (int i = 0; i < Triangle; i++) {
// Calculate value of check node without symbol
Variables[FirstVarOfTriangle + i].Symbol = 0;
GFq label = Checks[i].Element(FirstVarOfTriangle + i);
Variables[FirstVarOfTriangle + i].Symbol = (Checks[i].Value() / label).Minus();
}
}
int LDPC_Code::GenerateEncoder_WithoutGap() {
//------------------------------------------------------
// Approximate lower triangularize
//------------------------------------------------------
// Init
Variables.Init(Graph.variable_nodes, Graph.N);
Checks.Init(Graph.check_nodes, Graph.M);
UrbankeAlgorithmAH(/* columns */Checks, /* rows */Variables);
// Reverse because we have made checks the columns and variables the rows
Variables.Reverse();
Checks.Reverse();
// Determine values
Systematic = Variables.GetLength() - Checks.GetLength();
Gap = Checks.Gap;
Triangle = Variables.GetLength() - Systematic - Gap;
int FirstCheckOfGap = Checks.GetLength() - Gap;
//------------------------------------------------------
// Eliminate gap check nodes
//------------------------------------------------------
if (Gap > MAX_GAP) {
cout << "GenerateEncoder_WithoutGap: Gap = " << Gap << " too big\n";
// exit(1);
return 1;
}
for (int i = FirstCheckOfGap; i < Checks.GetLength(); i++) {
Checks[i].Disconnect();
}
// Update variables
Systematic += Gap;
Gap = 0;
GapMatrix.deAllocate();
MinusPhiInverse.deAllocate();
return 0;
}
void LDPC_Code::GenerateEncoder() {
//------------------------------------------------------
// Approximate lower triangularize
//------------------------------------------------------
// Init
Variables.Init(Graph.variable_nodes, Graph.N);
Checks.Init(Graph.check_nodes, Graph.M);
UrbankeAlgorithmAH(/* columns */Checks, /* rows */Variables);
// Reverse because we have made checks the columns and variables the rows
Variables.Reverse();
Checks.Reverse();
// Determine values
Systematic = Variables.GetLength() - Checks.GetLength();
Gap = Checks.Gap;
Triangle = Variables.GetLength() - Systematic - Gap;
cout << "GenerateEncoder: Gap = " << Gap << "\n";
//ofstream bbbTemp("Temp.txt");
//for (int i = 0; i < Variables.GetLength(); i++)
// for (int j = 0; j < Variables[i].GetDegree(); j++)
// bbbTemp << Variables[i].AdjacentNode(j).GetID() << " " << i << "\n";
//bbbTemp.close();
//exit(0);
int FirstCheckOfGap = Checks.GetLength() - Gap;
int FirstVarOfTriangle = Systematic + Gap;
//------------------------------------------------------
// Handle gap
//------------------------------------------------------
// Init gap matrix
GapMatrix.Init(Gap, Variables.GetLength());
for (int i = 0; i < Gap; i++) {
//cout << FirstCheckOfGap + i << ">" << Checks[FirstCheckOfGap + i].GetID() << " " << Checks[FirstCheckOfGap + i].degree << "\n";
GapMatrix.Set(i, Checks[FirstCheckOfGap + i]);
}
//ofstream bbbTemp2("Temp.txt");
//GapMatrix.SparseOut(bbbTemp2);
//bbbTemp2.close();
//exit(0);
// Gaussian elimination
for (int j = Triangle - 1; j >= 0; j--) // column
{
// Find element appropriate matrix element
int EliminatedCol = FirstVarOfTriangle + j; // Column to be eliminated
check_node &CheckRow = Checks[j]; // j'th check should be nonzero at j'th column
GFq EliminatingRowVal = CheckRow.Element(EliminatedCol); // Value of row at column to be eliminated
for (int i = 0; i < GapMatrix.M; i++) // row of GapMatrix
{
GFq ValToBeEliminated = GapMatrix.Element(i, EliminatedCol);
if (!ValToBeEliminated.IsZero()) {
GFq Mult = (ValToBeEliminated / EliminatingRowVal).Minus();
GapMatrix.Add(i, CheckRow, Mult);
}
}
}
// obtain phi^-1
// While matrix is singular, switch columns
bool Success = false;
for (int Attempts = 0; Attempts < 10000; Attempts++) {
matrix phi = GapMatrix.Extract(Systematic, Gap); // Systematic = first col after systematic
MinusPhiInverse = phi.Inverse();
if (!MinusPhiInverse.IsNull()) // if success
{
MinusPhiInverse.MultiplyByMinusOne();
Success = true;
break;
} else { // switch columns randomly
int i1 = uniform_random(Systematic);
int i2 = uniform_random(Gap) + Systematic;
GapMatrix.SwitchColumns(i1, i2);
Variables.SwitchNodes(i1, i2);
}
}
if (!Success) {
cout
<< "Unable to find an invertible phi, maybe increase number of attempts\n";
exit(1);
}
}
double LDPC_Code::SumLambda() {
double sum = 0;
for (int i = 0; lambda_degs[i] != -1; i++)
sum += lambda_wts[i];
return sum;
}
double LDPC_Code::SumRho() {
double sum = 0;
for (int i = 0; rho_degs[i] != -1; i++)
sum += rho_wts[i];
return sum;
}
double LDPC_Code::Calc_Bit_Rate() {
return Calc_Symbol_Rate() * log((double) GFq::q) / log(2.);
}
void LDPC_Code::MakeLambdasValid() /// Make lambdas sum = 1
{
double sum = SumLambda();
for (int i = 0; lambda_degs[i] != -1; i++)
lambda_wts[i] /= sum;
}
void LDPC_Code::MakeRhosValid() /// Make rhos sum = 1
{
double sum = SumRho();
for (int i = 0; rho_degs[i] != -1; i++)
rho_wts[i] /= sum;
}
int LDPC_Code::CountLambdaDegs() {
int count;
for (count = 0; lambda_degs[count] != -1; count++)
;
return count;
}
int LDPC_Code::CountRhoDegs() {
int count;
for (count = 0; rho_degs[count] != -1; count++)
;
return count;
}
void LDPC_Code::ResetGraph() {
Graph.Reset(BlockLength, lambda_degs, lambda_wts, rho_degs, rho_wts, MapInUse);
Variables.Init(Graph.variable_nodes, Graph.N);
Checks.Init(Graph.check_nodes, Graph.M);
}
| 26.681725 | 131 | 0.583038 | [
"vector"
] |
8733a97d7b7e6de9d9c099bdc0394ae7b0ffa349 | 2,246 | hpp | C++ | src/_common/common.hpp | andry81/bittools | 6c0a87188f0cd86d44118c6fe468e121fefd2940 | [
"MIT"
] | null | null | null | src/_common/common.hpp | andry81/bittools | 6c0a87188f0cd86d44118c6fe468e121fefd2940 | [
"MIT"
] | null | null | null | src/_common/common.hpp | andry81/bittools | 6c0a87188f0cd86d44118c6fe468e121fefd2940 | [
"MIT"
] | null | null | null | #ifndef __COMMON_HPP__
#define __COMMON_HPP__
#include <windows.h>
#include <tchar.h>
#include <string>
#include <vector>
#include <limits>
#include <algorithm>
#include "std/tstring.hpp"
#include "std/tstdio.hpp"
#include "tacklelib/utility/platform.hpp"
#include "tacklelib/utility/type_traits.hpp"
#include "tacklelib/utility/addressof.hpp"
#include "tacklelib/utility/utility.hpp"
#include "tacklelib/utility/math.hpp"
#include "tacklelib/utility/locale.hpp"
#ifdef _UNICODE
# define IF_UNICODE_(x, y) x
#else
# define IF_UNICODE_(x, y) y
#endif
#define IF_UNICODE(x, y) IF_UNICODE_(x, y)
using uint_t = unsigned int;
namespace utils
{
template<class Compare, class T, class ForwardIt>
inline ForwardIt lower_bound(ForwardIt first, ForwardIt last, const T & value, Compare comp)
{
ForwardIt it;
typename std::iterator_traits<ForwardIt>::difference_type count, step;
count = std::distance(first, last);
while (count > 0) {
it = first;
step = count / 2;
std::advance(it, step);
if (comp(*it, value)) {
first = ++it;
count -= step + 1;
}
else
count = step;
}
return first;
}
template<class Compare, class T, class ForwardIt>
inline ForwardIt upper_bound(ForwardIt first, ForwardIt last, const T & value, Compare comp)
{
ForwardIt it;
typename std::iterator_traits<ForwardIt>::difference_type count, step;
count = std::distance(first, last);
while (count > 0) {
it = first;
step = count / 2;
std::advance(it, step);
if (!comp(value, *it)) {
first = ++it;
count -= step + 1;
}
else
count = step;
}
return first;
}
template<typename T, typename Pred>
inline typename std::vector<T>::iterator insert_sorted(std::vector<T> & vec, const T & value, Pred pred)
{
return vec.insert(utils::upper_bound(vec.begin(), vec.end(), value, pred), value);
}
}
#endif
| 26.116279 | 109 | 0.569012 | [
"vector"
] |
8739d49076000d4bd3472c781c81b49b353807ac | 1,757 | cpp | C++ | Contest/Contest 154/D/main.cpp | Minecodecraft/LeetCode-Minecode | 185fd6efe88d8ffcad94e581915c41502a0361a0 | [
"MIT"
] | 1 | 2021-11-19T19:58:33.000Z | 2021-11-19T19:58:33.000Z | Contest/Contest 154/D/main.cpp | Minecodecraft/LeetCode-Minecode | 185fd6efe88d8ffcad94e581915c41502a0361a0 | [
"MIT"
] | null | null | null | Contest/Contest 154/D/main.cpp | Minecodecraft/LeetCode-Minecode | 185fd6efe88d8ffcad94e581915c41502a0361a0 | [
"MIT"
] | 2 | 2021-11-26T12:47:27.000Z | 2022-01-13T16:14:46.000Z | //
// main.cpp
// D
//
// Created by 边俊林 on 2019/9/15.
// Copyright © 2019 Minecode.Link. All rights reserved.
//
#include <map>
#include <set>
#include <queue>
#include <stack>
#include <vector>
#include <cstdio>
#include <numeric>
#include <cstdlib>
#include <iostream>
#include <algorithm>
#include <unordered_map>
#include <unordered_set>
using namespace std;
/// Solution:
//
class Solution {
public:
vector<vector<int>> criticalConnections(int n, vector<vector<int>>& connections) {
vector<int> indegree (n, 0);
unordered_map<int, set<int>> mp;
for (int i = 0; i < n; ++i)
mp[i] = {};
for (int i = 0; i < connections.size(); ++i) {
vector<int> conn = connections[i];
indegree[conn[0]]++;
indegree[conn[1]]++;
mp[conn[0]].insert(conn[1]);
mp[conn[1]].insert(conn[0]);
}
queue<int> Q;
for (int i = 0; i < n; ++i)
if (indegree[i] == 1)
Q.push(i);
vector<vector<int>> res;
while (!Q.empty()) {
int idx = Q.front(); Q.pop();
if (indegree[idx] != 1) continue;
indegree[idx]--;
auto edges = mp[idx];
for (auto it = edges.begin(); it != edges.end(); ++it) {
res.push_back({idx, *it});
// clear edges
mp[*it].erase(idx);
indegree[*it]--;
if (indegree[*it] == 1)
Q.push(*it);
}
}
return res;
}
};
int main() {
Solution sol = Solution();
vector<vector<int>> conn = {
{0,1}, {1,2}, {2,0}, {1,3}
};
auto res = sol.criticalConnections(4, conn);
return 0;
}
| 23.426667 | 86 | 0.483779 | [
"vector"
] |
873b98ac2f02b793110b1f81b996368558d94130 | 1,561 | cpp | C++ | trunk/RayTracer/RayTracer/src/Image.cpp | Monster88Ra/RayTracer | 948cc707e12ef0e75266b26aaca42ee07adb6b0b | [
"MIT"
] | null | null | null | trunk/RayTracer/RayTracer/src/Image.cpp | Monster88Ra/RayTracer | 948cc707e12ef0e75266b26aaca42ee07adb6b0b | [
"MIT"
] | 1 | 2018-11-23T04:56:10.000Z | 2018-11-27T04:29:58.000Z | trunk/RayTracer/RayTracer/src/Image.cpp | Monster88Ra/RayTracer | 948cc707e12ef0e75266b26aaca42ee07adb6b0b | [
"MIT"
] | null | null | null | #include <Windows.h>
#include <sstream>
#include <cassert>
#include <limits>
#include "Image.h"
Image::Image(const std::string &fileName, const Vector2i &outputResolution):
m_pixelColors(outputResolution.y),
m_outputResolution(outputResolution),
m_fileName(fileName)
{
// Resize each vector to the amount of vertical pixels
for (auto& row : m_pixelColors)
row.resize(outputResolution.x);
}
Image::~Image()
{
}
void Image::SetPixel(const uint32_t &x, const uint32_t &y, const Color &color)
{
assert(y < m_pixelColors.capacity());
assert(x < m_pixelColors[y].capacity());
m_pixelColors[y][x] = color;
}
void Image::WriteImage()
{
// Write to a .ppm image
m_fileName += ".ppm";
std::ostringstream headerStream;
headerStream << "P6\n";
headerStream << m_outputResolution.x << ' ' << m_outputResolution.y << '\n';
headerStream << "255\n";
std::ofstream fileStream(m_fileName, std::ios::out | std::ios::binary);
fileStream << headerStream.str();
for (const auto& row : m_pixelColors)
for (const auto& pixel : row)
fileStream << static_cast<unsigned char>(pixel.m_R * 255)
<< static_cast<unsigned char>(pixel.m_G * 255)
<< static_cast<unsigned char>(pixel.m_B * 255);
fileStream.flush();
fileStream.close();
// open the new image
const std::wstring WFilename(m_fileName.begin(), m_fileName.end());
ShellExecute(0, 0, WFilename.c_str(), 0, 0, SW_SHOW);
}
void Image::SetFilename(const std::string& Filename)
{
m_fileName = Filename;
}
std::string Image::GetFilename() const
{
return m_fileName;
}
| 24.777778 | 79 | 0.695708 | [
"vector"
] |
87410aa0a8a62b99f6cb4080bd9aac4ee506bd57 | 4,697 | cpp | C++ | CrossArchitecture.cpp | laie/CrossArchitecture | 6de01acc713630736bbe9dfe6c3b73693ee35261 | [
"MIT"
] | 9 | 2016-01-04T10:02:49.000Z | 2018-11-08T08:33:53.000Z | CrossArchitecture.cpp | laie/CrossArchitecture | 6de01acc713630736bbe9dfe6c3b73693ee35261 | [
"MIT"
] | null | null | null | CrossArchitecture.cpp | laie/CrossArchitecture | 6de01acc713630736bbe9dfe6c3b73693ee35261 | [
"MIT"
] | 1 | 2021-02-01T03:42:32.000Z | 2021-02-01T03:42:32.000Z | #include "CrossArchitecture.h"
#include <vector>
#include <intrin.h>
using namespace CrossArchitecture;
TEB64 CrossArchitecture::GetTEB64()
{
#if _WIN64
return *(TEB64*)__readgsqword(0x30);
#else
TEB64 teb64;
Ptr64 teb64Ptr=0;
BeginX64Stub;
DB_(0x41) DB_(0x54); //push r12 ; R12 register should always contain pointer to TEB64 in WoW64 processes
__asm pop dword ptr[teb64Ptr]; // ; this will pop QWORD from stack, as we're in x64 mode now
EndX64Stub;
memcpy64((DWORD64)&teb64, teb64Ptr, sizeof(teb64));
return teb64;
#endif
}
PEB64 CrossArchitecture::GetPEB64()
{
auto teb = GetTEB64();
PEB64 peb64;
memcpy64((DWORD64)&peb64, teb.ProcessEnvironmentBlock, sizeof(PEB64));
return peb64;
}
HMODULE64 CrossArchitecture::GetModuleHandle64(const std::wstring& moduleName)
{
auto peb64 = GetPEB64();
PEB_LDR_DATA64 ldr;
memcpy64((DWORD64)&ldr, peb64.Ldr, sizeof(ldr));
// traversing loader module list, find matched module handle
// NOTE: we should acquire the loader lock here, but I found none of elegant ways to find ntdll!LdrLockLoaderLock without manually implemented GetModuleHandle64
// TODO: resolve this.... sometime
auto head = (peb64.Ldr + (DWORD64)(&((PEB_LDR_DATA64*)nullptr)->InLoadOrderModuleList));
DWORD64 node;
memcpy64((DWORD64)&node, head, sizeof(node));
for (; node != head; memcpy64((DWORD64)&node, node, sizeof(node)))
{
LDR_DATA_TABLE_ENTRY64 tableEntry = {};
memcpy64((DWORD64)&tableEntry, node, sizeof(tableEntry));
std::wstring dllName;
dllName.resize(tableEntry.BaseDllName.Length / 2);
memcpy64((DWORD64)dllName.data(), tableEntry.BaseDllName.Buffer, (DWORD64)(dllName.size() * 2));
if (_wcsnicmp(moduleName.c_str(), dllName.c_str(), max(moduleName.size(), dllName.size())) == 0) return tableEntry.DllBase;
}
return 0;
}
Ptr64 CrossArchitecture::GetProcAddress64(HMODULE64 module, const char* procName)
{
IMAGE_DOS_HEADER dos;
IMAGE_NT_HEADERS64 nt64;
memcpy64(&dos, module, sizeof(dos));
memcpy64(&nt64, module + dos.e_lfanew, sizeof(nt64));
auto exportDirEntry = nt64.OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT];
if (exportDirEntry.VirtualAddress == 0 || exportDirEntry.Size == 0) return 0;
std::vector<unsigned char> dirBuffer;
dirBuffer.resize(exportDirEntry.Size);
memcpy64(dirBuffer.data(), module + exportDirEntry.VirtualAddress, exportDirEntry.Size);
DWORD64 bufferVA = -(int)exportDirEntry.VirtualAddress;
IMAGE_EXPORT_DIRECTORY& dir = *(IMAGE_EXPORT_DIRECTORY*)dirBuffer.data();
DWORD* namevasArray = (DWORD*)(dirBuffer.data() + bufferVA + dir.AddressOfNames);
WORD* nameordArray = (WORD*)(dirBuffer.data() + bufferVA + dir.AddressOfNameOrdinals);
DWORD* addrArray = (DWORD*)(dirBuffer.data() + bufferVA + dir.AddressOfFunctions);
int nameIndex = -1;
for (int ni = 0; ni < (int)dir.NumberOfNames; ni++)
{
const char* name = (const char*)(namevasArray[ni] + dirBuffer.data() + bufferVA);
if (strcmp(name, procName) == 0)
{
nameIndex = ni;
break;
}
}
if (nameIndex == -1) return 0;
return (DWORD)addrArray[nameordArray[nameIndex]] + module;
}
HMODULE64 CrossArchitecture::LoadLibrary64(const std::wstring& moduleName)
{
static HMODULE64 ntdll64 = GetModuleHandle64(L"ntdll.dll");
static Function64< NTSTATUS(const wchar_t* pathToFileWide, ULONG flags, _UNICODE_STRING_T<DWORD64>* moduleFileName, HMODULE64* out)> ldrLoadDll = GetProcAddress64(ntdll64, "LdrLoadDll");
_UNICODE_STRING_T<DWORD64> us;
us.Buffer = (DWORD64)moduleName.c_str();
us.Length = (WORD)(moduleName.size() * 2);
us.MaximumLength = (WORD)(moduleName.size() * 2);
HMODULE64 module = 0;
NTSTATUS ret = ldrLoadDll(nullptr, 0, &us, &module);
if (0 == ret) return module;
SetLastError(ret);
return 0;
}
#ifdef _WIN64
void CrossArchitecture::memcpy64(Ptr64 dst, Ptr64 src, DWORD64 size)
{
// it's equivalent in x64
memcpy((void*)dst.content_, (void*)src.content_, size);
}
#else
__declspec(noinline) void CrossArchitecture::memcpy64(Ptr64 dest, Ptr64 source, DWORD64 byteCount)
{
// it causes crash when inlined?
DWORD originalEsp;
__asm pushfd;
__asm mov[originalEsp], esp
//__asm and esp, 0xFFFFFFF0
__asm cld
BeginX64Stub;
__asm push esi;
__asm push edi;
__asm push ecx;
DB_(0x48) __asm mov edi, dword ptr[dest]; //mov rdi, QWORD PTR [rbp + 0x8]
DB_(0x48) __asm mov esi, dword ptr[source]; //mov rsi, QWORD PTR [rbp + 0x10]
DB_(0x48) __asm mov ecx, dword ptr[byteCount]; //mov rcx, QWORD PTR [rbp + 0x18]
__asm repe movsb;
__asm pop ecx;
__asm pop edi;
__asm pop esi;
EndX64Stub;
__asm mov esp, [originalEsp]
__asm popfd;
}
#endif
inline void CrossArchitecture::memcpy64(void* dst, DWORD64 src, DWORD size)
{
return memcpy64((DWORD64)dst, src, size);
}
| 31.52349 | 187 | 0.734298 | [
"vector"
] |
8741b4a86395965e81379bb4ba9bb9d1e2e7554c | 18,685 | cpp | C++ | ScatterGL/Source/main.cpp | Gian1080/ScatterGL | c9508d0e99448e7e29e7ad751758723a1dafc820 | [
"Unlicense"
] | null | null | null | ScatterGL/Source/main.cpp | Gian1080/ScatterGL | c9508d0e99448e7e29e7ad751758723a1dafc820 | [
"Unlicense"
] | null | null | null | ScatterGL/Source/main.cpp | Gian1080/ScatterGL | c9508d0e99448e7e29e7ad751758723a1dafc820 | [
"Unlicense"
] | null | null | null | #include "pch.h"
#include "GeneralStructs.h"
#include "ScatterGLui.h"
#include "Camera.h"
#include "Shader.h"
#include "GLTexture.h"
#include "MeshObject.h"
#include "StaticFunction.h"
#include "Mesh.h"
#include "Model.h"
#include "Framebuffer.h"
#include "Scatter.h"
ScatterGL::GenericInfo info{};
ScatterGL::Framebuffer framebuffer;
ScatterGL::Framebuffer postProcess;
ScatterGL::Camera camera(glm::vec3(0.0f, 1.0f, 5.0f));
std::vector<uint64_t> meshHandlesBlocks;
std::vector<uint64_t> meshHandlesSponza;
ScatterGL::Material cubeMaterial
{
glm::vec3(1.0f, 0.5f, 0.31f), //ambient
glm::vec3(0.2f, 0.7f, 0.12f), //diffuse
glm::vec3(0.5f, 0.5f, 0.5f), //specular
8.0f //shine
};
ScatterGL::DirectionalLight sunLight
{
glm::vec3(0.0f, -1.0f, 0.0f), //direction
glm::vec3(0.5f, 0.5f, 0.5f),
glm::vec3(0.5f, 0.5f, 0.5f),
glm::vec3(0.5f, 0.5f, 0.5f),
1.0f //intensity
};
ScatterGL::PointLight lightOrbOne
{
glm::vec3(0.0f, 0.0f, 0.0f), //position
0.05f, //constant
0.05f, //linear
0.01f //quadratic
};
ScatterGL::PointLight lightOrbTwo
{
glm::vec3(0.0f, 0.0f, 0.0f), //position
0.04f, //constant
0.04f, //linear
0.01f //quadratic
};
struct PointLightCollection
{
std::vector<ScatterGL::PointLight> lights;
std::vector<glm::mat4*> pointLightMatrices;
};
void framebuffer_resize_callback(GLFWwindow* windowPTR, int width, int height)
{
glViewport(0, 0, width, height);
}
void mouse_callback(GLFWwindow* windowPTR, double xpos, double ypos)
{
if (info.firstMouse)
{
info.lastX = xpos;
info.lastY = ypos;
info.firstMouse = false;
}
float xoffset = xpos - info.lastX;
float yoffset = info.lastY - ypos;
info.lastX = xpos;
info.lastY = ypos;
camera.processMouseMovement(xoffset, yoffset);
}
void scroll_callback(GLFWwindow* window, double xoffset, double yoffset)
{
camera.processMouseScroll(yoffset);
}
void framebuffer_size_callback(GLFWwindow* window, int width, int height)
{
glViewport(0, 0, width, height);
}
void processInput(GLFWwindow* window, ScatterGL::GenericInfo& info)
{
if (glfwGetKey(window, GLFW_KEY_ESCAPE) == GLFW_PRESS)
{
glfwSetWindowShouldClose(window, true);
}
float cameraSpeed = 2.5f * info.deltaTime;
if (glfwGetKey(window, GLFW_KEY_W) == GLFW_PRESS)
{
camera.processKeyboard(FORWARD, info.deltaTime);
}
if (glfwGetKey(window, GLFW_KEY_S) == GLFW_PRESS)
{
camera.processKeyboard(BACKWARD, info.deltaTime);
}
if (glfwGetKey(window, GLFW_KEY_A) == GLFW_PRESS)
{
camera.processKeyboard(LEFT, info.deltaTime);
}
if (glfwGetKey(window, GLFW_KEY_D) == GLFW_PRESS)
{
camera.processKeyboard(RIGHT, info.deltaTime);
}
if (glfwGetKey(window, GLFW_KEY_SPACE) == GLFW_PRESS)
{
camera.processKeyboard(UP, info.deltaTime);
}
if (glfwGetKey(window, GLFW_KEY_LEFT_CONTROL) == GLFW_PRESS)
{
camera.processKeyboard(DOWN, info.deltaTime);
}
if (glfwGetKey(window, GLFW_KEY_LEFT_ALT) == GLFW_PRESS)
{
camera.mouseForMenu = true;
glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_NORMAL);
}
if (glfwGetKey(window, GLFW_KEY_RIGHT_ALT) == GLFW_PRESS)
{
camera.mouseForMenu = false;
glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED);
}
if (glfwGetKey(window, GLFW_KEY_0) == GLFW_PRESS)
{
//camera.position =
}
}
GLFWwindow* initWindow(ScatterGL::GenericInfo& info)
{
glfwInit();
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 4);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 6);
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
GLFWwindow* window = glfwCreateWindow(info.SCREEN_WIDTH, info.SCREEN_HEIGHT, "ScatterGL", NULL, NULL);
if (window == NULL)
{
throw std::runtime_error("failed to create window \n");
glfwTerminate();
}
glfwMakeContextCurrent(window);
//glfwSwapInterval(0); //If you dont want vsync
if (!gladLoadGLLoader((GLADloadproc)glfwGetProcAddress))
{
throw std::runtime_error("failed to initialize GLAD \n");
}
glfwMaximizeWindow(window);
glViewport(0, 0, info.SCREEN_WIDTH, info.SCREEN_HEIGHT);
glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED);
glfwSetFramebufferSizeCallback(window, framebuffer_size_callback);
glfwSetCursorPosCallback(window, mouse_callback);
glfwSetScrollCallback(window, scroll_callback);
glClearColor(0.2f, 0.2f, 0.2f, 1.0f);
glEnable(GL_DEBUG_OUTPUT);
glEnable(GL_DEBUG_OUTPUT_SYNCHRONOUS);
glDebugMessageCallback(ScatterGL::MessageCallback, nullptr);
glDepthFunc(GL_LEQUAL);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glEnable(GL_DEPTH_TEST);
//glFrontFace(GL_CCW);
//glEnable(GL_CULL_FACE);
//glCullFace(GL_BACK);
return window;
}
int main()
{
srand(static_cast <unsigned> (time(0)));
stbi_set_flip_vertically_on_load(false);
GLFWwindow* window = initWindow(info);
ScatterGL::ScatterGLui myGui;
myGui.init(window);
std::vector<ScatterGL::Mesh> lightOrbs;
ScatterGL::MeshObject fullScreenQuad = ScatterGL::MeshObject(ScatterGL::screenQuad, ScatterGL::screenQuadIndices);
ScatterGL::BlockCollection blockCollection;
PointLightCollection pointLightCollection;
ScatterGL::MeshObject blueBlock = ScatterGL::MeshObject(ScatterGL::cube, ScatterGL::cubeIndices);
ScatterGL::GLTexture blueTexture("Textures\\Nico.png");
ScatterGL::GLTexture blueSpecTexture("Textures\\Nico.png");
blockCollection.blocks.push_back(blueBlock);
blockCollection.blockTextures.push_back(blueTexture);
blockCollection.blockSpecTextures.push_back(blueSpecTexture);
ScatterGL::MeshObject stijnBlock = ScatterGL::MeshObject(ScatterGL::cube, ScatterGL::cubeIndices);
ScatterGL::GLTexture stijnTexture("Textures\\Stijn.png");
ScatterGL::GLTexture specStijnTexture("Textures\\Stijn.png");
blockCollection.blocks.push_back(stijnBlock);
blockCollection.blockTextures.push_back(stijnTexture);
blockCollection.blockSpecTextures.push_back(specStijnTexture);
ScatterGL::MeshObject jeroenBlock = ScatterGL::MeshObject(ScatterGL::cube, ScatterGL::cubeIndices);
ScatterGL::GLTexture jeroenTexture("Textures\\Jeroen.png");
ScatterGL::GLTexture specJeroenTexture("Textures\\Jeroen.png");
blockCollection.blocks.push_back(jeroenBlock);
blockCollection.blockTextures.push_back(jeroenTexture);
blockCollection.blockSpecTextures.push_back(specJeroenTexture);
ScatterGL::MeshObject lightBlock = ScatterGL::MeshObject(ScatterGL::cube, ScatterGL::cubeIndices);
ScatterGL::GLTexture lightTexture("Textures\\gianTwee.png");
ScatterGL::GLTexture specLightTexture("Textures\\gianTwee.png");
blockCollection.blocks.push_back(lightBlock);
blockCollection.blockTextures.push_back(lightTexture);
blockCollection.blockSpecTextures.push_back(specLightTexture);
std::filesystem::path pathName("Models\\sponzaTwo\\sponza.gltf");
ScatterGL::Model sponza(pathName.string());
glm::mat4 sponzaMatrix = glm::mat4(1.0f);
sponzaMatrix = glm::scale(sponzaMatrix, glm::vec3(0.05f, 0.05f, 0.05f));
//Sphere making
std::filesystem::path pathNameSphere("Models\\sphere\\sphere.obj");
ScatterGL::GLTexture whiteTexture("Textures\\whiteTexture.png");
ScatterGL::Model sphereModel(pathNameSphere.string());
// pointlights
glm::mat4 sphereMatrixOne = glm::mat4(1.0f);
sphereMatrixOne = glm::scale(sphereMatrixOne, glm::vec3(0.01f, 0.01f, 0.01f));
sphereMatrixOne = glm::translate(sphereMatrixOne, glm::vec3(-6000.0f, 777.7f, -2250.0f));
pointLightCollection.pointLightMatrices.push_back(&sphereMatrixOne);
pointLightCollection.lights.push_back(lightOrbOne);
glm::mat4 sphereMatrixTwo = glm::mat4(1.0f);
sphereMatrixTwo = glm::scale(sphereMatrixTwo, glm::vec3(0.01f, 0.01f, 0.01f));
sphereMatrixTwo = glm::translate(sphereMatrixTwo, glm::vec3(5800.0f, 777.7f, 2100.0f));
pointLightCollection.pointLightMatrices.push_back(&sphereMatrixTwo);
pointLightCollection.lights.push_back(lightOrbTwo);
ScatterGL::Shader depthShader;
depthShader.initialize("Shaders\\depthShader.vert",
"Shaders\\depthShader.frag");
ScatterGL::Shader uberShader;
uberShader.initialize("Shaders\\UberShader.vert",
"Shaders\\UberShader.frag");
ScatterGL::Shader shadowShader;
shadowShader.initialize("Shaders\\postProcess.vert",
"Shaders\\postProcess.frag");
//initializing framebuffers
postProcess.initialize(info.SCREEN_WIDTH, info.SCREEN_HEIGHT);
framebuffer.initialize(info.SCREEN_WIDTH, info.SCREEN_HEIGHT);
//starting Shadow API Scatter
scatter::Scatter myScatter;
myScatter.init();
//Setting Vertex information in API
myScatter.setVertexFormat(scatter::VertexFormat::R32G32B32_SFLOAT);
myScatter.setVertexOffset(0);
myScatter.setVertexStride(sizeof(ScatterGL::Vertex));
myScatter.setIndexFormat(scatter::IndexFormat::UINT32);
myScatter.createTextures(info.SCREEN_WIDTH, info.SCREEN_HEIGHT);
//creating memory handles for Scatter
void* shadowtxtMemHandle = myScatter.getShadowTextureMemoryHandle();
void* depthTxtMemHandle = myScatter.getDepthTextureMemoryhandle();
//memory size allocation
size_t shadowTexMemSize = myScatter.getShadowTextureMemorySize();
size_t depthTexMemSize = myScatter.getDepthTextureMemorySize();
//semaphores creation
void* getReadySemaphore = myScatter.getReadySemaphoreHandle();
void* getDoneSemaphore = myScatter.getDoneSemaphoreHandle();
unsigned int readySemaphore;
unsigned int doneSemaphore;
glGenSemaphoresEXT(1, &readySemaphore);
glGenSemaphoresEXT(1, &doneSemaphore);
glImportSemaphoreWin32HandleEXT(readySemaphore, GL_HANDLE_TYPE_OPAQUE_WIN32_EXT, getReadySemaphore);
glImportSemaphoreWin32HandleEXT(doneSemaphore, GL_HANDLE_TYPE_OPAQUE_WIN32_EXT, getDoneSemaphore);
unsigned int shadowTextureMemory;
glCreateMemoryObjectsEXT(1, &shadowTextureMemory);
glImportMemoryWin32HandleEXT(shadowTextureMemory, shadowTexMemSize, GL_HANDLE_TYPE_OPAQUE_WIN32_EXT, shadowtxtMemHandle);
glCreateTextures(GL_TEXTURE_2D, 1, &framebuffer.shadowTexture);
glTextureStorageMem2DEXT(framebuffer.shadowTexture, 1, GL_RGBA8, info.SCREEN_WIDTH, info.SCREEN_HEIGHT, shadowTextureMemory, 0);
glTextureParameteri(framebuffer.shadowTexture, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTextureParameteri(framebuffer.shadowTexture, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
unsigned int depthTextureMemory;
glCreateMemoryObjectsEXT(1, &depthTextureMemory);
glImportMemoryWin32HandleEXT(depthTextureMemory, depthTexMemSize, GL_HANDLE_TYPE_OPAQUE_WIN32_EXT, depthTxtMemHandle);
glCreateTextures(GL_TEXTURE_2D, 1, &framebuffer.depthTexture);
glTextureStorageMem2DEXT(framebuffer.depthTexture, 1, GL_DEPTH_COMPONENT32F, info.SCREEN_WIDTH, info.SCREEN_HEIGHT, depthTextureMemory, 0);
glTextureParameteri(framebuffer.depthTexture, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTextureParameteri(framebuffer.depthTexture, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
std::vector<ScatterGL::Mesh> tempMeshCollection;
for (unsigned int i = 0; i < sponza.getMeshes().size(); i++)
{
ScatterGL::Mesh& tempMesh = sponza.getMeshes()[i];
tempMeshCollection.push_back(tempMesh);
uint64_t tempMeshHandle = myScatter.addMesh(tempMesh.vertices.data(), tempMesh.indices.data(), tempMesh.vertices.size(), tempMesh.indices.size());
meshHandlesSponza.push_back(tempMeshHandle);
myScatter.addInstance(tempMeshHandle, glm::value_ptr(sponzaMatrix));
}
//creating cube identity matrix
glm::mat4 cubeMatrix = glm::mat4(1.0);
cubeMatrix = glm::scale(cubeMatrix, glm::vec3(1.0f, 1.0f, 1.0f));
for (unsigned int i = 0; i < blockCollection.blocks.size(); i++)
{
cubeMatrix = glm::translate(cubeMatrix, glm::vec3((float)i * 1.25f, (float)i + 0.5f, (float)i * 1.25f));
ScatterGL::MeshObject& tempMesh = blockCollection.blocks[i];
blockCollection.blockMatrices.push_back(cubeMatrix);
glm::mat4 matrixNew = blockCollection.blockMatrices[i];
matrixNew = glm::transpose(matrixNew);
uint64_t tempMeshHandle = myScatter.addMesh(tempMesh.vertices.data(), tempMesh.indices.data(), tempMesh.vertices.size(), tempMesh.indices.size());
meshHandlesBlocks.push_back(tempMeshHandle);
myScatter.addInstance(tempMeshHandle, glm::value_ptr(matrixNew));
}
myScatter.build();
framebuffer.attachTexture(framebuffer.depthTexture);
glm::mat4 projection = glm::perspectiveRH(glm::radians(camera.zoom),
(float)info.SCREEN_WIDTH / (float)info.SCREEN_HEIGHT, info.nearPlane, info.farPlane);
while(!glfwWindowShouldClose(window))
{
//calculating time passed since last frame
float currentFrame = glfwGetTime();
info.deltaTime = currentFrame - info.lastFrame;
info.lastFrame = currentFrame;
float travelSpeed = 1200 * info.deltaTime;
myScatter.clearInstances();
for (unsigned int i = 0; i < sponza.getMeshes().size(); i++)
{
myScatter.addInstance(meshHandlesSponza[i], glm::value_ptr(sponzaMatrix));
}
for (unsigned int i = 0; i < blockCollection.blocks.size(); i++)
{
cubeMatrix = glm::translate(cubeMatrix, glm::vec3((float)i * 1.25f, (float)i + 0.5f, (float)i * 1.25f));
glm::mat4 matrixNew = blockCollection.blockMatrices[i];
matrixNew = glm::transpose(matrixNew);
myScatter.addInstance(meshHandlesBlocks[i], glm::value_ptr(matrixNew));
}
myScatter.build();
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glViewport(0, 0, info.SCREEN_WIDTH, info.SCREEN_HEIGHT);
// user input
processInput(window, info);
// setting view matrix
glm::mat4 view = camera.getViewMatrix();
// cube renderpass
framebuffer.bind();
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
// setting shader
uberShader.use();
uberShader.setMat4("projection", projection);
uberShader.setMat4("view", view);
uberShader.setVec3("viewPosition", camera.position);
if (info.timeTraveled < 10.0f)
{
*pointLightCollection.pointLightMatrices[0] = glm::translate(*pointLightCollection.pointLightMatrices[0], glm::vec3(travelSpeed, 0.0, 0.0));
*pointLightCollection.pointLightMatrices[1] = glm::translate(*pointLightCollection.pointLightMatrices[1], glm::vec3(-travelSpeed, 0.0, 0.0));
info.timeTraveled += info.deltaTime;
}
else
{
*pointLightCollection.pointLightMatrices[0] = glm::translate(*pointLightCollection.pointLightMatrices[0], glm::vec3(-travelSpeed, 0.0, 0.0));
*pointLightCollection.pointLightMatrices[1] = glm::translate(*pointLightCollection.pointLightMatrices[1], glm::vec3(travelSpeed, 0.0, 0.0));
info.timeTraveled += info.deltaTime;
if (info.timeTraveled > 20.0f)
{
info.timeTraveled = 0.0;
}
}
for (unsigned int i = 0; i < blockCollection.blocks.size(); i++)
{
if (info.frameCount > 1250)
{
info.xPositive *= -1;
info.frameCount = 0;
}
if (i % 2)
{
blockCollection.blockMatrices[i] = glm::translate(blockCollection.blockMatrices[i], glm::vec3(info.xPositive, 0.0, 0.0));
}
else if (i % 3)
{
blockCollection.blockMatrices[i] = glm::rotate(blockCollection.blockMatrices[i], info.deltaTime, glm::vec3(0.05f, 0.0f, 0.05f));
}
uberShader.setMat4("model", blockCollection.blockMatrices[i]);
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, blockCollection.blockTextures[i].texture);
glActiveTexture(GL_TEXTURE1);
glBindTexture(GL_TEXTURE_2D, blockCollection.blockSpecTextures[i].texture);
uberShader.setInt("material.diffuse", 0);
uberShader.setInt("material.specular", 1);
uberShader.setFloat("material.shine", 32.0f);
uberShader.setVec3("light.direction", sunLight.direction);
uberShader.setVec3("light.ambient", sunLight.ambient);
uberShader.setVec3("light.diffuse", sunLight.diffuse);
uberShader.setVec3("light.specular", sunLight.specular);
blockCollection.blocks[i].drawObject();
}
//Starting PointLights!
uberShader.setInt("numberOfPointLights", pointLightCollection.lights.size());
for (unsigned int i = 0; i < pointLightCollection.lights.size(); i++)
{
std::string iString = std::to_string(i);
glm::mat4 thing = *pointLightCollection.pointLightMatrices[i];
glm::vec3 pointLightPos;
std::cout << glm::to_string(pointLightPos) << std::endl;
pointLightPos = glm::vec3(thing[3]);
uberShader.setMat4("model", *pointLightCollection.pointLightMatrices[i]);
uberShader.setVec3("pointLightArray[" + iString + "].position", pointLightPos);
uberShader.setFloat("pointLightArray[" + iString + "].constant", pointLightCollection.lights[i].constant);
uberShader.setFloat("pointLightArray[" + iString + "].linear", pointLightCollection.lights[i].linear);
uberShader.setFloat("pointLightArray[" + iString + "].quadratic", pointLightCollection.lights[i].quadratic);
}
uberShader.setBool("isModel", true);
uberShader.setInt("texture_diffuse1", 0);
uberShader.setMat4("model", sponzaMatrix);
sponza.draw(uberShader);
uberShader.setBool("isModel", false);
// Starting Sponza!
info.frameCount++;
framebuffer.unbind();
//Scatter API render calls & semaphore calls
unsigned int texturesThings[] = { framebuffer.shadowTexture, framebuffer.depthTexture };
GLenum textureThingsHelper[] = { GL_LAYOUT_GENERAL_EXT, GL_LAYOUT_GENERAL_EXT };
glSignalSemaphoreEXT(readySemaphore, 0, nullptr, 2, texturesThings, textureThingsHelper);
myScatter.setLightDirection(sunLight.direction.r, sunLight.direction.g, sunLight.direction.b);
glm::mat4 invertedMatrix = glm::inverse(projection * view);
myScatter.setInverseViewProjectionMatrix(glm::value_ptr(invertedMatrix));
myScatter.submit(info.SCREEN_WIDTH, info.SCREEN_HEIGHT);
GLenum layoutThingsHelper[] = { GL_LAYOUT_SHADER_READ_ONLY_EXT, GL_LAYOUT_DEPTH_STENCIL_ATTACHMENT_EXT };
glWaitSemaphoreEXT(doneSemaphore, 0, nullptr, 2, texturesThings, layoutThingsHelper);
postProcess.bind();
shadowShader.use();
shadowShader.setFloat("intensity", sunLight.intensity);
shadowShader.setInt("shadowTexture", 0);
shadowShader.setInt("colorTexture", 1);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, framebuffer.shadowTexture);
glActiveTexture(GL_TEXTURE1);
glBindTexture(GL_TEXTURE_2D, framebuffer.colorTexture);
fullScreenQuad.drawObject();
postProcess.unbind();
myGui.beginFrameGui();
myGui.drawGui();
myGui.drawDirectionalLight(sunLight);
myGui.drawTexture("scene", postProcess.colorTexture);
myGui.drawTexture("normals", framebuffer.normalTexture);
myGui.drawTexture("positions", framebuffer.positionTexture);
myGui.drawTexture("shadow", framebuffer.shadowTexture);
myGui.endFrameGui();
glfwSwapBuffers(window);
glfwPollEvents();
}
myGui.destroy();
glfwTerminate();
}
//float r = static_cast <float> (rand()) / static_cast <float> (RAND_MAX);
//cubeShader.setFloat("r", r);
//float g = static_cast <float> (rand()) / static_cast <float> (RAND_MAX);
//cubeShader.setFloat("g", g);
//float b = static_cast <float> (rand()) / static_cast <float> (RAND_MAX);
//cubeShader.setFloat("b", b);
//std::cout << pointLightCollection.pointLights.size() << std::endl;
| 38.288934 | 148 | 0.763447 | [
"mesh",
"render",
"vector",
"model"
] |
8741d4852fa9812c766df52f8a468ebc958210f1 | 6,630 | cc | C++ | cc/algorithms/algorithm_test.cc | Jolly608090/differential-privacy | 74d5be96d4abe6820ef4838c00a1b78c72ae01af | [
"Apache-2.0"
] | null | null | null | cc/algorithms/algorithm_test.cc | Jolly608090/differential-privacy | 74d5be96d4abe6820ef4838c00a1b78c72ae01af | [
"Apache-2.0"
] | null | null | null | cc/algorithms/algorithm_test.cc | Jolly608090/differential-privacy | 74d5be96d4abe6820ef4838c00a1b78c72ae01af | [
"Apache-2.0"
] | null | null | null | //
// Copyright 2019 Google LLC
//
// 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 "algorithms/algorithm.h"
#include <forward_list>
#include <list>
#include <vector>
#include "base/testing/status_matchers.h"
#include "gmock/gmock.h"
#include "gtest/gtest.h"
#include "base/statusor.h"
namespace differential_privacy {
namespace {
using ::testing::DoubleNear;
using ::testing::HasSubstr;
using ::differential_privacy::base::testing::StatusIs;
const double kTestPrecision = 1e-5;
template <typename T>
class TestAlgorithm : public Algorithm<T> {
public:
class Builder : public AlgorithmBuilder<T, TestAlgorithm<T>, Builder> {
using AlgorithmBuilder =
differential_privacy::AlgorithmBuilder<T, TestAlgorithm<T>, Builder>;
public:
Builder() : AlgorithmBuilder() {}
private:
base::StatusOr<std::unique_ptr<TestAlgorithm<T>>> BuildAlgorithm()
override {
return absl::WrapUnique(
new TestAlgorithm(AlgorithmBuilder::GetEpsilon().value()));
}
};
TestAlgorithm() : Algorithm<T>(1.0) {}
TestAlgorithm(double epsilon) : Algorithm<T>(epsilon) {}
void AddEntry(const T& t) override {}
Summary Serialize() const override { return Summary(); }
absl::Status Merge(const Summary& summary) override {
return absl::OkStatus();
}
int64_t MemoryUsed() override { return sizeof(TestAlgorithm<T>); }
protected:
base::StatusOr<Output> GenerateResult(double noise_interval_level) override {
Output output;
ConfidenceInterval ci;
ci.set_confidence_level(noise_interval_level);
return MakeOutput("Data", ci);
}
void ResetState() override {}
};
TEST(AlgorithmTest, PartialResultPassesConfidenceLevel) {
TestAlgorithm<double> alg;
const double level = .9;
base::StatusOr<Output> result = alg.PartialResult(level);
ASSERT_OK(result);
EXPECT_EQ(GetNoiseConfidenceInterval(*result).confidence_level(), level);
// Although the ErrorReport.noise_confidence_interval is deprecated, we still
// keep it updated for a more seamless transition for existing clients. After
// some time, we should no longer use ErrorReport.noise_confidence_interval.
// But for now, test to make sure ErrorReport.noise_confidence_interval is
// being set.
EXPECT_EQ(
result->error_report().noise_confidence_interval().confidence_level(),
level);
}
TEST(AlgorithmTest, RepeatedResultsFail) {
TestAlgorithm<double> alg;
EXPECT_OK(alg.PartialResult());
EXPECT_THAT(alg.PartialResult(),
StatusIs(absl::StatusCode::kInvalidArgument,
HasSubstr("can only produce results once")));
}
TEST(AlgorithmTest, Reset) {
TestAlgorithm<double> alg;
ASSERT_OK(alg.PartialResult());
alg.Reset();
EXPECT_OK(alg.PartialResult());
}
TEST(AlgorithmTest, InvalidEpsilon) {
EXPECT_DEATH(TestAlgorithm<double> alg(-1.0), "Check failed: epsilon > 0.0");
EXPECT_DEATH(
TestAlgorithm<double> alg(std::numeric_limits<double>::quiet_NaN()),
"Check failed: epsilon > 0.0");
EXPECT_DEATH(
TestAlgorithm<double> alg(std::numeric_limits<double>::infinity()),
"Check failed: epsilon != std::numeric_limits<double>::infinity.*");
}
TEST(AlgorithmBuilderTest, InvalidEpsilonFailsBuild) {
TestAlgorithm<double>::Builder builder;
EXPECT_THAT(builder.SetEpsilon(-1).Build(),
StatusIs(absl::StatusCode::kInvalidArgument,
HasSubstr("Epsilon must be finite and positive")));
EXPECT_THAT(
builder.SetEpsilon(std::numeric_limits<double>::quiet_NaN()).Build(),
StatusIs(absl::StatusCode::kInvalidArgument,
HasSubstr("Epsilon must be a valid numeric value")));
EXPECT_THAT(
builder.SetEpsilon(std::numeric_limits<double>::infinity()).Build(),
StatusIs(absl::StatusCode::kInvalidArgument,
HasSubstr("Epsilon must be finite")));
}
TEST(AlgorithmBuilderTest, InvalidDeltaFailsBuild) {
TestAlgorithm<double>::Builder builder;
EXPECT_THAT(
builder.SetDelta(-0.1).Build(),
StatusIs(absl::StatusCode::kInvalidArgument,
HasSubstr("Delta must be in the inclusive interval [0,1]")));
EXPECT_THAT(
builder.SetDelta(1.1).Build(),
StatusIs(absl::StatusCode::kInvalidArgument,
HasSubstr("Delta must be in the inclusive interval [0,1]")));
EXPECT_THAT(
builder.SetDelta(std::numeric_limits<double>::quiet_NaN()).Build(),
StatusIs(absl::StatusCode::kInvalidArgument,
HasSubstr("Delta must be a valid numeric value")));
EXPECT_THAT(
builder.SetDelta(std::numeric_limits<double>::infinity()).Build(),
StatusIs(absl::StatusCode::kInvalidArgument,
HasSubstr("Delta must be in the inclusive interval [0,1]")));
}
TEST(AlgorithmBuilderTest, InvalidL0SensitivityFailsBuild) {
TestAlgorithm<double>::Builder builder;
EXPECT_THAT(
builder.SetMaxPartitionsContributed(-1).Build(),
StatusIs(
absl::StatusCode::kInvalidArgument,
HasSubstr("Maximum number of partitions that can be "
"contributed to (i.e., L0 sensitivity) must be positive")));
EXPECT_THAT(
builder.SetMaxPartitionsContributed(0).Build(),
StatusIs(
absl::StatusCode::kInvalidArgument,
HasSubstr("Maximum number of partitions that can be "
"contributed to (i.e., L0 sensitivity) must be positive")));
}
TEST(AlgorithmBuilderTest, InvalidMaxContributionsPerPartitionFailsBuild) {
TestAlgorithm<double>::Builder builder;
EXPECT_THAT(builder.SetMaxContributionsPerPartition(-1).Build(),
StatusIs(absl::StatusCode::kInvalidArgument,
HasSubstr("Maximum number of contributions per "
"partition must be positive")));
EXPECT_THAT(builder.SetMaxContributionsPerPartition(0).Build(),
StatusIs(absl::StatusCode::kInvalidArgument,
HasSubstr("Maximum number of contributions per "
"partition must be positive")));
}
} // namespace
} // namespace differential_privacy
| 34.53125 | 80 | 0.695023 | [
"vector"
] |
8742206b13eec95ecb8cb84bd8c8c74695509ec7 | 731 | cpp | C++ | day04/part2.cpp | Moremar/advent_of_code_2016 | dea264671fc2c31baa42b1282751dfd1ae071a7d | [
"Apache-2.0"
] | null | null | null | day04/part2.cpp | Moremar/advent_of_code_2016 | dea264671fc2c31baa42b1282751dfd1ae071a7d | [
"Apache-2.0"
] | null | null | null | day04/part2.cpp | Moremar/advent_of_code_2016 | dea264671fc2c31baa42b1282751dfd1ae071a7d | [
"Apache-2.0"
] | null | null | null | #include "part2.hpp"
using namespace std;
const string ALPHABET = "abcdefghijklmnopqrstuvwxyz";
string decryptName(const Room &room) {
string res;
for (const char &c : room.encryptedName) {
if (c == '-') {
res += ' ';
} else {
res += ALPHABET[(ALPHABET.find(c) + room.sectorId) % 26];
}
}
return res;
}
int Part2::solve(vector<Room> data) {
for (const Room &room : data) {
if (room.isReal()) {
const auto decrypted = decryptName(room);
if (decrypted.find("northpole") != string::npos) {
return room.sectorId;
}
}
}
throw AdventException("No room found containing 'northpole'.");
} | 22.84375 | 69 | 0.543092 | [
"vector"
] |
87457ee50e9e7fd4c0b2b2a88802fbc75818c63e | 895 | cpp | C++ | DataStructures/Slot-2_04-11-2019/BFS.cpp | EnEm/cs204 | e74e8a7353f5f3bb22f6077e55e591160287d422 | [
"MIT"
] | null | null | null | DataStructures/Slot-2_04-11-2019/BFS.cpp | EnEm/cs204 | e74e8a7353f5f3bb22f6077e55e591160287d422 | [
"MIT"
] | null | null | null | DataStructures/Slot-2_04-11-2019/BFS.cpp | EnEm/cs204 | e74e8a7353f5f3bb22f6077e55e591160287d422 | [
"MIT"
] | 3 | 2019-08-22T09:37:44.000Z | 2019-11-09T03:29:07.000Z | #include<iostream>
#include<vector>
#include<queue>
using namespace std;
vector<int> bfs(int root,vector<int> adjancency_list[],int n)
{
bool visited[n+1]={};
queue<int> precedence_list;
vector<int> bfs_order;
precedence_list.push(root);
while(!precedence_list.empty())
{
root=precedence_list.front();
precedence_list.pop();
if(visited[root])
continue;
visited[root]=1;
bfs_order.push_back(root);
for(auto node:adjancency_list[root])
{
precedence_list.push(node);
}
}
return bfs_order;
}
int main()
{
int n,m;
cin>>n>>m;
vector<int> ad[n+1];
while(m--)
{
int u,v;
cin>>u>>v;
ad[u].push_back(v);
ad[v].push_back(u);
}
vector<int> v=bfs(1,ad,n);
for(auto x:v)
{
cout<<x<<' ';
}
return 0;
} | 18.645833 | 61 | 0.53743 | [
"vector"
] |
87466342e617add10f4fb0c5c7b809d6605d2dd0 | 5,012 | cxx | C++ | Base/QTGUI/qSlicerSingletonViewFactory.cxx | forfullstack/slicersources-src | 91bcecf037a27f3fad4c0ab57e8286fc258bb0f5 | [
"Apache-2.0"
] | null | null | null | Base/QTGUI/qSlicerSingletonViewFactory.cxx | forfullstack/slicersources-src | 91bcecf037a27f3fad4c0ab57e8286fc258bb0f5 | [
"Apache-2.0"
] | null | null | null | Base/QTGUI/qSlicerSingletonViewFactory.cxx | forfullstack/slicersources-src | 91bcecf037a27f3fad4c0ab57e8286fc258bb0f5 | [
"Apache-2.0"
] | null | null | null | /*==============================================================================
Copyright (c) Laboratory for Percutaneous Surgery (PerkLab)
Queen's University, Kingston, ON, Canada. All Rights Reserved.
See COPYRIGHT.txt
or http://www.slicer.org/copyright/copyright.txt for details.
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.
This file was originally developed by Kyle Sunderland, PerkLab, Queen's University
and was supported through CANARIE's Research Software Program, and Cancer
Care Ontario.
==============================================================================*/
// QtGUI includes
#include "qSlicerSingletonViewFactory.h"
#include <QDebug>
#include <QMap>
#include <QSharedPointer>
#include <QWidget>
//-----------------------------------------------------------------------------
class qSlicerSingletonViewFactoryPrivate
{
Q_DECLARE_PUBLIC(qSlicerSingletonViewFactory);
protected:
qSlicerSingletonViewFactory* q_ptr;
public:
qSlicerSingletonViewFactoryPrivate(qSlicerSingletonViewFactory& object);
virtual ~qSlicerSingletonViewFactoryPrivate();
virtual void init();
// Widget returned from createViewFromXML
QWidget* Widget;
// Tag used for widget in createViewFromXML
QString TagName;
// Internal QWidget used to hold the widget until it is taken over by the layout manager
QSharedPointer<QWidget> InternalWidget;
};
//-----------------------------------------------------------------------------
// qSlicerSingletonViewFactoryPrivate methods
qSlicerSingletonViewFactoryPrivate
::qSlicerSingletonViewFactoryPrivate(qSlicerSingletonViewFactory& object)
: q_ptr(&object)
, Widget(nullptr)
, InternalWidget(new QWidget())
{
}
//-----------------------------------------------------------------------------
qSlicerSingletonViewFactoryPrivate::~qSlicerSingletonViewFactoryPrivate()
{
Q_Q(qSlicerSingletonViewFactory);
q->setWidget(nullptr);
}
//-----------------------------------------------------------------------------
void qSlicerSingletonViewFactoryPrivate::init()
{
}
//-----------------------------------------------------------------------------
// qSlicerSingletonViewFactory methods
//-----------------------------------------------------------------------------
qSlicerSingletonViewFactory::qSlicerSingletonViewFactory(QObject* parent)
: Superclass(parent)
, d_ptr(new qSlicerSingletonViewFactoryPrivate(*this))
{
Q_D(qSlicerSingletonViewFactory);
d->init();
this->setUseCachedViews(false);
}
//-----------------------------------------------------------------------------
qSlicerSingletonViewFactory::~qSlicerSingletonViewFactory() = default;
//-----------------------------------------------------------------------------
QWidget* qSlicerSingletonViewFactory::widget()
{
Q_D(qSlicerSingletonViewFactory);
return d->Widget;
}
//-----------------------------------------------------------------------------
void qSlicerSingletonViewFactory::setWidget(QWidget* widget)
{
Q_D(qSlicerSingletonViewFactory);
if (d->Widget == widget)
{
return;
}
if (d->Widget)
{
QObject::disconnect(d->Widget, &QWidget::destroyed, this, &qSlicerSingletonViewFactory::onWidgetDestroyed);
}
d->Widget = widget;
if (d->Widget)
{
d->Widget->setParent(d->InternalWidget.data()); // Hold the widget in the internal widget until the layout manager can take it
QObject::connect(d->Widget, &QWidget::destroyed, this, &qSlicerSingletonViewFactory::onWidgetDestroyed);
}
}
//-----------------------------------------------------------------------------
void qSlicerSingletonViewFactory::onWidgetDestroyed()
{
this->setWidget(nullptr);
}
//-----------------------------------------------------------------------------
QString qSlicerSingletonViewFactory::tagName()
{
Q_D(qSlicerSingletonViewFactory);
return d->TagName;
}
//-----------------------------------------------------------------------------
void qSlicerSingletonViewFactory::setTagName(QString tagName)
{
Q_D(qSlicerSingletonViewFactory);
d->TagName = tagName;
}
//-----------------------------------------------------------------------------
QStringList qSlicerSingletonViewFactory::supportedElementNames() const
{
Q_D(const qSlicerSingletonViewFactory);
return QStringList() << d->TagName;
}
//---------------------------------------------------------------------------
QWidget* qSlicerSingletonViewFactory::createViewFromXML(QDomElement layoutElement)
{
Q_UNUSED(layoutElement);
Q_D(qSlicerSingletonViewFactory);
if (d->Widget && d->Widget->isVisible())
{
qCritical() << "qSlicerSingletonViewFactory::createViewFromXML - Widget for view \"" << d->TagName << "\" is already in use within the current layout!";
}
return this->widget();
}
| 32.128205 | 156 | 0.576816 | [
"object"
] |
8748d5b9157a59ee7dccab858d44897c0a1828a1 | 2,458 | cpp | C++ | db/silkworm/etl/collector.cpp | Giulio2002/silkworm | 137073771a32cfb1282eaa2469e8ea6d4f7a998b | [
"Apache-2.0"
] | null | null | null | db/silkworm/etl/collector.cpp | Giulio2002/silkworm | 137073771a32cfb1282eaa2469e8ea6d4f7a998b | [
"Apache-2.0"
] | null | null | null | db/silkworm/etl/collector.cpp | Giulio2002/silkworm | 137073771a32cfb1282eaa2469e8ea6d4f7a998b | [
"Apache-2.0"
] | null | null | null | /*
Copyright 2020 The Silkworm Authors
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 "collector.hpp"
namespace silkworm::etl{
void Collector::flush_buffer() {
data_providers_.push_back(FileProvider(data_providers_.size()));
data_providers_.back().write_buffer_to_disk(buffer_);
buffer_->reset();
}
void Collector::collect(silkworm::ByteView key, silkworm::ByteView value) {
buffer_->put(key, value);
if (buffer_->check_flush_size()) {
flush_buffer();
}
}
void Collector::load(silkworm::lmdb::Table *table, Load load) {
if (data_providers_.size() == 0) {
buffer_->sort();
for(const auto& entry: buffer_->get_entries()) {
auto pairs = load(entry.key, entry.value);
for (auto pair: pairs) table->put(pair.key, pair.value);
}
buffer_->reset();
return;
}
flush_buffer();
auto heap = std::vector<Entry>();
std::make_heap(heap.begin(), heap.end(), compareEntries);
for (unsigned int i = 0; i < data_providers_.size(); i++)
{
auto entry = data_providers_.at(i).next();
heap.push_back({entry.key, entry.value, (int)i});
std::push_heap(heap.begin(), heap.end(), compareEntries);
}
while (heap.size() != 0) {
std::pop_heap(heap.begin(), heap.end(), compareEntries);
auto entry{heap.back()};
heap.pop_back();
auto pairs{load(entry.key, entry.value)};
for (auto pair: pairs) table->put(pair.key, pair.value);
auto next{data_providers_.at(entry.i).next()};
next.i = entry.i;
if (next.key.size() == 0) {
data_providers_.at(entry.i).reset();
continue;
}
heap.push_back(next);
std::push_heap(heap.begin(), heap.end(), compareEntries);
}
}
std::vector<Entry> default_load(silkworm::ByteView key, silkworm::ByteView value) {
return std::vector<Entry>({{key, value, 0}});
}
} | 31.113924 | 83 | 0.638324 | [
"vector"
] |
87651bc87ae5d4e48ef986cf9d2787f43938711e | 973 | cpp | C++ | qrrepo/private/classes/logicalObject.cpp | anastasia143/qreal | 9bd224b41e569c9c50ab88848a5746a010c65ad7 | [
"Apache-2.0"
] | 39 | 2015-01-26T16:18:43.000Z | 2021-12-20T23:36:41.000Z | qrrepo/private/classes/logicalObject.cpp | anastasia143/qreal | 9bd224b41e569c9c50ab88848a5746a010c65ad7 | [
"Apache-2.0"
] | 1,248 | 2019-02-21T19:32:09.000Z | 2022-03-29T16:50:04.000Z | qrrepo/private/classes/logicalObject.cpp | anastasia143/qreal | 9bd224b41e569c9c50ab88848a5746a010c65ad7 | [
"Apache-2.0"
] | 58 | 2015-03-03T12:57:28.000Z | 2020-05-09T15:54:42.000Z | /* Copyright 2007-2015 QReal Research Group
*
* 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 "logicalObject.h"
using namespace qrRepo::details;
LogicalObject::LogicalObject(const qReal::Id &id)
: Object(id)
{
}
LogicalObject::LogicalObject(const QDomElement &element)
: Object(element)
{
}
Object *LogicalObject::createClone() const
{
return new LogicalObject(mId.sameTypeId());
}
bool LogicalObject::isLogicalObject() const
{
return true;
}
| 25.605263 | 75 | 0.746146 | [
"object"
] |
876dd82c2ceee4da74a86191cd9f9b761f84979a | 5,771 | cpp | C++ | test/fragmentation_benchmark_pmem.cpp | JohnSully/memkind | 7c11836a9b0262ff23ef7f45b47a44996f25ab36 | [
"BSD-3-Clause"
] | 1 | 2019-07-02T21:30:48.000Z | 2019-07-02T21:30:48.000Z | test/fragmentation_benchmark_pmem.cpp | JohnSully/memkind | 7c11836a9b0262ff23ef7f45b47a44996f25ab36 | [
"BSD-3-Clause"
] | null | null | null | test/fragmentation_benchmark_pmem.cpp | JohnSully/memkind | 7c11836a9b0262ff23ef7f45b47a44996f25ab36 | [
"BSD-3-Clause"
] | null | null | null | /*
* Copyright (C) 2019 Intel Corporation.
* 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(s),
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice(s),
* 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 HOLDER(S) ``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) 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 <memkind.h>
#include <chrono>
#include <cstdio>
#include <random>
#include <vector>
#define MB (1024 * 1024)
#define PRINT_FREQ 100000
#define ARRAY_SIZE(x) (sizeof(x) / sizeof((x)[0]))
static size_t block_size [] =
{8519680, 4325376, 8519680, 4325376, 8519680, 4325376, 8519680, 4325376, 432517, 608478};
static struct memkind *pmem_kind = nullptr;
static FILE *output_file = nullptr;
static void usage(char *name)
{
fprintf(stderr,
"Usage: %s pmem_kind_dir_path pmem_size test_time_limit_in_sec output_file_name\n",
name);
}
static int fragmentatation_test(size_t pmem_max_size, double test_time)
{
std::random_device rd;
std::mt19937 mt(rd());
std::uniform_int_distribution<> m_size(0, ARRAY_SIZE(block_size) - 1);
char *pmem_str = nullptr;
std::vector<char *> pmem_strs;
size_t total_size = pmem_max_size;
size_t print_iter = 0;
size_t total_allocated = 0;
double elapsed_seconds;
auto start = std::chrono::steady_clock::now();
do {
print_iter++;
int index = m_size(mt);
size_t size = block_size[index];
int length = pmem_strs.size() / 2;
std::uniform_int_distribution<> m_index(0, length - 1);
while ((pmem_str = static_cast<char *>(memkind_malloc(pmem_kind,
size))) == nullptr) {
int to_evict = m_index(mt);
char *str_to_evict = pmem_strs[to_evict];
size_t evict_size = memkind_malloc_usable_size(pmem_kind, str_to_evict);
total_allocated -= evict_size;
if (total_allocated < total_size * 0.1) {
fprintf(stderr,"allocated less than 10 percent\n");
return 1;
}
memkind_free(pmem_kind, str_to_evict);
pmem_strs.erase(pmem_strs.begin() + to_evict);
}
pmem_strs.push_back(pmem_str);
total_allocated += memkind_malloc_usable_size(pmem_kind, pmem_str);
if (print_iter % PRINT_FREQ == 0) {
fprintf(output_file,"%f\n", static_cast<double>(total_allocated) / total_size);
fflush(stdout);
}
auto finish = std::chrono::steady_clock::now();
elapsed_seconds = std::chrono::duration_cast<std::chrono::duration<double>>
(finish - start).count();
} while (elapsed_seconds < test_time);
return 0;
}
int main(int argc, char *argv[])
{
char *pmem_dir;
char *output_log_path;
size_t pmem_size;
unsigned long pmem_policy;
double test_time_limit_in_sec;
int err = 0;
memkind_config *pmem_cfg;
int status = 0;
if (argc != 6) {
usage(argv[0]);
return 1;
} else {
pmem_dir = argv[1];
pmem_size = std::stoull(argv[2]) * MB;
pmem_policy = std::stoul(argv[3]);
test_time_limit_in_sec = std::stod(argv[4]);
output_log_path = argv[5];
}
if (pmem_size == 0 ) {
fprintf(stderr, "Invalid size to pmem kind must be not equal zero\n");
return 1;
}
if ((output_file = fopen(output_log_path, "w+")) == nullptr) {
fprintf(stderr, "Cannot create output file %s\n", output_log_path);
return 1;
}
if (pmem_policy > MEMKIND_MEM_USAGE_POLICY_MAX_VALUE) {
fprintf(stderr, "Invalid memory usage policy param %lu.\n", pmem_policy);
goto err_fopen;
}
pmem_cfg = memkind_config_new();
if (!pmem_cfg) {
fprintf(stderr, "Unable to create pmem configuration.\n");
goto err_fopen;
}
memkind_config_set_path(pmem_cfg, pmem_dir);
memkind_config_set_size(pmem_cfg, pmem_size);
memkind_config_set_memory_usage_policy(pmem_cfg,
static_cast<memkind_mem_usage_policy>(pmem_policy));
err = memkind_create_pmem_with_config(pmem_cfg, &pmem_kind);
if (err) {
fprintf(stderr, "Unable to create pmem kind.\n");
goto err_create_pmem;
}
memkind_config_delete(pmem_cfg);
status = fragmentatation_test(pmem_size, test_time_limit_in_sec);
err = memkind_destroy_kind(pmem_kind);
if (err) {
fprintf(stdout, "Unable to destroy pmem kind.\n");
goto err_fopen;
}
fclose(output_file);
return status;
err_create_pmem:
memkind_config_delete(pmem_cfg);
err_fopen:
fclose(output_file);
return 1;
}
| 34.147929 | 95 | 0.656039 | [
"vector"
] |
878a211e9a193abc0025514eb13308228c0b169a | 2,672 | hpp | C++ | packages/monte_carlo/estimator/native/src/MonteCarlo_CellTrackLengthFluxEstimator.hpp | lkersting/SCR-2123 | 06ae3d92998664a520dc6a271809a5aeffe18f72 | [
"BSD-3-Clause"
] | null | null | null | packages/monte_carlo/estimator/native/src/MonteCarlo_CellTrackLengthFluxEstimator.hpp | lkersting/SCR-2123 | 06ae3d92998664a520dc6a271809a5aeffe18f72 | [
"BSD-3-Clause"
] | null | null | null | packages/monte_carlo/estimator/native/src/MonteCarlo_CellTrackLengthFluxEstimator.hpp | lkersting/SCR-2123 | 06ae3d92998664a520dc6a271809a5aeffe18f72 | [
"BSD-3-Clause"
] | null | null | null | //---------------------------------------------------------------------------//
//!
//! \file MonteCarlo_CellTrackLengthFluxEstimator.hpp
//! \author Alex Robinson
//! \brief Cell track length flux estimator class declaration.
//!
//---------------------------------------------------------------------------//
#ifndef FACEMC_CELL_TRACK_LENGTH_FLUX_ESTIMATOR_HPP
#define FACEMC_CELL_TRACK_LENGTH_FLUX_ESTIMATOR_HPP
// Boost Includes
#include <boost/mpl/vector.hpp>
// FRENSIE Includes
#include "MonteCarlo_StandardCellEstimator.hpp"
#include "MonteCarlo_ParticleSubtrackEndingInCellEventObserver.hpp"
#include "MonteCarlo_EstimatorContributionMultiplierPolicy.hpp"
namespace MonteCarlo{
//! The cell track length flux estimator class
template<typename ContributionMultiplierPolicy = WeightMultiplier>
class CellTrackLengthFluxEstimator : public StandardCellEstimator,
public ParticleSubtrackEndingInCellEventObserver
{
public:
//! Typedef for event tags used for quick dispatcher registering
typedef boost::mpl::vector<ParticleSubtrackEndingInCellEventObserver::EventTag>
EventTags;
//! Constructor
CellTrackLengthFluxEstimator(
const Estimator::idType id,
const double multiplier,
const Teuchos::Array<StandardCellEstimator::cellIdType>& cell_ids,
const Teuchos::Array<double>& cell_volumes );
//! Destructor
~CellTrackLengthFluxEstimator()
{ /* ... */ }
//! Set the response functions
void setResponseFunctions(
const Teuchos::Array<Teuchos::RCP<ResponseFunction> >& response_functions );
//! Add current history estimator contribution
void updateFromParticleSubtrackEndingInCellEvent(
const ParticleState& particle,
const StandardCellEstimator::cellIdType cell_of_subtrack,
const double track_length );
//! Print the estimator data
void print( std::ostream& os ) const;
private:
// Assign bin boundaries to an estimator dimension
void assignBinBoundaries(
const Teuchos::RCP<EstimatorDimensionDiscretization>& bin_boundaries );
};
} // end MonteCarlo namespace
//---------------------------------------------------------------------------//
// Template Includes
//---------------------------------------------------------------------------//
#include "MonteCarlo_CellTrackLengthFluxEstimator_def.hpp"
//---------------------------------------------------------------------------//
#endif // end FACEMC_CELL_TRACK_LENGTH_FLUX_ESTIMATOR_HPP
//---------------------------------------------------------------------------//
// end MonteCarlo_CellTrackLengthFluxEstimator.hpp
//---------------------------------------------------------------------------//
| 33.4 | 81 | 0.619386 | [
"vector"
] |
879ef581278608bae48e289936b2574926334b97 | 14,243 | cpp | C++ | Lib-ZeroG/src/ZeroG/vulkan/VulkanBackend.cpp | PetorSFZ/ZeroG | 0e3330c2877c3dd840f2a7864b5767d53a92b97d | [
"Zlib"
] | null | null | null | Lib-ZeroG/src/ZeroG/vulkan/VulkanBackend.cpp | PetorSFZ/ZeroG | 0e3330c2877c3dd840f2a7864b5767d53a92b97d | [
"Zlib"
] | null | null | null | Lib-ZeroG/src/ZeroG/vulkan/VulkanBackend.cpp | PetorSFZ/ZeroG | 0e3330c2877c3dd840f2a7864b5767d53a92b97d | [
"Zlib"
] | null | null | null | // Copyright (c) Peter Hillerström (skipifzero.com, peter@hstroem.se)
//
// This software is provided 'as-is', without any express or implied
// warranty. In no event will the authors be held liable for any damages
// arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it
// freely, subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented; you must not
// claim that you wrote the original software. If you use this software
// in a product, an acknowledgment in the product documentation would be
// appreciated but is not required.
// 2. Altered source versions must be plainly marked as such, and must not be
// misrepresented as being the original software.
// 3. This notice may not be removed or altered from any source distribution.
#include "ZeroG/vulkan/VulkanBackend.hpp"
#include <vulkan/vulkan.h>
#include "ZeroG/util/Assert.hpp"
#include "ZeroG/util/CpuAllocation.hpp"
#include "ZeroG/util/Logging.hpp"
#include "ZeroG/util/Mutex.hpp"
#include "ZeroG/util/Strings.hpp"
#include "ZeroG/util/Vector.hpp"
#include "ZeroG/vulkan/VulkanCommandQueue.hpp"
#include "ZeroG/vulkan/VulkanCommon.hpp"
#include "ZeroG/vulkan/VulkanDebug.hpp"
namespace zg {
// Vulkan Backend State
// ------------------------------------------------------------------------------------------------
struct VulkanContext final {
VkInstance instance = nullptr; // Externally synchronized
VkSurfaceKHR surface = nullptr;
VkPhysicalDevice physicalDevice = nullptr;
VkPhysicalDeviceProperties physicalDeviceProperties = {};
VkDevice device = nullptr;
};
struct VulkanSwapchain final {
uint32_t width = 0;
uint32_t height = 0;
};
struct VulkanBackendState final {
// Collection of some externally synchronized vulkan state that could roughly be considered
// a "context" when grouped together
Mutex<VulkanContext> context;
Mutex<VulkanSwapchain> swapchain;
VulkanCommandQueue presentQueue;
VulkanCommandQueue copyQueue;
};
// Statics
// ------------------------------------------------------------------------------------------------
// Vulkan Backend implementation
// ------------------------------------------------------------------------------------------------
class VulkanBackend final : public ZgBackend {
public:
// Constructors & destructors
// --------------------------------------------------------------------------------------------
VulkanBackend() = default;
VulkanBackend(const VulkanBackend&) = delete;
VulkanBackend& operator= (const VulkanBackend&) = delete;
VulkanBackend(VulkanBackend&&) = delete;
VulkanBackend& operator= (VulkanBackend&&) = delete;
virtual ~VulkanBackend() noexcept
{
// Access context
MutexAccessor<VulkanContext> context = mState->context.access();
// Destroy VkInstance
if (context.data().instance != nullptr) {
// TODO: Allocation callbacks
if (mDebugMode) {
auto vkDestroyDebugReportCallbackEXT = (PFN_vkDestroyDebugReportCallbackEXT)
vkGetInstanceProcAddr(context.data().instance, "vkDestroyDebugReportCallbackEXT");
vkDestroyDebugReportCallbackEXT(context.data().instance, vulkanDebugCallback, nullptr);
}
vkDestroyInstance(context.data().instance, nullptr);
}
// Delete remaining state
zgDelete(mState);
}
// State methods
// --------------------------------------------------------------------------------------------
ZgResult init(ZgContextInitSettings& settings) noexcept
{
// Initialize members and create state struct
mDebugMode = settings.debugMode;
mState = zgNew<VulkanBackendState>( "VulkanBackendState");
// Log available instance layers and extensions
vulkanLogAvailableInstanceLayers();
vulkanLogAvailableInstanceExtensions();
// Application info struct
VkApplicationInfo appInfo = {};
appInfo.sType = VK_STRUCTURE_TYPE_APPLICATION_INFO;
appInfo.apiVersion = VK_API_VERSION_1_0;
// Layers and extensions arrays
Vector<const char*> layers;
layers.create(64, "VulkanInit: layers");
Vector<const char*> extensions;
extensions.create(64, "VulkanInit: extensions");
// Debug mode layers and extensions
if (mDebugMode) {
layers.add("VK_LAYER_LUNARG_standard_validation");
layers.add("VK_LAYER_LUNARG_core_validation");
layers.add("VK_LAYER_LUNARG_parameter_validation");
layers.add("VK_LAYER_LUNARG_object_tracker");
extensions.add("VK_EXT_debug_report");
}
// TODO: Add other required layers and extensions
// pNext can optionally point to a VkDebugReportCallbackCreateInfoEXT in order to create a
// debug report callback that is used only during vkCreateInstance() and vkDestroyInstance(),
// which can't be covered by a normal persistent debug report callback.
void* instanceInfoPNext = nullptr;
/*VkDebugReportCallbackCreateInfoEXT createDestroyCallbackInfo = {};
if (mDebugMode) {
createDestroyCallbackInfo.sType = VK_STRUCTURE_TYPE_DEBUG_REPORT_CALLBACK_CREATE_INFO_EXT;
createDestroyCallbackInfo.flags = VK_DEBUG_REPORT_INFORMATION_BIT_EXT
| VK_DEBUG_REPORT_WARNING_BIT_EXT
| VK_DEBUG_REPORT_PERFORMANCE_WARNING_BIT_EXT
| VK_DEBUG_REPORT_ERROR_BIT_EXT
| VK_DEBUG_REPORT_DEBUG_BIT_EXT;
createDestroyCallbackInfo.pfnCallback = &vulkanDebugReportCallback;
instanceInfoPNext = &createDestroyCallbackInfo;
}*/
// Instance create info struct
VkInstanceCreateInfo instanceInfo = {};
instanceInfo.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO;
instanceInfo.pNext = instanceInfoPNext;
instanceInfo.flags = 0;
instanceInfo.pApplicationInfo = &appInfo;
instanceInfo.enabledLayerCount = layers.size();
instanceInfo.ppEnabledLayerNames = layers.size() != 0 ? layers.data() : nullptr;
instanceInfo.enabledExtensionCount = extensions.size();
instanceInfo.ppEnabledExtensionNames = extensions.size() != 0 ? extensions.data() : nullptr;
// Create Vulkan instance
// TODO: Set allocators (if not on macOS/iOS)
MutexAccessor<VulkanContext> context = mState->context.access();
bool createInstanceSuccess = CHECK_VK vkCreateInstance(
&instanceInfo,
nullptr,
&context.data().instance);
if (!createInstanceSuccess) {
ZG_ERROR("Failed to create VkInstance");
return ZG_ERROR_GENERIC;
}
ZG_INFO("VkInstance created");
// Register debug report callback
if (mDebugMode) {
// Setup callback creation information
VkDebugReportCallbackCreateInfoEXT callbackCreateInfo = {};
callbackCreateInfo.sType = VK_STRUCTURE_TYPE_DEBUG_REPORT_CALLBACK_CREATE_INFO_EXT;
callbackCreateInfo.flags = VK_DEBUG_REPORT_INFORMATION_BIT_EXT
| VK_DEBUG_REPORT_WARNING_BIT_EXT
| VK_DEBUG_REPORT_PERFORMANCE_WARNING_BIT_EXT
| VK_DEBUG_REPORT_ERROR_BIT_EXT
| VK_DEBUG_REPORT_DEBUG_BIT_EXT;
callbackCreateInfo.pfnCallback = &vulkanDebugReportCallback;
// Register the callback
// TODO: Set allocators
auto vkCreateDebugReportCallbackEXT = (PFN_vkCreateDebugReportCallbackEXT)
vkGetInstanceProcAddr(context.data().instance, "vkCreateDebugReportCallbackEXT");
CHECK_VK vkCreateDebugReportCallbackEXT(
context.data().instance, &callbackCreateInfo, nullptr, &vulkanDebugCallback);
}
// TODO: At this point we should create a VkSurface using platform specific code
// Log available physical devices
vulkanLogAvailablePhysicalDevices(context.data().instance, context.data().surface);
// TODO: Heuristic to choose physical device
// Should probably take DISCRETE_GPU with largest amount of device local memory.
const uint32_t physicalDeviceIdx = 0;
{
constexpr uint32_t MAX_NUM_PHYSICAL_DEVICES = 32;
// Check how many physical devices there is
uint32_t numPhysicalDevices = 0;
CHECK_VK vkEnumeratePhysicalDevices(context.data().instance, &numPhysicalDevices, nullptr);
ZG_ASSERT(numPhysicalDevices <= MAX_NUM_PHYSICAL_DEVICES);
if (numPhysicalDevices > MAX_NUM_PHYSICAL_DEVICES) numPhysicalDevices = MAX_NUM_PHYSICAL_DEVICES;
// Retrieve physical devices
VkPhysicalDevice physicalDevices[MAX_NUM_PHYSICAL_DEVICES] = {};
CHECK_VK vkEnumeratePhysicalDevices(context.data().instance, &numPhysicalDevices, physicalDevices);
// Select the choosen physical device
ZG_ASSERT(physicalDeviceIdx < numPhysicalDevices);
context.data().physicalDevice = physicalDevices[physicalDeviceIdx];
// Store physical devices properties for the choosen device
vkGetPhysicalDeviceProperties(
context.data().physicalDevice, &context.data().physicalDeviceProperties);
}
ZG_INFO("Using physical device: %u -- %s",
physicalDeviceIdx, context.data().physicalDeviceProperties.deviceName);
// Log available device extensions
vulkanLogDeviceExtensions(physicalDeviceIdx,
context.data().physicalDevice, context.data().physicalDeviceProperties);
// Log available queue families
vulkanLogQueueFamilies(context.data().physicalDevice, context.data().surface);
// TODO: Heuristic to choose queue family for present and copy queues
// Should require the correct flags for each queue
const uint32_t queueFamilyIdx = 0;
return ZG_SUCCESS;
}
// Context methods
// --------------------------------------------------------------------------------------------
ZgResult swapchainResize(
uint32_t width,
uint32_t height) noexcept override final
{
(void)width;
(void)height;
return ZG_WARNING_UNIMPLEMENTED;
}
ZgResult swapchainBeginFrame(
ZgFramebuffer** framebufferOut) noexcept override final
{
(void)framebufferOut;
return ZG_WARNING_UNIMPLEMENTED;
}
ZgResult swapchainFinishFrame() noexcept override final
{
return ZG_WARNING_UNIMPLEMENTED;
}
ZgResult fenceCreate(ZgFence** fenceOut) noexcept override final
{
(void)fenceOut;
return ZG_WARNING_UNIMPLEMENTED;
}
// Stats
// --------------------------------------------------------------------------------------------
ZgResult getStats(ZgStats& statsOut) noexcept override final
{
(void)statsOut;
return ZG_WARNING_UNIMPLEMENTED;
}
// Pipeline methods
// --------------------------------------------------------------------------------------------
ZgResult pipelineRenderCreateFromFileSPIRV(
ZgPipelineRender** pipelineOut,
ZgPipelineRenderSignature* signatureOut,
const ZgPipelineRenderCreateInfoFileSPIRV& createInfo) noexcept override final
{
(void)pipelineOut;
(void)signatureOut;
(void)createInfo;
return ZG_WARNING_UNIMPLEMENTED;
}
ZgResult pipelineRenderCreateFromFileHLSL(
ZgPipelineRender** pipelineOut,
ZgPipelineRenderSignature* signatureOut,
const ZgPipelineRenderCreateInfoFileHLSL& createInfo) noexcept override final
{
(void)pipelineOut;
(void)signatureOut;
(void)createInfo;
return ZG_WARNING_UNIMPLEMENTED;
}
ZgResult pipelineRenderCreateFromSourceHLSL(
ZgPipelineRender** pipelineOut,
ZgPipelineRenderSignature* signatureOut,
const ZgPipelineRenderCreateInfoSourceHLSL& createInfo) noexcept override final
{
(void)pipelineOut;
(void)signatureOut;
(void)createInfo;
return ZG_WARNING_UNIMPLEMENTED;
}
ZgResult pipelineRenderRelease(
ZgPipelineRender* pipeline) noexcept override final
{
(void)pipeline;
return ZG_WARNING_UNIMPLEMENTED;
}
ZgResult pipelineRenderGetSignature(
const ZgPipelineRender* pipeline,
ZgPipelineRenderSignature* signatureOut) const noexcept override final
{
(void)pipeline;
(void)signatureOut;
return ZG_WARNING_UNIMPLEMENTED;
}
// Memory methods
// --------------------------------------------------------------------------------------------
ZgResult memoryHeapCreate(
ZgMemoryHeap** memoryHeapOut,
const ZgMemoryHeapCreateInfo& createInfo) noexcept override final
{
(void)memoryHeapOut;
(void)createInfo;
return ZG_WARNING_UNIMPLEMENTED;
}
ZgResult memoryHeapRelease(
ZgMemoryHeap* memoryHeap) noexcept override final
{
(void)memoryHeap;
return ZG_WARNING_UNIMPLEMENTED;
}
ZgResult bufferMemcpyTo(
ZgBuffer* dstBufferInterface,
uint64_t bufferOffsetBytes,
const uint8_t* srcMemory,
uint64_t numBytes) noexcept override final
{
(void)dstBufferInterface;
(void)bufferOffsetBytes;
(void)srcMemory;
(void)numBytes;
return ZG_WARNING_UNIMPLEMENTED;
}
// Texture methods
// --------------------------------------------------------------------------------------------
ZgResult texture2DGetAllocationInfo(
ZgTexture2DAllocationInfo& allocationInfoOut,
const ZgTexture2DCreateInfo& createInfo) noexcept override final
{
(void)allocationInfoOut;
(void)createInfo;
return ZG_WARNING_UNIMPLEMENTED;
}
// Framebuffer methods
// --------------------------------------------------------------------------------------------
ZgResult framebufferCreate(
ZgFramebuffer** framebufferOut,
const ZgFramebufferCreateInfo& createInfo) noexcept override final
{
(void)framebufferOut;
(void)createInfo;
return ZG_WARNING_UNIMPLEMENTED;
}
void framebufferRelease(
ZgFramebuffer* framebuffer) noexcept override final
{
(void)framebuffer;
}
// CommandQueue methods
// --------------------------------------------------------------------------------------------
ZgResult getPresentQueue(ZgCommandQueue** presentQueueOut) noexcept override final
{
*presentQueueOut = &mState->presentQueue;
return ZG_SUCCESS;
}
ZgResult getCopyQueue(ZgCommandQueue** copyQueueOut) noexcept override final
{
*copyQueueOut = &mState->copyQueue;
return ZG_SUCCESS;
}
// Private methods
// --------------------------------------------------------------------------------------------
private:
bool mDebugMode = false;
VulkanBackendState* mState = nullptr;
};
// Vulkan backend
// ------------------------------------------------------------------------------------------------
ZgResult createVulkanBackend(ZgBackend** backendOut, ZgContextInitSettings& settings) noexcept
{
// Allocate and create Vulkan backend
VulkanBackend* backend = zgNew<VulkanBackend>("Vulkan Backend");
// Initialize backend, return nullptr if init failed
ZgResult initRes = backend->init(settings);
if (initRes != ZG_SUCCESS)
{
zgDelete(backend);
return initRes;
}
*backendOut = backend;
return ZG_SUCCESS;
}
} // namespace zg
| 32.370455 | 102 | 0.70231 | [
"vector"
] |
87a34c5ff2a9d78609f1b025ec47bf51d5fb4f10 | 1,685 | hpp | C++ | lib/vector/Vector.hpp | frndmg/simplex-method | 0fe509d43ac794344b5d95f7e4faacd0dd444d56 | [
"MIT"
] | 2 | 2019-11-25T20:54:56.000Z | 2019-11-25T20:55:20.000Z | lib/vector/Vector.hpp | frndmg/simplex-method | 0fe509d43ac794344b5d95f7e4faacd0dd444d56 | [
"MIT"
] | null | null | null | lib/vector/Vector.hpp | frndmg/simplex-method | 0fe509d43ac794344b5d95f7e4faacd0dd444d56 | [
"MIT"
] | 1 | 2019-11-25T23:14:18.000Z | 2019-11-25T23:14:18.000Z | #pragma once
#include <vector>
#include <functional>
#include "Types.hpp"
class Vector {
public:
typedef tensor_t <1> :: type line_t;
typedef const std::function <real_t (real_t)> mapfunc_t;
typedef const std::function <real_t (real_t, real_t)> mapfunc_2_t;
private:
line_t line_;
public:
//Vector
Vector();
Vector(size_t size, real_t value);
Vector(line_t line);
Vector(size_t size, const std::function <real_t (size_t)> &construct);
~Vector();
const bool
operator== (const Vector &other)
const;
static void
Print(const Vector &v);
// VectorAttributes
const
line_t &GetLine()
const;
size_t
Size() const;
real_t
First() const,
Last() const,
&operator[] (const size_t index);
const real_t
&operator[] (const size_t index)
const;
// VectorTransformations
void
Pop(),
Push(const real_t value),
Push(const Vector &other),
Resize(const size_t new_size, const real_t value);
Vector
Reverse() const;
// VectorFunctional
static Vector
Map(const Vector &a, const Vector &b, mapfunc_2_t &map_lambda);
Vector
Map(mapfunc_t &map_lambda) const;
real_t
Reduce(mapfunc_2_t &map_lambda) const;
// TODO reduce,
// VectorOperators
Vector
operator+ () const,
operator- () const,
operator+ (const real_t scalar) const,
operator- (const real_t scalar) const,
operator* (const real_t scalar) const,
operator/ (const real_t scalar) const,
operator+ (const Vector &B) const,
operator- (const Vector &B) const;
// VectorPermutations
// TODO
// VectorAlgorithms
real_t
Abs() const,
operator^ (const Vector &other) const;
Vector
operator* (const Vector &other) const,
operator% (const Vector &other) const;
};
| 19.593023 | 71 | 0.703858 | [
"vector"
] |
87aaf7ac5fc0f3341814e8200341abcc5dd66bcd | 4,348 | cpp | C++ | src/integrators/deterministdirect.cpp | TheoBouche/pbrt-v3 | a44745896bd31458df55fdf0cdf0ffff7a7b2328 | [
"BSD-2-Clause"
] | null | null | null | src/integrators/deterministdirect.cpp | TheoBouche/pbrt-v3 | a44745896bd31458df55fdf0cdf0ffff7a7b2328 | [
"BSD-2-Clause"
] | null | null | null | src/integrators/deterministdirect.cpp | TheoBouche/pbrt-v3 | a44745896bd31458df55fdf0cdf0ffff7a7b2328 | [
"BSD-2-Clause"
] | null | null | null | // integrators/deterministDirect.cpp*
#include "integrators/deterministdirect.h"
#include "interaction.h"
#include "paramset.h"
#include "camera.h"
#include "film.h"
#include "stats.h"
namespace pbrt {
void DeterministDirectIntegrator::Preprocess(const Scene &scene,
Sampler &sampler) {
std::vector<int> nLightSamples;
//create a new instance of the sampler for sampling during preprocess
std::unique_ptr<Sampler> preSampler = sampler.Clone(0);
//initialize the sampler (the point used is not important in this case)
for (const auto &light : scene.lights) {
nLightSamples.push_back(preSampler->RoundCount(light->nSamples));
}
//Request samples for sampling all lights
for (size_t i = 0; i < scene.lights.size(); ++i) {
preSampler->Request2DArray(nLightSamples[i]);
}
Point2i pixel(0.0, 0.0);
preSampler->StartPixel(pixel);
preSampler->GetCameraSample(pixel);
//sample points on the lights and put the resulting point lights in the lightSources vector to make re-ordering them easier later on
for (size_t i = 0; i < scene.lights.size(); ++i) {
int nSamples = nLightSamples[i];
const Point2f *uLightArray = preSampler->Get2DArray(nSamples);
//if the array wasn't sampled correctly, sample the source normally
if(!uLightArray){
//store a point on the source
LightSource newSource {};
newSource.light = &scene.lights[i];
newSource.uLight = preSampler->Get2D();
newSource.nSamples = 1;
lightSources.push_back(newSource);
}
else{
for (int j = 0; j < nSamples; ++j){
//store a point on the source
LightSource newSource {};
newSource.light = &scene.lights[i];
newSource.uLight = uLightArray[j];
newSource.nSamples = nSamples;
lightSources.push_back(newSource);
}
}
}
}
Spectrum DeterministDirectIntegrator::Li(const RayDifferential &ray,
const Scene &scene, Sampler &sampler,
MemoryArena &arena, int depth) const {
BxDFType bsdfFlags = BxDFType(BSDF_ALL & ~BSDF_SPECULAR);
Spectrum L(0.f);
SurfaceInteraction isect;
//if no intersection found, consider that there is no incoming light (not considering environment maps)
if (!scene.Intersect(ray, &isect)) {
for (const auto &light : scene.lights) L += light->Le(ray);
return L;
}
isect.ComputeScatteringFunctions(ray, arena);
if (!isect.bsdf){
return Li(isect.SpawnRay(ray.d), scene, sampler, arena, depth);
}
Vector3f wo = isect.wo;
L += isect.Le(wo);
if (lightSources.size() > 0) {
for(int i = 0; i<lightSources.size();++i){
Vector3f wi;
Float lightPdf = 0;
VisibilityTester visibility;
Point2f uLight = sampler.Get2D();
Spectrum Li = (*lightSources[i].light)->Sample_Li(isect, lightSources[i].uLight, &wi, &lightPdf, &visibility);
if (lightPdf > 0 && !Li.IsBlack()) {
//compute the BSDF
Spectrum f;
f = isect.bsdf->f(isect.wo, wi, bsdfFlags) * AbsDot(wi, isect.shading.n);
if (!f.IsBlack()) {
if (!visibility.Unoccluded(scene)) {
Li = Spectrum(0.f);
}
if (!Li.IsBlack()) {
L += (f * Li / lightPdf) / lightSources[i].nSamples;
}
}
}
}
}
if (depth + 1 < maxDepth) {
// Trace rays for specular reflection and refraction
L += SpecularReflect(ray, isect, scene, sampler, arena, depth);
L += SpecularTransmit(ray, isect, scene, sampler, arena, depth);
}
return L;
}
DeterministDirectIntegrator *CreateDeterministDirectIntegrator(
const ParamSet ¶ms, std::shared_ptr<Sampler> sampler,
std::shared_ptr<const Camera> camera) {
int np;
const int *pb = params.FindInt("pixelbounds", &np);
int maxDepth = params.FindOneInt("maxdepth", 5);
Bounds2i pixelBounds = camera->film->GetSampleBounds();
if (pb) {
if (np != 4)
Error("Expected four values for \"pixelbounds\" parameter. Got %d.",
np);
else {
pixelBounds = Intersect(pixelBounds,
Bounds2i{{pb[0], pb[2]}, {pb[1], pb[3]}});
if (pixelBounds.Area() == 0)
Error("Degenerate \"pixelbounds\" specified.");
}
}
return new DeterministDirectIntegrator(maxDepth, camera, sampler, pixelBounds);
}
} // namespace pbrt
| 34.784 | 134 | 0.640524 | [
"vector"
] |
87afdcc613c261860f3db514f9f40d02a0b8ce56 | 4,437 | hpp | C++ | wz4/wz4frlib/fxparticle_mc.hpp | wzman/werkkzeug4CE | af5ff27829ed4c501515ef5131165048e991c9b4 | [
"BSD-2-Clause"
] | 47 | 2015-03-22T05:58:47.000Z | 2022-03-29T19:13:37.000Z | wz4/wz4frlib/fxparticle_mc.hpp | whpskyeagle/werkkzeug4CE | af5ff27829ed4c501515ef5131165048e991c9b4 | [
"BSD-2-Clause"
] | null | null | null | wz4/wz4frlib/fxparticle_mc.hpp | whpskyeagle/werkkzeug4CE | af5ff27829ed4c501515ef5131165048e991c9b4 | [
"BSD-2-Clause"
] | 16 | 2015-12-31T08:13:18.000Z | 2021-03-09T02:07:30.000Z | /*+**************************************************************************/
/*** ***/
/*** This file is distributed under a BSD license. ***/
/*** See LICENSE.txt for details. ***/
/*** ***/
/**************************************************************************+*/
#ifndef FILE_WZ4FRLIB_FXPARTICLE_MC_HPP
#define FILE_WZ4FRLIB_FXPARTICLE_MC_HPP
#include "base/types.hpp"
#include "wz4frlib/wz4_demo2.hpp"
#include "wz4frlib/wz4_demo2_ops.hpp"
#include "wz4frlib/wz4_mesh.hpp"
#include "wz4frlib/wz4_mtrl2.hpp"
#include "wz4frlib/fxparticle_ops.hpp"
#include "util/shaders.hpp"
#include "extra/mcubes.hpp"
/****************************************************************************/
// template<class PartType,class SimdType,class FieldType>
struct RNMarchingCubesTemplate
{
static const sInt Color = 0;
struct SimdType
{
__m128 x,y,z;
static __m128 cr,cg,cb;
};
struct PartType
{
sF32 x,y,z;
static sU32 c;
};
typedef MCPotField FieldType;
typedef Wz4RenderParaMarchingCubes OpParaType;
typedef Wz4RenderAnimMarchingCubes OpAnimType;
};
/****************************************************************************/
struct RNMarchingCubesColorTemplate
{
static const sInt Color = 1;
struct SimdType
{
__m128 x,y,z;
__m128 cr,cg,cb;
};
struct PartType
{
sF32 x,y,z;
sU32 c;
};
typedef MCPotFieldColor FieldType;
typedef Wz4RenderParaMarchingCubesColor OpParaType;
typedef Wz4RenderAnimMarchingCubesColor OpAnimType;
};
/****************************************************************************/
template<class T>
class RNMarchingCubesBase : public Wz4RenderNode
{
public:
enum RNMarchingCubesConsts
{
ContainerSize = 64,
// CellSize = 8,
HashSize = (1<<10),
HashMask = (HashSize-1),
};
struct funcinfo
{
__m128 tresh4;
__m128 treshf4;
__m128 one;
__m128 epsilon;
typename T::SimdType *parts4;
sInt pn4;
sF32 iso;
sF32 tresh;
sF32 treshf;
typename T::PartType *parts;
sInt pn;
};
private:
// particle system interface
Wz4PartInfo PInfo;
sF32 Time;
MarchingCubesHelper MC;
sInt MaxThread;
typename T::FieldType **PotData;
sInt PotSize;
typename T::SimdType **SimdParts;
sInt SimdCount;
sStsWorkload *Workload;
// hashing
struct PartContainer
{
PartContainer *Next;
sInt Count;
typename T::PartType Parts[ContainerSize];
};
struct HashContainer
{
HashContainer *Next;
PartContainer *FirstPart;
sInt IX,IY,IZ;
};
sArray<HashContainer *> FreeHashConts; // currently free containers
sArray<HashContainer *> NodeHashConts; // for each gridcube, the first container in list
sArray<HashContainer *> ThreadHashConts;// for each gridcube, the first container in list
sArray<PartContainer *> AllPartContBlocks; // i allocate the containers in blocks of 1024, because i need so many of them
sArray<PartContainer *> FreePartConts; // currently free containers
sArray<PartContainer *> NodePartConts; // particle containers in NodeConts list
sArray<PartContainer *> ThreadPartConts;//
HashContainer *HashTable[HashSize];
// GeoBuffers
GeoBufferHelper Geos;
GeoBufferHelper::GeoBuffer *CurrentGeo;
// functions
HashContainer *GetHashContainer();
PartContainer *GetPartContainer();
static void func(const sVector31 &v,typename T::FieldType &pot,const funcinfo &fi);
void Spatial();
public:
template <int base,int subdiv> void RenderT(sInt start,sInt count,sInt thread);
private:
void Render();
public:
RNMarchingCubesBase();
~RNMarchingCubesBase();
void Init();
typename T::OpParaType Para,ParaBase;
typename T::OpAnimType Anim;
Wz4ParticleNode *Source;
Wz4Mtrl *Mtrl;
void Simulate(Wz4RenderContext *ctx);
void Prepare(Wz4RenderContext *ctx);
void Render(Wz4RenderContext *ctx);
};
/****************************************************************************/
typedef RNMarchingCubesBase<RNMarchingCubesTemplate> RNMarchingCubes;
typedef RNMarchingCubesBase<RNMarchingCubesColorTemplate> RNMarchingCubesColor;
/****************************************************************************/
#endif // FILE_WZ4FRLIB_FXPARTICLE_MC_HPP
| 24.11413 | 124 | 0.599053 | [
"render"
] |
87b0112e0fc6ecc154a0c25e1b9de505158c1670 | 1,109 | cpp | C++ | main.cpp | zu1kbackup/pangolin | b2b668f7f3419d6dfd7eb04c7cba28d4385cfd35 | [
"Unlicense"
] | 37 | 2020-11-27T00:31:43.000Z | 2022-03-30T11:27:49.000Z | main.cpp | zu1kbackup/pangolin | b2b668f7f3419d6dfd7eb04c7cba28d4385cfd35 | [
"Unlicense"
] | null | null | null | main.cpp | zu1kbackup/pangolin | b2b668f7f3419d6dfd7eb04c7cba28d4385cfd35 | [
"Unlicense"
] | 12 | 2021-07-10T12:23:16.000Z | 2022-03-07T06:48:14.000Z | #include "inject/injector.h"
#include <zero/log.h>
#include <zero/cmdline.h>
int main(int argc, char ** argv) {
INIT_CONSOLE_LOG(zero::INFO);
zero::CCmdline cmdline;
cmdline.add({"pid", "process id", zero::value<int>()});
cmdline.addOptional({"daemon", 'd', "daemon mode", zero::value<bool>(), true});
cmdline.addOptional({"environs", 'e', "environment variables", zero::value<std::vector<std::string>>()});
cmdline.footer("inject argv");
cmdline.parse(argc, argv);
int pid = cmdline.get<int>("pid");
bool daemon = cmdline.getOptional<bool>("daemon");
std::vector<std::string> arguments = cmdline.rest();
std::vector<std::string> environs = cmdline.getOptional<std::vector<std::string>>("environs");
if (arguments.empty()) {
LOG_ERROR("inject empty argv");
return -1;
}
LOG_INFO("exec %s", zero::strings::join(arguments, " ").c_str());
CInjector injector;
if (!injector.open(pid)) {
LOG_ERROR("process injector open failed");
return -1;
}
return injector.inject(arguments, environs, daemon);
}
| 28.435897 | 109 | 0.630298 | [
"vector"
] |
87bbd8b39c1eae357a1ac1d1e529335d5e8479ef | 3,145 | cpp | C++ | test/nuc/main.cpp | atrtnkw/sph | c6bb3d7fd18f57c51fe60197706741e5a26e6ce4 | [
"MIT"
] | 2 | 2018-07-11T00:43:01.000Z | 2020-01-11T13:41:50.000Z | test/nuc/main.cpp | atrtnkw/sph | c6bb3d7fd18f57c51fe60197706741e5a26e6ce4 | [
"MIT"
] | null | null | null | test/nuc/main.cpp | atrtnkw/sph | c6bb3d7fd18f57c51fe60197706741e5a26e6ce4 | [
"MIT"
] | 1 | 2020-01-06T14:22:25.000Z | 2020-01-06T14:22:25.000Z | #include <iostream>
#include <vector>
#include <cassert>
#include <cstring>
#include <limits>
enum KernelType {CubicSpline = 0, WendlandC2 = 1, WendlandC4 = 2};
#include "particle_simulator.hpp"
#include "hdr_run.hpp"
#include "hdr_time.hpp"
#include "hdr_heos.hpp"
#include "hdr_nuc.hpp"
#include "hdr_nse.hpp"
inline PS::F64 getRandomNumber() {
return ((PS::F64) rand() / ((PS::F64)RAND_MAX + 1.));
}
struct SPH {
PS::F64 dens;
PS::F64 uene;
PS::F64 temp;
PS::F64 pres;
PS::F64 vsnd;
PS::F64 abar;
PS::F64 zbar;
PS::F64 dnuc;
NR::Nucleon cmps;
PS::S64 cnt;
SPH() {
dens = 0.;
uene = 0.;
temp = 0.;
pres = 0.;
vsnd = 0.;
abar = 0.;
zbar = 0.;
dnuc = 0.;
for(PS::S32 k = 0; k < NR::NumberOfNucleon; k++) {
cmps[k] = 0.;
}
cnt = 0;
}
void calcAbarZbar() {
PS::F64 abarinv = 0.;
PS::F64 zbar = 0.;
for(PS::S32 k = 0; k < NR::NumberOfNucleon; k++) {
abarinv += NR::ainv[k] * this->cmps[k];
zbar += NR::zaratio * this->cmps[k];
}
this->abar = 1. / abarinv;
this->zbar = this->abar * zbar;
}
void calcReleasedEnergyConstantTimestep(PS::F64 dt) {
this->dnuc = CalcNRH::getGeneratedEnergy(dt,
this->dens,
this->temp,
this->cmps.getPointer());
}
void calcInternalEnergy() {
PS::F64 dd = this->dens * CodeUnit::UnitOfDensity;
PS::F64 pp = 0.;
PS::F64 uu = 0.;
PS::F64 du = 0.;
PS::F64 cs = 0.;
bool eosfail;
helmeos2_(&this->temp, &dd, &this->abar, &this->zbar, &pp, &uu, &du, &cs, &eosfail);
this->uene = uu * CodeUnit::UnitOfEnergyInv;
}
void scan(FILE *fp) {
fscanf(fp, "%lf%lf", &this->temp, &this->dens);
for(PS::S32 k = 0; k < NR::NumberOfNucleon; k++) {
fscanf(fp, "%lf", &this->cmps[k]);
}
this->dens *= CodeUnit::UnitOfDensityInv;
}
void print(FILE *fp,
PS::F64 time = 0.) {
fprintf(fp, "%+e\n", time);
fprintf(fp, "%+e %+e %+e %+e\n", this->temp,
this->dens * CodeUnit::UnitOfDensity,
this->uene * CodeUnit::UnitOfEnergy,
this->dnuc * CodeUnit::UnitOfEnergy);
for(PS::S32 k = 0; k < NR::NumberOfNucleon; k++) { // 5 -- 17
fprintf(fp, " %+.8e", this->cmps[k]);
if(k == 5 || k == 11 || k == NR::NumberOfNucleon - 1) {
fprintf(fp, "\n");
}
}
}
};
int main(int argc,
char ** argv) {
RP::FlagDamping = 0;
PS::F64 dtime;
SPH sph;
FILE *fp = fopen(argv[1], "r");
fscanf(fp, "%lf", &dtime);
sph.scan(fp);
fclose(fp);
sph.calcAbarZbar();
sph.calcInternalEnergy();
sph.calcReleasedEnergyConstantTimestep(dtime);
fp = fopen(argv[2], "w");
sph.print(fp, dtime);
fclose(fp);
return 0;
}
| 25.778689 | 92 | 0.475994 | [
"vector"
] |
87bc4ba2faf4a36c01c914bc590236ca8d9217c6 | 1,088 | hpp | C++ | thirdparty/libgenerator/inc/generator/PathVertex.hpp | ppiecuch/godot | ff2098b324b814a0d1bd9d5722aa871fc5214fab | [
"MIT",
"Apache-2.0",
"CC-BY-4.0",
"Unlicense"
] | null | null | null | thirdparty/libgenerator/inc/generator/PathVertex.hpp | ppiecuch/godot | ff2098b324b814a0d1bd9d5722aa871fc5214fab | [
"MIT",
"Apache-2.0",
"CC-BY-4.0",
"Unlicense"
] | null | null | null | thirdparty/libgenerator/inc/generator/PathVertex.hpp | ppiecuch/godot | ff2098b324b814a0d1bd9d5722aa871fc5214fab | [
"MIT",
"Apache-2.0",
"CC-BY-4.0",
"Unlicense"
] | null | null | null |
// Copyright 2015 Markus Ilmola
// This library is free software; you can redistribute it and/or
// modify it under the terms of 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.
#ifndef GENERATOR_PATHVERTEX_HPP
#define GENERATOR_PATHVERTEX_HPP
#include "math.hpp"
namespace generator {
class PathVertex {
public:
/// Unit length vector perpendicular to the path at this point.
/// Also the x-axis of the path coordinate system at this point.
gml::dvec3 normal;
gml::dvec3 position;
/// Unit length vector parallel to the path at this point.
/// Also the z-axis of the path at this point.
gml::dvec3 tangent;
double texCoord;
PathVertex() :
normal{},
position{},
tangent{},
texCoord{} {}
/// Returns tangent x normal.
/// Also the y-axis of the path coordinate system.
/// See: http://mathworld.wolfram.com/BinormalVector.html
gml::dvec3 binormal() const noexcept {
return cross(tangent, normal);
}
};
} // namespace generator
#endif
| 23.652174 | 69 | 0.722426 | [
"vector"
] |
87c40d5a2134e4d510653a5fb4b646d82eb64403 | 977 | cpp | C++ | InterviewBit/Heaps And Maps/WaysToFormMaxHeap.cpp | Code-With-Aagam/competitive-programming | 610520cc396fb13a03c606b5fb6739cfd68cc444 | [
"MIT"
] | 2 | 2022-02-08T12:37:41.000Z | 2022-03-09T03:48:56.000Z | InterviewBit/Heaps And Maps/WaysToFormMaxHeap.cpp | ShubhamJagtap2000/competitive-programming-1 | 3a9a2e3dd08f8fa8ab823f295cd020d08d3bff84 | [
"MIT"
] | null | null | null | InterviewBit/Heaps And Maps/WaysToFormMaxHeap.cpp | ShubhamJagtap2000/competitive-programming-1 | 3a9a2e3dd08f8fa8ab823f295cd020d08d3bff84 | [
"MIT"
] | 2 | 2021-01-23T14:35:48.000Z | 2021-03-15T05:04:24.000Z | const long long mod = 1e9 + 7;
const long long N = 101;
vector<vector<long long>> nCr(N, vector<long long>(N, -1));
vector<long long> dp(N, -1);
long long findNcR(long long n, long long r) {
if (nCr[n][r] != -1) {
return nCr[n][r] % mod;
}
if (r > n) {
nCr[n][r] = 0;
return nCr[n][r];
}
if (n <= 1 || r == 0) {
nCr[n][r] = 1;
return nCr[n][r];
}
nCr[n][r] = (findNcR(n - 1, r - 1) % mod + findNcR(n - 1, r) % mod) % mod;
return nCr[n][r] % mod;
}
long long getLeft(long long n) {
if (n == 1) {
return 0;
}
long long h = log2(n);
long long numh = (1 << h);
long long last = n - ((1 << h) - 1);
if (last >= (numh / 2)) {
return (1 << h) - 1;
} else {
return (1 << h) - 1 - ((numh / 2) - last);
}
}
int Solution::solve(int n) {
if (n <= 1) {
return 1;
}
if (dp[n] != -1) {
return dp[n];
}
long long left = getLeft(n);
dp[n] = (findNcR(n - 1, left) % mod * solve(left) % mod * solve(n - left - 1) % mod) % mod;
return dp[n] % mod;
}
| 20.354167 | 92 | 0.501535 | [
"vector"
] |
87c7f8e6dea01769004daf5aa75e588bc1b81bb3 | 16,292 | cpp | C++ | Src/GameManager.cpp | muffinista/palm-pitch | aa09c857b1ccc14672b3eb038a419bd13abc0925 | [
"MIT"
] | 1 | 2015-11-13T21:40:35.000Z | 2015-11-13T21:40:35.000Z | Src/GameManager.cpp | muffinista/palm-pitch | aa09c857b1ccc14672b3eb038a419bd13abc0925 | [
"MIT"
] | null | null | null | Src/GameManager.cpp | muffinista/palm-pitch | aa09c857b1ccc14672b3eb038a419bd13abc0925 | [
"MIT"
] | null | null | null | #include <PalmOS.h>
#include "Common.h"
#include "ComputerPlayer.h"
#include "GameManager.h"
#include "GameTable.h"
#include "HumanPlayer.h"
#include "PitchApp.h"
GameManager::GameManager() {
//
// set some defaults
//
cutthroat = false;
winning_score = 11;
first_game = true;
scores[0] = 0;
scores[1] = 0;
scores[2] = 0;
numPlayers = 0;
game_status = PreGame;
trick_rounds = 0;
cards_played = 0;
human = NULL;
current = NULL;
games_won[0] = 0;
games_won[1] = 0;
games_won[2] = 0;
ai_level = 100;
//
// create some objects
//
theDeck = new Deck();
trk = new Trick();
tbl = new GameTable();
}
GameManager::~GameManager() {
delete theDeck;
delete trk;
delete tbl;
for( Int16 i = 0; i < numPlayers; i++ ) {
delete players[i];
}
}
void GameManager::Reset() {
delete theDeck;
delete trk;
delete tbl;
for( Int16 i = 0; i < numPlayers; i++ ) {
delete players[i];
}
players.DeleteAll();
Player::playerIndex_static = 0;
first_game = true;
scores[0] = 0;
scores[1] = 0;
scores[2] = 0;
numPlayers = 0;
game_status = PreGame;
trick_rounds = 0;
cards_played = 0;
human = NULL;
current = NULL;
theDeck = new Deck();
trk = new Trick();
tbl = new GameTable();
}
void GameManager::ShortDelay() {
if ( HostGremlinIsRunning() == false ) {
SysTaskDelay( play_delay_ticks * 3 / 4);
}
}
void GameManager::LongDelay() {
if ( HostGremlinIsRunning() == false ) {
SysTaskDelay( play_delay_ticks );
}
}
void GameManager::Load() {
CAppPrefStream pref(CreatorID, PrefID, PrefVersion);
if ( pref.Read() ) {
Int16 tmp = 0;
// load the GameStatus
pref >> tmp;
Status((GameStatus)tmp);
// load the # of players
pref >> numPlayers;
if ( numPlayers ) {
createPlayers();
}
// load player data accoring to # of players
for ( Int16 i = 0; i < numPlayers; i++ ) {
players[i]->Read(pref);
} // for
assignTeams();
// load the human
pref >> tmp;
if ( tmp != -1 ) {
human = getPlayerIter(tmp);
}
else {
human = NULL;
}
// load the current player
pref >> tmp;
if ( tmp != -1 ) {
current = getPlayerIter(tmp);
}
else {
current = NULL;
}
pref >> scores[0];
pref >> scores[1];
pref >> scores[2];
pref >> first_hand;
pref >> first_game;
pref >> winning_score;
for ( int i = 0; i < 4; i++ ) {
pref >> player_names[i];
}
pref >> play_delay_ticks;
pref >> no_trump_first_trick;
pref >> dealer_take_bid;
pref >> win_on_bid;
pref >> games_played;
pref >> games_won[0];
pref >> games_won[1];
pref >> games_won[2];
pref >> cards_played;
pref >> trick_rounds;
pref >> ai_level;
pref >> win_on_smudge;
pref >> cutthroat;
// load any trick data
trk->Read(pref);
// load the game table
tbl->Read(pref);
pref.Close();
}
else {
cutthroat = false;
no_trump_first_trick = true;
dealer_take_bid = true;
win_on_bid = true;
play_delay_ticks = SysTicksPerSecond();
const char *random_name[] = {"Chuck", "Mary", "Bob", "Igor", "Marge", "Jill",
"Billy", "Beth", "Jane", "Izzy", "Yvette",
"Han", "Peter", "Bruce", "Brian", "Phil", "Eunice"};
const Int16 name_count = 16;
Int16 random_num[3];
random_num[0] = SysRandom(0) % name_count;
random_num[1] = SysRandom(0) % name_count;
random_num[2] = SysRandom(0) % name_count;
while ( random_num[0] == random_num[1] || random_num[0] == random_num[2] ||
random_num[1] == random_num[2] ) {
random_num[0] = SysRandom(0) % name_count;
random_num[1] = SysRandom(0) % name_count;
random_num[2] = SysRandom(0) % name_count;
}
player_names[1] = random_name[random_num[0]];
player_names[2] = random_name[random_num[1]];
player_names[3] = random_name[random_num[2]];
const char *human = "Human";
player_names[0] = human;
games_played = 0;
}
}
void GameManager::Save() {
CAppPrefStream pref(CreatorID, PrefID, PrefVersion);
pref.SetSaved(true);
// save the GameStatus
pref << (Int16)Status();
// save the # of players
pref << numPlayers;
// save player data
for ( Int16 i = 0; i < numPlayers; i++ ) {
players[i]->Write(pref);
} // for
// save the human
if ( human ) {
pref << (*human)->playerIndex;
}
else {
pref << -1;
}
// save the current player
if ( current ) {
pref << (*current)->playerIndex;
}
else {
pref << -1;
}
pref << scores[0];
pref << scores[1];
pref << scores[2];
pref << first_hand;
pref << first_game;
pref << winning_score;
for ( int i = 0; i < 4; i++ ) {
pref << player_names[i];
}
pref << play_delay_ticks;
pref << no_trump_first_trick;
pref << dealer_take_bid;
pref << win_on_bid;
pref << games_played;
pref << games_won[0];
pref << games_won[1];
pref << games_won[2];
pref << cards_played;
pref << trick_rounds;
pref << ai_level;
pref << win_on_smudge;
pref << cutthroat;
// save any trick data
trk->Write(pref);
// save the game table
tbl->Write(pref);
} // Save
Boolean GameManager::CutThroat() {
return cutthroat;
}
void GameManager::CutThroat(Boolean x) {
if ( players.GetCount() == 0 ) {
createPlayers();
}
if ( cutthroat != x && x == true ) {
// if ( players.GetCount() == 4 ) {
// delete players[3];
// numPlayers = 3;
players[0]->team = 'a';
players[1]->team = 'b';
players[2]->team = 'c';
// }
}
else if ( cutthroat != x && x == false ) {
if ( players.GetCount() == 3 ) {
players.Add( new ComputerPlayer('b', player_names[3]) );
numPlayers = 4;
}
players[0]->team = 'a';
players[2]->team = 'a';
players[1]->team = 'b';
players[3]->team = 'b';
// }
}
cutthroat = x;
}
void GameManager::createPlayers() {
if ( players.GetCount() == 0 ) {
if ( numPlayers == 3 || CutThroat() ) {
numPlayers = 3;
humanIndex = 0;
CString name1 = player_names[0];
CString name2 = player_names[1];
CString name3 = player_names[2];
players.Add( new HumanPlayer('a', name1) );
players.Add( new ComputerPlayer('b', name2) );
players.Add( new ComputerPlayer('c', name3) );
// players.Add( new HumanPlayer('a', player_names[0]) );
// players.Add( new ComputerPlayer('b', player_names[1]) );
// players.Add( new ComputerPlayer('c', player_names[2]) );
}
else {
numPlayers = 4;
humanIndex = 0;
CString name1 = player_names[0];
CString name2 = player_names[1];
CString name3 = player_names[2];
CString name4 = player_names[3];
players.Add( new HumanPlayer('a', name1) );
players.Add( new ComputerPlayer('b', name2) );
players.Add( new ComputerPlayer('a', name3) );
players.Add( new ComputerPlayer('b', name4) );
// players.Add( new HumanPlayer('a', player_names[0]) );
// players.Add( new ComputerPlayer('b', player_names[1]) );
// players.Add( new ComputerPlayer('a', player_names[2]) );
// players.Add( new ComputerPlayer('b', player_names[3]) );
}
}
current = players.BeginIterator();
tbl->lead = players[0];
tbl->winning_bidder = NULL;
human = players.BeginIterator();
humanIndex = 0;
}
Player* GameManager::getPlayer(Int16 index) {
Player *tmp = players[index];
return tmp;
}
CArray <Player*>::iterator GameManager::getPlayerIter(Int16 index) {
CArray <Player*>::iterator tmp = players.BeginIterator();
for ( Int16 i = 0; i < index; i++ ) {
tmp++;
}
return tmp;
}
CArray <Player*>::iterator GameManager::getNextPlayerIter(CArray<Player*>::iterator i) {
Int16 index = (*i)->playerIndex;
if ( index == numPlayers - 1 ) {
CArray <Player*>::iterator tmp = players.BeginIterator();
return tmp;
}
return getPlayerIter(index + 1);
}
Player* GameManager::getNextPlayer(Player *p) {
if ( p->playerIndex == numPlayers - 1 ) {
return players[0];
}
return players[p->playerIndex + 1];
}
Player* GameManager::getPrevPlayer(Player *p) {
if ( p->playerIndex == 0 ) {
return players[numPlayers - 1];
}
return players[p->playerIndex - 1];
}
Player* GameManager::getNextPlayer(CArray <Player*>::iterator i) {
Int16 index = (*i)->playerIndex;
return getNextPlayer(players[index]);
}
void GameManager::assignTeams() {
for (CArray <Player*>::iterator i = players.BeginIterator(); i != players.EndIterator(); i++ ) {
for (CArray <Player*>::iterator a = players.BeginIterator(); a != players.EndIterator(); a++ ) {
if( (*a)->getTeam() == (*i)->getTeam() & (*a) != (*i) ) {
(*a)->assignPartner(*i);
(*i)->assignPartner(*a);
}
}
}
}
Boolean GameManager::tied() {
if ( CutThroat() && ( scores[0] == scores[1] || scores[0] == scores[2] || scores[1] == scores[2] ) ) {
return true;
}
else if ( scores[0] == scores[1] ) {
return true;
}
return false;
}
void GameManager::dealCards() {
// clear out our list of played cards
tbl->clear_played_cards();
theDeck->reset();
for (CArray <Player*>::iterator i = players.BeginIterator(); i != players.EndIterator(); i++ )
{
(*i)->dealCards(*theDeck, CARDS_IN_HAND);
(*i)->clearWinnings();
}
}
void GameManager::FinalizeBidding( ) {
}
void GameManager::BidSummary( ) {
}
void GameManager::ResetBidding() {
// winner = tbl->dealer;
tbl->winning_bidder = NULL;
tbl->high_bid = -1;
}
Boolean GameManager::GetNextBid(Trick *trk, Boolean bid_already_set ) {
Player *p = *tbl->current_bidder;
Int16 tmp = -1;
/* if ( tbl->winning_bidder ) {
tmp = p->BeginBidProcess( (*tbl->dealer), *tbl->winning_bidder );
}
else {
tmp = p->BeginBidProcess( (*tbl->dealer), NULL );
}
if ( p->playerIndex == (*tbl->dealer)->playerIndex && tmp < 2 && tbl->high_bid < 2 ) {
tmp = 2;
}
*/
if ( p->playerIndex == (*tbl->dealer)->playerIndex && tbl->high_bid < 2 ) {
p->BeginBidProcess( (*tbl->dealer), NULL );
tmp = 2;
}
else if ( tbl->winning_bidder ) {
tmp = p->BeginBidProcess( (*tbl->dealer), *tbl->winning_bidder );
}
else {
tmp = p->BeginBidProcess( (*tbl->dealer), NULL );
}
//
// the bid either must be higher, or the dealer can take the bid - if that pref is set
//
if (
tmp > tbl->high_bid ||
( dealer_take_bid &&
(*tbl->current_bidder)->playerIndex == (*tbl->dealer)->playerIndex &&
tmp >= tbl->high_bid )
) {
//
// this bidder is the new winner
//
tbl->winning_bidder = tbl->current_bidder;
tbl->lead = (*tbl->winning_bidder);
// don't let the dealer bid more than has already been
// bid, unless it's smudge
if ( tbl->winning_bidder == tbl->dealer && tmp != 5 ) {
tmp = tbl->high_bid;
}
if ( tbl->winning_bidder == tbl->dealer ) {
if ( tmp <= 2 ) {
tmp = 2;
tbl->high_bid = 2;
(*tbl->winning_bidder)->bid = 2;
}
tbl->high_bid = tmp;
tbl->bid = tmp;
}
else {
tbl->high_bid = tmp;
tbl->bid = tmp;
}
return true;
}
else if ( tbl->winning_bidder == tbl->dealer && tbl->high_bid < 2 ) {
tbl->high_bid = 2;
return true;
}
if ( tbl->current_bidder == tbl->dealer && tbl->high_bid < 2 ) {
tbl->winning_bidder = tbl->dealer;
tbl->lead = (*tbl->winning_bidder);
(*tbl->winning_bidder)->bid = 2;
return true;
}
// this was not a winning bid
return false;
}
void GameManager::NewGame() {
Reset();
createPlayers();
assignTeams();
tbl->Reset();
Status(SetGameInfo);
}
void GameManager::NewTrick() {
NewTrick(true);
}
void GameManager::NewTrick(Boolean move_deal) {
trk->CleanUp();
cards_played = 0;
tbl->Reset(move_deal);
}
Boolean GameManager::IsTrickOver() {
if ( cards_played == numPlayers ) {
return true;
}
return false;
}
Boolean GameManager::IsHandOver() {
if ( trick_rounds == CARDS_IN_HAND ) {
return true;
} // if ( rounds == 6 )
return false;
}
void GameManager::HandleEndOfTrick() {
tbl->lead = trk->Winner();
current = getPlayerIter( tbl->lead->playerIndex );
cards_played = 0;
trick_rounds++;
for (CArray <Player*>::iterator i = players.BeginIterator(); i != players.EndIterator(); i++ ) {
if ( (*i)->played_card != NULL ) {
(*i)->played_card = NULL;
}
}
trk->book->DeleteAll();
trk->current_winner = NULL;
trk->lead = NULL;
Status(ReadyToPlay);
}
void GameManager::HandleEndOfHand() {
Status(HandOver);
trick_rounds = 0;
trk->PostHandCleanUp();
tbl->Reset();
Int16 cnt = 0;
for (cnt = 0; cnt < numPlayers; cnt++ )
{
players[cnt]->post_hand_cleanup();
}
}
Boolean GameManager::GetNextPlay(Trick *trk ) {
Boolean result = (*current)->PickCard(trk);
if ( result == true ) {
char hand[22];
hand[0] = 0;
for (int cnt = 0; cnt < (*current)->hand.GetCount(); cnt++ ) {
char tmpstr[4];
tmpstr[0] = (*current)->hand[cnt]->FaceChar();
tmpstr[1] = (*current)->hand[cnt]->SuitChar();
tmpstr[2] = ' ';
tmpstr[3] = 0;
StrCat(hand, tmpstr);
}
HostTraceOutputTL(sysErrorClass,
"%d: %s -> %c%c ",
(*current)->playerIndex,
hand,
(*current)->PlayedCard()->FaceChar(),
(*current)->PlayedCard()->SuitChar() );
if ( cards_played + 1 == numPlayers ) {
HostTraceOutputTL(sysErrorClass, "*********************");
}
}
return result;
}
Boolean GameManager::NextPlayedCard(Player *p, Card *c) {
if ( c != NULL ) {
cards_played++;
//
// analyze the current standings for this hand
//
trk->RecordPlayedCard( p, c );
current = getNextPlayerIter(current);
// add the card to the vector of played cards
// so that our AI can do some figuring
tbl->played_cards.Add(c);
return true;
}
return false;
}
GameStatus GameManager::CheckGameCondition() {
return game_status;
}
void GameManager::Status(GameStatus x) {
game_status = x;
}
GameStatus GameManager::Status() {
return game_status;
}
void GameManager::DealHands() {
dealCards();
trick_rounds = 0;
cards_played = 0;
Status(GetHandBids);
}
/*
if neither team has won, return true
*/
Boolean GameManager::NoWinner() {
if (
// don't allow ties!!
( ! win_on_bid && tied() ) ||
// can't win if you have to win on a bid
( win_on_bid && tbl->last_bid_winner == -1 ) ) {
return true;
}
//
// if you can win on smudge and someone got it, game over
//
if ( win_on_bid && win_on_smudge &&
tbl->last_bid_winner != -1 &&
tbl->won_smudge == true ) {
return false;
}
if ( CutThroat() && scores[2] >= winning_score &&
( ! win_on_bid || tbl->last_bid_winner == 2 )
) {
return false;
}
if (
( scores[1] >= winning_score ) &&
( ! win_on_bid || tbl->last_bid_winner == 1 || tbl->last_bid_winner == 3 )
) {
return false;
}
if (
( scores[0] >= winning_score ) &&
( ! win_on_bid || tbl->last_bid_winner == 0 || tbl->last_bid_winner == 2 )
) {
return false;
}
return true;
}
Player * GameManager::GetWinner() {
//
// if you must win on a bid,
// the last bid winner will be the winner;
//
if ( win_on_bid && tbl->last_bid_winner != -1 ) {
return players[tbl->last_bid_winner];
}
//
// otherwise, just pick the higher score
//
if ( scores[2] != 0 ) {
if ( scores[2] >= scores[1] && scores[2] >= scores[0] ) {
return players[2];
}
}
else if ( scores[0] >= scores[1] ) {
return players[0];
}
return players[1];
}
Int16 GameManager::GetTeamPoints(char t) {
for (CArray <Player*>::iterator i = players.BeginIterator(); i != players.EndIterator(); i++ ) {
Player *p = (*i);
if ( p->team == t && p->partner != NULL ) {
return p->getPoints() + p->partner->getPoints();
}
else if ( p->team == t ) {
return p->getPoints();
}
}
return 0;
} | 18.40904 | 104 | 0.574883 | [
"vector"
] |
87c9b466d06c675e05ddc2de800b55473b9ac2aa | 31,622 | cpp | C++ | MonoNative.Tests/mscorlib/System/mscorlib_System_Type_Fixture.cpp | brunolauze/MonoNative | 959fb52c2c1ffe87476ab0d6e4fcce0ad9ce1e66 | [
"BSD-2-Clause"
] | 7 | 2015-03-10T03:36:16.000Z | 2021-11-05T01:16:58.000Z | MonoNative.Tests/mscorlib/System/mscorlib_System_Type_Fixture.cpp | brunolauze/MonoNative | 959fb52c2c1ffe87476ab0d6e4fcce0ad9ce1e66 | [
"BSD-2-Clause"
] | 1 | 2020-06-23T10:02:33.000Z | 2020-06-24T02:05:47.000Z | MonoNative.Tests/mscorlib/System/mscorlib_System_Type_Fixture.cpp | brunolauze/MonoNative | 959fb52c2c1ffe87476ab0d6e4fcce0ad9ce1e66 | [
"BSD-2-Clause"
] | null | null | null | // Mono Native Fixture
// Assembly: mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
// Namespace: System
// Name: Type
// C++ Typed Name: mscorlib::System::Type
#include <gtest/gtest.h>
#include <mscorlib/System/mscorlib_System_Type.h>
#include <mscorlib/System/Reflection/mscorlib_System_Reflection_Assembly.h>
#include <mscorlib/System/mscorlib_System_String.h>
#include <mscorlib/System/mscorlib_System_Guid.h>
#include <mscorlib/System/Reflection/mscorlib_System_Reflection_Module.h>
#include <mscorlib/System/mscorlib_System_RuntimeTypeHandle.h>
#include <mscorlib/System/Reflection/mscorlib_System_Reflection_ConstructorInfo.h>
#include <mscorlib/System/mscorlib_System_Array.h>
#include <mscorlib/System/Reflection/mscorlib_System_Reflection_InterfaceMapping.h>
#include <mscorlib/System/Reflection/mscorlib_System_Reflection_EventInfo.h>
#include <mscorlib/System/Reflection/mscorlib_System_Reflection_FieldInfo.h>
#include <mscorlib/System/Reflection/mscorlib_System_Reflection_MethodInfo.h>
#include <mscorlib/System/Reflection/mscorlib_System_Reflection_ParameterModifier.h>
#include <mscorlib/System/Reflection/mscorlib_System_Reflection_Binder.h>
#include <mscorlib/System/Reflection/mscorlib_System_Reflection_PropertyInfo.h>
#include <mscorlib/System/Globalization/mscorlib_System_Globalization_CultureInfo.h>
#include <mscorlib/System/Reflection/mscorlib_System_Reflection_MethodBase.h>
#include <mscorlib/System/Runtime/InteropServices/mscorlib_System_Runtime_InteropServices_StructLayoutAttribute.h>
#include <mscorlib/System/Reflection/mscorlib_System_Reflection_CustomAttributeData.h>
#include <mscorlib/System/Reflection/mscorlib_System_Reflection_AssemblyName.h>
namespace mscorlib
{
namespace System
{
//Public Methods Tests
// Method Equals
// Signature: mscorlib::System::Object o
TEST(mscorlib_System_Type_Fixture,Equals_1_Test)
{
}
// Method Equals
// Signature: mscorlib::System::Type o
TEST(mscorlib_System_Type_Fixture,Equals_2_Test)
{
}
// Method GetEnumUnderlyingType
// Signature:
TEST(mscorlib_System_Type_Fixture,GetEnumUnderlyingType_Test)
{
}
// Method GetEnumNames
// Signature:
TEST(mscorlib_System_Type_Fixture,GetEnumNames_Test)
{
}
// Method GetEnumValues
// Signature:
TEST(mscorlib_System_Type_Fixture,GetEnumValues_Test)
{
}
// Method GetEnumName
// Signature: mscorlib::System::Object value
TEST(mscorlib_System_Type_Fixture,GetEnumName_Test)
{
}
// Method IsEnumDefined
// Signature: mscorlib::System::Object value
TEST(mscorlib_System_Type_Fixture,IsEnumDefined_Test)
{
}
// Method GetType
// Signature:
TEST(mscorlib_System_Type_Fixture,GetType_Test)
{
}
// Method IsSubclassOf
// Signature: mscorlib::System::Type c
TEST(mscorlib_System_Type_Fixture,IsSubclassOf_Test)
{
}
// Method FindInterfaces
// Signature: mscorlib::Callback<mscorlib::System::Boolean (mscorlib::System::Type , mscorlib::System::Object )> filter, mscorlib::System::Object filterCriteria
TEST(mscorlib_System_Type_Fixture,FindInterfaces_Test)
{
}
// Method GetInterface
// Signature: mscorlib::System::String name
TEST(mscorlib_System_Type_Fixture,GetInterface_1_Test)
{
}
// Method GetInterface
// Signature: mscorlib::System::String name, mscorlib::System::Boolean ignoreCase
TEST(mscorlib_System_Type_Fixture,GetInterface_2_Test)
{
}
// Method GetInterfaceMap
// Signature: mscorlib::System::Type interfaceType
TEST(mscorlib_System_Type_Fixture,GetInterfaceMap_Test)
{
}
// Method GetInterfaces
// Signature:
TEST(mscorlib_System_Type_Fixture,GetInterfaces_Test)
{
}
// Method IsAssignableFrom
// Signature: mscorlib::System::Type c
TEST(mscorlib_System_Type_Fixture,IsAssignableFrom_Test)
{
}
// Method IsInstanceOfType
// Signature: mscorlib::System::Object o
TEST(mscorlib_System_Type_Fixture,IsInstanceOfType_Test)
{
}
// Method GetArrayRank
// Signature:
TEST(mscorlib_System_Type_Fixture,GetArrayRank_Test)
{
}
// Method GetElementType
// Signature:
TEST(mscorlib_System_Type_Fixture,GetElementType_Test)
{
}
// Method GetEvent
// Signature: mscorlib::System::String name
TEST(mscorlib_System_Type_Fixture,GetEvent_1_Test)
{
}
// Method GetEvent
// Signature: mscorlib::System::String name, mscorlib::System::Reflection::BindingFlags::__ENUM__ bindingAttr
TEST(mscorlib_System_Type_Fixture,GetEvent_2_Test)
{
}
// Method GetEvents
// Signature:
TEST(mscorlib_System_Type_Fixture,GetEvents_1_Test)
{
}
// Method GetEvents
// Signature: mscorlib::System::Reflection::BindingFlags::__ENUM__ bindingAttr
TEST(mscorlib_System_Type_Fixture,GetEvents_2_Test)
{
}
// Method GetField
// Signature: mscorlib::System::String name
TEST(mscorlib_System_Type_Fixture,GetField_1_Test)
{
}
// Method GetField
// Signature: mscorlib::System::String name, mscorlib::System::Reflection::BindingFlags::__ENUM__ bindingAttr
TEST(mscorlib_System_Type_Fixture,GetField_2_Test)
{
}
// Method GetFields
// Signature:
TEST(mscorlib_System_Type_Fixture,GetFields_1_Test)
{
}
// Method GetFields
// Signature: mscorlib::System::Reflection::BindingFlags::__ENUM__ bindingAttr
TEST(mscorlib_System_Type_Fixture,GetFields_2_Test)
{
}
// Method GetHashCode
// Signature:
TEST(mscorlib_System_Type_Fixture,GetHashCode_Test)
{
}
// Method GetMember
// Signature: mscorlib::System::String name
TEST(mscorlib_System_Type_Fixture,GetMember_1_Test)
{
}
// Method GetMember
// Signature: mscorlib::System::String name, mscorlib::System::Reflection::BindingFlags::__ENUM__ bindingAttr
TEST(mscorlib_System_Type_Fixture,GetMember_2_Test)
{
}
// Method GetMember
// Signature: mscorlib::System::String name, mscorlib::System::Reflection::MemberTypes::__ENUM__ type, mscorlib::System::Reflection::BindingFlags::__ENUM__ bindingAttr
TEST(mscorlib_System_Type_Fixture,GetMember_3_Test)
{
}
// Method GetMembers
// Signature:
TEST(mscorlib_System_Type_Fixture,GetMembers_1_Test)
{
}
// Method GetMembers
// Signature: mscorlib::System::Reflection::BindingFlags::__ENUM__ bindingAttr
TEST(mscorlib_System_Type_Fixture,GetMembers_2_Test)
{
}
// Method GetMethod
// Signature: mscorlib::System::String name
TEST(mscorlib_System_Type_Fixture,GetMethod_1_Test)
{
}
// Method GetMethod
// Signature: mscorlib::System::String name, mscorlib::System::Reflection::BindingFlags::__ENUM__ bindingAttr
TEST(mscorlib_System_Type_Fixture,GetMethod_2_Test)
{
}
// Method GetMethod
// Signature: mscorlib::System::String name, std::vector<mscorlib::System::Type*> types
TEST(mscorlib_System_Type_Fixture,GetMethod_3_Test)
{
}
// Method GetMethod
// Signature: mscorlib::System::String name, std::vector<mscorlib::System::Type*> types, std::vector<mscorlib::System::Reflection::ParameterModifier*> modifiers
TEST(mscorlib_System_Type_Fixture,GetMethod_4_Test)
{
}
// Method GetMethod
// Signature: mscorlib::System::String name, mscorlib::System::Reflection::BindingFlags::__ENUM__ bindingAttr, mscorlib::System::Reflection::Binder binder, std::vector<mscorlib::System::Type*> types, std::vector<mscorlib::System::Reflection::ParameterModifier*> modifiers
TEST(mscorlib_System_Type_Fixture,GetMethod_5_Test)
{
}
// Method GetMethod
// Signature: mscorlib::System::String name, mscorlib::System::Reflection::BindingFlags::__ENUM__ bindingAttr, mscorlib::System::Reflection::Binder binder, mscorlib::System::Reflection::CallingConventions::__ENUM__ callConvention, std::vector<mscorlib::System::Type*> types, std::vector<mscorlib::System::Reflection::ParameterModifier*> modifiers
TEST(mscorlib_System_Type_Fixture,GetMethod_6_Test)
{
}
// Method GetMethods
// Signature:
TEST(mscorlib_System_Type_Fixture,GetMethods_1_Test)
{
}
// Method GetMethods
// Signature: mscorlib::System::Reflection::BindingFlags::__ENUM__ bindingAttr
TEST(mscorlib_System_Type_Fixture,GetMethods_2_Test)
{
}
// Method GetNestedType
// Signature: mscorlib::System::String name
TEST(mscorlib_System_Type_Fixture,GetNestedType_1_Test)
{
}
// Method GetNestedType
// Signature: mscorlib::System::String name, mscorlib::System::Reflection::BindingFlags::__ENUM__ bindingAttr
TEST(mscorlib_System_Type_Fixture,GetNestedType_2_Test)
{
}
// Method GetNestedTypes
// Signature:
TEST(mscorlib_System_Type_Fixture,GetNestedTypes_1_Test)
{
}
// Method GetNestedTypes
// Signature: mscorlib::System::Reflection::BindingFlags::__ENUM__ bindingAttr
TEST(mscorlib_System_Type_Fixture,GetNestedTypes_2_Test)
{
}
// Method GetProperties
// Signature:
TEST(mscorlib_System_Type_Fixture,GetProperties_1_Test)
{
}
// Method GetProperties
// Signature: mscorlib::System::Reflection::BindingFlags::__ENUM__ bindingAttr
TEST(mscorlib_System_Type_Fixture,GetProperties_2_Test)
{
}
// Method GetProperty
// Signature: mscorlib::System::String name
TEST(mscorlib_System_Type_Fixture,GetProperty_1_Test)
{
}
// Method GetProperty
// Signature: mscorlib::System::String name, mscorlib::System::Reflection::BindingFlags::__ENUM__ bindingAttr
TEST(mscorlib_System_Type_Fixture,GetProperty_2_Test)
{
}
// Method GetProperty
// Signature: mscorlib::System::String name, mscorlib::System::Type returnType
TEST(mscorlib_System_Type_Fixture,GetProperty_3_Test)
{
}
// Method GetProperty
// Signature: mscorlib::System::String name, std::vector<mscorlib::System::Type*> types
TEST(mscorlib_System_Type_Fixture,GetProperty_4_Test)
{
}
// Method GetProperty
// Signature: mscorlib::System::String name, mscorlib::System::Type returnType, std::vector<mscorlib::System::Type*> types
TEST(mscorlib_System_Type_Fixture,GetProperty_5_Test)
{
}
// Method GetProperty
// Signature: mscorlib::System::String name, mscorlib::System::Type returnType, std::vector<mscorlib::System::Type*> types, std::vector<mscorlib::System::Reflection::ParameterModifier*> modifiers
TEST(mscorlib_System_Type_Fixture,GetProperty_6_Test)
{
}
// Method GetProperty
// Signature: mscorlib::System::String name, mscorlib::System::Reflection::BindingFlags::__ENUM__ bindingAttr, mscorlib::System::Reflection::Binder binder, mscorlib::System::Type returnType, std::vector<mscorlib::System::Type*> types, std::vector<mscorlib::System::Reflection::ParameterModifier*> modifiers
TEST(mscorlib_System_Type_Fixture,GetProperty_7_Test)
{
}
// Method GetConstructor
// Signature: std::vector<mscorlib::System::Type*> types
TEST(mscorlib_System_Type_Fixture,GetConstructor_1_Test)
{
}
// Method GetConstructor
// Signature: mscorlib::System::Reflection::BindingFlags::__ENUM__ bindingAttr, mscorlib::System::Reflection::Binder binder, std::vector<mscorlib::System::Type*> types, std::vector<mscorlib::System::Reflection::ParameterModifier*> modifiers
TEST(mscorlib_System_Type_Fixture,GetConstructor_2_Test)
{
}
// Method GetConstructor
// Signature: mscorlib::System::Reflection::BindingFlags::__ENUM__ bindingAttr, mscorlib::System::Reflection::Binder binder, mscorlib::System::Reflection::CallingConventions::__ENUM__ callConvention, std::vector<mscorlib::System::Type*> types, std::vector<mscorlib::System::Reflection::ParameterModifier*> modifiers
TEST(mscorlib_System_Type_Fixture,GetConstructor_3_Test)
{
}
// Method GetConstructors
// Signature:
TEST(mscorlib_System_Type_Fixture,GetConstructors_1_Test)
{
}
// Method GetConstructors
// Signature: mscorlib::System::Reflection::BindingFlags::__ENUM__ bindingAttr
TEST(mscorlib_System_Type_Fixture,GetConstructors_2_Test)
{
}
// Method GetDefaultMembers
// Signature:
TEST(mscorlib_System_Type_Fixture,GetDefaultMembers_Test)
{
}
// Method FindMembers
// Signature: mscorlib::System::Reflection::MemberTypes::__ENUM__ memberType, mscorlib::System::Reflection::BindingFlags::__ENUM__ bindingAttr, mscorlib::Callback<mscorlib::System::Boolean (mscorlib::System::Reflection::MemberInfo , mscorlib::System::Object )> filter, mscorlib::System::Object filterCriteria
TEST(mscorlib_System_Type_Fixture,FindMembers_Test)
{
}
// Method InvokeMember
// Signature: mscorlib::System::String name, mscorlib::System::Reflection::BindingFlags::__ENUM__ invokeAttr, mscorlib::System::Reflection::Binder binder, mscorlib::System::Object target, std::vector<mscorlib::System::Object*> args
TEST(mscorlib_System_Type_Fixture,InvokeMember_1_Test)
{
}
// Method InvokeMember
// Signature: mscorlib::System::String name, mscorlib::System::Reflection::BindingFlags::__ENUM__ invokeAttr, mscorlib::System::Reflection::Binder binder, mscorlib::System::Object target, std::vector<mscorlib::System::Object*> args, mscorlib::System::Globalization::CultureInfo culture
TEST(mscorlib_System_Type_Fixture,InvokeMember_2_Test)
{
}
// Method InvokeMember
// Signature: mscorlib::System::String name, mscorlib::System::Reflection::BindingFlags::__ENUM__ invokeAttr, mscorlib::System::Reflection::Binder binder, mscorlib::System::Object target, std::vector<mscorlib::System::Object*> args, std::vector<mscorlib::System::Reflection::ParameterModifier*> modifiers, mscorlib::System::Globalization::CultureInfo culture, std::vector<mscorlib::System::String*> namedParameters
TEST(mscorlib_System_Type_Fixture,InvokeMember_3_Test)
{
}
// Method ToString
// Signature:
TEST(mscorlib_System_Type_Fixture,ToString_Test)
{
}
// Method GetGenericArguments
// Signature:
TEST(mscorlib_System_Type_Fixture,GetGenericArguments_Test)
{
}
// Method GetGenericTypeDefinition
// Signature:
TEST(mscorlib_System_Type_Fixture,GetGenericTypeDefinition_Test)
{
}
// Method MakeGenericType
// Signature: std::vector<mscorlib::System::Type*> typeArguments
TEST(mscorlib_System_Type_Fixture,MakeGenericType_Test)
{
}
// Method GetGenericParameterConstraints
// Signature:
TEST(mscorlib_System_Type_Fixture,GetGenericParameterConstraints_Test)
{
}
// Method MakeArrayType
// Signature:
TEST(mscorlib_System_Type_Fixture,MakeArrayType_1_Test)
{
}
// Method MakeArrayType
// Signature: mscorlib::System::Int32 rank
TEST(mscorlib_System_Type_Fixture,MakeArrayType_2_Test)
{
}
// Method MakeByRefType
// Signature:
TEST(mscorlib_System_Type_Fixture,MakeByRefType_Test)
{
}
// Method MakePointerType
// Signature:
TEST(mscorlib_System_Type_Fixture,MakePointerType_Test)
{
}
// Method IsEquivalentTo
// Signature: mscorlib::System::Type other
TEST(mscorlib_System_Type_Fixture,IsEquivalentTo_Test)
{
}
//Public Static Methods Tests
// Method GetType
// Signature: mscorlib::System::String typeName, mscorlib::Callback<mscorlib::System::Reflection::Assembly (mscorlib::System::Reflection::AssemblyName )> assemblyResolver, mscorlib::Callback<mscorlib::System::Type (mscorlib::System::Reflection::Assembly , mscorlib::System::String , mscorlib::System::Boolean )> typeResolver
TEST(mscorlib_System_Type_Fixture,GetType_1_StaticTest)
{
}
// Method GetType
// Signature: mscorlib::System::String typeName, mscorlib::Callback<mscorlib::System::Reflection::Assembly (mscorlib::System::Reflection::AssemblyName )> assemblyResolver, mscorlib::Callback<mscorlib::System::Type (mscorlib::System::Reflection::Assembly , mscorlib::System::String , mscorlib::System::Boolean )> typeResolver, mscorlib::System::Boolean throwOnError
TEST(mscorlib_System_Type_Fixture,GetType_2_StaticTest)
{
}
// Method GetType
// Signature: mscorlib::System::String typeName, mscorlib::Callback<mscorlib::System::Reflection::Assembly (mscorlib::System::Reflection::AssemblyName )> assemblyResolver, mscorlib::Callback<mscorlib::System::Type (mscorlib::System::Reflection::Assembly , mscorlib::System::String , mscorlib::System::Boolean )> typeResolver, mscorlib::System::Boolean throwOnError, mscorlib::System::Boolean ignoreCase
TEST(mscorlib_System_Type_Fixture,GetType_3_StaticTest)
{
}
// Method GetType
// Signature: mscorlib::System::String typeName
TEST(mscorlib_System_Type_Fixture,GetType_4_StaticTest)
{
}
// Method GetType
// Signature: mscorlib::System::String typeName, mscorlib::System::Boolean throwOnError
TEST(mscorlib_System_Type_Fixture,GetType_5_StaticTest)
{
}
// Method GetType
// Signature: mscorlib::System::String typeName, mscorlib::System::Boolean throwOnError, mscorlib::System::Boolean ignoreCase
TEST(mscorlib_System_Type_Fixture,GetType_6_StaticTest)
{
}
// Method GetTypeArray
// Signature: std::vector<mscorlib::System::Object*> args
TEST(mscorlib_System_Type_Fixture,GetTypeArray_StaticTest)
{
}
// Method GetTypeCode
// Signature: mscorlib::System::Type type
TEST(mscorlib_System_Type_Fixture,GetTypeCode_StaticTest)
{
}
// Method GetTypeFromCLSID
// Signature: mscorlib::System::Guid clsid
TEST(mscorlib_System_Type_Fixture,GetTypeFromCLSID_1_StaticTest)
{
}
// Method GetTypeFromCLSID
// Signature: mscorlib::System::Guid clsid, mscorlib::System::Boolean throwOnError
TEST(mscorlib_System_Type_Fixture,GetTypeFromCLSID_2_StaticTest)
{
}
// Method GetTypeFromCLSID
// Signature: mscorlib::System::Guid clsid, mscorlib::System::String server
TEST(mscorlib_System_Type_Fixture,GetTypeFromCLSID_3_StaticTest)
{
}
// Method GetTypeFromCLSID
// Signature: mscorlib::System::Guid clsid, mscorlib::System::String server, mscorlib::System::Boolean throwOnError
TEST(mscorlib_System_Type_Fixture,GetTypeFromCLSID_4_StaticTest)
{
}
// Method GetTypeFromHandle
// Signature: mscorlib::System::RuntimeTypeHandle handle
TEST(mscorlib_System_Type_Fixture,GetTypeFromHandle_StaticTest)
{
}
// Method GetTypeFromProgID
// Signature: mscorlib::System::String progID
TEST(mscorlib_System_Type_Fixture,GetTypeFromProgID_1_StaticTest)
{
}
// Method GetTypeFromProgID
// Signature: mscorlib::System::String progID, mscorlib::System::Boolean throwOnError
TEST(mscorlib_System_Type_Fixture,GetTypeFromProgID_2_StaticTest)
{
}
// Method GetTypeFromProgID
// Signature: mscorlib::System::String progID, mscorlib::System::String server
TEST(mscorlib_System_Type_Fixture,GetTypeFromProgID_3_StaticTest)
{
}
// Method GetTypeFromProgID
// Signature: mscorlib::System::String progID, mscorlib::System::String server, mscorlib::System::Boolean throwOnError
TEST(mscorlib_System_Type_Fixture,GetTypeFromProgID_4_StaticTest)
{
}
// Method GetTypeHandle
// Signature: mscorlib::System::Object o
TEST(mscorlib_System_Type_Fixture,GetTypeHandle_StaticTest)
{
}
// Method ReflectionOnlyGetType
// Signature: mscorlib::System::String typeName, mscorlib::System::Boolean throwIfNotFound, mscorlib::System::Boolean ignoreCase
TEST(mscorlib_System_Type_Fixture,ReflectionOnlyGetType_StaticTest)
{
}
//Public Properties Tests
// Property Assembly
// Return Type: mscorlib::System::Reflection::Assembly
// Property Get Method
TEST(mscorlib_System_Type_Fixture,get_Assembly_Test)
{
}
// Property AssemblyQualifiedName
// Return Type: mscorlib::System::String
// Property Get Method
TEST(mscorlib_System_Type_Fixture,get_AssemblyQualifiedName_Test)
{
}
// Property Attributes
// Return Type: mscorlib::System::Reflection::TypeAttributes::__ENUM__
// Property Get Method
TEST(mscorlib_System_Type_Fixture,get_Attributes_Test)
{
}
// Property BaseType
// Return Type: mscorlib::System::Type
// Property Get Method
TEST(mscorlib_System_Type_Fixture,get_BaseType_Test)
{
}
// Property DeclaringType
// Return Type: mscorlib::System::Type
// Property Get Method
TEST(mscorlib_System_Type_Fixture,get_DeclaringType_Test)
{
}
// Property FullName
// Return Type: mscorlib::System::String
// Property Get Method
TEST(mscorlib_System_Type_Fixture,get_FullName_Test)
{
}
// Property GUID
// Return Type: mscorlib::System::Guid
// Property Get Method
TEST(mscorlib_System_Type_Fixture,get_GUID_Test)
{
}
// Property HasElementType
// Return Type: mscorlib::System::Boolean
// Property Get Method
TEST(mscorlib_System_Type_Fixture,get_HasElementType_Test)
{
}
// Property IsAbstract
// Return Type: mscorlib::System::Boolean
// Property Get Method
TEST(mscorlib_System_Type_Fixture,get_IsAbstract_Test)
{
}
// Property IsAnsiClass
// Return Type: mscorlib::System::Boolean
// Property Get Method
TEST(mscorlib_System_Type_Fixture,get_IsAnsiClass_Test)
{
}
// Property IsArray
// Return Type: mscorlib::System::Boolean
// Property Get Method
TEST(mscorlib_System_Type_Fixture,get_IsArray_Test)
{
}
// Property IsAutoClass
// Return Type: mscorlib::System::Boolean
// Property Get Method
TEST(mscorlib_System_Type_Fixture,get_IsAutoClass_Test)
{
}
// Property IsAutoLayout
// Return Type: mscorlib::System::Boolean
// Property Get Method
TEST(mscorlib_System_Type_Fixture,get_IsAutoLayout_Test)
{
}
// Property IsByRef
// Return Type: mscorlib::System::Boolean
// Property Get Method
TEST(mscorlib_System_Type_Fixture,get_IsByRef_Test)
{
}
// Property IsClass
// Return Type: mscorlib::System::Boolean
// Property Get Method
TEST(mscorlib_System_Type_Fixture,get_IsClass_Test)
{
}
// Property IsCOMObject
// Return Type: mscorlib::System::Boolean
// Property Get Method
TEST(mscorlib_System_Type_Fixture,get_IsCOMObject_Test)
{
}
// Property IsConstructedGenericType
// Return Type: mscorlib::System::Boolean
// Property Get Method
TEST(mscorlib_System_Type_Fixture,get_IsConstructedGenericType_Test)
{
}
// Property IsContextful
// Return Type: mscorlib::System::Boolean
// Property Get Method
TEST(mscorlib_System_Type_Fixture,get_IsContextful_Test)
{
}
// Property IsEnum
// Return Type: mscorlib::System::Boolean
// Property Get Method
TEST(mscorlib_System_Type_Fixture,get_IsEnum_Test)
{
}
// Property IsExplicitLayout
// Return Type: mscorlib::System::Boolean
// Property Get Method
TEST(mscorlib_System_Type_Fixture,get_IsExplicitLayout_Test)
{
}
// Property IsImport
// Return Type: mscorlib::System::Boolean
// Property Get Method
TEST(mscorlib_System_Type_Fixture,get_IsImport_Test)
{
}
// Property IsInterface
// Return Type: mscorlib::System::Boolean
// Property Get Method
TEST(mscorlib_System_Type_Fixture,get_IsInterface_Test)
{
}
// Property IsLayoutSequential
// Return Type: mscorlib::System::Boolean
// Property Get Method
TEST(mscorlib_System_Type_Fixture,get_IsLayoutSequential_Test)
{
}
// Property IsMarshalByRef
// Return Type: mscorlib::System::Boolean
// Property Get Method
TEST(mscorlib_System_Type_Fixture,get_IsMarshalByRef_Test)
{
}
// Property IsNestedAssembly
// Return Type: mscorlib::System::Boolean
// Property Get Method
TEST(mscorlib_System_Type_Fixture,get_IsNestedAssembly_Test)
{
}
// Property IsNestedFamANDAssem
// Return Type: mscorlib::System::Boolean
// Property Get Method
TEST(mscorlib_System_Type_Fixture,get_IsNestedFamANDAssem_Test)
{
}
// Property IsNestedFamily
// Return Type: mscorlib::System::Boolean
// Property Get Method
TEST(mscorlib_System_Type_Fixture,get_IsNestedFamily_Test)
{
}
// Property IsNestedFamORAssem
// Return Type: mscorlib::System::Boolean
// Property Get Method
TEST(mscorlib_System_Type_Fixture,get_IsNestedFamORAssem_Test)
{
}
// Property IsNestedPrivate
// Return Type: mscorlib::System::Boolean
// Property Get Method
TEST(mscorlib_System_Type_Fixture,get_IsNestedPrivate_Test)
{
}
// Property IsNestedPublic
// Return Type: mscorlib::System::Boolean
// Property Get Method
TEST(mscorlib_System_Type_Fixture,get_IsNestedPublic_Test)
{
}
// Property IsNotPublic
// Return Type: mscorlib::System::Boolean
// Property Get Method
TEST(mscorlib_System_Type_Fixture,get_IsNotPublic_Test)
{
}
// Property IsPointer
// Return Type: mscorlib::System::Boolean
// Property Get Method
TEST(mscorlib_System_Type_Fixture,get_IsPointer_Test)
{
}
// Property IsPrimitive
// Return Type: mscorlib::System::Boolean
// Property Get Method
TEST(mscorlib_System_Type_Fixture,get_IsPrimitive_Test)
{
}
// Property IsPublic
// Return Type: mscorlib::System::Boolean
// Property Get Method
TEST(mscorlib_System_Type_Fixture,get_IsPublic_Test)
{
}
// Property IsSealed
// Return Type: mscorlib::System::Boolean
// Property Get Method
TEST(mscorlib_System_Type_Fixture,get_IsSealed_Test)
{
}
// Property IsSerializable
// Return Type: mscorlib::System::Boolean
// Property Get Method
TEST(mscorlib_System_Type_Fixture,get_IsSerializable_Test)
{
}
// Property IsSpecialName
// Return Type: mscorlib::System::Boolean
// Property Get Method
TEST(mscorlib_System_Type_Fixture,get_IsSpecialName_Test)
{
}
// Property IsUnicodeClass
// Return Type: mscorlib::System::Boolean
// Property Get Method
TEST(mscorlib_System_Type_Fixture,get_IsUnicodeClass_Test)
{
}
// Property IsValueType
// Return Type: mscorlib::System::Boolean
// Property Get Method
TEST(mscorlib_System_Type_Fixture,get_IsValueType_Test)
{
}
// Property MemberType
// Return Type: mscorlib::System::Reflection::MemberTypes::__ENUM__
// Property Get Method
TEST(mscorlib_System_Type_Fixture,get_MemberType_Test)
{
}
// Property Module
// Return Type: mscorlib::System::Reflection::Module
// Property Get Method
TEST(mscorlib_System_Type_Fixture,get_Module_Test)
{
}
// Property Namespace
// Return Type: mscorlib::System::String
// Property Get Method
TEST(mscorlib_System_Type_Fixture,get_Namespace_Test)
{
}
// Property ReflectedType
// Return Type: mscorlib::System::Type
// Property Get Method
TEST(mscorlib_System_Type_Fixture,get_ReflectedType_Test)
{
}
// Property TypeHandle
// Return Type: mscorlib::System::RuntimeTypeHandle
// Property Get Method
TEST(mscorlib_System_Type_Fixture,get_TypeHandle_Test)
{
}
// Property TypeInitializer
// Return Type: mscorlib::System::Reflection::ConstructorInfo
// Property Get Method
TEST(mscorlib_System_Type_Fixture,get_TypeInitializer_Test)
{
}
// Property UnderlyingSystemType
// Return Type: mscorlib::System::Type
// Property Get Method
TEST(mscorlib_System_Type_Fixture,get_UnderlyingSystemType_Test)
{
}
// Property IsSecurityTransparent
// Return Type: mscorlib::System::Boolean
// Property Get Method
TEST(mscorlib_System_Type_Fixture,get_IsSecurityTransparent_Test)
{
}
// Property IsSecurityCritical
// Return Type: mscorlib::System::Boolean
// Property Get Method
TEST(mscorlib_System_Type_Fixture,get_IsSecurityCritical_Test)
{
}
// Property IsSecuritySafeCritical
// Return Type: mscorlib::System::Boolean
// Property Get Method
TEST(mscorlib_System_Type_Fixture,get_IsSecuritySafeCritical_Test)
{
}
// Property GenericTypeArguments
// Return Type: mscorlib::System::Type*
// Property Get Method
TEST(mscorlib_System_Type_Fixture,get_GenericTypeArguments_Test)
{
}
// Property ContainsGenericParameters
// Return Type: mscorlib::System::Boolean
// Property Get Method
TEST(mscorlib_System_Type_Fixture,get_ContainsGenericParameters_Test)
{
}
// Property IsGenericTypeDefinition
// Return Type: mscorlib::System::Boolean
// Property Get Method
TEST(mscorlib_System_Type_Fixture,get_IsGenericTypeDefinition_Test)
{
}
// Property IsGenericType
// Return Type: mscorlib::System::Boolean
// Property Get Method
TEST(mscorlib_System_Type_Fixture,get_IsGenericType_Test)
{
}
// Property IsGenericParameter
// Return Type: mscorlib::System::Boolean
// Property Get Method
TEST(mscorlib_System_Type_Fixture,get_IsGenericParameter_Test)
{
}
// Property IsNested
// Return Type: mscorlib::System::Boolean
// Property Get Method
TEST(mscorlib_System_Type_Fixture,get_IsNested_Test)
{
}
// Property IsVisible
// Return Type: mscorlib::System::Boolean
// Property Get Method
TEST(mscorlib_System_Type_Fixture,get_IsVisible_Test)
{
}
// Property GenericParameterPosition
// Return Type: mscorlib::System::Int32
// Property Get Method
TEST(mscorlib_System_Type_Fixture,get_GenericParameterPosition_Test)
{
}
// Property GenericParameterAttributes
// Return Type: mscorlib::System::Reflection::GenericParameterAttributes::__ENUM__
// Property Get Method
TEST(mscorlib_System_Type_Fixture,get_GenericParameterAttributes_Test)
{
}
// Property DeclaringMethod
// Return Type: mscorlib::System::Reflection::MethodBase
// Property Get Method
TEST(mscorlib_System_Type_Fixture,get_DeclaringMethod_Test)
{
}
// Property StructLayoutAttribute
// Return Type: mscorlib::System::Runtime::InteropServices::StructLayoutAttribute
// Property Get Method
TEST(mscorlib_System_Type_Fixture,get_StructLayoutAttribute_Test)
{
}
// Property Name
// Return Type: mscorlib::System::String
// Property Get Method
TEST(mscorlib_System_Type_Fixture,get_Name_Test)
{
}
// Property MetadataToken
// Return Type: mscorlib::System::Int32
// Property Get Method
TEST(mscorlib_System_Type_Fixture,get_MetadataToken_Test)
{
}
// Property CustomAttributes
// Return Type: mscorlib::System::Collections::Generic::IEnumerable<mscorlib::System::Reflection::CustomAttributeData>
// Property Get Method
TEST(mscorlib_System_Type_Fixture,get_CustomAttributes_Test)
{
}
// Property DefaultBinder
// Return Type: mscorlib::System::Reflection::Binder
// Property Get Method
TEST(mscorlib_System_Type_Fixture,get_DefaultBinder_Test)
{
}
}
}
| 23.285714 | 417 | 0.723705 | [
"object",
"vector"
] |
d7aaa749fe7a6f364bc9e0b9ef9c5e1e0c2ba167 | 10,641 | cpp | C++ | TreeCode_link/double_sort.cpp | glenco/SLsimLib | fb7a3c450d2487a823fa3f0ae8c8ecf7945c3ebb | [
"MIT"
] | 2 | 2017-03-22T13:18:32.000Z | 2021-05-01T01:54:31.000Z | TreeCode_link/double_sort.cpp | glenco/SLsimLib | fb7a3c450d2487a823fa3f0ae8c8ecf7945c3ebb | [
"MIT"
] | 49 | 2016-10-05T03:08:38.000Z | 2020-11-03T15:39:26.000Z | TreeCode_link/double_sort.cpp | glenco/SLsimLib | fb7a3c450d2487a823fa3f0ae8c8ecf7945c3ebb | [
"MIT"
] | 1 | 2017-07-10T08:52:53.000Z | 2017-07-10T08:52:53.000Z |
/* double_sort is adapted from NR sort2 to take an unsigned long */
/* second array brr */
/* note #undef's at end of file */
#include "slsimlib.h"
#include <nrutil.h>
#include <mutex>
#include <thread>
#include <future>
#define NRANSI
#define M 7
#define NSTACK 50
namespace Utilities{
void double_sort(unsigned long n, PosType *arr, unsigned long *brr)
{
unsigned long i,ir=n,j,k,l=1,*istack,b;
int jstack=0;
PosType a;
istack=lvector(1,NSTACK);
for (;;) {
if (ir-l < M) {
for (j=l+1;j<=ir;j++) {
a=arr[j];
b=brr[j];
for (i=j-1;i>=l;i--) {
if (arr[i] <= a) break;
arr[i+1]=arr[i];
brr[i+1]=brr[i];
}
arr[i+1]=a;
brr[i+1]=b;
}
if (!jstack) {
free_lvector(istack,1,NSTACK);
return;
}
ir=istack[jstack];
l=istack[jstack-1];
jstack -= 2;
} else {
k=(l+ir) >> 1;
std::swap(arr[k],arr[l+1]);
std::swap(brr[k],brr[l+1]);
if (arr[l] > arr[ir]) {
std::swap(arr[l],arr[ir]);
std::swap(brr[l],brr[ir]);
}
if (arr[l+1] > arr[ir]) {
std::swap(arr[l+1],arr[ir]);
std::swap(brr[l+1],brr[ir]);
}
if (arr[l] > arr[l+1]) {
std::swap(arr[l],arr[l+1]);
std::swap(brr[l],brr[l+1]);
}
i=l+1;
j=ir;
a=arr[l+1];
b=brr[l+1];
for (;;) {
do i++; while (arr[i] < a);
do j--; while (arr[j] > a);
if (j < i) break;
std::swap(arr[i],arr[j]);
std::swap(brr[i],brr[j]);
}
arr[l+1]=arr[j];
arr[j]=a;
brr[l+1]=brr[j];
brr[j]=b;
jstack += 2;
if (jstack > NSTACK) nrerror("NSTACK too small in double_sort");
if (ir-i+1 >= j-l) {
istack[jstack]=ir;
istack[jstack-1]=i;
ir=j-1;
} else {
istack[jstack]=j-1;
istack[jstack-1]=l;
l=i;
}
}
}
}
/** \brief Sorts points in a point array.
*
* arr array uses NR standard indexing i.e arr[1...n]
* but brr[0..n-1]
* if the point array is two-way-coupled to another point array
* the image pointers of that array will follow sort
* if the array is not two-way-coupled to another the image
* pointers in the other array will be untouched
*/
void double_sort_points(unsigned long n, PosType *arr, Point *brr){
unsigned long i,ir=n,j,k,l=1,*istack;
long jstack=0;
PosType a;
Point b;
istack=lvector(1,NSTACK);
for (;;) {
if (ir-l < M) {
for (j=l+1;j<=ir;j++) {
a=arr[j];
/*b=brr[j-1];*/
PointCopy(&b,&brr[j-1]);
for (i=j-1;i>=l;i--) {
if (arr[i] <= a) break;
arr[i+1]=arr[i];
/*brr[i]=brr[i-1];*/
PointCopy(&brr[i],&brr[i-1]);
}
arr[i+1]=a;
/*brr[i]=b;*/
PointCopy(&brr[i],&b);
}
if (!jstack) {
free_lvector(istack,1,NSTACK);
return;
}
ir=istack[jstack];
l=istack[jstack-1];
jstack -= 2;
} else {
k=(l+ir) >> 1;
std::swap(arr[k],arr[l+1]);
assert(k < n + 1);
assert(l < n);
SwapPointsInArray(&brr[k-1],&brr[l]);
if (arr[l] > arr[ir]) {
std::swap(arr[l],arr[ir]);
assert(l < n + 1);
assert(ir < n + 1);
SwapPointsInArray(&brr[l-1],&brr[ir-1]);
}
if (arr[l+1] > arr[ir]) {
assert(l < n);
assert(ir < n+1);
std::swap(arr[l+1],arr[ir]);
SwapPointsInArray(&brr[l],&brr[ir-1]);
}
if (arr[l] > arr[l+1]) {
assert(l < n);
std::swap(arr[l],arr[l+1]);
SwapPointsInArray(&brr[l-1],&brr[l]);
}
i=l+1;
j=ir;
a=arr[l+1];
/*b=brr[l];*/
PointCopy(&b,&brr[l]);
for (;;) {
do i++; while (arr[i] < a);
do j--; while (arr[j] > a);
if (j < i) break;
std::swap(arr[i],arr[j]);
assert(l < n + 1);
assert(j < n + 1);
SwapPointsInArray(&brr[i-1],&brr[j-1]);
}
arr[l+1]=arr[j];
arr[j]=a;
/*brr[l]=brr[j-1];*/
PointCopy(&brr[l],&brr[j-1]);
/*brr[j-1]=b;*/
PointCopy(&brr[j-1],&b);
jstack += 2;
if (jstack > NSTACK) nrerror("NSTACK too small in double_sort_points");
if (ir-i+1 >= j-l) {
istack[jstack]=ir;
istack[jstack-1]=i;
ir=j-1;
} else {
istack[jstack]=j-1;
istack[jstack-1]=l;
l=i;
}
}
}
}
#undef M
#undef NSTACK
#undef NRANSI
/**
* \brief Sorts points from smallest to largest according to the value of arr[].
* Sorts arr[] and pointarray[] simultaneously.
*/
void quicksortPoints(Point *pointarray,PosType *arr,unsigned long N){
PosType pivotvalue;
unsigned long pivotindex,newpivotindex,i;
if(N <= 1) return ;
// pick pivot as the median of the first, last and middle values
if ((arr[0] >= arr[N/2] && arr[0] <= arr[N-1])
|| (arr[0] >= arr[N-1] && arr[0] <= arr[N/2])) pivotindex = 0;
else if ((arr[N/2] >= arr[0] && arr[N/2] <= arr[N-1])
|| (arr[N/2] >= arr[N-1] && arr[N/2] <= arr[0])) pivotindex = N/2;
else pivotindex = N-1;
pivotvalue=arr[pivotindex];
// move pivot to end of array
std::swap(arr[pivotindex],arr[N-1]);
assert(pivotindex < N);
SwapPointsInArray(&pointarray[pivotindex],&pointarray[N-1]);
newpivotindex=0;
// partition list and array
for(i=0;i<N;++i){
if(arr[i] <= pivotvalue){
std::swap(arr[newpivotindex],arr[i]);
assert(newpivotindex < N);
SwapPointsInArray(&pointarray[newpivotindex],&pointarray[i]);
++newpivotindex;
}
}
if(newpivotindex != 0) --newpivotindex;
quicksortPoints(pointarray,arr,newpivotindex);
quicksortPoints(&pointarray[newpivotindex+1],&arr[newpivotindex+1],N-newpivotindex-1);
return ;
}
void quicksortPoints(Point *pointarray,double (*func)(Point &),unsigned long N){
PosType pivotvalue;
unsigned long pivotindex,newpivotindex,i;
if(N <= 1) return ;
// pick pivot as the median of the first, last and middle values
if ((func(pointarray[0]) >= func(pointarray[N/2]) && func(pointarray[0]) <= func(pointarray[N-1]))
|| (func(pointarray[0]) >= func(pointarray[N-1]) && func(pointarray[0]) <= func(pointarray[N/2]))) pivotindex = 0;
else if ((func(pointarray[N/2]) >= func(pointarray[0]) && func(pointarray[N/2]) <= func(pointarray[N-1]))
|| (func(pointarray[N/2]) >= func(pointarray[N-1]) && func(pointarray[N/2]) <= func(pointarray[0]))) pivotindex = N/2;
else pivotindex = N-1;
pivotvalue=func(pointarray[pivotindex]);
// move pivot to end of array
assert(pivotindex < N);
SwapPointsInArray(&pointarray[pivotindex],&pointarray[N-1]);
newpivotindex=0;
// partition list and array
for(i=0;i<N;++i){
if(func(pointarray[i]) <= pivotvalue){
assert(newpivotindex < N);
SwapPointsInArray(&pointarray[newpivotindex],&pointarray[i]);
++newpivotindex;
}
}
if(newpivotindex != 0) --newpivotindex;
quicksortPoints(pointarray,func,newpivotindex);
quicksortPoints(&pointarray[newpivotindex+1],func,N-newpivotindex-1);
return ;
}
void quicksort(unsigned long *particles,PosType *arr,unsigned long N){
std::vector<size_t> index(N);
Utilities::sort_indexes(arr,index,N);
Utilities::apply_permutation(particles,index);
Utilities::apply_permutation(arr,index);
//std::cout << arr[0] << " " << arr[1] << " " << arr[2] << std::endl;
assert(arr[0] <= arr[N-1]);
return;
PosType pivotvalue;
unsigned long pivotindex,newpivotindex,i;
if(N <= 1) return ;
// pick pivot as the median of the first, last and middle values
if ((arr[0] >= arr[N/2] && arr[0] <= arr[N-1])
|| (arr[0] >= arr[N-1] && arr[0] <= arr[N/2])) pivotindex = 0;
else if ((arr[N/2] >= arr[0] && arr[N/2] <= arr[N-1])
|| (arr[N/2] >= arr[N-1] && arr[N/2] <= arr[0])) pivotindex = N/2;
else pivotindex = N-1;
pivotvalue=arr[pivotindex];
// move pivet to end of array
std::swap(arr[pivotindex],arr[N-1]);
std::swap(particles[pivotindex],particles[N-1]);
newpivotindex=0;
// partition list and array
for(i=0;i<N;++i){
if(arr[i] <= pivotvalue){
std::swap(arr[newpivotindex],arr[i]);
std::swap(particles[newpivotindex],particles[i]);
++newpivotindex;
}
}
if(newpivotindex != 0) --newpivotindex;
quicksort(particles,arr,newpivotindex);
quicksort(&particles[newpivotindex+1],&arr[newpivotindex+1],N-newpivotindex-1);
return ;
}
/*
* Partitions arr[] and particles[] into those with x <= pivotvalue and those with
* x > pivotvalue pivotindex is left at first array value with x > pivotvalue
*/
void quickPartition(PosType pivotvalue,unsigned long *pivotindex,unsigned long *particles
,PosType *arr,unsigned long N){
unsigned long i;
*pivotindex=0;
for(i=0;i<N;++i){
if(arr[i] <= pivotvalue){
std::swap(arr[*pivotindex],arr[i]);
std::swap(particles[*pivotindex],particles[i]);
++(*pivotindex);
}
}
return ;
}
void quickPartitionPoints(PosType pivotvalue,unsigned long *pivotindex
,Point *pointarray,PosType *arr,unsigned long N){
unsigned long i;
*pivotindex=0;
for(i=0;i<N;++i){
if(arr[i] <= pivotvalue){
std::swap(arr[*pivotindex],arr[i]);
assert(*pivotindex < N);
SwapPointsInArray(&pointarray[*pivotindex],&pointarray[i]);
++(*pivotindex);
}
}
return ;
}
void quickPartitionPoints(PosType pivotvalue,unsigned long *pivotindex
,Point *pointarray,PosType (*func)(Point &p),unsigned long N){
unsigned long i;
*pivotindex=0;
for(i=0;i<N;++i){
if(func(pointarray[i]) <= pivotvalue){
assert(*pivotindex < N);
SwapPointsInArray(&pointarray[*pivotindex],&pointarray[i]);
++(*pivotindex);
}
}
return ;
}
}
| 28.604839 | 131 | 0.517245 | [
"vector"
] |
d7ad16b39944be8bfe7cc74e5ec07b49505eb22d | 12,148 | cpp | C++ | src/main.cpp | handsomefox/uni_cpp_project | b05a3a5b64d757c7ccd08271bda7de1ccd04c94b | [
"MIT"
] | 1 | 2021-01-10T12:55:43.000Z | 2021-01-10T12:55:43.000Z | src/main.cpp | handsomefox/uni_cpp_project | b05a3a5b64d757c7ccd08271bda7de1ccd04c94b | [
"MIT"
] | null | null | null | src/main.cpp | handsomefox/uni_cpp_project | b05a3a5b64d757c7ccd08271bda7de1ccd04c94b | [
"MIT"
] | null | null | null | #include "pch.h"
int* GenArray(const size_t size)
{
srand(static_cast<unsigned>(time(nullptr)));
int* array = new int[size];
for (size_t i = 0; i < size; ++i)
array[i] = 1 + rand() % 100;
return array;
}
void ArrayAdd(const size_t size)
{
int* array = GenArray(1000);
double sum = 0;
for (size_t i = 0; i < size; ++i)
sum = sum + array[i];
}
uint64_t GetRDTSCCount()
{
uint64_t c;
__asm {
cpuid
rdtsc
mov dword ptr[c + 0], eax
mov dword ptr[c + 4], edx
}
return c;
}
void GetMax32BitTime()
{
const LONGLONG time = Int32x32To64(0x7FFFFFFF, 10000000) + 116444736000000000;
FILETIME ft;
SYSTEMTIME st;
ft.dwLowDateTime = static_cast<DWORD>(time);
ft.dwHighDateTime = time >> 32;
FileTimeToSystemTime(&ft, &st);
std::cout << st.wYear << "-" << std::setw(2) << std::setfill('0') << st.wMonth
<< "-" << std::setw(2) << std::setfill('0') << st.wDay << " "
<< std::setw(2) << std::setfill('0') << st.wHour << ":"
<< std::setw(2) << std::setfill('0') << st.wMinute << ":"
<< std::setw(2) << std::setfill('0') << st.wSecond << "."
<< std::setw(3) << std::setfill('0') << st.wMilliseconds << "\n";
}
double GetTimeAccuracy()
{
time_t start, end;
time(&start);
end = start;
while (end == start)
time(&end);
return difftime(end, start); // sec
}
float GetClockAccuracy()
{
const clock_t start = clock();
clock_t end = start;
while (end == start)
end = clock();
return static_cast<float>(end - start) / CLOCKS_PER_SEC * 1000; // ms
}
LONGLONG GetFiletimeAccuracy()
{
LARGE_INTEGER time1, time2;
FILETIME start, end;
GetSystemTimeAsFileTime(&start);
end = start;
time1.HighPart = start.dwHighDateTime;
time1.LowPart = start.dwLowDateTime;
time2.HighPart = end.dwHighDateTime;
time2.LowPart = end.dwLowDateTime;
while (time2.QuadPart == time1.QuadPart)
{
GetSystemTimeAsFileTime(&end);
time2.HighPart = end.dwHighDateTime;
time2.LowPart = end.dwLowDateTime;
}
return time2.QuadPart - time1.QuadPart; // 100ns
}
LONGLONG GetFiletimePreciseAccuracy()
{
LARGE_INTEGER time1, time2;
FILETIME start, end;
GetSystemTimePreciseAsFileTime(&start);
end = start;
time1.HighPart = start.dwHighDateTime;
time1.LowPart = start.dwLowDateTime;
time2.HighPart = end.dwHighDateTime;
time2.LowPart = end.dwLowDateTime;
while (time2.QuadPart == time1.QuadPart)
{
GetSystemTimePreciseAsFileTime(&end);
time2.HighPart = end.dwHighDateTime;
time2.LowPart = end.dwLowDateTime;
}
return time2.QuadPart - time1.QuadPart; // 100ns
}
ULONGLONG GetTickCountAccuracy()
{
const ULONGLONG start = GetTickCount64();
ULONGLONG end = start;
while (end == start)
end = GetTickCount64();
return end - start; // ms
}
uint64_t GetRDTSCAccuracy()
{
const uint64_t start = GetRDTSCCount();
uint64_t end = start;
while (end == start)
end = GetRDTSCCount();
return end - start;
}
unsigned long long GetIntrinsicRDTSCAccuracy()
{
const uint64_t start = __rdtsc();
uint64_t end = start;
while (end == start)
end = __rdtsc();
return end - start;
}
LONGLONG GetQPCAccuracy()
{
LARGE_INTEGER start, end, freq, elapsed;
QueryPerformanceFrequency(&freq);
QueryPerformanceCounter(&start);
end = start;
while (end.QuadPart == start.QuadPart)
QueryPerformanceCounter(&end);
elapsed.QuadPart = end.QuadPart - start.QuadPart;
elapsed.QuadPart *= 1000000000; // convert to nanoseconds
elapsed.QuadPart /= freq.QuadPart;
return elapsed.QuadPart; // ns
}
long long GetChronoAccuracy()
{
const auto start = std::chrono::high_resolution_clock::now();
auto end = start;
while (end == start)
end = std::chrono::high_resolution_clock::now();
const std::chrono::duration<double> duration = end - start;
const auto accuracy = std::chrono::duration_cast<std::chrono::nanoseconds>(duration);
return accuracy.count(); // ns
}
double GetOMPAccuracy()
{
const double start = omp_get_wtime();
double end = start;
while (end <= start)
end = omp_get_wtime();
return (end - start) * 1000; // ms
}
void ArrayBenchmarkRDTSC()
{
ULONGLONG duration = ULLONG_MAX;
const size_t n = 10;
DWORD64 start = 0, end = 0;
for (size_t i = 0; i < n; ++i)
{
start = __rdtsc();
ArrayAdd(1000);
end = __rdtsc();
duration = std::min(duration, end - start);
}
std::cout << std::setfill(' ') << "__rdtsc() " << std::setw(34) << "minimal time out of " << n
<< ": " << duration << " ticks" << "(~" << (end - start) / GetCPUFreq() << " us)\n";
}
void ArrayBenchmarkQPC()
{
const size_t n = 10;
LARGE_INTEGER start, freq, elapsed, end;
elapsed.QuadPart = LLONG_MAX;
QueryPerformanceFrequency(&freq);
for (unsigned int i = 0; i < n; ++i)
{
QueryPerformanceCounter(&start);
ArrayAdd(1000);
QueryPerformanceCounter(&end);
elapsed.QuadPart =
std::min(elapsed.QuadPart, end.QuadPart - start.QuadPart);
}
elapsed.QuadPart *= 1000000; // convert to microseconds
elapsed.QuadPart /= freq.QuadPart;
std::cout << std::setfill(' ')
<< "GetPerformanceCounter() minimal time out of " << n << ": "
<< elapsed.QuadPart << " us\n\n";
}
double ArrayBenchmarkAbsolute(const size_t size)
{
int* array = GenArray(size);
double add = 0;
const double start = omp_get_wtime();
for (size_t i = 0; i < size; ++i)
add += array[i];
const double end = omp_get_wtime();
const double duration = end - start;
std::cout << "\nAdding " << size << " elements of array\n";
std::cout << "Sum = " << add << "\n";
std::cout << "Time elapsed: " << duration << " seconds\n";
return duration;
}
int ArrayBenchmarkRelative(const size_t size)
{
int* array = GenArray(size), cycles = 0;
double add = 0;
ULONGLONG elapsed = 0;
const ULONGLONG start = GetTickCount64();
while (elapsed <= 2000)
{
for (size_t i = 0; i < size; ++i)
{
add += array[i];
elapsed = GetTickCount64() - start;
}
cycles++;
}
std::cout << "\nAdding " << size << " elements of array\n";
std::cout << "Max possible cycles in 2 sec: " << cycles << "\n";
return cycles;
}
void Task1()
{
SetConsoleColor(10);
std::cout << "Max possible 32-bit time\n";
std::cout << "------------------------\n";
SetConsoleColor(14);
GetMax32BitTime();
}
void Task2()
{
SetConsoleColor(10);
std::cout << "\nTimer functions benchmark\n";
std::cout << "-------------------------\n";
SetConsoleColor(9);
std::cout << "\nFunction:" << std::setfill(' ') << std::setw(41) << "Accuracy:\n\n";
SetConsoleColor(14);
std::cout << "Time()" << std::setfill(' ') << std::setw(40) << GetTimeAccuracy() << " sec\n";
std::cout << "Clock()" << std::setfill(' ') << std::setw(39) << GetClockAccuracy() << " ms\n";
std::cout << "GetSystemTimeAsFileTime()" << std::setfill(' ') << std::setw(21) << GetFiletimeAccuracy() * 100 << " ns\n";
std::cout << "GetSystemTimePreciseAsFileTime()" << std::setfill(' ') << std::setw(14) << GetFiletimePreciseAccuracy() * 100 << " ns\n";
std::cout << "GetTickCount()" << std::setfill(' ') << std::setw(32) << GetTickCountAccuracy() << " ms\n";
std::cout << "Rdtsc()" << std::setfill(' ') << std::setw(39) << GetRDTSCAccuracy() << " ticks(" << GetRDTSCAccuracy() / GetCPUFreq() << " ms)\n";
std::cout << "__Rdtsc()" << std::setfill(' ') << std::setw(37) << GetIntrinsicRDTSCAccuracy() << " ticks(" << GetIntrinsicRDTSCAccuracy() / GetCPUFreq() << " ms)\n";
std::cout << "QueryPerformanceCounter()" << std::setfill(' ') << std::setw(21) << GetQPCAccuracy() << " ns\n";
std::cout << "Chrono Class" << std::setfill(' ') << std::setw(34) << GetChronoAccuracy() << " ns\n";
std::cout << "omp_get_wtime()" << std::setfill(' ') << std::setw(31) << GetOMPAccuracy() << " ms\n";
}
void Task3()
{
SetConsoleColor(10);
std::cout << "\nArray benchmark\n";
std::cout << "---------------\n";
SetConsoleColor(14);
ArrayBenchmarkRDTSC();
ArrayBenchmarkQPC();
}
void Task4()
{
SetConsoleColor(10);
std::cout << "\nArray addition benchmark\n";
std::cout << "------------------------\n";
SetConsoleColor(9);
std::cout << "\nAbsolute benchmark:\n";
SetConsoleColor(14);
const double time1 = ArrayBenchmarkAbsolute(100000);
const double time2 = ArrayBenchmarkAbsolute(200000);
const double time3 = ArrayBenchmarkAbsolute(300000);
SetConsoleColor(1);
const double ttime2 = time2 / time1;
const double ttime3 = time3 / time1;
std::cout << "\nT(200000/100000) = " << ttime2 << "\n";
std::cout << "T(300000/100000) = " << ttime3 << "\n";
SetConsoleColor(9);
std::cout << "\nRelative benchmark:\n";
SetConsoleColor(14);
const double ops1 = ArrayBenchmarkRelative(100000);
const double ops2 = ArrayBenchmarkRelative(200000);
const double ops3 = ArrayBenchmarkRelative(300000);
const double tops2 = ops2 / ops1;
const double tops3 = ops3 / ops1;
SetConsoleColor(1);
std::cout << "\nT(200000/100000) = " << tops2 << "\n";
std::cout << "T(300000/100000) = " << tops3 << "\n";
SetConsoleColor(10);
std::cout << "\nDifference between absolute and relative:\n";
SetConsoleColor(14);
std::cout << "\nDifference in T(200000/100000) = " << std::setprecision(4) << 100 * abs(1 - ttime2 * tops2) << "%\n";
std::cout << "Difference in T(300000/100000) = " << std::setprecision(4) << 100 * abs(1 - ttime3 * tops3) << "%\n";
}
void Task5()
{
size_t MatrixSize = 512;
SetConsoleColor(10);
std::cout << "\nMatrix multiplication benchmark\n";
std::cout << "-------------------------------\n";
for (auto i = 0; i < 3; ++i)
{
SetConsoleColor(14);
std::cout << "\nSize = " << MatrixSize << "\n";
Matrix<int> object(MatrixSize);
int** matrix = CreateFilledMatrix(matrix, MatrixSize);
std::cout << "Matrix multiplication with objects took: " << RunMatrixBenchmark(object, object, MatrixSize) << " sec\n";
std::cout << "Matrix multiplication without objects took: " << RunMatrixBenchmark(matrix, matrix, MatrixSize) << " sec\n\n";
for (size_t j = 0; j < MatrixSize; ++j)
{
delete[] matrix[j];
}
delete[] matrix;
MatrixSize *= 2;
}
}
void Task9()
{
size_t matrix_size = 1024;
SetConsoleColor(10);
std::cout << "\nInfluence of data types on the Matrix multiplication benchmark\n";
std::cout << "--------------------------------------------------------------\n";
SetConsoleColor(14);
int8_t** MatrixInt8 = CreateFilledMatrix(MatrixInt8, matrix_size);
std::cout << "Matrix multiplication with int8 took: " << RunMatrixBenchmark(MatrixInt8, MatrixInt8, matrix_size) << " sec\n\n";
for (size_t i = 0; i < matrix_size; ++i)
delete[] MatrixInt8[i];
delete[] MatrixInt8;
int16_t** MatrixInt16 = CreateFilledMatrix(MatrixInt16, matrix_size);
std::cout << "Matrix multiplication with int16 took: " << RunMatrixBenchmark(MatrixInt16, MatrixInt16, matrix_size) << " sec\n\n";
for (size_t i = 0; i < matrix_size; ++i)
delete[] MatrixInt16[i];
delete[] MatrixInt16;
int32_t** MatrixInt32 = CreateFilledMatrix(MatrixInt32, matrix_size);
std::cout << "Matrix multiplication with int32 took: " << RunMatrixBenchmark(MatrixInt32, MatrixInt32, matrix_size) << " sec\n\n";
for (size_t i = 0; i < matrix_size; ++i)
delete[] MatrixInt32[i];
delete[] MatrixInt32;
int64_t** MatrixInt64 = CreateFilledMatrix(MatrixInt64, matrix_size);
std::cout << "Matrix multiplication with int64 took: " << RunMatrixBenchmark(MatrixInt64, MatrixInt64, matrix_size) << " sec\n\n";
for (size_t i = 0; i < matrix_size; ++i)
delete[] MatrixInt64[i];
delete[] MatrixInt64;
double** MatrixDouble = CreateFilledMatrix(MatrixDouble, matrix_size);
std::cout << "Matrix multiplication with double took: " << RunMatrixBenchmark(MatrixDouble, MatrixDouble, matrix_size) << " sec\n\n";
for (size_t i = 0; i < matrix_size; ++i)
delete[] MatrixDouble[i];
delete[] MatrixDouble;
float** MatrixFloat = CreateFilledMatrix(MatrixFloat, matrix_size);
std::cout << "Matrix multiplication with float took: " << RunMatrixBenchmark(MatrixFloat, MatrixFloat, matrix_size) << " sec\n\n";
for (size_t i = 0; i < matrix_size; ++i)
delete[] MatrixFloat[i];
delete[] MatrixFloat;
}
int main()
{
PrintBuildType();
SetConsoleColor(10);
std::cout << "Max CPU Freq\n-------------\n";
SetConsoleColor(14);
std::cout << GetCPUFreq() << " Mhz\n\n";
Task1();
Task2();
Task3();
Task4();
Task5();
Task9();
SetConsoleColor(15);
system("PAUSE");
return 0;
} | 28.383178 | 166 | 0.647926 | [
"object"
] |
d7ad2dd0e0618d77a8f800a0f5e63163c922231a | 2,120 | cpp | C++ | segmentation/Caffe_Segmentation/examples/seg/cropDet.cpp | USCDataScience/cmu-fg-bg-similarity | d8fc9a53937551f7a052bc2c6f442bcc29ea2615 | [
"Apache-2.0"
] | 8 | 2020-04-13T21:40:26.000Z | 2022-01-22T11:32:31.000Z | segmentation/Caffe_Segmentation/examples/seg/cropDet.cpp | USCDataScience/cmu-fg-bg-similarity | d8fc9a53937551f7a052bc2c6f442bcc29ea2615 | [
"Apache-2.0"
] | null | null | null | segmentation/Caffe_Segmentation/examples/seg/cropDet.cpp | USCDataScience/cmu-fg-bg-similarity | d8fc9a53937551f7a052bc2c6f442bcc29ea2615 | [
"Apache-2.0"
] | null | null | null | /*
* cropDet.cpp
*
* Created on: Nov 30, 2014
* Author: rohitgirdhar
*/
#include <glog/logging.h>
#include <leveldb/db.h>
#include <leveldb/write_batch.h>
#include <cstdio>
#include <algorithm>
#include <string>
#include <iostream>
#include <fstream>
#include <vector>
#include <set>
#include <algorithm>
#include <libgen.h> // for dirname
#include <boost/filesystem.hpp>
#include <opencv2/opencv.hpp>
#include "caffe/proto/caffe.pb.h"
#include "caffe/util/io.hpp"
using namespace caffe;
using std::string;
using namespace cv;
using namespace std;
#define SZ_X 256
#define SZ_Y 256
#define OFFSET ((256-227)/2)
int CreateDir(const char*, int);
int main(int argc, char** argv) {
::google::InitGoogleLogging(argv[0]);
if (argc != 4) {
LOG(ERROR) << "Usage: " << argv[0] << " LOC_RES_FILE IMGS_DIR OUT_DIR";
return -1;
}
char* LOC_RES_FILE = argv[1];
char* IMGS_DIR = argv[2];
char* OUT_DIR = argv[3];
string fname;
float xmin, ymin, xmax, ymax;
ifstream infile(LOC_RES_FILE);
if (!infile.is_open()) {
LOG(ERROR) << "Unable to open file: " << LOC_RES_FILE;
return -1;
}
Mat I, C;
while (infile >> fname >> xmin >> ymin >> xmax >> ymax) {
string fpath = string(IMGS_DIR) + string("/") + fname;
I = imread(fpath.c_str());
if (!I.data) {
LOG(ERROR) << "Unable to read image : " << fpath;
continue;
}
resize(I, I, Size(SZ_X, SZ_Y));
xmin = std::min(std::max(xmin + OFFSET, (float) 0), (float) SZ_X-1);
ymin = std::min(std::max(ymin + OFFSET, (float) 0), (float) SZ_Y-1);
xmax = std::min(std::max(xmax + OFFSET, (float) 0), (float) SZ_X-1);
ymax = std::min(std::max(ymax + OFFSET, (float) 0), (float) SZ_Y-1);
C = I(Rect(xmin, ymin, xmax - xmin, ymax - ymin));
string filename = OUT_DIR + string("/") + fname;
boost::filesystem::create_directory(dirname(strdup(filename.c_str())));
imwrite(filename, C);
LOG(ERROR)<<filename<<" "<<xmin<<" "<<ymin<<" "<<xmax<<" "<<ymax;
}
return 0;
}
| 26.835443 | 79 | 0.588208 | [
"vector"
] |
d7bbe85c1371f2ee0b5b3a3d69ffc097e6090656 | 599 | cpp | C++ | src/test_ztj.cpp | TaojingZHANG/openvslam | 846ecaa825c83602014808de5bb412196d701561 | [
"Apache-2.0",
"BSD-2-Clause",
"MIT"
] | null | null | null | src/test_ztj.cpp | TaojingZHANG/openvslam | 846ecaa825c83602014808de5bb412196d701561 | [
"Apache-2.0",
"BSD-2-Clause",
"MIT"
] | null | null | null | src/test_ztj.cpp | TaojingZHANG/openvslam | 846ecaa825c83602014808de5bb412196d701561 | [
"Apache-2.0",
"BSD-2-Clause",
"MIT"
] | null | null | null | //
// Created by ztj on 2021/6/6.
//
#include <map>
#include <vector>
#include <unordered_map>
#include <iostream>
using namespace std;
vector<int> inorderTraversal(){
vector<int> ret;
vector<int> ret2;
ret.insert(ret.end(),ret2.begin(),ret2.end());
return vector<int>();
};
int main(int argc, char** argv) {
inorderTraversal();
vector<int> nums(10, 0);
nums.push_back(2);
cout << nums.size() << endl;
unordered_map<int,int> um1;
um1[5];
cout<<um1.size()<<endl;
map<int,int> m1;
m1[5];
cout<<m1.size()<<endl;
return 0;
} | 13.021739 | 50 | 0.585977 | [
"vector"
] |
d7cd73f8fd9ce56d340d11bbfdd95ea03af93070 | 7,262 | hpp | C++ | include/Textbox.hpp | edbird/Worlds-Best-Text-Editor | 92c4175ab1f34109c98374aa6839bc6dd0eb34fc | [
"MIT"
] | null | null | null | include/Textbox.hpp | edbird/Worlds-Best-Text-Editor | 92c4175ab1f34109c98374aa6839bc6dd0eb34fc | [
"MIT"
] | 26 | 2018-03-15T12:03:40.000Z | 2018-06-01T21:14:48.000Z | include/Textbox.hpp | edbird/Worlds-Best-Text-Editor | 92c4175ab1f34109c98374aa6839bc6dd0eb34fc | [
"MIT"
] | null | null | null | #ifndef TEXTBOX_HPP
#define TEXTBOX_HPP
#include "Functions.hpp"
#include "GUIObject.hpp"
#include "Buffer.hpp"
#include "FontTextureManager.hpp"
//#include "CharMatrix.hpp"
#include <SDL.h>
#include <SDL_ttf.h>
#include <string>
#include <sstream>
class Textbox : public Buffer, public GUIObject
{
public:
Textbox(const Config& config, const FontTextureManager& ftm, const int width, const int height)
: GUIObject(width, height)
, _config_{config}
, _ftm_{ftm}
//, _size_x_{width}
//, _size_y_{height}
//, _pos_x_{0} // TODO: test with/out line number
//, _pos_y_{0}
//, _line_text_first_line_{0}
, _scroll_index_{0}
, _scroll_sub_index_{0}
, _line_number_enabled_{false}
{
//const std::map<const char, SDL_Texture*>& texture_chars{_ftm_.GetCharTexture()};
const std::map<const char, SDL_Rect>& texture_chars_size{ftm.GetCharSize()};
int size_x{texture_chars_size.at(' ').w};
int size_y{texture_chars_size.at(' ').h};
_cursor_.reset(new Cursor(size_x, size_y, /*2 * size_x, 0,*/ config));
// TODO: implement
_cursor_->SetPos(0, 0); // the cursor is always drawn in the location where the next
// character will be inserted: the buffer starts with zero
// size however the cursor will be drawn at position 0
// even though the buffer is not of size 1
//_charmatrix_ptr_ = new CharMatrix(_pos_x_, _pos_y_, _size_x_, _size_y_, *_cursor_, _config_, _ftm_);
////////////////////////////////////////////////////////////////////////////
// READ CONFIG
////////////////////////////////////////////////////////////////////////////
//bool line_number_enabled{false};
//int line_number_width{0};
// Note: only 1 is true, any other integer is false
if(_config_.GetInt("linenumber") == 1)
{
_line_number_enabled_ = true;
}
}
// TODO: change to get cursor not subfunctions of cursor class
//Cursor::CursorPos_t GetCursorLine() const;
//Cursor::CursorPos_t GetCursorCol() const;
const Cursor& GetCursor() const;
// TODO: should the buffer be responsible for setting the cursor
// position or should the cursor be responsible for setting its own
// bounds ?
void CursorLeft();
void CursorRight();
// TODO: remember target line position
// TODO: config: set rememberlineposition
void CursorUp();
void CursorDown();
void CursorCR();
private:
/*
Cursor& MutableCursor()
*/
// TODO: Do i still want the XAtCursor() functions?
// Does the cursor "live" in this class? Are the cursor related functions
// still relevant?
public:
void InsertAtCursor(const char ch);
void ReturnAtCursor();
void BackspaceAtCursor();
//void ResetCursorLastBlinkTime();
private:
////////////////////////////////////////////////////////////////////////////
// Rendering helper functions
////////////////////////////////////////////////////////////////////////////
// Convert line number to string
std::string line_number_to_string(const int line_number, const int line_number_width) const;
// compute line number width
unsigned int get_line_number_width() const;
// TODO: pass dst_rect by reference and modify within function
// TODO: remove _texture_chars_ arguments
void print_line_number(const int line_number, const int line_number_width, const unsigned int print_index_y, SDL_Renderer *const _renderer_) const;
// print char
// TODO: optimize this, flag might not be required
//void print_char_texture(SDL_Renderer *const renderer, SDL_Texture* const texture,
// const SDL_Rect& src_rect, SDL_Rect& dst_rect) const;
public:
// TODO: the buffer object should know its own WIDTH and HEIGHT
void Draw(SDL_Renderer *const renderer, const Uint32 timer) const;
//{
//const std::map<const char, SDL_Texture*>& texture_chars{_ftm_.GetCharTexture()};
// const std::map<const char, SDL_Rect>& texture_chars_size{_ftm_.GetCharSize()};
// compute line width
// TODO: can be done inside CharMatrix
//std::size_t line_width{(std::size_t)(_size_x_ / texture_chars_size.at(' ').w)};
// create character matrix object
// TODO: this should be a long life object
//CharMatrix cm(/*line_width,*/ _buffer_, _pos_x_, _pos_y_, _size_x_, _size_y_, *_cursor_, _config_, _ftm_);
//_charmatrix_ptr_->Update(_buffer_, renderer, _timer_);
// set first line to draw from
//_charmatrix_ptr_->SetFirstLine(_line_text_first_line_);
//cm.Draw(renderer, _timer_);
//_charmatrix_ptr_->Draw(renderer, _timer_);
//}
// get const buffer reference
//const Buffer& GetBuffer() const
//{
// return _buffer_;
//}
//Buffer& MutableBuffer()
//{
// return _buffer_;
//}
void ResetCursor() // used when opening new file
{
_cursor_->SetPos(0, 0);
}
void ScrollDown();
void ScrollUp();
void ScrollDownSub();
void ScrollUpSub();
private:
void update_wrap_count();
////////////////////////////////////////////////////////////////////////////
// DATA MEMBERS
////////////////////////////////////////////////////////////////////////////
// cursor
std::unique_ptr<Cursor> _cursor_;
//std::size_t _cursor_x_;
//std::size_t _cursor_y_;
const Config& _config_;
const FontTextureManager& _ftm_;
//CharMatrix *_charmatrix_ptr_;
//Buffer _buffer_;
// size of buffer on screen (for drawing)
//int _size_x_;
//int _size_y_;
// position (for drawing)
//int _pos_x_;
//int _pos_y_;
/// Drawing specific members ///
// break lines (wrap)
//std::vector<std::string> _matrix;
//std::vector<int> _line_number_;
//std::vector<unsigned int> _line_wrap_count_;
// first line of text to print
// first line to start printing from
//std::size_t _line_text_first_line_;
// Note: new system: this index counts the number of wrapped lines
// a line wrapped 3 times is counted through 3 times
std::size_t _scroll_index_;
std::size_t _scroll_sub_index_;
bool _line_number_enabled_;
std::vector<unsigned int> wrap_count;
};
// TODO: this is now implemented by Textbox class
class ActionBuffer : Buffer
{
// TODO: the "actions" are implemented here
// eg; left key press should move the _cursor_ inside of buffer
};
/*
Cursor& MutableCursor()
{
return _cursor_;
}
*/
/*
Cursor::CursorPos_t Textbox::GetCursorLine() const
{
return _cursor_->GetPosLine();
}
Cursor::CursorPos_t Textbox::GetCursorCol() const
{
return _cursor_->GetPosCol();
}
*/
//void ResetCursorLastBlinkTime();
#endif
| 23.966997 | 151 | 0.580832 | [
"object",
"vector"
] |
d7d4b668e9ad5e80a96715e5945ae0a3ebcc98bc | 1,522 | cpp | C++ | exe/src/control/parameters/setrationodecountvsgridspotcountcmd.cpp | jonpetri/CollectGame | 251beb560f8246468479f04461bfc0b1298a7e70 | [
"MIT"
] | null | null | null | exe/src/control/parameters/setrationodecountvsgridspotcountcmd.cpp | jonpetri/CollectGame | 251beb560f8246468479f04461bfc0b1298a7e70 | [
"MIT"
] | null | null | null | exe/src/control/parameters/setrationodecountvsgridspotcountcmd.cpp | jonpetri/CollectGame | 251beb560f8246468479f04461bfc0b1298a7e70 | [
"MIT"
] | null | null | null | #include "setrationodecountvsgridspotcountcmd.h"
#include "model/game/collectgame.h"
#include "model/game/gameparameters.h"
//-----------------------------------------------------------------------------------------------------------------------
// SetRatioNodeCountVsGridSpotCountCmd :: Constructors / Destructors
//-----------------------------------------------------------------------------------------------------------------------
SetRatioNodeCountVsGridSpotCountCmd::SetRatioNodeCountVsGridSpotCountCmd()
{
// Command's terms/arguments definition
this->addCommandTerm("NC");
this->setDescription("Modify the ratio Node count / grid spot count");
this->setExpectedParameterCount(1);
}
SetRatioNodeCountVsGridSpotCountCmd::~SetRatioNodeCountVsGridSpotCountCmd()
{
}
//-----------------------------------------------------------------------------------------------------------------------
// SetRatioNodeCountVsGridSpotCountCmd :: Methods
//-----------------------------------------------------------------------------------------------------------------------
/**
* Set the parameter Node count / grid spot count ratio
*/
void SetRatioNodeCountVsGridSpotCountCmd::execute()
{
float fParaValue;
if (this->checkParameterIsPositiveFloat(0, fParaValue) == false)
return;
if (this->m_model->gameParameters()->setRatio_NodeCountVsGridSpotCount(fParaValue) == false)
{
this->sendMessageToUser("Incorrect entry.\n");
return;
}
this->modelModified();
}
| 36.238095 | 121 | 0.507227 | [
"model"
] |
d7d7b2496155157788dc5bec016259fc3b2a62fd | 7,934 | cpp | C++ | sumu/aps/aps-0.9.1/aps/test.cpp | Sera91/sumu | 1ad51e89c62ea8074735611d88668094d5cf1c3d | [
"BSD-3-Clause"
] | 4 | 2021-11-04T11:32:33.000Z | 2021-12-24T14:55:14.000Z | sumu/aps/aps-0.9.1/aps/test.cpp | Sera91/sumu | 1ad51e89c62ea8074735611d88668094d5cf1c3d | [
"BSD-3-Clause"
] | 18 | 2021-10-30T07:31:12.000Z | 2022-02-05T10:25:08.000Z | sumu/aps/aps-0.9.1/aps/test.cpp | Sera91/sumu | 1ad51e89c62ea8074735611d88668094d5cf1c3d | [
"BSD-3-Clause"
] | 3 | 2020-12-29T11:45:18.000Z | 2022-03-10T12:09:18.000Z | #include "aps.h"
#include "ar.h"
#include "array.h"
#include "conf.h"
#include "logdouble.h"
#include "types.h"
#include <cmath>
#include <limits>
#include <random>
#include <vector>
namespace aps {
namespace {
template <typename A, typename B>
void check_equal(const A& a, const B& b, const char* file, int line) {
if(!(a == b)) {
fail("CHECK_EQUAL(", a, ", ", b, ") failed in ", file, ":", line);
}
}
#define CHECK_EQUAL(a, b) check_equal((a), (b), __FILE__, __LINE__)
void check_true(bool val, const char* file, int line) {
if(!val) {
fail("CHECK_TRUE failed in ", file, ":", line);
}
}
#define CHECK_TRUE(v) check_true((v), __FILE__, __LINE__)
std::mt19937 rng(std::random_device{}());
template <typename T>
void testNumber() {
for(int i = 0; i < 1000; ++i) {
double a = std::uniform_real_distribution<double>(0.0, 10.0)(rng);
double b = std::uniform_real_distribution<double>(0.0, 10.0)(rng);
if(!std::uniform_int_distribution<int>(0, 9)(rng)) {
a = 0.0;
}
if(!std::uniform_int_distribution<int>(0, 9)(rng)) {
b = 0.0;
}
if(!std::uniform_int_distribution<int>(0, 9)(rng)) {
b = a;
}
T a2 = (T)a;
T b2 = (T)b;
{
double c = a + b;
T c2 = a2 + b2;
double d = std::abs(c - (double)c2);
CHECK_TRUE(d < 1e-10);
}
{
double c = a * b;
T c2 = a2 * b2;
double d = std::abs(c - (double)c2);
CHECK_TRUE(d < 1e-10);
}
{
double c = nonnegativeSubtraction(a, b);
T c2 = nonnegativeSubtraction(a2, b2);
double d = std::abs(c - (double)c2);
CHECK_TRUE(d < 1e-10);
}
}
}
void checkCanonical(ExtDouble x) {
CHECK_TRUE(
(x.coef == 0.0 && x.exp == 0) ||
(
x.coef >= 1.0 - 1e-6 &&
x.coef < (1.0 + 1e-6) * ExtDouble::E &&
x.exp >= ExtDouble::MinExp &&
x.exp <= ExtDouble::MaxExp
)
);
}
void crossTestExtLogDouble() {
for(int t = 0; t < 100; ++t) {
LogDouble a = LogDouble::fromLog(
std::uniform_real_distribution<double>(-1e6, 1e6)(rng)
);
LogDouble b = LogDouble::fromLog(
std::uniform_real_distribution<double>(-1e6, 1e6)(rng)
);
ExtDouble a2 = (ExtDouble)a;
ExtDouble b2 = (ExtDouble)b;
{
LogDouble c = a + b;
ExtDouble c2 = a2 + b2;
checkCanonical(c2);
CHECK_TRUE(std::abs(c.log - LogDouble(c2).log) < 1e-6);
}
{
LogDouble c = nonnegativeSubtraction(a, b);
ExtDouble c2 = nonnegativeSubtraction(a2, b2);
checkCanonical(c2);
if(c.log != LogDouble(c2).log) {
CHECK_TRUE(std::abs(c.log - LogDouble(c2).log) < 1e-6);
}
}
{
LogDouble c = a * b;
ExtDouble c2 = a2 * b2;
checkCanonical(c2);
CHECK_TRUE(std::abs(c.log - LogDouble(c2).log) < 1e-6);
}
}
}
bool isValidWeightValue(uint64_t) {
return true;
}
bool isValidWeightValue(double x) {
return std::isfinite(x);
}
bool isValidWeightValue(LogDouble x) {
return std::isfinite(x.log) || x.log == -std::numeric_limits<double>::infinity();
}
bool isValidWeightValue(ExtDouble x) {
return
(x.coef == 0.0 && x.exp == 0) ||
(
x.coef >= 1.0 - 1e-6 &&
x.coef < (1.0 + 1e-6) * ExtDouble::E &&
x.exp >= ExtDouble::MinExp &&
x.exp <= ExtDouble::MaxExp
);
}
void genWeightValue(uint64_t& ret) {
ret = std::uniform_int_distribution<uint64_t>()(rng);
}
void genWeightValue(double& ret) {
ret = std::uniform_real_distribution<double>(1.0, 2.0)(rng);
}
void genWeightValue(LogDouble& ret) {
ret = (LogDouble)std::uniform_real_distribution<double>(1.0, 2.0)(rng);
}
void genWeightValue(ExtDouble& ret) {
ret = (ExtDouble)std::uniform_real_distribution<double>(1.0, 2.0)(rng);
}
template <typename T>
void genWeight(size_t n, Array<Array<T>>& ret) {
ret = Array<Array<T>>(n);
for(size_t v = 0; v < n; ++v) {
ret[v] = Array<T>(S1 << (n - 1));
for(size_t i = 0; i < ret[v].size(); ++i) {
genWeightValue(ret[v][i]);
}
}
}
template <typename T>
void checkWeightValuesEqual(const T& a, const T& b) {
CHECK_EQUAL(a, b);
}
void checkWeightValuesEqual(double a, double b) {
CHECK_TRUE(std::abs((b - a) / a) < 1e-8);
}
void checkWeightValuesEqual(LogDouble a, LogDouble b) {
CHECK_TRUE(std::abs(b.log - a.log) < 1e-8);
}
void checkWeightValuesEqual(ExtDouble a, ExtDouble b) {
return checkWeightValuesEqual((LogDouble)a, (LogDouble)b);
}
template <typename T>
void checkWeightsEqual(const Array<Array<T>>& a, const Array<Array<T>>& b) {
size_t n = a.size();
CHECK_EQUAL(b.size(), n);
for(size_t v = 0; v < n; ++v) {
CHECK_EQUAL(a[v].size(), S1 << (n - 1));
CHECK_EQUAL(b[v].size(), S1 << (n - 1));
for(size_t i = 0; i < a[v].size(); ++i) {
checkWeightValuesEqual(a[v][i], b[v][i]);
}
}
}
template <typename T>
void checkARResultsEqual(const Array<Array<T>>& a, const Array<Array<T>>& b) {
size_t n = a.size();
CHECK_EQUAL(b.size(), n);
for(size_t v = 0; v < n; ++v) {
CHECK_EQUAL(a[v].size(), n);
CHECK_EQUAL(b[v].size(), n);
for(size_t i = 0; i < n; ++i) {
checkWeightValuesEqual(a[v][i], b[v][i]);
}
}
}
template <typename T>
void testAPS(const std::vector<std::pair<std::string, APSFunc<T>>>& funcs) {
for(size_t n = 0; n <= 16; ++n) {
if(conf::verbose) {
std::cerr << " n = " << n << ":\n";
}
Array<Array<T>> w;
genWeight(n, w);
Array<Array<T>> cmpResult;
for(const std::pair<std::string, APSFunc<T>>& func : funcs) {
if(conf::verbose) {
std::cerr << " Method " << func.first << "\n";
}
Array<Array<T>> result = func.second(w, true);
if(n && !result.size()) {
if(conf::verbose) {
std::cerr << " ^ SKIPPED\n";
}
continue;
}
CHECK_EQUAL(result.size(), n);
for(size_t v = 0; v < n; ++v) {
CHECK_EQUAL(result[v].size(), S1 << (n - 1));
for(size_t i = 0; i < result[v].size(); ++i) {
CHECK_TRUE(isValidWeightValue(result[v][i]));
}
}
if(cmpResult.size()) {
checkWeightsEqual(cmpResult, result);
} else {
cmpResult = move(result);
}
}
}
}
template <typename T>
void testOrderModularAPS() {
if(conf::verbose) {
std::cerr << " Order-modular APS\n";
}
testAPS(getOrderModularAPSFuncs<T>());
}
template <typename T>
void testModularAPS() {
if(conf::verbose) {
std::cerr << " Modular APS\n";
}
testAPS(getModularAPSFuncs<T>());
}
template <typename T>
void testAPS() {
testModularAPS<T>();
testOrderModularAPS<T>();
}
template <typename T>
void testAR(const std::vector<std::pair<std::string, APSFunc<T>>>& funcs) {
for(size_t n = 0; n <= 16; ++n) {
if(conf::verbose) {
std::cerr << " n = " << n << ":\n";
}
Array<Array<T>> w;
genWeight(n, w);
Array<Array<T>> cmpResult;
for(const std::pair<std::string, APSFunc<T>>& func : funcs) {
if(conf::verbose) {
std::cerr << " Method " << func.first << "\n";
}
Array<Array<T>> result = func.second(w, true);
if(n && !result.size()) {
if(conf::verbose) {
std::cerr << " ^ SKIPPED\n";
}
continue;
}
CHECK_EQUAL(result.size(), n);
for(size_t v = 0; v < n; ++v) {
CHECK_EQUAL(result[v].size(), n);
for(size_t i = 0; i < result[v].size(); ++i) {
CHECK_TRUE(isValidWeightValue(result[v][i]));
}
}
if(cmpResult.size()) {
checkARResultsEqual(cmpResult, result);
} else {
cmpResult = move(result);
}
}
}
}
template <typename T>
void testOrderModularAR() {
if(conf::verbose) {
std::cerr << " Order-modular AR\n";
}
testAR(getOrderModularARFuncs<T>());
}
template <typename T>
void testModularAR() {
if(conf::verbose) {
std::cerr << " Modular AR\n";
}
testAR(getModularARFuncs<T>());
}
template <typename T>
void testAR() {
testModularAR<T>();
testOrderModularAR<T>();
}
}
void runTests() {
testNumber<LogDouble>();
testNumber<ExtDouble>();
crossTestExtLogDouble();
#undef APS_FOR_EACH_NUMBER_TYPE_TEMPLATE
#define APS_FOR_EACH_NUMBER_TYPE_TEMPLATE(T) \
if(conf::verbose) { \
std::cerr << "T = " << #T << "\n"; \
} \
testAPS<T>(); \
testAR<T>();
APS_FOR_EACH_NUMBER_TYPE
if(conf::verbose) {
std::cerr << "All tests completed successfully\n";
}
}
}
| 22.798851 | 82 | 0.60247 | [
"vector"
] |
d7e2e6cd6b63be796b238f2e277177d4c6df36b7 | 1,623 | hpp | C++ | pose_refinement/SA-LMPE/ba/openMVG/sfm/sfm_view_io.hpp | Aurelio93/satellite-pose-estimation | 46957a9bc9f204d468f8fe3150593b3db0f0726a | [
"MIT"
] | 90 | 2019-05-19T03:48:23.000Z | 2022-02-02T15:20:49.000Z | pose_refinement/SA-LMPE/ba/openMVG/sfm/sfm_view_io.hpp | Aurelio93/satellite-pose-estimation | 46957a9bc9f204d468f8fe3150593b3db0f0726a | [
"MIT"
] | 11 | 2019-05-22T07:45:46.000Z | 2021-05-20T01:48:26.000Z | pose_refinement/SA-LMPE/ba/openMVG/sfm/sfm_view_io.hpp | Aurelio93/satellite-pose-estimation | 46957a9bc9f204d468f8fe3150593b3db0f0726a | [
"MIT"
] | 18 | 2019-05-19T03:48:32.000Z | 2021-05-29T18:19:16.000Z | // This file is part of OpenMVG, an Open Multiple View Geometry C++ library.
// Copyright (c) 2015 Pierre Moulon.
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
#ifndef OPENMVG_SFM_SFM_VIEW_IO_HPP
#define OPENMVG_SFM_SFM_VIEW_IO_HPP
#include "openMVG/sfm/sfm_view.hpp"
#include "third_party/stlplus3/filesystemSimplified/file_system.hpp"
#include <cereal/types/polymorphic.hpp>
template <class Archive>
void openMVG::sfm::View::save( Archive & ar ) const
{
ar(cereal::make_nvp("local_path", stlplus::folder_part(s_Img_path)),
cereal::make_nvp("filename", stlplus::filename_part(s_Img_path)),
cereal::make_nvp("width", ui_width),
cereal::make_nvp("height", ui_height),
cereal::make_nvp("id_view", id_view),
cereal::make_nvp("id_intrinsic", id_intrinsic),
cereal::make_nvp("id_pose", id_pose));
}
template <class Archive>
void openMVG::sfm::View::load( Archive & ar )
{
//Define a view with two string (base_path & basename)
std::string local_path = s_Img_path;
std::string filename = s_Img_path;
ar(cereal::make_nvp("local_path", local_path),
cereal::make_nvp("filename", filename),
cereal::make_nvp("width", ui_width),
cereal::make_nvp("height", ui_height),
cereal::make_nvp("id_view", id_view),
cereal::make_nvp("id_intrinsic", id_intrinsic),
cereal::make_nvp("id_pose", id_pose));
s_Img_path = stlplus::create_filespec(local_path, filename);
}
#endif // OPENMVG_SFM_SFM_VIEW_IO_HPP
| 32.46 | 76 | 0.72212 | [
"geometry"
] |
d7f60c19125337c5d755692b4ea6425970363b09 | 357 | cpp | C++ | Engine/Source/FishEngine/InstantiateObject.cpp | ValtoGameEngines/Fish-Engine | a4b9fb9b0a6dc202f7990e75f4b7d8d5163209d9 | [
"MIT"
] | 240 | 2017-02-17T10:08:19.000Z | 2022-03-25T14:45:29.000Z | Engine/Source/FishEngine/InstantiateObject.cpp | ValtoGameEngines/Fish-Engine | a4b9fb9b0a6dc202f7990e75f4b7d8d5163209d9 | [
"MIT"
] | 2 | 2016-10-12T07:08:38.000Z | 2017-04-05T01:56:30.000Z | Engine/Source/FishEngine/InstantiateObject.cpp | yushroom/FishEngine | a4b9fb9b0a6dc202f7990e75f4b7d8d5163209d9 | [
"MIT"
] | 39 | 2017-03-02T09:40:07.000Z | 2021-12-04T07:28:53.000Z | #include <FishEngine/Object.hpp>
#include <FishEngine/GameObject.hpp>
namespace FishEngine
{
//template<>
//GameObjectPtr Object::Instantiate(GameObjectPtr const & original)
//{
// //return std::dynamic_pointer_cast<GameObject>( original->Clone() );
// auto ret = std::make_shared<GameObject>();
// original->CopyValueTo(ret);
// return ret;
//}
}
| 23.8 | 72 | 0.708683 | [
"object"
] |
d7fa680392eef65f34957ddfe8a0238636af58a2 | 1,232 | cpp | C++ | libs/numeric/mtl/test/resize_vector_test.cpp | lit-uriy/mtl4-mirror | 37cf7c2847165d3537cbc3400cb5fde6f80e3d8b | [
"MTLL"
] | 24 | 2019-03-26T15:25:45.000Z | 2022-03-26T10:00:45.000Z | libs/numeric/mtl/test/resize_vector_test.cpp | lit-uriy/mtl4-mirror | 37cf7c2847165d3537cbc3400cb5fde6f80e3d8b | [
"MTLL"
] | 2 | 2020-04-17T12:35:32.000Z | 2021-03-03T15:46:25.000Z | libs/numeric/mtl/test/resize_vector_test.cpp | lit-uriy/mtl4-mirror | 37cf7c2847165d3537cbc3400cb5fde6f80e3d8b | [
"MTLL"
] | 10 | 2019-12-01T13:40:30.000Z | 2022-01-14T08:39:54.000Z | // Software License for MTL
//
// Copyright (c) 2007 The Trustees of Indiana University.
// 2008 Dresden University of Technology and the Trustees of Indiana University.
// 2010 SimuNova UG (haftungsbeschränkt), www.simunova.com.
// All rights reserved.
// Authors: Peter Gottschling and Andrew Lumsdaine
//
// This file is part of the Matrix Template Library
//
// See also license.mtl.txt in the distribution.
#include <iostream>
#include <cmath>
#include <boost/numeric/mtl/mtl.hpp>
using namespace std;
int main(int, char**)
{
mtl::dense_vector<float> x;
MTL_THROW_IF(size(x) != 0, mtl::runtime_error("vector should be empty"));
x.change_dim(5);
MTL_THROW_IF(size(x) != 5, mtl::runtime_error("vector should have size 5"));
x= 3.0;
cout << "Vector x is initialized to: " << x;
x.change_dim(7);
MTL_THROW_IF(size(x) != 7, mtl::runtime_error("vector should have size 7"));
x= 3.0;
cout << "Vector x after resizing (larger): " << x;
x.change_dim(4);
MTL_THROW_IF(size(x) != 4, mtl::runtime_error("vector should have size 4"));
x= 3.0;
cout << "Vector x after resizing (smaller): " << x;
return 0;
}
| 18.953846 | 94 | 0.632305 | [
"vector"
] |
d7fb91c8d1928e384fed642b182f33ed763607db | 5,226 | cpp | C++ | examples/word_count/word_count_run.cpp | TiFu/thrill-hyperloglog | bac13cd4ba23ec4bf6fe2e32ffa79d68c348cbcf | [
"BSD-2-Clause"
] | 2 | 2021-01-03T19:29:25.000Z | 2021-01-03T19:29:31.000Z | examples/word_count/word_count_run.cpp | TiFu/thrill-hyperloglog | bac13cd4ba23ec4bf6fe2e32ffa79d68c348cbcf | [
"BSD-2-Clause"
] | null | null | null | examples/word_count/word_count_run.cpp | TiFu/thrill-hyperloglog | bac13cd4ba23ec4bf6fe2e32ffa79d68c348cbcf | [
"BSD-2-Clause"
] | null | null | null | /*******************************************************************************
* examples/word_count/word_count_run.cpp
*
* Part of Project Thrill - http://project-thrill.org
*
* Copyright (C) 2015 Alexander Noe <aleexnoe@gmail.com>
* Copyright (C) 2016 Timo Bingmann <tb@panthema.net>
*
* All rights reserved. Published under the BSD-2 license in the LICENSE file.
******************************************************************************/
#include <examples/word_count/random_text_writer.hpp>
#include <examples/word_count/word_count.hpp>
#include <thrill/api/generate.hpp>
#include <thrill/api/read_lines.hpp>
#include <thrill/api/write_lines.hpp>
#include <thrill/common/cmdline_parser.hpp>
#include <thrill/common/logger.hpp>
#include <thrill/common/string.hpp>
#include <algorithm>
#include <random>
#include <string>
#include <utility>
#include <vector>
using namespace thrill; // NOLINT
using namespace examples::word_count; // NOLINT
/******************************************************************************/
// Run methods
static void RunWordCount(
api::Context& ctx,
const std::vector<std::string>& input_filelist, const std::string& output) {
ctx.enable_consume();
auto lines = ReadLines(ctx, input_filelist);
auto word_pairs = WordCount(lines);
if (output.size()) {
word_pairs
.Map([](const WordCountPair& wc) {
return wc.first + ": " + std::to_string(wc.second);
})
.WriteLines(output);
}
else {
word_pairs.Execute();
}
}
static void RunHashWordCount(
api::Context& ctx,
const std::vector<std::string>& input_filelist, const std::string& output) {
ctx.enable_consume();
auto lines = ReadLines(ctx, input_filelist);
auto word_pairs = HashWordCountExample(lines);
if (output.size()) {
word_pairs
.Map([](const WordCountPair& wc) {
return wc.first + ": " + std::to_string(wc.second);
})
.WriteLines(output);
}
else {
word_pairs.Execute();
}
}
/******************************************************************************/
// Run methods with generated input, duplicate some code since it makes the
// example easier to understand.
static void RunWordCountGenerated(
api::Context& ctx, size_t num_words, const std::string& output) {
ctx.enable_consume();
std::default_random_engine rng(std::random_device { } ());
auto lines = Generate(
ctx, num_words / 10,
[&](size_t /* index */) {
return RandomTextWriterGenerate(10, rng);
});
auto word_pairs = WordCount(lines);
if (output.size()) {
word_pairs
.Map([](const WordCountPair& wc) {
return wc.first + ": " + std::to_string(wc.second);
})
.WriteLines(output);
}
else {
word_pairs.Execute();
}
}
static void RunHashWordCountGenerated(
api::Context& ctx, size_t num_words, const std::string& output) {
ctx.enable_consume();
std::default_random_engine rng(std::random_device { } ());
auto lines = Generate(
ctx, num_words / 10,
[&](size_t /* index */) {
return RandomTextWriterGenerate(10, rng);
});
auto word_pairs = HashWordCountExample(lines);
if (output.size()) {
word_pairs
.Map([](const WordCountPair& wc) {
return wc.first + ": " + std::to_string(wc.second);
})
.WriteLines(output);
}
else {
word_pairs.Execute();
}
}
/******************************************************************************/
int main(int argc, char* argv[]) {
common::CmdlineParser clp;
std::string output;
clp.AddString('o', "output", output,
"output file pattern");
std::vector<std::string> input;
clp.AddParamStringlist("input", input,
"input file pattern(s)");
bool generate = false;
clp.AddFlag('g', "generate", generate,
"generate random words, first file pattern "
"specifies approximately how many.");
bool hash_words = false;
clp.AddFlag('H', "hash_words", hash_words,
"explicitly calculate hash values for words "
"to accelerate reduction.");
if (!clp.Process(argc, argv)) {
return -1;
}
clp.PrintResult();
return api::Run(
[&](api::Context& ctx) {
if (generate) {
size_t num_words;
if (!common::from_str<size_t>(input[0], num_words))
die("For generated word data, set input to the number of words.");
if (hash_words)
RunHashWordCountGenerated(ctx, num_words, output);
else
RunWordCountGenerated(ctx, num_words, output);
}
else {
if (hash_words)
RunWordCount(ctx, input, output);
else
RunHashWordCount(ctx, input, output);
}
});
}
/******************************************************************************/
| 28.402174 | 86 | 0.529468 | [
"vector"
] |
cc01e1f702a52e482d31eab7f421016373c24d38 | 9,636 | cpp | C++ | src/scan1_pg.cpp | gatarelib/qtl2 | 4aba67a3a43ca16888c18f913934098bb28895c0 | [
"RSA-MD"
] | null | null | null | src/scan1_pg.cpp | gatarelib/qtl2 | 4aba67a3a43ca16888c18f913934098bb28895c0 | [
"RSA-MD"
] | null | null | null | src/scan1_pg.cpp | gatarelib/qtl2 | 4aba67a3a43ca16888c18f913934098bb28895c0 | [
"RSA-MD"
] | null | null | null | // scan chromosome with linear mixed model for polygenic effect
// [[Rcpp::depends(RcppEigen)]]
#include "scan1_pg.h"
#include <RcppEigen.h>
#include <math.h>
#include "lmm.h"
#include "scan1_hk.h"
#include "matrix.h"
#include "linreg.h"
using namespace Rcpp;
// LMM scan of a single chromosome with additive covariates and weights
//
// genoprobs = 3d array of genotype probabilities (individuals x genotypes x positions)
// pheno = vector of numeric phenotypes
// (no missing data allowed)
// addcovar = additive covariates (an intercept, at least)
// eigenvec = matrix of transposed eigenvectors of variance matrix
// weights = vector of weights (really the SQUARE ROOT of the weights)
//
// output = vector of log likelihood values
//
// [[Rcpp::export]]
NumericVector scan_pg_onechr(const NumericVector& genoprobs, const NumericMatrix& pheno,
const NumericMatrix& addcovar, const NumericMatrix& eigenvec,
const NumericVector& weights, const double tol=1e-12)
{
const int n_ind = pheno.rows();
if(pheno.cols() != 1)
throw std::range_error("ncol(pheno) != 1");
const Dimension d = genoprobs.attr("dim");
if(d.size() != 3)
throw std::invalid_argument("genoprobs should be a 3d array");
const int n_pos = d[2];
if(n_ind != d[0])
throw std::range_error("ncol(pheno) != nrow(genoprobs)");
if(n_ind != addcovar.rows())
throw std::range_error("ncol(pheno) != nrow(addcovar)");
if(n_ind != weights.size())
throw std::range_error("ncol(pheno) != length(weights)");
if(n_ind != eigenvec.rows())
throw std::range_error("ncol(pheno) != nrow(eigenvec)");
if(n_ind != eigenvec.cols())
throw std::range_error("ncol(pheno) != ncol(eigenvec)");
// pre-multiply everything by the eigenvectors
NumericVector genoprobs_copy(clone(genoprobs)); // FIX_ME: would be better not to copy
NumericVector genoprobs_rev = matrix_x_3darray(eigenvec, genoprobs_copy);
NumericMatrix addcovar_rev = matrix_x_matrix(eigenvec, addcovar);
NumericMatrix pheno_rev = matrix_x_matrix(eigenvec, pheno);
// multiply everything by the (square root) of the weights
// (weights should ALREADY be the square-root of the real weights)
addcovar_rev = weighted_matrix(addcovar_rev, weights);
pheno_rev = weighted_matrix(pheno_rev, weights);
genoprobs_rev = weighted_3darray(genoprobs_rev, weights);
// now regress out the additive covariates
genoprobs_rev = calc_resid_linreg_3d(addcovar_rev, genoprobs_rev, tol);
pheno_rev = calc_resid_linreg(addcovar_rev, pheno_rev, tol);
// now the scan, return RSS
NumericMatrix rss = scan_hk_onechr_nocovar(genoprobs_rev, pheno_rev, tol);
// 0.5*sum(log(weights)) [since these are sqrt(weights)]
double sum_logweights = sum(log(weights));
NumericVector result(n_pos);
for(int pos=0; pos<n_pos; pos++)
result[pos] = -(double)n_ind/2.0*log(rss[pos]) + sum_logweights;
return result;
}
// LMM scan of a single chromosome with interactive covariates
// this version should be fast but requires more memory
// (since we first expand the genotype probabilities to probs x intcovar)
// and this one allows weights for the individuals (the same for all phenotypes)
//
// genoprobs = 3d array of genotype probabilities (individuals x genotypes x positions)
// pheno = matrix with one column of numeric phenotypes
// (no missing data allowed)
// addcovar = additive covariates (an intercept, at least)
// intcovar = interactive covariates (should also be included in addcovar)
// eigenvec = matrix of transposed eigenvectors of variance matrix
// weights = vector of weights (really the SQUARE ROOT of the weights)
//
// output = vector of log likelihood values
//
// [[Rcpp::export]]
NumericVector scan_pg_onechr_intcovar_highmem(const NumericVector& genoprobs,
const NumericMatrix& pheno,
const NumericMatrix& addcovar,
const NumericMatrix& intcovar,
const NumericMatrix& eigenvec,
const NumericVector& weights,
const double tol=1e-12)
{
const int n_ind = pheno.rows();
if(pheno.cols() != 1)
throw std::range_error("ncol(pheno) != 1");
const Dimension d = genoprobs.attr("dim");
if(d.size() != 3)
throw std::invalid_argument("genoprobs should be a 3d array");
const int n_pos = d[2];
if(n_ind != d[0])
throw std::range_error("nrow(pheno) != nrow(genoprobs)");
if(n_ind != addcovar.rows())
throw std::range_error("nrow(pheno) != nrow(addcovar)");
if(n_ind != intcovar.rows())
throw std::range_error("nrow(pheno) != nrow(intcovar)");
if(n_ind != weights.size())
throw std::range_error("nrow(pheno) != length(weights)");
if(n_ind != eigenvec.rows())
throw std::range_error("ncol(pheno) != nrow(eigenvec)");
if(n_ind != eigenvec.cols())
throw std::range_error("ncol(pheno) != ncol(eigenvec)");
// expand genotype probabilities to include geno x interactive covariate
NumericVector genoprobs_rev = expand_genoprobs_intcovar(genoprobs, intcovar);
// pre-multiply everything by eigenvectors
genoprobs_rev = matrix_x_3darray(eigenvec, genoprobs_rev);
NumericMatrix addcovar_rev = matrix_x_matrix(eigenvec, addcovar);
NumericMatrix pheno_rev = matrix_x_matrix(eigenvec, pheno);
// multiply everything by the (square root) of the weights
// (weights should ALREADY be the square-root of the real weights)
addcovar_rev = weighted_matrix(addcovar_rev, weights);
pheno_rev = weighted_matrix(pheno_rev, weights);
genoprobs_rev = weighted_3darray(genoprobs_rev, weights);
// regress out the additive covariates
genoprobs_rev = calc_resid_linreg_3d(addcovar_rev, genoprobs_rev, tol);
pheno_rev = calc_resid_linreg(addcovar_rev, pheno_rev, tol);
// now the scan, return RSS
NumericMatrix rss = scan_hk_onechr_nocovar(genoprobs_rev, pheno_rev, tol);
// 0.5*sum(log(weights)) [since these are sqrt(weights)]
double sum_logweights = sum(log(weights));
// calculate log likelihood
NumericVector result(n_pos);
for(int pos=0; pos<n_pos; pos++)
result[pos] = -(double)n_ind/2.0*log(rss[pos]) + sum_logweights;
return result;
}
// LMM scan of a single chromosome with interactive covariates
// this version uses less memory but will be slower
// (since we need to work with each position, one at a time)
// and this one allows weights for the individuals (the same for all phenotypes)
//
// genoprobs = 3d array of genotype probabilities (individuals x genotypes x positions)
// pheno = matrix with one column of numeric phenotypes
// (no missing data allowed)
// addcovar = additive covariates (an intercept, at least)
// intcovar = interactive covariates (should also be included in addcovar)
// eigenvec = matrix of transposed eigenvectors of variance matrix
// weights = vector of weights (really the SQUARE ROOT of the weights)
//
// output = vector of log likelihood values
//
// [[Rcpp::export]]
NumericVector scan_pg_onechr_intcovar_lowmem(const NumericVector& genoprobs,
const NumericMatrix& pheno,
const NumericMatrix& addcovar,
const NumericMatrix& intcovar,
const NumericMatrix& eigenvec,
const NumericVector& weights,
const double tol=1e-12)
{
const int n_ind = pheno.rows();
if(pheno.cols() != 1)
throw std::range_error("ncol(pheno) != 1");
const Dimension d = genoprobs.attr("dim");
if(d.size() != 3)
throw std::invalid_argument("genoprobs should be a 3d array");
const int n_pos = d[2];
if(n_ind != d[0])
throw std::range_error("nrow(pheno) != nrow(genoprobs)");
if(n_ind != addcovar.rows())
throw std::range_error("nrow(pheno) != nrow(addcovar)");
if(n_ind != intcovar.rows())
throw std::range_error("nrow(pheno) != nrow(intcovar)");
if(n_ind != weights.size())
throw std::range_error("ncol(pheno) != length(weights)");
if(n_ind != eigenvec.rows())
throw std::range_error("ncol(pheno) != nrow(eigenvec)");
if(n_ind != eigenvec.cols())
throw std::range_error("ncol(pheno) != ncol(eigenvec)");
NumericVector result(n_pos);
// multiply pheno by eigenvectors and then by weights
NumericMatrix pheno_rev = matrix_x_matrix(eigenvec, pheno);
pheno_rev = weighted_matrix(pheno_rev, weights);
// 0.5*sum(log(weights)) [since these are sqrt(weights)]
double sum_logweights = sum(log(weights));
for(int pos=0; pos<n_pos; pos++) {
Rcpp::checkUserInterrupt(); // check for ^C from user
// form X matrix
NumericMatrix X = formX_intcovar(genoprobs, addcovar, intcovar, pos, true);
// multiply by eigenvectors
X = matrix_x_matrix(eigenvec, X);
// multiply by weights
X = weighted_matrix(X, weights);
// do regression
NumericVector rss = calc_rss_linreg(X, pheno_rev, tol);
result[pos] = -(double)n_ind/2.0*log(rss[0]) + sum_logweights;
}
return result;
}
| 42.637168 | 90 | 0.649751 | [
"vector",
"model",
"3d"
] |
cc094f49ae43a841359f14e5ac531016e0d25a2c | 15,294 | cc | C++ | chrome/browser/password_manager/android/password_store_android_backend_unittest.cc | zealoussnow/chromium | fd8a8914ca0183f0add65ae55f04e287543c7d4a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 1 | 2021-11-16T13:10:29.000Z | 2021-11-16T13:10:29.000Z | chrome/browser/password_manager/android/password_store_android_backend_unittest.cc | zealoussnow/chromium | fd8a8914ca0183f0add65ae55f04e287543c7d4a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | chrome/browser/password_manager/android/password_store_android_backend_unittest.cc | zealoussnow/chromium | fd8a8914ca0183f0add65ae55f04e287543c7d4a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | // Copyright 2021 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/password_manager/android/password_store_android_backend.h"
#include <memory>
#include <vector>
#include "base/callback_forward.h"
#include "base/callback_helpers.h"
#include "base/test/metrics/histogram_tester.h"
#include "base/test/mock_callback.h"
#include "base/test/task_environment.h"
#include "chrome/browser/password_manager/android/password_store_android_backend_bridge.h"
#include "components/password_manager/core/browser/password_manager_test_utils.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace password_manager {
namespace {
using testing::_;
using testing::ElementsAre;
using testing::Eq;
using testing::Return;
using testing::StrictMock;
using testing::WithArg;
using JobId = PasswordStoreAndroidBackendBridge::JobId;
std::vector<std::unique_ptr<PasswordForm>> CreateTestLogins() {
std::vector<std::unique_ptr<PasswordForm>> forms;
forms.push_back(CreateEntry("Todd Tester", "S3cr3t",
GURL(u"https://example.com"),
/*psl=*/false,
/*affiliation=*/false));
forms.push_back(CreateEntry("Marcus McSpartanGregor", "S0m3th1ngCr34t1v3",
GURL(u"https://m.example.com"), /*psl=*/true,
/*affiliation=*/false));
return forms;
}
PasswordForm CreateTestLogin() {
PasswordForm form;
form.username_value = u"Todd Tester";
form.password_value = u"S3cr3t";
form.url = GURL(u"https://example.com");
return form;
}
std::vector<PasswordForm> UnwrapForms(
std::vector<std::unique_ptr<PasswordForm>> password_ptrs) {
std::vector<PasswordForm> forms;
forms.reserve(password_ptrs.size());
for (auto& password : password_ptrs) {
forms.push_back(std::move(*password));
}
return forms;
}
class MockPasswordStoreAndroidBackendBridge
: public PasswordStoreAndroidBackendBridge {
public:
MOCK_METHOD(void, SetConsumer, (base::WeakPtr<Consumer>), (override));
MOCK_METHOD(JobId, GetAllLogins, (), (override));
MOCK_METHOD(JobId, AddLogin, (const PasswordForm&), (override));
MOCK_METHOD(JobId, UpdateLogin, (const PasswordForm&), (override));
MOCK_METHOD(JobId, RemoveLogin, (const PasswordForm&), (override));
};
} // namespace
class PasswordStoreAndroidBackendTest : public testing::Test {
protected:
PasswordStoreAndroidBackendTest() {
backend_ =
std::make_unique<PasswordStoreAndroidBackend>(CreateMockBridge());
}
~PasswordStoreAndroidBackendTest() override {
testing::Mock::VerifyAndClearExpectations(bridge_);
}
PasswordStoreBackend& backend() { return *backend_; }
PasswordStoreAndroidBackendBridge::Consumer& consumer() { return *backend_; }
MockPasswordStoreAndroidBackendBridge* bridge() { return bridge_; }
void RunUntilIdle() { task_environment_.RunUntilIdle(); }
base::test::SingleThreadTaskEnvironment task_environment_{
base::test::TaskEnvironment::MainThreadType::UI,
base::test::TaskEnvironment::TimeSource::MOCK_TIME};
private:
std::unique_ptr<PasswordStoreAndroidBackendBridge> CreateMockBridge() {
auto unique_bridge =
std::make_unique<StrictMock<MockPasswordStoreAndroidBackendBridge>>();
bridge_ = unique_bridge.get();
EXPECT_CALL(*bridge_, SetConsumer);
return unique_bridge;
}
std::unique_ptr<PasswordStoreAndroidBackend> backend_;
StrictMock<MockPasswordStoreAndroidBackendBridge>* bridge_;
};
TEST_F(PasswordStoreAndroidBackendTest, CallsCompletionCallbackAfterInit) {
base::MockCallback<base::OnceCallback<void(bool)>> completion_callback;
EXPECT_CALL(completion_callback, Run(true));
backend().InitBackend(PasswordStoreAndroidBackend::RemoteChangesReceived(),
base::RepeatingClosure(), completion_callback.Get());
}
TEST_F(PasswordStoreAndroidBackendTest, CallsBridgeForLogins) {
backend().InitBackend(PasswordStoreAndroidBackend::RemoteChangesReceived(),
base::RepeatingClosure(), base::DoNothing());
const JobId kJobId{1337};
base::MockCallback<LoginsReply> mock_reply;
EXPECT_CALL(*bridge(), GetAllLogins).WillOnce(Return(kJobId));
backend().GetAllLoginsAsync(mock_reply.Get());
std::vector<std::unique_ptr<PasswordForm>> expected_logins =
CreateTestLogins();
EXPECT_CALL(mock_reply,
Run(UnorderedPasswordFormElementsAre(&expected_logins)));
consumer().OnCompleteWithLogins(kJobId, UnwrapForms(CreateTestLogins()));
RunUntilIdle();
}
TEST_F(PasswordStoreAndroidBackendTest, CallsBridgeForRemoveLogin) {
backend().InitBackend(PasswordStoreAndroidBackend::RemoteChangesReceived(),
base::RepeatingClosure(), base::DoNothing());
const JobId kJobId{13388};
base::MockCallback<PasswordStoreChangeListReply> mock_reply;
PasswordForm form = CreateTestLogin();
EXPECT_CALL(*bridge(), RemoveLogin(form)).WillOnce(Return(kJobId));
backend().RemoveLoginAsync(form, mock_reply.Get());
PasswordStoreChangeList expected_changes;
expected_changes.emplace_back(
PasswordStoreChange(PasswordStoreChange::REMOVE, form));
EXPECT_CALL(mock_reply, Run(expected_changes));
consumer().OnLoginsChanged(kJobId, expected_changes);
RunUntilIdle();
}
TEST_F(PasswordStoreAndroidBackendTest, CallsBridgeForAddLogin) {
backend().InitBackend(PasswordStoreAndroidBackend::RemoteChangesReceived(),
base::RepeatingClosure(), base::DoNothing());
const JobId kJobId{13388};
base::MockCallback<PasswordStoreChangeListReply> mock_reply;
PasswordForm form = CreateTestLogin();
EXPECT_CALL(*bridge(), AddLogin(form)).WillOnce(Return(kJobId));
backend().AddLoginAsync(form, mock_reply.Get());
PasswordStoreChangeList expected_changes;
expected_changes.emplace_back(
PasswordStoreChange(PasswordStoreChange::ADD, form));
EXPECT_CALL(mock_reply, Run(expected_changes));
consumer().OnLoginsChanged(kJobId, expected_changes);
RunUntilIdle();
}
TEST_F(PasswordStoreAndroidBackendTest, CallsBridgeForUpdateLogin) {
backend().InitBackend(PasswordStoreAndroidBackend::RemoteChangesReceived(),
base::RepeatingClosure(), base::DoNothing());
const JobId kJobId{13388};
base::MockCallback<PasswordStoreChangeListReply> mock_reply;
PasswordForm form = CreateTestLogin();
EXPECT_CALL(*bridge(), UpdateLogin(form)).WillOnce(Return(kJobId));
backend().UpdateLoginAsync(form, mock_reply.Get());
PasswordStoreChangeList expected_changes;
expected_changes.emplace_back(
PasswordStoreChange(PasswordStoreChange::UPDATE, form));
EXPECT_CALL(mock_reply, Run(expected_changes));
consumer().OnLoginsChanged(kJobId, expected_changes);
RunUntilIdle();
}
TEST_F(PasswordStoreAndroidBackendTest, OnExternalError) {
backend().InitBackend(PasswordStoreAndroidBackend::RemoteChangesReceived(),
base::RepeatingClosure(), base::DoNothing());
const JobId kJobId{1337};
base::HistogramTester histogram_tester;
base::MockCallback<LoginsReply> mock_reply;
EXPECT_CALL(*bridge(), GetAllLogins).WillOnce(Return(kJobId));
backend().GetAllLoginsAsync(mock_reply.Get());
EXPECT_CALL(mock_reply, Run(_)).Times(0);
AndroidBackendError error{AndroidBackendErrorType::kExternalError};
error.api_error_code = absl::optional<int>(11004);
consumer().OnError(kJobId, std::move(error));
RunUntilIdle();
const char kErrorCodeMetric[] =
"PasswordManager.PasswordStoreAndroidBackend.ErrorCode";
const char kAPIErrorMetric[] =
"PasswordManager.PasswordStoreAndroidBackend.APIError";
histogram_tester.ExpectBucketCount(kErrorCodeMetric, 7, 1);
histogram_tester.ExpectBucketCount(kAPIErrorMetric, 11004, 1);
}
class PasswordStoreAndroidBackendTestForMetrics
: public PasswordStoreAndroidBackendTest,
public testing::WithParamInterface<bool> {
public:
bool ShouldSucceed() const { return GetParam(); }
};
// Tests the PasswordManager.PasswordStore.GetAllLoginsAsync metric.
TEST_P(PasswordStoreAndroidBackendTestForMetrics, GetAllLoginsAsyncMetrics) {
backend().InitBackend(
PasswordStoreAndroidBackend::RemoteChangesReceived(),
/*sync_enabled_or_disabled_cb=*/base::RepeatingClosure(),
/*completion=*/base::DoNothing());
constexpr auto kLatencyDelta = base::Milliseconds(123u);
constexpr JobId kJobId{1337};
const char kDurationMetric[] =
"PasswordManager.PasswordStoreAndroidBackend.GetAllLoginsAsync.Latency";
const char kSuccessMetric[] =
"PasswordManager.PasswordStoreAndroidBackend.GetAllLoginsAsync.Success";
const char kErrorCodeMetric[] =
"PasswordManager.PasswordStoreAndroidBackend.ErrorCode";
base::HistogramTester histogram_tester;
base::MockCallback<LoginsReply> mock_reply;
EXPECT_CALL(*bridge(), GetAllLogins).WillOnce(Return(kJobId));
backend().GetAllLoginsAsync(mock_reply.Get());
EXPECT_CALL(mock_reply, Run(_)).Times(ShouldSucceed() ? 1 : 0);
task_environment_.FastForwardBy(kLatencyDelta);
if (ShouldSucceed())
consumer().OnCompleteWithLogins(kJobId, {});
else
consumer().OnError(
kJobId, AndroidBackendError(AndroidBackendErrorType::kUncategorized));
RunUntilIdle();
histogram_tester.ExpectTotalCount(kDurationMetric, 1);
histogram_tester.ExpectTimeBucketCount(kDurationMetric, kLatencyDelta, 1);
histogram_tester.ExpectTotalCount(kSuccessMetric, 1);
histogram_tester.ExpectBucketCount(kSuccessMetric, true, ShouldSucceed());
histogram_tester.ExpectBucketCount(kSuccessMetric, false, !ShouldSucceed());
if (!ShouldSucceed()) {
histogram_tester.ExpectBucketCount(kErrorCodeMetric, 0, 1);
}
}
// Tests the PasswordManager.PasswordStore.AddLoginAsync.* metric.
TEST_P(PasswordStoreAndroidBackendTestForMetrics, AddLoginAsyncMetrics) {
backend().InitBackend(
PasswordStoreAndroidBackend::RemoteChangesReceived(),
/*sync_enabled_or_disabled_cb=*/base::RepeatingClosure(),
/*completion=*/base::DoNothing());
constexpr auto kLatencyDelta = base::Milliseconds(123u);
constexpr JobId kJobId{1337};
const char kDurationMetric[] =
"PasswordManager.PasswordStoreAndroidBackend.AddLoginAsync.Latency";
const char kSuccessMetric[] =
"PasswordManager.PasswordStoreAndroidBackend.AddLoginAsync.Success";
const char kErrorCodeMetric[] =
"PasswordManager.PasswordStoreAndroidBackend.ErrorCode";
base::HistogramTester histogram_tester;
base::MockCallback<PasswordStoreChangeListReply> mock_reply;
EXPECT_CALL(*bridge(), AddLogin).WillOnce(Return(kJobId));
PasswordForm form = CreateTestLogin();
backend().AddLoginAsync(form, mock_reply.Get());
EXPECT_CALL(mock_reply, Run).Times(ShouldSucceed() ? 1 : 0);
task_environment_.FastForwardBy(kLatencyDelta);
if (ShouldSucceed()) {
consumer().OnLoginsChanged(kJobId, {});
} else {
consumer().OnError(
kJobId, AndroidBackendError(AndroidBackendErrorType::kUncategorized));
}
RunUntilIdle();
histogram_tester.ExpectTotalCount(kDurationMetric, 1);
histogram_tester.ExpectTimeBucketCount(kDurationMetric, kLatencyDelta, 1);
histogram_tester.ExpectTotalCount(kSuccessMetric, 1);
histogram_tester.ExpectBucketCount(kSuccessMetric, true, ShouldSucceed());
histogram_tester.ExpectBucketCount(kSuccessMetric, false, !ShouldSucceed());
if (!ShouldSucceed()) {
histogram_tester.ExpectBucketCount(kErrorCodeMetric, 0, 1);
}
}
// Tests the PasswordManager.PasswordStore.UpdateLoginAsync metric.
TEST_P(PasswordStoreAndroidBackendTestForMetrics, UpdateLoginAsyncMetrics) {
backend().InitBackend(
PasswordStoreAndroidBackend::RemoteChangesReceived(),
/*sync_enabled_or_disabled_cb=*/base::RepeatingClosure(),
/*completion=*/base::DoNothing());
constexpr auto kLatencyDelta = base::Milliseconds(123u);
constexpr JobId kJobId{1337};
const char kDurationMetric[] =
"PasswordManager.PasswordStoreAndroidBackend.UpdateLoginAsync.Latency";
const char kSuccessMetric[] =
"PasswordManager.PasswordStoreAndroidBackend.UpdateLoginAsync.Success";
const char kErrorCodeMetric[] =
"PasswordManager.PasswordStoreAndroidBackend.ErrorCode";
base::HistogramTester histogram_tester;
base::MockCallback<PasswordStoreChangeListReply> mock_reply;
EXPECT_CALL(*bridge(), UpdateLogin).WillOnce(Return(kJobId));
PasswordForm form = CreateTestLogin();
backend().UpdateLoginAsync(form, mock_reply.Get());
EXPECT_CALL(mock_reply, Run).Times(ShouldSucceed() ? 1 : 0);
task_environment_.FastForwardBy(kLatencyDelta);
if (ShouldSucceed()) {
consumer().OnLoginsChanged(kJobId, {});
} else {
consumer().OnError(
kJobId, AndroidBackendError(AndroidBackendErrorType::kUncategorized));
}
RunUntilIdle();
histogram_tester.ExpectTotalCount(kDurationMetric, 1);
histogram_tester.ExpectTimeBucketCount(kDurationMetric, kLatencyDelta, 1);
histogram_tester.ExpectTotalCount(kSuccessMetric, 1);
histogram_tester.ExpectBucketCount(kSuccessMetric, true, ShouldSucceed());
histogram_tester.ExpectBucketCount(kSuccessMetric, false, !ShouldSucceed());
if (!ShouldSucceed()) {
histogram_tester.ExpectBucketCount(kErrorCodeMetric, 0, 1);
}
}
// Tests the PasswordManager.PasswordStore.RemoveLoginAsync metric.
TEST_P(PasswordStoreAndroidBackendTestForMetrics, RemoveLoginAsyncMetrics) {
backend().InitBackend(
PasswordStoreAndroidBackend::RemoteChangesReceived(),
/*sync_enabled_or_disabled_cb=*/base::RepeatingClosure(),
/*completion=*/base::DoNothing());
constexpr auto kLatencyDelta = base::Milliseconds(123u);
constexpr JobId kJobId{1337};
const char kDurationMetric[] =
"PasswordManager.PasswordStoreAndroidBackend.RemoveLoginAsync.Latency";
const char kSuccessMetric[] =
"PasswordManager.PasswordStoreAndroidBackend.RemoveLoginAsync.Success";
const char kErrorCodeMetric[] =
"PasswordManager.PasswordStoreAndroidBackend.ErrorCode";
base::HistogramTester histogram_tester;
base::MockCallback<PasswordStoreChangeListReply> mock_reply;
EXPECT_CALL(*bridge(), RemoveLogin).WillOnce(Return(kJobId));
PasswordForm form = CreateTestLogin();
backend().RemoveLoginAsync(form, mock_reply.Get());
EXPECT_CALL(mock_reply, Run).Times(ShouldSucceed() ? 1 : 0);
task_environment_.FastForwardBy(kLatencyDelta);
if (ShouldSucceed()) {
consumer().OnLoginsChanged(kJobId, {});
} else {
consumer().OnError(
kJobId, AndroidBackendError(AndroidBackendErrorType::kUncategorized));
}
RunUntilIdle();
histogram_tester.ExpectTotalCount(kDurationMetric, 1);
histogram_tester.ExpectTimeBucketCount(kDurationMetric, kLatencyDelta, 1);
histogram_tester.ExpectTotalCount(kSuccessMetric, 1);
histogram_tester.ExpectBucketCount(kSuccessMetric, true, ShouldSucceed());
histogram_tester.ExpectBucketCount(kSuccessMetric, false, !ShouldSucceed());
if (!ShouldSucceed()) {
histogram_tester.ExpectBucketCount(kErrorCodeMetric, 0, 1);
}
}
INSTANTIATE_TEST_SUITE_P(,
PasswordStoreAndroidBackendTestForMetrics,
testing::Bool());
} // namespace password_manager
| 40.567639 | 90 | 0.759056 | [
"vector"
] |
cc1110124cfd3e31afde13e478d310364f152b64 | 6,226 | cpp | C++ | src/Sparrow/Sparrow/Implementations/Nddo/Utils/IntegralsEvaluationUtils/ChargesInMultipoles.cpp | DockBio/sparrow | f82cf86584e9edfc6f2c78af4896dc6f2ee8a455 | [
"BSD-3-Clause"
] | null | null | null | src/Sparrow/Sparrow/Implementations/Nddo/Utils/IntegralsEvaluationUtils/ChargesInMultipoles.cpp | DockBio/sparrow | f82cf86584e9edfc6f2c78af4896dc6f2ee8a455 | [
"BSD-3-Clause"
] | null | null | null | src/Sparrow/Sparrow/Implementations/Nddo/Utils/IntegralsEvaluationUtils/ChargesInMultipoles.cpp | DockBio/sparrow | f82cf86584e9edfc6f2c78af4896dc6f2ee8a455 | [
"BSD-3-Clause"
] | null | null | null | /**
* @file
* @copyright This code is licensed under the 3-clause BSD license.\n
* Copyright ETH Zurich, Laboratory for Physical Chemistry, Reiher Group.\n
* See LICENSE.txt for details.
*/
#include "ChargesInMultipoles.h"
namespace Scine {
namespace Sparrow {
namespace nddo {
namespace multipole {
const std::vector<MultipoleCharge>& ChargesInMultipoles::getChargeConfiguration(multipole_t t) {
static MultipoleChargesArray chargeConfigurations = createChargeConfigurations();
return chargeConfigurations[static_cast<int>(t)];
}
ChargesInMultipoles::MultipoleChargesArray ChargesInMultipoles::createChargeConfigurations() {
MultipoleChargesArray chargeConfigurations;
chargeConfigurations[static_cast<int>(M00)].emplace_back(ChargeDistance::d0, ChargeDistance::d0, ChargeDistance::d0, 1);
chargeConfigurations[static_cast<int>(Qxx)].emplace_back(ChargeDistance::dm2, ChargeDistance::d0, ChargeDistance::d0, 0.25);
chargeConfigurations[static_cast<int>(Qxx)].emplace_back(ChargeDistance::dp2, ChargeDistance::d0, ChargeDistance::d0, 0.25);
chargeConfigurations[static_cast<int>(Qxx)].emplace_back(ChargeDistance::d0, ChargeDistance::d0, ChargeDistance::d0, -0.50);
chargeConfigurations[static_cast<int>(Qyy)].emplace_back(ChargeDistance::d0, ChargeDistance::dm2, ChargeDistance::d0, 0.25);
chargeConfigurations[static_cast<int>(Qyy)].emplace_back(ChargeDistance::d0, ChargeDistance::dp2, ChargeDistance::d0, 0.25);
chargeConfigurations[static_cast<int>(Qyy)].emplace_back(ChargeDistance::d0, ChargeDistance::d0, ChargeDistance::d0, -0.50);
chargeConfigurations[static_cast<int>(Qzz)].emplace_back(ChargeDistance::d0, ChargeDistance::d0, ChargeDistance::dm2, 0.25);
chargeConfigurations[static_cast<int>(Qzz)].emplace_back(ChargeDistance::d0, ChargeDistance::d0, ChargeDistance::dp2, 0.25);
chargeConfigurations[static_cast<int>(Qzz)].emplace_back(ChargeDistance::d0, ChargeDistance::d0, ChargeDistance::d0, -0.50);
chargeConfigurations[static_cast<int>(M2m2)].emplace_back(ChargeDistance::dp1, ChargeDistance::dp1, ChargeDistance::d0, 0.25);
chargeConfigurations[static_cast<int>(M2m2)].emplace_back(ChargeDistance::dm1, ChargeDistance::dm1, ChargeDistance::d0, 0.25);
chargeConfigurations[static_cast<int>(M2m2)].emplace_back(ChargeDistance::dp1, ChargeDistance::dm1, ChargeDistance::d0, -0.25);
chargeConfigurations[static_cast<int>(M2m2)].emplace_back(ChargeDistance::dm1, ChargeDistance::dp1, ChargeDistance::d0, -0.25);
chargeConfigurations[static_cast<int>(M2m1)].emplace_back(ChargeDistance::d0, ChargeDistance::dp1, ChargeDistance::dp1, 0.25);
chargeConfigurations[static_cast<int>(M2m1)].emplace_back(ChargeDistance::d0, ChargeDistance::dm1, ChargeDistance::dm1, 0.25);
chargeConfigurations[static_cast<int>(M2m1)].emplace_back(ChargeDistance::d0, ChargeDistance::dp1, ChargeDistance::dm1, -0.25);
chargeConfigurations[static_cast<int>(M2m1)].emplace_back(ChargeDistance::d0, ChargeDistance::dm1, ChargeDistance::dp1, -0.25);
chargeConfigurations[static_cast<int>(M21)].emplace_back(ChargeDistance::dp1, ChargeDistance::d0, ChargeDistance::dp1, 0.25);
chargeConfigurations[static_cast<int>(M21)].emplace_back(ChargeDistance::dm1, ChargeDistance::d0, ChargeDistance::dm1, 0.25);
chargeConfigurations[static_cast<int>(M21)].emplace_back(ChargeDistance::dp1, ChargeDistance::d0, ChargeDistance::dm1, -0.25);
chargeConfigurations[static_cast<int>(M21)].emplace_back(ChargeDistance::dm1, ChargeDistance::d0, ChargeDistance::dp1, -0.25);
chargeConfigurations[static_cast<int>(M20)].emplace_back(ChargeDistance::d0, ChargeDistance::d0, ChargeDistance::dps2, 0.250);
chargeConfigurations[static_cast<int>(M20)].emplace_back(ChargeDistance::d0, ChargeDistance::d0, ChargeDistance::dms2, 0.250);
chargeConfigurations[static_cast<int>(M20)].emplace_back(ChargeDistance::dps2, ChargeDistance::d0, ChargeDistance::d0, -0.375);
chargeConfigurations[static_cast<int>(M20)].emplace_back(ChargeDistance::dms2, ChargeDistance::d0, ChargeDistance::d0, -0.375);
chargeConfigurations[static_cast<int>(M20)].emplace_back(ChargeDistance::d0, ChargeDistance::dps2, ChargeDistance::d0, 0.125);
chargeConfigurations[static_cast<int>(M20)].emplace_back(ChargeDistance::d0, ChargeDistance::dms2, ChargeDistance::d0, 0.125);
chargeConfigurations[static_cast<int>(M22)].emplace_back(ChargeDistance::dps2, ChargeDistance::d0, ChargeDistance::d0, 0.25);
chargeConfigurations[static_cast<int>(M22)].emplace_back(ChargeDistance::dms2, ChargeDistance::d0, ChargeDistance::d0, 0.25);
chargeConfigurations[static_cast<int>(M22)].emplace_back(ChargeDistance::d0, ChargeDistance::dps2, ChargeDistance::d0, -0.25);
chargeConfigurations[static_cast<int>(M22)].emplace_back(ChargeDistance::d0, ChargeDistance::dms2, ChargeDistance::d0, -0.25);
chargeConfigurations[static_cast<int>(Qzx)].emplace_back(ChargeDistance::d0, ChargeDistance::d0, ChargeDistance::dps2, 0.25);
chargeConfigurations[static_cast<int>(Qzx)].emplace_back(ChargeDistance::d0, ChargeDistance::d0, ChargeDistance::dms2, 0.25);
chargeConfigurations[static_cast<int>(Qzx)].emplace_back(ChargeDistance::dps2, ChargeDistance::d0, ChargeDistance::d0, -0.25);
chargeConfigurations[static_cast<int>(Qzx)].emplace_back(ChargeDistance::dms2, ChargeDistance::d0, ChargeDistance::d0, -0.25);
chargeConfigurations[static_cast<int>(M10)].emplace_back(ChargeDistance::d0, ChargeDistance::d0, ChargeDistance::dm1, -0.5);
chargeConfigurations[static_cast<int>(M10)].emplace_back(ChargeDistance::d0, ChargeDistance::d0, ChargeDistance::dp1, 0.5);
chargeConfigurations[static_cast<int>(M11)].emplace_back(ChargeDistance::dm1, ChargeDistance::d0, ChargeDistance::d0, -0.5);
chargeConfigurations[static_cast<int>(M11)].emplace_back(ChargeDistance::dp1, ChargeDistance::d0, ChargeDistance::d0, 0.5);
chargeConfigurations[static_cast<int>(M1m1)].emplace_back(ChargeDistance::d0, ChargeDistance::dm1, ChargeDistance::d0, -0.5);
chargeConfigurations[static_cast<int>(M1m1)].emplace_back(ChargeDistance::d0, ChargeDistance::dp1, ChargeDistance::d0, 0.5);
return chargeConfigurations;
}
} // namespace multipole
} // namespace nddo
} // namespace Sparrow
} // namespace Scine
| 72.395349 | 129 | 0.788468 | [
"vector"
] |
cc11bc7d2c10dda80012221e6eae5ce3b678707d | 880 | cpp | C++ | aws-cpp-sdk-connect/source/model/UpdateRoutingProfileDefaultOutboundQueueRequest.cpp | Neusoft-Technology-Solutions/aws-sdk-cpp | 88c041828b0dbee18a297c3cfe98c5ecd0706d0b | [
"Apache-2.0"
] | 1 | 2022-02-12T08:09:30.000Z | 2022-02-12T08:09:30.000Z | aws-cpp-sdk-connect/source/model/UpdateRoutingProfileDefaultOutboundQueueRequest.cpp | Neusoft-Technology-Solutions/aws-sdk-cpp | 88c041828b0dbee18a297c3cfe98c5ecd0706d0b | [
"Apache-2.0"
] | 1 | 2021-10-14T16:57:00.000Z | 2021-10-18T10:47:24.000Z | aws-cpp-sdk-connect/source/model/UpdateRoutingProfileDefaultOutboundQueueRequest.cpp | ravindra-wagh/aws-sdk-cpp | 7d5ff01b3c3b872f31ca98fb4ce868cd01e97696 | [
"Apache-2.0"
] | 1 | 2021-11-09T11:58:03.000Z | 2021-11-09T11:58:03.000Z | /**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#include <aws/connect/model/UpdateRoutingProfileDefaultOutboundQueueRequest.h>
#include <aws/core/utils/json/JsonSerializer.h>
#include <utility>
using namespace Aws::Connect::Model;
using namespace Aws::Utils::Json;
using namespace Aws::Utils;
UpdateRoutingProfileDefaultOutboundQueueRequest::UpdateRoutingProfileDefaultOutboundQueueRequest() :
m_instanceIdHasBeenSet(false),
m_routingProfileIdHasBeenSet(false),
m_defaultOutboundQueueIdHasBeenSet(false)
{
}
Aws::String UpdateRoutingProfileDefaultOutboundQueueRequest::SerializePayload() const
{
JsonValue payload;
if(m_defaultOutboundQueueIdHasBeenSet)
{
payload.WithString("DefaultOutboundQueueId", m_defaultOutboundQueueId);
}
return payload.View().WriteReadable();
}
| 23.157895 | 101 | 0.790909 | [
"model"
] |
cc1cae1619edf1b2fd3af9f5effcde1bd35ee67c | 1,051 | cpp | C++ | src/Entity.cpp | algisb/shadiray | eb0d782c726ccf5d718c9abcde0fe2bc6fe54b0a | [
"MIT"
] | null | null | null | src/Entity.cpp | algisb/shadiray | eb0d782c726ccf5d718c9abcde0fe2bc6fe54b0a | [
"MIT"
] | null | null | null | src/Entity.cpp | algisb/shadiray | eb0d782c726ccf5d718c9abcde0fe2bc6fe54b0a | [
"MIT"
] | null | null | null | ///
/// @file Entity.cpp
/// @brief Anything and everything
#include "Entity.h"
using namespace kelp;
Entity::Entity(World * _world, std::string _tag)
{
m_world = _world;
m_tag = _tag;
m_world->m_entities.push_back(this);
}
Entity::~Entity()
{
for(int i = 0; i< m_components.size(); i++)
delete m_components[i];
m_components.clear();
}
void Entity::init()
{
for(int i = 0; i< m_components.size(); i++)
m_components[i]->init();
}
void Entity::update()
{
//TEMPORARY CODE FOR ADDING COMPONENTS DURING RUNTIME
for(int i = 0; i< m_lateComponents.size(); i++)
{
m_lateComponents[i]->init();
m_components.push_back(m_lateComponents[i]);
}
m_lateComponents.clear();
for(int i = 0; i< m_components.size(); i++)
m_components[i]->update();
}
void Entity::render()
{
for(int i = 0; i< m_components.size(); i++)
m_components[i]->render();
}
void Entity::addComponent(Component * io_c)
{
io_c->m_owner = this;
m_components.push_back(io_c);
}
| 19.830189 | 57 | 0.610847 | [
"render"
] |
cc1fc39a0158e5137836dba5842b28176aeb68ad | 7,756 | cpp | C++ | src/app/Toolbar.cpp | lahwran/Rack | d63e23b2b64cdad54da7609ee8e018d9f45ced2f | [
"Zlib",
"BSD-3-Clause"
] | 84 | 2018-05-02T13:15:42.000Z | 2019-11-25T15:53:59.000Z | src/app/Toolbar.cpp | lahwran/Rack | d63e23b2b64cdad54da7609ee8e018d9f45ced2f | [
"Zlib",
"BSD-3-Clause"
] | 17 | 2018-05-02T13:18:44.000Z | 2019-10-29T00:16:56.000Z | src/app/Toolbar.cpp | lahwran/Rack | d63e23b2b64cdad54da7609ee8e018d9f45ced2f | [
"Zlib",
"BSD-3-Clause"
] | 9 | 2018-05-06T18:39:58.000Z | 2019-10-03T15:15:26.000Z | #include "app.hpp"
#include "window.hpp"
#include "engine.hpp"
#include "settings.hpp"
#include "asset.hpp"
namespace rack {
struct NewItem : MenuItem {
void onAction(EventAction &e) override {
gRackWidget->reset();
}
};
struct DisconnectItem : MenuItem {
void onAction(EventAction &e) override {
gRackWidget->disconnect();
}
};
struct OpenItem : MenuItem {
void onAction(EventAction &e) override {
#ifndef ARCH_WEB
gRackWidget->openDialog();
#else
EM_ASM(
alert('Drop a .vcv file on the window to open.');
);
#endif
}
};
struct SaveItem : MenuItem {
void onAction(EventAction &e) override {
#ifndef ARCH_WEB
gRackWidget->saveDialog();
#else
gRackWidget->savePatch(assetHidden("autosave.vcv"));
EM_ASM(
FS.syncfs(false, function() {});
);
#endif
}
};
#ifdef ARCH_WEB
struct DownloadItem : MenuItem {
void onAction(EventAction &e) override {
gRackWidget->savePatch(assetHidden("autosave.vcv"));
EM_ASM(
FS.syncfs(false, function() {
//TODO: use binary
var text = FS.readFile('/work/autosave.vcv', { encoding: 'utf8' });
var blob = new Blob([text], { type:"text/plain;charset=utf-8" });
saveAs(blob, 'download.vcv', true);
});
);
}
};
#endif
struct SaveAsItem : MenuItem {
void onAction(EventAction &e) override {
gRackWidget->saveAsDialog();
}
};
struct RevertItem : MenuItem {
void onAction(EventAction &e) override {
gRackWidget->revert();
}
};
struct QuitItem : MenuItem {
void onAction(EventAction &e) override {
windowClose();
}
};
struct FileChoice : ChoiceButton {
void onAction(EventAction &e) override {
Menu *menu = gScene->createMenu();
menu->box.pos = getAbsoluteOffset(Vec(0, box.size.y));
menu->box.size.x = box.size.x;
menu->addChild(MenuItem::create<NewItem>("New", WINDOW_MOD_KEY_NAME "+N"));
menu->addChild(MenuItem::create<DisconnectItem>("Disconnect Cables"));
menu->addChild(MenuItem::create<OpenItem>("Open", WINDOW_MOD_KEY_NAME "+O"));
menu->addChild(MenuItem::create<SaveItem>("Save", WINDOW_MOD_KEY_NAME "+S"));
#ifndef ARCH_WEB
menu->addChild(MenuItem::create<SaveAsItem>("Save As", WINDOW_MOD_KEY_NAME "+Shift+S"));
menu->addChild(MenuItem::create<RevertItem>("Revert"));
menu->addChild(MenuItem::create<QuitItem>("Quit", WINDOW_MOD_KEY_NAME "+Q"));
#else
menu->addChild(MenuItem::create<DownloadItem>("Save & Download", WINDOW_MOD_KEY_NAME "+Shift+S"));
#endif
}
};
struct LargerHitBoxesItem : MenuItem {
void onAction(EventAction &e) override {
largerHitBoxes = !largerHitBoxes;
//TODO: save settings
}
};
struct LockModulesItem : MenuItem {
void onAction(EventAction &e) override {
lockModules = !lockModules;
//TODO: save settings
}
};
struct SensitiveKnobsItem : MenuItem {
void onAction(EventAction &e) override {
knobSensitivity = (isNear(knobSensitivity, KNOB_SENSITIVITY) ? KNOB_SENSITIVITY * 2 : KNOB_SENSITIVITY);
//TODO: save settings
}
};
struct OptionsChoice : ChoiceButton {
void onAction(EventAction &e) override {
Menu *menu = gScene->createMenu();
menu->box.pos = getAbsoluteOffset(Vec(0, box.size.y));
menu->box.size.x = box.size.x;
menu->addChild(MenuItem::create<LargerHitBoxesItem>("Larger Hit Boxes", CHECKMARK(largerHitBoxes)));
menu->addChild(MenuItem::create<LockModulesItem>("Lock Modules", CHECKMARK(lockModules)));
menu->addChild(MenuItem::create<SensitiveKnobsItem>("Sensitive Knobs", CHECKMARK(!isNear(knobSensitivity, KNOB_SENSITIVITY))));
}
};
struct EnginePauseItem : MenuItem {
void onAction(EventAction &e) override {
gPaused = !gPaused;
}
};
struct EngineSampleRateItem : MenuItem {
float sampleRate;
void onAction(EventAction &e) override {
engineSetSampleRate(sampleRate);
gPaused = false;
}
};
struct EngineSampleRateChoice : ChoiceButton {
void onAction(EventAction &e) override {
Menu *menu = gScene->createMenu();
menu->box.pos = getAbsoluteOffset(Vec(0, box.size.y));
menu->box.size.x = box.size.x;
// EnginePauseItem *pauseItem = new EnginePauseItem();
// pauseItem->text = gPaused ? "Resume engine" : "Pause engine";
// menu->addChild(pauseItem);
std::vector<float> sampleRates = {44100, 48000, 88200, 96000, 176400, 192000};
for (float sampleRate : sampleRates) {
EngineSampleRateItem *item = new EngineSampleRateItem();
item->text = stringf("%.0f Hz", sampleRate);
item->sampleRate = sampleRate;
menu->addChild(item);
}
}
void step() override {
if (gPaused)
text = "Paused";
else
text = stringf("%.0f Hz", engineGetSampleRate());
}
};
Toolbar::Toolbar() {
box.size.y = BND_WIDGET_HEIGHT + 2*5;
layoutLeft = new SequentialLayout();
layoutLeft->padding = Vec(5, 5);
layoutLeft->spacing = 5;
addChild(layoutLeft);
ChoiceButton *fileChoice = new FileChoice();
fileChoice->box.size.x = 100;
fileChoice->text = "File";
layoutLeft->addChild(fileChoice);
ChoiceButton *optionsChoice = new OptionsChoice();
optionsChoice->box.size.x = 100;
optionsChoice->text = "Options";
layoutLeft->addChild(optionsChoice);
// EngineSampleRateChoice *srChoice = new EngineSampleRateChoice();
// srChoice->box.size.x = 100;
// layoutLeft->addChild(srChoice);
wireOpacitySlider = new Slider();
wireOpacitySlider->box.size.x = 150;
wireOpacitySlider->label = "Cable opacity";
wireOpacitySlider->precision = 0;
wireOpacitySlider->unit = "%";
wireOpacitySlider->setLimits(0.0, 100.0);
wireOpacitySlider->setDefaultValue(50.0);
layoutLeft->addChild(wireOpacitySlider);
wireTensionSlider = new Slider();
wireTensionSlider->box.size.x = 150;
wireTensionSlider->label = "Cable tension";
wireTensionSlider->unit = "";
wireTensionSlider->setLimits(0.0, 1.0);
wireTensionSlider->setDefaultValue(0.5);
layoutLeft->addChild(wireTensionSlider);
struct ZoomSlider : Slider {
void onAction(EventAction &e) override {
Slider::onAction(e);
gRackScene->zoomWidget->setZoom(roundf(value) / 100.0);
gRackScene->scrollWidget->updateForOffsetChange();
}
};
zoomSlider = new ZoomSlider();
zoomSlider->box.size.x = 150;
zoomSlider->precision = 0;
zoomSlider->label = "Zoom";
zoomSlider->unit = "%";
zoomSlider->setLimits(25.0, 200.0);
zoomSlider->setDefaultValue(100.0);
layoutLeft->addChild(zoomSlider);
struct AddModuleButton : Button {
void onAction(EventAction &e) override {
appModuleBrowserCreate();
}
};
auto addModuleButton = new AddModuleButton();
addModuleButton->text = "Add Module";
addModuleButton->box.size.x = 100;
layoutLeft->addChild(addModuleButton);
#ifdef TOUCH
layoutRight = new SequentialLayout();
layoutRight->padding = Vec(5, 5);
layoutRight->spacing = 5;
layoutRight->alignment = SequentialLayout::RIGHT_ALIGNMENT;
addChild(layoutRight);
struct RMBButton : Button {
void draw(NVGcontext *vg) override {
bndToolButton(vg, 0.0, 0.0, box.size.x, box.size.y, BND_CORNER_ALL, (gForceRMB ? BND_ACTIVE : state), -1, text.c_str());
}
void onAction(EventAction &e) override {
//TODO: in reality at the moment it can only activate the mode
gForceRMB = !gForceRMB;
}
};
auto rmbButton = new RMBButton();
rmbButton->text = "RMB";
rmbButton->box.size.x = BND_WIDGET_HEIGHT*2.5;
layoutRight->addChild(rmbButton);
#endif
/*
cpuUsageButton = new RadioButton();
cpuUsageButton->box.size.x = 100;
cpuUsageButton->label = "CPU usage";
layoutLeft->addChild(cpuUsageButton);
*/
/*#if defined(RELEASE)
Widget *pluginManager = new PluginManagerWidget();
layoutLeft->addChild(pluginManager);
#endif*/
}
void Toolbar::draw(NVGcontext *vg) {
bndBackground(vg, 0.0, 0.0, box.size.x, box.size.y);
bndBevel(vg, 0.0, 0.0, box.size.x, box.size.y);
Widget::draw(vg);
}
void Toolbar::onResize() {
#ifdef TOUCH
layoutRight->box.size.x = box.size.x;
#endif
}
} // namespace rack
| 26.561644 | 129 | 0.707323 | [
"vector"
] |
cc25fbdccc0e28564af91fccf6f9ab7985b38ed9 | 5,978 | hpp | C++ | blades/freelan/libs/kfather/include/kfather/formatter.hpp | krattai/AEBL | a7b12c97479e1236d5370166b15ca9f29d7d4265 | [
"BSD-2-Clause"
] | 4 | 2016-04-26T03:43:54.000Z | 2016-11-17T08:09:04.000Z | blades/freelan/libs/kfather/include/kfather/formatter.hpp | krattai/AEBL | a7b12c97479e1236d5370166b15ca9f29d7d4265 | [
"BSD-2-Clause"
] | 17 | 2015-01-05T21:06:22.000Z | 2015-12-07T20:45:44.000Z | blades/freelan/libs/kfather/include/kfather/formatter.hpp | krattai/AEBL | a7b12c97479e1236d5370166b15ca9f29d7d4265 | [
"BSD-2-Clause"
] | 3 | 2016-04-26T03:43:55.000Z | 2020-11-06T11:02:08.000Z | /*
* libkfather - C++ JSON parser/producer library.
* Copyright (C) 2010-2012 Julien Kauffmann <julien.kauffmann@freelan.org>
*
* This file is part of libkfather.
*
* libkfather 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 of
* the License, or (at your option) any later version.
*
* libkfather 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 this program. If not, see
* <http://www.gnu.org/licenses/>.
*
* If you intend to use libkfather in a commercial software, please
* contact me : we may arrange this for a small fee or no fee at all,
* depending on the nature of your project.
*/
/**
* \file formatter.hpp
* \author Julien Kauffmann <julien.kauffmann@freelan.org>
* \brief Formatter classes.
*/
#ifndef KFATHER_FORMATTER_HPP
#define KFATHER_FORMATTER_HPP
#include <iostream>
#include <sstream>
#include "value.hpp"
namespace kfather
{
class parser;
/**
* \brief A base formatter class.
*
* The same formatter can be used to format JSON values in a thread-safe and
* reentrant manner.
*/
template <typename FormatterVisitorType>
class generic_formatter
{
public:
/**
* \brief Format the specified value to the specified stream.
* \param os The stream to format the value to.
* \param value The value to format.
* \return os.
*/
std::ostream& format(std::ostream& os, const value_type& value) const
{
return boost::apply_visitor(FormatterVisitorType(os), value);
}
/**
* \brief Format a value to a string.
* \param value The value to format.
* \return The formatted string.
*
* If your intent is to print a value to an output stream, use the first
* format() overload instead as it will be far more efficient.
*/
std::string format(const value_type& value) const
{
std::ostringstream oss;
format(oss, value);
return oss.str();
}
};
/**
* \brief The base formatter visitor class.
*/
class base_formatter_visitor : public boost::static_visitor<std::ostream&>
{
public:
/**
* \brief Prints a null value.
* \return The referenced output stream.
*/
std::ostream& operator()(const null_type&) const;
/**
* \brief Prints a boolean value.
* \return The referenced output stream.
*/
std::ostream& operator()(const boolean_type&) const;
/**
* \brief Prints a number.
* \return The referenced output stream.
*/
std::ostream& operator()(const number_type&) const;
/**
* \brief Prints a string.
* \return The referenced output stream.
*/
std::ostream& operator()(const string_type&) const;
protected:
/**
* \brief Construct a formatter visitor.
* \param _os The output stream to hold a reference to.
*/
base_formatter_visitor(std::ostream& _os) : m_os(_os) {}
/**
* \brief Get the referenced output stream.
* \return The referenced output stream instance.
*/
std::ostream& os() const { return m_os; }
private:
std::ostream& m_os;
};
/**
* \brief A formatter visitor that compact its values.
*/
class compact_formatter_visitor : public base_formatter_visitor
{
public:
/**
* \brief Construct a formatter visitor.
* \param _os The output stream to hold a reference to.
*/
compact_formatter_visitor(std::ostream& _os) : base_formatter_visitor(_os) {}
/**
* \brief Prints an array.
* \return The referenced output stream.
*/
std::ostream& operator()(const array_type&) const;
/**
* \brief Prints an object.
* \return The referenced output stream.
*/
std::ostream& operator()(const object_type&) const;
using base_formatter_visitor::operator();
};
/**
* \brief A formatter visitor that inlines its values.
*/
class inline_formatter_visitor : public base_formatter_visitor
{
public:
/**
* \brief Construct a formatter visitor.
* \param _os The output stream to hold a reference to.
*/
inline_formatter_visitor(std::ostream& _os) : base_formatter_visitor(_os) {}
/**
* \brief Prints an array.
* \return The referenced output stream.
*/
std::ostream& operator()(const array_type&) const;
/**
* \brief Prints an object.
* \return The referenced output stream.
*/
std::ostream& operator()(const object_type&) const;
using base_formatter_visitor::operator();
};
/**
* \brief A formatter visitor that pretty prints its values.
*/
class pretty_print_formatter_visitor : public base_formatter_visitor
{
public:
/**
* \brief Construct a formatter visitor.
* \param _os The output stream to hold a reference to.
*/
pretty_print_formatter_visitor(std::ostream& _os) : base_formatter_visitor(_os), m_indent_level(0) {}
/**
* \brief Prints an array.
* \return The referenced output stream.
*/
std::ostream& operator()(const array_type&) const;
/**
* \brief Prints an object.
* \return The referenced output stream.
*/
std::ostream& operator()(const object_type&) const;
using base_formatter_visitor::operator();
private:
std::ostream& indent() const;
mutable unsigned int m_indent_level;
};
/**
* \brief A compact formatter class.
*/
typedef generic_formatter<compact_formatter_visitor> compact_formatter;
/**
* \brief An inline formatter class.
*/
typedef generic_formatter<inline_formatter_visitor> inline_formatter;
/**
* \brief A pretty-print formatter class.
*/
typedef generic_formatter<pretty_print_formatter_visitor> pretty_print_formatter;
}
#endif /* KFATHER_FORMATTER_HPP */
| 24.804979 | 104 | 0.678488 | [
"object"
] |
cc32285d47cff40e589f990257b0929385f33720 | 7,892 | cpp | C++ | KablunkEditor/src/Panels/ContentBrowserPanel.cpp | happymonkey1/KablunkEngine | ca7dff1e3dfcdc47fe0f776adef6f2c99ca5557e | [
"MIT"
] | null | null | null | KablunkEditor/src/Panels/ContentBrowserPanel.cpp | happymonkey1/KablunkEngine | ca7dff1e3dfcdc47fe0f776adef6f2c99ca5557e | [
"MIT"
] | null | null | null | KablunkEditor/src/Panels/ContentBrowserPanel.cpp | happymonkey1/KablunkEngine | ca7dff1e3dfcdc47fe0f776adef6f2c99ca5557e | [
"MIT"
] | null | null | null | #include "Panels/ContentBrowserPanel.h"
#include "Kablunk/Project/Project.h"
#include <imgui/imgui.h>
#include <glm/gtc/type_ptr.hpp>
#include "imgui/imgui_internal.h"
#include <thread>
#include <assimp/Importer.hpp>
#include <assimp/scene.h>
namespace Kablunk
{
//extern const std::filesystem::path g_asset_path = "assets";
//extern const std::filesystem::path g_resources_path = "resources";
ContentBrowserPanel::ContentBrowserPanel()
: m_current_directory{ Project::GetActive() ? Project::GetAssetDirectoryPath() : "" }
{
m_directory_icon = Asset<Texture2D>("resources/content_browser/icons/directoryicon.png");
m_file_icon = Asset<Texture2D>("resources/content_browser/icons/textfileicon.png");
m_back_button = Asset<Texture2D>("resources/content_browser/icons/back_button.png");
m_forward_button = Asset<Texture2D>("resources/content_browser/icons/forward_button.png");
m_refresh_button = Asset<Texture2D>("resources/content_browser/icons/refresh_button.png");
memset(m_search_buffer, 0, sizeof(char) * MAX_SEARCH_BUFFER_LENGTH);
Refresh();
}
void ContentBrowserPanel::OnImGuiRender()
{
ImGui::Begin("Content Browser", NULL, ImGuiWindowFlags_NoScrollWithMouse | ImGuiWindowFlags_NoScrollbar);
if (!Project::GetActive())
{
ImGui::End();
return;
}
RenderTopBar();
static float padding = 16.0f;
static float thumbnail_size = 48.0f;
float cell_size = thumbnail_size + padding;
//std::shared_lock lock{ m_mutex };
ImGuiTableFlags content_browser_panel_flags = ImGuiTableFlags_BordersInnerV;
if (ImGui::BeginTable("Directory Browser", 2, content_browser_panel_flags))
{
auto imgui_table = ImGui::GetCurrentTable();
//ImGui::TableSetupColumn("##Directories", ImGuiTableColumnFlags_WidthFixed, 75.0f);
//ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, { 4.0f, 4.0f });
//ImGui::TableSetupColumn("##Directories", ImGuiTableColumnFlags_WidthStretch, 75.0f);
//ImGui::TableHeadersRow();
// #TODO fix width of first column. Minimum width with stretching?
ImGui::TableNextColumn();
ImGui::TableSetColumnIndex(0);
ImGui::TableSetColumnWidthAutoAll(imgui_table);
auto working_dir = Project::GetAssetDirectory();
ImGui::Text(working_dir.string().c_str());
for (auto& directory_entry : m_directory_entries)
{
if (directory_entry.is_directory())
{
const auto& path = directory_entry.path();
auto relative_path = std::filesystem::relative(path, Project::GetAssetDirectoryPath());
auto relative_path_string = relative_path.string();
ImGuiTreeNodeFlags directory_tree_node_flags = ImGuiTreeNodeFlags_OpenOnArrow;
// #TODO should only draw tree node if are files within directory
if (ImGui::TreeNodeEx(relative_path_string.c_str(), directory_tree_node_flags))
{
// #TODO recursively populate inner directories;
ImGui::Text("FIXME!");
ImGui::TreePop();
}
}
}
auto cell_rect = ImGui::TableGetCellBgRect(imgui_table, 0);
auto directory_panel_width = cell_rect.Max.x - cell_rect.Min.x;
//ImGui::PopStyleVar(); // Frame padding
ImGui::TableNextColumn();
// Calculate how many columns we need to display files/folders
auto files_column_width = ImGui::GetContentRegionAvailWidth();
auto column_count = static_cast<int>(files_column_width / cell_size);
column_count = column_count < 1 ? 1 : column_count;
//ImGui::TableSetColumnIndex(1);
//ImGui::TableSetColumnWidth(1, panel_width - directory_panel_width);
int i = 0;
if (ImGui::BeginTable("Intra Directory Browser", column_count))
{
auto mouse_double_click = ImGui::IsMouseDoubleClicked(ImGuiMouseButton_Left);
for (auto& directory_entry : m_directory_entries)
{
const auto& path = directory_entry.path();
auto relative_path = std::filesystem::relative(path, Project::GetAssetDirectory());
auto filename_string = relative_path.filename().string();
auto is_dir = directory_entry.is_directory();
ImGui::TableNextColumn();
ImGui::PushID(i++);
// #TODO include more file icons and adjust icon texture accordingly
auto icon_renderer_id = is_dir ? m_directory_icon.Get()->GetRendererID() : m_file_icon.Get()->GetRendererID();
ImGui::PushStyleColor(ImGuiCol_Button, { 0, 0, 0, 0 });
ImGui::ImageButton((ImTextureID)icon_renderer_id, { thumbnail_size, thumbnail_size }, { 0, 1 }, { 1, 0 });
ImGui::PopStyleColor();
if (ImGui::BeginDragDropSource())
{
const auto item_path = relative_path.c_str();
ImGui::SetDragDropPayload("CONTENT_BROWSER_ITEM", item_path, (wcslen(item_path) + 1) * sizeof(wchar_t), ImGuiCond_Once);
ImGui::EndDragDropSource();
}
if (ImGui::IsItemHovered() && mouse_double_click)
{
if (directory_entry.is_directory())
{
m_current_directory /= path.filename();
Refresh();
}
else if (directory_entry.path().extension() == FILE_EXTENSIONS::FBX)
{
// #TODO open model in asset viewer
}
}
ImGui::TextWrapped(filename_string.c_str());
ImGui::PopID();
}
ImGui::EndTable(); // File Browser
}
ImGui::EndTable(); // Directory Browser
}
ImGui::NewLine();
static bool debug_settings = false;
ImGui::Checkbox("Settings", &debug_settings);
if (debug_settings)
{
ImGui::SliderFloat("Thumbnail size", &thumbnail_size, 16, 512);
ImGui::SliderFloat("Padding", &padding, 0, 32);
}
ImGui::End();
}
void ContentBrowserPanel::OnUpdate(Timestep ts)
{
//Threading::JobSystem::AddJob(std::function<void()>([this]() { UpdateDirectoryList(); }));
/*m_update_directory_timer += ts.GetMiliseconds() / 1000.0f;
if (m_update_directory_timer >= m_update_directory_timer_max)
{
Threading::JobSystem::AddJob(std::function<void()>([this]() { UpdateDirectoryList(); }));
m_update_directory_timer -= m_update_directory_timer_max;
}*/
}
void ContentBrowserPanel::RenderTopBar()
{
ImGui::BeginChild("##top_bar", { 0, 30 });
if (ImGui::ImageButton((ImTextureID)m_back_button->GetRendererID(), { 22, 22 }) && m_current_directory != Project::GetAssetDirectory())
{
m_current_directory = m_current_directory.parent_path();
Refresh();
}
ImGui::SameLine();
if (ImGui::ImageButton((ImTextureID)m_forward_button->GetRendererID(), { 22, 22 }))
{
// #TODO go to next directory
KB_CORE_WARN("Forward directory not implemented!");
}
ImGui::SameLine();
if (ImGui::ImageButton((ImTextureID)m_refresh_button->GetRendererID(), { 22, 22 }))
{
Refresh();
}
ImGui::SameLine();
ImGui::PushItemWidth(200);
if (ImGui::InputTextWithHint("", "Search...", m_search_buffer, MAX_SEARCH_BUFFER_LENGTH))
{
if (strlen(m_search_buffer) == 0)
{
// #TODO reset search to current directory
}
else
{
// #TODO add item searching
KB_CORE_WARN("searching for items not implemented!");
}
ImGui::PopItemWidth();
}
ImGui::SameLine();
// #TODO update to use project's asset directory when projects are implemented
auto project_asset_dir = Project::GetProjectDirectory();
auto asset_dir_name = std::filesystem::relative(m_current_directory, project_asset_dir);
auto text_size = ImGui::CalcTextSize(asset_dir_name.string().c_str());
if (ImGui::Selectable(asset_dir_name.string().c_str(), false, 0, { text_size.x, 22 }))
{
m_current_directory = Project::GetAssetDirectoryPath();
}
// #TODO add other directories in current path
ImGui::EndChild();
}
void ContentBrowserPanel::Refresh()
{
if (m_current_directory.empty())
return;
// #TODO probably better to store as a hashmap instead of recreating vector
m_directory_entries = {};
for (auto& directory_entry : std::filesystem::directory_iterator{ m_current_directory })
m_directory_entries.push_back(directory_entry);
}
}
| 30.828125 | 137 | 0.702864 | [
"vector",
"model"
] |
cc36c88f63d7b9fff07ac8b33ce5cf6377e369e4 | 1,914 | hpp | C++ | Common/Database.hpp | arves100/retrospy-server | 079d786c84e9271c041000d10cf7610d8e96cec4 | [
"BSD-3-Clause"
] | null | null | null | Common/Database.hpp | arves100/retrospy-server | 079d786c84e9271c041000d10cf7610d8e96cec4 | [
"BSD-3-Clause"
] | null | null | null | Common/Database.hpp | arves100/retrospy-server | 079d786c84e9271c041000d10cf7610d8e96cec4 | [
"BSD-3-Clause"
] | null | null | null | #ifndef _RSS_COMMON_DATABASE_HPP_
#define _RSS_COMMON_DATABASE_HPP_
#include <string>
#include <vector>
#include "sqlite3.h"
// Use ResultQuery if you want to execute "SELECT" queries
class ResultQuery
{
public:
ResultQuery();
~ResultQuery();
bool next(const char *query);
bool isFirst() { return nCurrRow == 1 ? true : false; }
bool isLast() { return nCurrRow == nRows ? true : false; }
int getRow() { return nCurrRow; }
void close();
bool isClose() { return isClosed; }
bool wasNull() { return nRows > 0 ? false : true; }
std::string getString(unsigned int columnIndex) { return std::string((char *)sqlite3_value_text(get(columnIndex))); }
bool getBoolean(unsigned int columnIndex) { return getInt(columnIndex) > 0 ? true : false; }
int getInt(unsigned int columnIndex) { return sqlite3_value_int(get(columnIndex)); }
void *getPointer(unsigned int columnIndex, const char* type) { return sqlite3_value_pointer(get(columnIndex), type); }
double getDouble(unsigned int columnIndex) { return sqlite3_value_double(get(columnIndex)); }
int getAffectedColumns() { return nColumns; }
int getAffectedRows() { return nRows; }
private:
int nRows;
int nColumns;
int nCurrRow;
std::vector<sqlite3_value *> values;
bool isClosed;
sqlite3_stmt *stmt;
void vector_free();
bool exec(const char *query);
sqlite3_value *get(unsigned int columnIndex);
};
extern int database_exec_count(const char *query, int *nOut);
extern int database_exec_count_from_select(std::string query, int *nOut);
extern int database_is_column_null(sqlite3_stmt *stmt, int column);
extern int database_open(const char *name);
extern void database_close();
extern int database_exec(const char *query);
extern void database_finalize(sqlite3_stmt *stmt);
extern int database_prepare(const char *sql, int sql_length, sqlite3_stmt **ppStmt, const char **pzTail);
extern int database_step(sqlite3_stmt *stmt);
#endif
| 29.446154 | 119 | 0.751306 | [
"vector"
] |
cc3b5f217488551e8920a11204f82f72b0164293 | 33,009 | cpp | C++ | modules/visual_script/visual_script_expression.cpp | leyyin/godot | 68325d7254db711beaedddad218e2cddb405c42c | [
"CC-BY-3.0",
"MIT"
] | 5 | 2017-02-06T18:37:37.000Z | 2021-06-29T06:45:26.000Z | modules/visual_script/visual_script_expression.cpp | leyyin/godot | 68325d7254db711beaedddad218e2cddb405c42c | [
"CC-BY-3.0",
"MIT"
] | 17 | 2016-12-30T14:35:53.000Z | 2017-03-07T21:07:50.000Z | modules/visual_script/visual_script_expression.cpp | leyyin/godot | 68325d7254db711beaedddad218e2cddb405c42c | [
"CC-BY-3.0",
"MIT"
] | 1 | 2020-10-22T12:22:52.000Z | 2020-10-22T12:22:52.000Z | #include "visual_script_expression.h"
bool VisualScriptExpression::_set(const StringName& p_name, const Variant& p_value) {
if (String(p_name)=="expression") {
expression=p_value;
expression_dirty=true;
ports_changed_notify();
return true;
}
if (String(p_name)=="out_type") {
output_type=Variant::Type(int(p_value));
expression_dirty=true;
ports_changed_notify();
return true;
}
if (String(p_name)=="sequenced") {
sequenced=p_value;
ports_changed_notify();
return true;
}
if (String(p_name)=="input_count") {
int from=inputs.size();
inputs.resize(int(p_value));
for(int i=from;i<inputs.size();i++) {
inputs[i].name=String::chr('a'+i);
if (from==0) {
inputs[i].type=output_type;
} else {
inputs[i].type=inputs[from-1].type;
}
}
expression_dirty=true;
ports_changed_notify();
_change_notify();
return true;
}
if (String(p_name).begins_with("input/")) {
int idx=String(p_name).get_slice("/",1).to_int();
ERR_FAIL_INDEX_V(idx,inputs.size(),false);
String what=String(p_name).get_slice("/",2);
if (what=="type") {
inputs[idx].type=Variant::Type(int(p_value));
} else if (what=="name") {
inputs[idx].name=p_value;
} else {
return false;
}
expression_dirty=true;
ports_changed_notify();
return true;
}
return false;
}
bool VisualScriptExpression::_get(const StringName& p_name,Variant &r_ret) const {
if (String(p_name)=="expression") {
r_ret=expression;
return true;
}
if (String(p_name)=="out_type") {
r_ret=output_type;
return true;
}
if (String(p_name)=="sequenced") {
r_ret=sequenced;
return true;
}
if (String(p_name)=="input_count") {
r_ret=inputs.size();
return true;
}
if (String(p_name).begins_with("input/")) {
int idx=String(p_name).get_slice("/",1).to_int();
ERR_FAIL_INDEX_V(idx,inputs.size(),false);
String what=String(p_name).get_slice("/",2);
if (what=="type") {
r_ret=inputs[idx].type;
} else if (what=="name") {
r_ret=inputs[idx].name;
} else {
return false;
}
return true;
}
return false;
}
void VisualScriptExpression::_get_property_list( List<PropertyInfo> *p_list) const {
String argt="Any";
for(int i=1;i<Variant::VARIANT_MAX;i++) {
argt+=","+Variant::get_type_name(Variant::Type(i));
}
p_list->push_back(PropertyInfo(Variant::STRING,"expression",PROPERTY_HINT_NONE,"",PROPERTY_USAGE_NOEDITOR));
p_list->push_back(PropertyInfo(Variant::INT,"out_type",PROPERTY_HINT_ENUM,argt));
p_list->push_back(PropertyInfo(Variant::INT,"input_count",PROPERTY_HINT_RANGE,"0,64,1"));
p_list->push_back(PropertyInfo(Variant::BOOL,"sequenced"));
for(int i=0;i<inputs.size();i++) {
p_list->push_back(PropertyInfo(Variant::INT,"input/"+itos(i)+"/type",PROPERTY_HINT_ENUM,argt));
p_list->push_back(PropertyInfo(Variant::STRING,"input/"+itos(i)+"/name"));
}
}
int VisualScriptExpression::get_output_sequence_port_count() const {
return sequenced?1:0;
}
bool VisualScriptExpression::has_input_sequence_port() const{
return sequenced;
}
String VisualScriptExpression::get_output_sequence_port_text(int p_port) const{
return String();
}
int VisualScriptExpression::get_input_value_port_count() const{
return inputs.size();
}
int VisualScriptExpression::get_output_value_port_count() const{
return 1;
}
PropertyInfo VisualScriptExpression::get_input_value_port_info(int p_idx) const{
return PropertyInfo(inputs[p_idx].type,inputs[p_idx].name);
}
PropertyInfo VisualScriptExpression::get_output_value_port_info(int p_idx) const{
return PropertyInfo(output_type,"result");
}
String VisualScriptExpression::get_caption() const{
return "Expression";
}
String VisualScriptExpression::get_text() const{
return expression;
}
Error VisualScriptExpression::_get_token(Token& r_token) {
while (true) {
#define GET_CHAR() (str_ofs>=expression.length()?0:expression[str_ofs++])
CharType cchar = GET_CHAR();
if (cchar==0) {
r_token.type=TK_EOF;
return OK;
}
switch(cchar) {
case 0: {
r_token.type=TK_EOF;
return OK;
} break;
case '{': {
r_token.type=TK_CURLY_BRACKET_OPEN;
return OK;
};
case '}': {
r_token.type=TK_CURLY_BRACKET_CLOSE;
return OK;
};
case '[': {
r_token.type=TK_BRACKET_OPEN;
return OK;
};
case ']': {
r_token.type=TK_BRACKET_CLOSE;
return OK;
};
case '(': {
r_token.type=TK_PARENTHESIS_OPEN;
return OK;
};
case ')': {
r_token.type=TK_PARENTHESIS_CLOSE;
return OK;
};
case ',': {
r_token.type=TK_COMMA;
return OK;
};
case ':': {
r_token.type=TK_COLON;
return OK;
};
case '.': {
r_token.type=TK_PERIOD;
return OK;
};
case '=': {
cchar=GET_CHAR();
if (cchar=='=') {
r_token.type=TK_OP_EQUAL;
} else {
_set_error("Expected '='");
r_token.type=TK_ERROR;
return ERR_PARSE_ERROR;
}
return OK;
};
case '!': {
if (expression[str_ofs]=='=') {
r_token.type=TK_OP_NOT_EQUAL;
str_ofs++;
} else {
r_token.type=TK_OP_NOT;
}
return OK;
};
case '>': {
if (expression[str_ofs]=='=') {
r_token.type=TK_OP_GREATER_EQUAL;
str_ofs++;
} else if (expression[str_ofs]=='>') {
r_token.type=TK_OP_SHIFT_RIGHT;
str_ofs++;
} else {
r_token.type=TK_OP_GREATER;
}
return OK;
};
case '<': {
if (expression[str_ofs]=='=') {
r_token.type=TK_OP_LESS_EQUAL;
str_ofs++;
} else if (expression[str_ofs]=='<') {
r_token.type=TK_OP_SHIFT_LEFT;
str_ofs++;
} else {
r_token.type=TK_OP_LESS;
}
return OK;
};
case '+': {
r_token.type=TK_OP_ADD;
return OK;
};
case '-': {
r_token.type=TK_OP_SUB;
return OK;
};
case '/': {
r_token.type=TK_OP_DIV;
return OK;
};
case '*': {
r_token.type=TK_OP_MUL;
return OK;
};
case '%': {
r_token.type=TK_OP_MOD;
return OK;
};
case '&': {
if (expression[str_ofs]=='&') {
r_token.type=TK_OP_AND;
str_ofs++;
} else {
r_token.type=TK_OP_BIT_AND;
}
return OK;
};
case '|': {
if (expression[str_ofs]=='|') {
r_token.type=TK_OP_OR;
str_ofs++;
} else {
r_token.type=TK_OP_BIT_OR;
}
return OK;
};
case '^': {
r_token.type=TK_OP_BIT_XOR;
return OK;
};
case '~': {
r_token.type=TK_OP_BIT_INVERT;
return OK;
};
case '"': {
String str;
while(true) {
CharType ch=GET_CHAR();
if (ch==0) {
_set_error("Unterminated String");
r_token.type=TK_ERROR;
return ERR_PARSE_ERROR;
} else if (ch=='"') {
break;
} else if (ch=='\\') {
//escaped characters...
CharType next = GET_CHAR();
if (next==0) {
_set_error("Unterminated String");
r_token.type=TK_ERROR;
return ERR_PARSE_ERROR;
}
CharType res=0;
switch(next) {
case 'b': res=8; break;
case 't': res=9; break;
case 'n': res=10; break;
case 'f': res=12; break;
case 'r': res=13; break;
case 'u': {
//hexnumbarh - oct is deprecated
for(int j=0;j<4;j++) {
CharType c = GET_CHAR();
if (c==0) {
_set_error("Unterminated String");
r_token.type=TK_ERROR;
return ERR_PARSE_ERROR;
}
if (!((c>='0' && c<='9') || (c>='a' && c<='f') || (c>='A' && c<='F'))) {
_set_error("Malformed hex constant in string");
r_token.type=TK_ERROR;
return ERR_PARSE_ERROR;
}
CharType v;
if (c>='0' && c<='9') {
v=c-'0';
} else if (c>='a' && c<='f') {
v=c-'a';
v+=10;
} else if (c>='A' && c<='F') {
v=c-'A';
v+=10;
} else {
ERR_PRINT("BUG");
v=0;
}
res<<=4;
res|=v;
}
} break;
//case '\"': res='\"'; break;
//case '\\': res='\\'; break;
//case '/': res='/'; break;
default: {
res = next;
//r_err_str="Invalid escape sequence";
//return ERR_PARSE_ERROR;
} break;
}
str+=res;
} else {
str+=ch;
}
}
r_token.type=TK_CONSTANT;
r_token.value=str;
return OK;
} break;
default: {
if (cchar<=32) {
break;
}
if (cchar=='-' || (cchar>='0' && cchar<='9')) {
//a number
String num;
#define READING_SIGN 0
#define READING_INT 1
#define READING_DEC 2
#define READING_EXP 3
#define READING_DONE 4
int reading=READING_INT;
if (cchar=='-') {
num+='-';
cchar=GET_CHAR();
}
CharType c = cchar;
bool exp_sign=false;
bool exp_beg=false;
bool is_float=false;
while(true) {
switch(reading) {
case READING_INT: {
if (c>='0' && c<='9') {
//pass
} else if (c=='.') {
reading=READING_DEC;
is_float=true;
} else if (c=='e') {
reading=READING_EXP;
} else {
reading=READING_DONE;
}
} break;
case READING_DEC: {
if (c>='0' && c<='9') {
} else if (c=='e') {
reading=READING_EXP;
} else {
reading=READING_DONE;
}
} break;
case READING_EXP: {
if (c>='0' && c<='9') {
exp_beg=true;
} else if ((c=='-' || c=='+') && !exp_sign && !exp_beg) {
if (c=='-')
is_float=true;
exp_sign=true;
} else {
reading=READING_DONE;
}
} break;
}
if (reading==READING_DONE)
break;
num+=String::chr(c);
c = GET_CHAR();
}
str_ofs--;
r_token.type=TK_CONSTANT;
if (is_float)
r_token.value=num.to_double();
else
r_token.value=num.to_int();
return OK;
} else if ((cchar>='A' && cchar<='Z') || (cchar>='a' && cchar<='z') || cchar=='_') {
String id;
bool first=true;
while((cchar>='A' && cchar<='Z') || (cchar>='a' && cchar<='z') || cchar=='_' || (!first && cchar>='0' && cchar<='9')) {
id+=String::chr(cchar);
cchar=GET_CHAR();
first=false;
}
str_ofs--; //go back one
if (id=="in") {
r_token.type=TK_OP_IN;
} else if (id=="null") {
r_token.type=TK_CONSTANT;
r_token.value=Variant();
} else if (id=="true") {
r_token.type=TK_CONSTANT;
r_token.value=true;
} else if (id=="false") {
r_token.type=TK_CONSTANT;
r_token.value=false;
} else if (id=="PI") {
r_token.type=TK_CONSTANT;
r_token.value=Math_PI;
} else if (id=="not") {
r_token.type=TK_OP_NOT;
} else if (id=="or") {
r_token.type=TK_OP_OR;
} else if (id=="and") {
r_token.type=TK_OP_AND;
} else if (id=="self") {
r_token.type=TK_SELF;
} else {
for(int i=0;i<Variant::VARIANT_MAX;i++) {
if (id==Variant::get_type_name(Variant::Type(i))) {
r_token.type=TK_BASIC_TYPE;
r_token.value=i;
return OK;
break;
}
}
VisualScriptBuiltinFunc::BuiltinFunc bifunc = VisualScriptBuiltinFunc::find_function(id);
if (bifunc!=VisualScriptBuiltinFunc::FUNC_MAX) {
r_token.type=TK_BUILTIN_FUNC;
r_token.value=bifunc;
return OK;
}
r_token.type=TK_IDENTIFIER;
r_token.value=id;
}
return OK;
} else {
_set_error("Unexpected character.");
r_token.type=TK_ERROR;
return ERR_PARSE_ERROR;
}
}
}
}
r_token.type=TK_ERROR;
return ERR_PARSE_ERROR;
}
const char* VisualScriptExpression::token_name[TK_MAX]={
"CURLY BRACKET OPEN",
"CURLY BRACKET CLOSE",
"BRACKET OPEN",
"BRACKET CLOSE",
"PARENTHESIS OPEN",
"PARENTHESIS CLOSE",
"IDENTIFIER",
"BUILTIN FUNC",
"SELF",
"CONSTANT",
"BASIC TYPE",
"COLON",
"COMMA",
"PERIOD",
"OP IN",
"OP EQUAL",
"OP NOT EQUAL",
"OP LESS",
"OP LESS EQUAL",
"OP GREATER",
"OP GREATER EQUAL",
"OP AND",
"OP OR",
"OP NOT",
"OP ADD",
"OP SUB",
"OP MUL",
"OP DIV",
"OP MOD",
"OP SHIFT LEFT",
"OP SHIFT RIGHT",
"OP BIT AND",
"OP BIT OR",
"OP BIT XOR",
"OP BIT INVERT",
"EOF",
"ERROR"
};
VisualScriptExpression::ENode* VisualScriptExpression::_parse_expression() {
Vector<Expression> expression;
while(true) {
//keep appending stuff to expression
ENode*expr=NULL;
Token tk;
_get_token(tk);
if (error_set)
return NULL;
switch(tk.type) {
case TK_CURLY_BRACKET_OPEN: {
//a dictionary
DictionaryNode *dn = alloc_node<DictionaryNode>();
while(true) {
int cofs=str_ofs;
_get_token(tk);
if (tk.type==TK_CURLY_BRACKET_CLOSE) {
break;
}
str_ofs=cofs; //revert
//parse an expression
ENode* expr=_parse_expression();
if (!expr)
return NULL;
dn->dict.push_back(expr);
_get_token(tk);
if (tk.type!=TK_COLON) {
_set_error("Expected ':'");
return NULL;
}
expr=_parse_expression();
if (!expr)
return NULL;
dn->dict.push_back(expr);
cofs=str_ofs;
_get_token(tk);
if (tk.type==TK_COMMA) {
//all good
} else if (tk.type==TK_CURLY_BRACKET_CLOSE) {
str_ofs=cofs;
} else {
_set_error("Expected ',' or '}'");
}
}
expr=dn;
} break;
case TK_BRACKET_OPEN: {
//an array
ArrayNode *an = alloc_node<ArrayNode>();
while(true) {
int cofs=str_ofs;
_get_token(tk);
if (tk.type==TK_BRACKET_CLOSE) {
break;
}
str_ofs=cofs; //revert
//parse an expression
ENode* expr=_parse_expression();
if (!expr)
return NULL;
an->array.push_back(expr);
cofs=str_ofs;
_get_token(tk);
if (tk.type==TK_COMMA) {
//all good
} else if (tk.type==TK_BRACKET_CLOSE) {
str_ofs=cofs;
} else {
_set_error("Expected ',' or ']'");
}
}
expr=an;
} break;
case TK_PARENTHESIS_OPEN: {
//a suexpression
ENode* e=_parse_expression();
if (error_set)
return NULL;
_get_token(tk);
if (tk.type!=TK_PARENTHESIS_CLOSE) {
_set_error("Expected ')'");
return NULL;
}
expr=e;
} break;
case TK_IDENTIFIER: {
String what = tk.value;
int index=-1;
for(int i=0;i<inputs.size();i++) {
if (what==inputs[i].name) {
index=i;
break;
}
}
if (index!=-1) {
InputNode *input = alloc_node<InputNode>();
input->index=index;
expr=input;
} else {
_set_error("Invalid input identifier '"+what+"'. For script variables, use self (locals are for inputs)."+what);
return NULL;
}
} break;
case TK_SELF: {
SelfNode *self = alloc_node<SelfNode>();
expr=self;
} break;
case TK_CONSTANT: {
ConstantNode *constant = alloc_node<ConstantNode>();
constant->value=tk.value;
expr=constant;
} break;
case TK_BASIC_TYPE: {
//constructor..
Variant::Type bt = Variant::Type(int(tk.value));
_get_token(tk);
if (tk.type!=TK_PARENTHESIS_OPEN) {
_set_error("Expected '('");
return NULL;
}
ConstructorNode *constructor = alloc_node<ConstructorNode>();
constructor->data_type=bt;
while(true) {
int cofs=str_ofs;
_get_token(tk);
if (tk.type==TK_PARENTHESIS_CLOSE) {
break;
}
str_ofs=cofs; //revert
//parse an expression
ENode* expr=_parse_expression();
if (!expr)
return NULL;
constructor->arguments.push_back(expr);
cofs=str_ofs;
_get_token(tk);
if (tk.type==TK_COMMA) {
//all good
} else if (tk.type==TK_PARENTHESIS_CLOSE) {
str_ofs=cofs;
} else {
_set_error("Expected ',' or ')'");
}
}
expr=constructor;
} break;
case TK_BUILTIN_FUNC: {
//builtin function
Variant::Type bt = Variant::Type(int(tk.value));
_get_token(tk);
if (tk.type!=TK_PARENTHESIS_OPEN) {
_set_error("Expected '('");
return NULL;
}
BuiltinFuncNode *bifunc = alloc_node<BuiltinFuncNode>();
bifunc->func=VisualScriptBuiltinFunc::BuiltinFunc(int(tk.value));
while(true) {
int cofs=str_ofs;
_get_token(tk);
if (tk.type==TK_PARENTHESIS_CLOSE) {
break;
}
str_ofs=cofs; //revert
//parse an expression
ENode* expr=_parse_expression();
if (!expr)
return NULL;
bifunc->arguments.push_back(expr);
cofs=str_ofs;
_get_token(tk);
if (tk.type==TK_COMMA) {
//all good
} else if (tk.type==TK_PARENTHESIS_CLOSE) {
str_ofs=cofs;
} else {
_set_error("Expected ',' or ')'");
}
}
int expected_args = VisualScriptBuiltinFunc::get_func_argument_count(bifunc->func);
if (bifunc->arguments.size() != expected_args) {
_set_error("Builtin func '"+VisualScriptBuiltinFunc::get_func_name(bifunc->func)+"' expects "+itos(expected_args)+" arguments.");
}
expr=bifunc;
} break;
case TK_OP_SUB: {
Expression e;
e.is_op=true;
e.op=Variant::OP_NEGATE;
expression.push_back(e);
continue;
} break;
case TK_OP_NOT: {
Expression e;
e.is_op=true;
e.op=Variant::OP_NOT;
expression.push_back(e);
continue;
} break;
default: {
_set_error("Expected expression.");
return NULL;
} break;
}
//before going to operators, must check indexing!
while(true) {
int cofs2=str_ofs;
_get_token(tk);
if (error_set)
return NULL;
bool done=false;
switch(tk.type) {
case TK_BRACKET_OPEN: {
//value indexing
IndexNode *index = alloc_node<IndexNode>();
index->base=expr;
ENode* what=_parse_expression();
if (!what)
return NULL;
index->index=what;
_get_token(tk);
if (tk.type!=TK_BRACKET_CLOSE) {
_set_error("Expected ']' at end of index.");
return NULL;
}
expr=index;
} break;
case TK_PERIOD: {
//named indexing or function call
_get_token(tk);
if (tk.type!=TK_IDENTIFIER) {
_set_error("Expected identifier after '.'");
return NULL;
}
StringName identifier=tk.value;
int cofs=str_ofs;
_get_token(tk);
if (tk.type==TK_PARENTHESIS_OPEN) {
//function call
CallNode *func_call = alloc_node<CallNode>();
func_call->method=identifier;
func_call->base=expr;
while(true) {
int cofs=str_ofs;
_get_token(tk);
if (tk.type==TK_PARENTHESIS_CLOSE) {
break;
}
str_ofs=cofs; //revert
//parse an expression
ENode* expr=_parse_expression();
if (!expr)
return NULL;
func_call->arguments.push_back(expr);
cofs=str_ofs;
_get_token(tk);
if (tk.type==TK_COMMA) {
//all good
} else if (tk.type==TK_PARENTHESIS_CLOSE) {
str_ofs=cofs;
} else {
_set_error("Expected ',' or ')'");
}
}
expr=func_call;
} else {
//named indexing
str_ofs=cofs;
NamedIndexNode *index = alloc_node<NamedIndexNode>();
index->base=expr;
index->name=identifier;
expr=index;
}
} break;
default: {
str_ofs=cofs2;
done=true;
} break;
}
if (done)
break;
}
//push expression
{
Expression e;
e.is_op=false;
e.node=expr;
expression.push_back(e);
}
//ok finally look for an operator
int cofs=str_ofs;
_get_token(tk);
if (error_set)
return NULL;
Variant::Operator op = Variant::OP_MAX;
switch(tk.type) {
case TK_OP_IN: op=Variant::OP_IN; break;
case TK_OP_EQUAL: op=Variant::OP_EQUAL; break;
case TK_OP_NOT_EQUAL: op=Variant::OP_NOT_EQUAL; break;
case TK_OP_LESS: op=Variant::OP_LESS; break;
case TK_OP_LESS_EQUAL: op=Variant::OP_LESS_EQUAL; break;
case TK_OP_GREATER: op=Variant::OP_GREATER; break;
case TK_OP_GREATER_EQUAL: op=Variant::OP_GREATER_EQUAL; break;
case TK_OP_AND: op=Variant::OP_AND; break;
case TK_OP_OR: op=Variant::OP_OR; break;
case TK_OP_NOT: op=Variant::OP_NOT; break;
case TK_OP_ADD: op=Variant::OP_ADD; break;
case TK_OP_SUB: op=Variant::OP_SUBSTRACT; break;
case TK_OP_MUL: op=Variant::OP_MULTIPLY; break;
case TK_OP_DIV: op=Variant::OP_DIVIDE; break;
case TK_OP_MOD: op=Variant::OP_MODULE; break;
case TK_OP_SHIFT_LEFT: op=Variant::OP_SHIFT_LEFT; break;
case TK_OP_SHIFT_RIGHT: op=Variant::OP_SHIFT_RIGHT; break;
case TK_OP_BIT_AND: op=Variant::OP_BIT_AND; break;
case TK_OP_BIT_OR: op=Variant::OP_BIT_OR; break;
case TK_OP_BIT_XOR: op=Variant::OP_BIT_XOR; break;
case TK_OP_BIT_INVERT: op=Variant::OP_BIT_NEGATE; break;
default: {};
}
if (op==Variant::OP_MAX) { //stop appending stuff
str_ofs=cofs;
break;
}
//push operator and go on
{
Expression e;
e.is_op=true;
e.op=op;
expression.push_back(e);
}
}
/* Reduce the set set of expressions and place them in an operator tree, respecting precedence */
while(expression.size()>1) {
int next_op=-1;
int min_priority=0xFFFFF;
bool is_unary=false;
for(int i=0;i<expression.size();i++) {
if (!expression[i].is_op) {
continue;
}
int priority;
bool unary=false;
switch(expression[i].op) {
case Variant::OP_BIT_NEGATE: priority=0; unary=true; break;
case Variant::OP_NEGATE: priority=1; unary=true; break;
case Variant::OP_MULTIPLY: priority=2; break;
case Variant::OP_DIVIDE: priority=2; break;
case Variant::OP_MODULE: priority=2; break;
case Variant::OP_ADD: priority=3; break;
case Variant::OP_SUBSTRACT: priority=3; break;
case Variant::OP_SHIFT_LEFT: priority=4; break;
case Variant::OP_SHIFT_RIGHT: priority=4; break;
case Variant::OP_BIT_AND: priority=5; break;
case Variant::OP_BIT_XOR: priority=6; break;
case Variant::OP_BIT_OR: priority=7; break;
case Variant::OP_LESS: priority=8; break;
case Variant::OP_LESS_EQUAL: priority=8; break;
case Variant::OP_GREATER: priority=8; break;
case Variant::OP_GREATER_EQUAL: priority=8; break;
case Variant::OP_EQUAL: priority=8; break;
case Variant::OP_NOT_EQUAL: priority=8; break;
case Variant::OP_IN: priority=10; break;
case Variant::OP_NOT: priority=11; unary=true; break;
case Variant::OP_AND: priority=12; break;
case Variant::OP_OR: priority=13; break;
default: {
_set_error("Parser bug, invalid operator in expression: "+itos(expression[i].op));
return NULL;
}
}
if (priority<min_priority) {
// < is used for left to right (default)
// <= is used for right to left
next_op=i;
min_priority=priority;
is_unary=unary;
}
}
if (next_op==-1) {
_set_error("Yet another parser bug....");
ERR_FAIL_COND_V(next_op==-1,NULL);
}
// OK! create operator..
if (is_unary) {
int expr_pos=next_op;
while(expression[expr_pos].is_op) {
expr_pos++;
if (expr_pos==expression.size()) {
//can happen..
_set_error("Unexpected end of expression..");
return NULL;
}
}
//consecutively do unary opeators
for(int i=expr_pos-1;i>=next_op;i--) {
OperatorNode *op = alloc_node<OperatorNode>();
op->op=expression[i].op;
op->nodes[0]=expression[i+1].node;
op->nodes[1]=NULL;
expression[i].is_op=false;
expression[i].node=op;
expression.remove(i+1);
}
} else {
if (next_op <1 || next_op>=(expression.size()-1)) {
_set_error("Parser bug..");
ERR_FAIL_V(NULL);
}
OperatorNode *op = alloc_node<OperatorNode>();
op->op=expression[next_op].op;
if (expression[next_op-1].is_op) {
_set_error("Parser bug..");
ERR_FAIL_V(NULL);
}
if (expression[next_op+1].is_op) {
// this is not invalid and can really appear
// but it becomes invalid anyway because no binary op
// can be followed by an unary op in a valid combination,
// due to how precedence works, unaries will always dissapear first
_set_error("Unexpected two consecutive operators.");
return NULL;
}
op->nodes[0]=expression[next_op-1].node; //expression goes as left
op->nodes[1]=expression[next_op+1].node; //next expression goes as right
//replace all 3 nodes by this operator and make it an expression
expression[next_op-1].node=op;
expression.remove(next_op);
expression.remove(next_op);
}
}
return expression[0].node;
}
bool VisualScriptExpression::_compile_expression() {
if (!expression_dirty)
return error_set;
if (nodes) {
memdelete(nodes);
nodes=NULL;
root=NULL;
}
error_str=String();
error_set=false;
str_ofs=0;
root=_parse_expression();
if (error_set) {
root=NULL;
if (nodes) {
memdelete(nodes);
}
nodes=NULL;
return true;
}
expression_dirty=false;
return false;
}
class VisualScriptNodeInstanceExpression : public VisualScriptNodeInstance {
public:
VisualScriptInstance* instance;
VisualScriptExpression *expression;
//virtual int get_working_memory_size() const { return 0; }
//execute by parsing the tree directly
virtual bool _execute(const Variant** p_inputs,VisualScriptExpression::ENode *p_node,Variant& r_ret,String& r_error_str,Variant::CallError &ce) {
switch(p_node->type) {
case VisualScriptExpression::ENode::TYPE_INPUT: {
const VisualScriptExpression::InputNode *in = static_cast<const VisualScriptExpression::InputNode*>(p_node);
r_ret=*p_inputs[in->index];
} break;
case VisualScriptExpression::ENode::TYPE_CONSTANT: {
const VisualScriptExpression::ConstantNode *c = static_cast<const VisualScriptExpression::ConstantNode*>(p_node);
r_ret=c->value;
} break;
case VisualScriptExpression::ENode::TYPE_SELF: {
r_ret=instance->get_owner_ptr();
} break;
case VisualScriptExpression::ENode::TYPE_OPERATOR: {
const VisualScriptExpression::OperatorNode *op = static_cast<const VisualScriptExpression::OperatorNode*>(p_node);
Variant a;
bool ret = _execute(p_inputs,op->nodes[0],a,r_error_str,ce);
if (ret)
return true;
Variant b;
if (op->nodes[1]) {
ret = _execute(p_inputs,op->nodes[1],b,r_error_str,ce);
if (ret)
return true;
}
bool valid=true;
Variant::evaluate(op->op,a,b,r_ret,valid);
if (!valid) {
r_error_str="Invalid operands to operator "+Variant::get_operator_name(op->op)+": "+Variant::get_type_name(a.get_type())+" and "+Variant::get_type_name(b.get_type())+".";
return true;
}
} break;
case VisualScriptExpression::ENode::TYPE_INDEX: {
const VisualScriptExpression::IndexNode *index = static_cast<const VisualScriptExpression::IndexNode*>(p_node);
Variant base;
bool ret = _execute(p_inputs,index->base,base,r_error_str,ce);
if (ret)
return true;
Variant idx;
ret = _execute(p_inputs,index->index,idx,r_error_str,ce);
if (ret)
return true;
bool valid;
r_ret=base.get(idx,&valid);
if (!valid) {
r_error_str="Invalid index of type "+Variant::get_type_name(idx.get_type())+" for base of type "+Variant::get_type_name(base.get_type())+".";
return true;
}
} break;
case VisualScriptExpression::ENode::TYPE_NAMED_INDEX: {
const VisualScriptExpression::NamedIndexNode *index = static_cast<const VisualScriptExpression::NamedIndexNode*>(p_node);
Variant base;
bool ret = _execute(p_inputs,index->base,base,r_error_str,ce);
if (ret)
return true;
bool valid;
r_ret=base.get_named(index->name,&valid);
if (!valid) {
r_error_str="Invalid index '"+String(index->name)+"' for base of type "+Variant::get_type_name(base.get_type())+".";
return true;
}
} break;
case VisualScriptExpression::ENode::TYPE_ARRAY: {
const VisualScriptExpression::ArrayNode *array = static_cast<const VisualScriptExpression::ArrayNode*>(p_node);
Array arr;
arr.resize(array->array.size());
for (int i=0;i<array->array.size();i++) {
Variant value;
bool ret = _execute(p_inputs,array->array[i],value,r_error_str,ce);
if (ret)
return true;
arr[i]=value;
}
r_ret=arr;
} break;
case VisualScriptExpression::ENode::TYPE_DICTIONARY: {
const VisualScriptExpression::DictionaryNode *dictionary = static_cast<const VisualScriptExpression::DictionaryNode*>(p_node);
Dictionary d;
for (int i=0;i<dictionary->dict.size();i+=2) {
Variant key;
bool ret = _execute(p_inputs,dictionary->dict[i+0],key,r_error_str,ce);
if (ret)
return true;
Variant value;
ret = _execute(p_inputs,dictionary->dict[i+1],value,r_error_str,ce);
if (ret)
return true;
d[key]=value;
}
r_ret=d;
} break;
case VisualScriptExpression::ENode::TYPE_CONSTRUCTOR: {
const VisualScriptExpression::ConstructorNode *constructor = static_cast<const VisualScriptExpression::ConstructorNode*>(p_node);
Vector<Variant> arr;
Vector<const Variant*> argp;
arr.resize(constructor->arguments.size());
argp.resize(constructor->arguments.size());
for (int i=0;i<constructor->arguments.size();i++) {
Variant value;
bool ret = _execute(p_inputs,constructor->arguments[i],value,r_error_str,ce);
if (ret)
return true;
arr[i]=value;
argp[i]=&arr[i];
}
r_ret=Variant::construct(constructor->data_type,argp.ptr(),argp.size(),ce);
if (ce.error!=Variant::CallError::CALL_OK) {
r_error_str="Invalid arguments to construct '"+Variant::get_type_name(constructor->data_type)+"'.";
return true;
}
} break;
case VisualScriptExpression::ENode::TYPE_BUILTIN_FUNC: {
const VisualScriptExpression::BuiltinFuncNode *bifunc = static_cast<const VisualScriptExpression::BuiltinFuncNode*>(p_node);
Vector<Variant> arr;
Vector<const Variant*> argp;
arr.resize(bifunc->arguments.size());
argp.resize(bifunc->arguments.size());
for (int i=0;i<bifunc->arguments.size();i++) {
Variant value;
bool ret = _execute(p_inputs,bifunc->arguments[i],value,r_error_str,ce);
if (ret)
return true;
arr[i]=value;
argp[i]=&arr[i];
}
VisualScriptBuiltinFunc::exec_func(bifunc->func,argp.ptr(),&r_ret,ce,r_error_str);
if (ce.error!=Variant::CallError::CALL_OK) {
r_error_str="Builtin Call Failed. "+r_error_str;
return true;
}
} break;
case VisualScriptExpression::ENode::TYPE_CALL: {
const VisualScriptExpression::CallNode *call = static_cast<const VisualScriptExpression::CallNode*>(p_node);
Variant base;
bool ret = _execute(p_inputs,call->base,base,r_error_str,ce);
if (ret)
return true;
Vector<Variant> arr;
Vector<const Variant*> argp;
arr.resize(call->arguments.size());
argp.resize(call->arguments.size());
for (int i=0;i<call->arguments.size();i++) {
Variant value;
bool ret = _execute(p_inputs,call->arguments[i],value,r_error_str,ce);
if (ret)
return true;
arr[i]=value;
argp[i]=&arr[i];
}
r_ret=base.call(call->method,argp.ptr(),argp.size(),ce);
if (ce.error!=Variant::CallError::CALL_OK) {
r_error_str="On call to '"+String(call->method)+"':";
return true;
}
} break;
}
return false;
}
virtual int step(const Variant** p_inputs,Variant** p_outputs,StartMode p_start_mode,Variant* p_working_mem,Variant::CallError& r_error,String& r_error_str) {
if (!expression->root || expression->error_set) {
r_error_str=expression->error_str;
r_error.error=Variant::CallError::CALL_ERROR_INVALID_METHOD;
return 0;
}
bool error = _execute(p_inputs,expression->root,*p_outputs[0],r_error_str,r_error);
if (error && r_error.error==Variant::CallError::CALL_OK) {
r_error.error=Variant::CallError::CALL_ERROR_INVALID_METHOD;
}
#ifdef DEBUG_ENABLED
if (!error && expression->output_type!=Variant::NIL && !Variant::can_convert_strict(p_outputs[0]->get_type(),expression->output_type)) {
r_error_str+="Can't convert expression result from "+Variant::get_type_name(p_outputs[0]->get_type())+" to "+Variant::get_type_name(expression->output_type)+".";
r_error.error=Variant::CallError::CALL_ERROR_INVALID_METHOD;
}
#endif
return 0;
}
};
VisualScriptNodeInstance* VisualScriptExpression::instance(VisualScriptInstance* p_instance){
_compile_expression();
VisualScriptNodeInstanceExpression *instance = memnew( VisualScriptNodeInstanceExpression );
instance->instance=p_instance;
instance->expression=this;
return instance;
}
VisualScriptExpression::VisualScriptExpression()
{
output_type=Variant::NIL;
expression_dirty=true;
error_set=true;
root=NULL;
nodes=NULL;
sequenced=false;
}
VisualScriptExpression::~VisualScriptExpression() {
if (nodes) {
memdelete(nodes);
}
}
void register_visual_script_expression_node() {
VisualScriptLanguage::singleton->add_register_func("operators/expression",create_node_generic<VisualScriptExpression>);
}
| 21.659449 | 175 | 0.621497 | [
"vector"
] |
cc3f54713c8bdd6d090dff84ae62504aee0a7fa5 | 2,873 | cpp | C++ | Day_17/03_Postorder_Traversal.cpp | premnaaath/SDE-180 | 6d7cc2404d310600a81adaa652049172f2e10ed8 | [
"MIT"
] | null | null | null | Day_17/03_Postorder_Traversal.cpp | premnaaath/SDE-180 | 6d7cc2404d310600a81adaa652049172f2e10ed8 | [
"MIT"
] | null | null | null | Day_17/03_Postorder_Traversal.cpp | premnaaath/SDE-180 | 6d7cc2404d310600a81adaa652049172f2e10ed8 | [
"MIT"
] | null | null | null | // Problem Link:
// https://leetcode.com/problems/binary-tree-postorder-traversal/
// Approach 1: (Recursive)
// TC: O(n)
// SC: O(n)
// Approach 2: (Iterative 2 Stacks)
// TC: O(n)
// SC: O(n)
// Approach 3: (Iterative 1 Stack) (Store negative type-casted address values)
// TC: O(n)
// SC: O(n)
#include <bits/stdc++.h>
using namespace std;
#define ll long long
#define deb(x) cout << #x << ": " << x << "\n"
class TreeNode
{
public:
TreeNode *left;
int val;
TreeNode *right;
TreeNode() { TreeNode(-1); }
TreeNode(int _val) : left(NULL), val(_val), right(NULL) {}
};
// Approach 1
void helper(TreeNode *root, vector<int> &res)
{
if (root)
{
helper(root->left, res);
helper(root->right, res);
res.push_back(root->val);
}
}
vector<int> postorderTraversal1(TreeNode *root)
{
vector<int> res{};
helper(root, res);
return res;
}
// Approach 2
vector<int> postorderTraversal2(TreeNode *root)
{
vector<int> res{};
stack<TreeNode *> st1;
stack<TreeNode *> st2;
if (!root)
return res;
st1.push(root);
while (!st1.empty())
{
TreeNode *curr = st1.top();
st2.push(curr);
st1.pop();
if (curr->right)
st1.push(curr->right);
if (curr->left)
st1.push(curr->left);
}
while (!st2.empty())
{
res.push_back(st2.top()->val);
st2.pop();
}
return res;
}
// Approach 3
vector<int> postorderTraversal3(TreeNode *root)
{
vector<int> res{};
stack<long long> st;
while (root or !st.empty())
{
if (root)
{
st.push((long long)root);
root = root->left;
}
else
{
long long curr = st.top();
st.pop();
if (curr > 0)
{
st.push(-curr);
root = ((TreeNode *)curr)->right;
}
else
res.push_back(((TreeNode *)-curr)->val);
}
}
return res;
}
void solve()
{
TreeNode *root = new TreeNode(1);
root->left = new TreeNode(2);
root->right = new TreeNode(3);
root->left->left = new TreeNode(4);
root->left->right = new TreeNode(5);
root->left->right->left = new TreeNode(6);
root->left->right->right = new TreeNode(7);
root->right->right = new TreeNode(8);
vector<int> res;
res = postorderTraversal1(root);
for (auto i : res)
cout << i << " ";
cout << endl;
res = postorderTraversal2(root);
for (auto i : res)
cout << i << " ";
cout << endl;
res = postorderTraversal3(root);
for (auto i : res)
cout << i << " ";
cout << endl;
}
int main()
{
ios_base::sync_with_stdio(0), cin.tie(0), cout.tie(0);
int t{1};
// cin >> t;
while (t--)
solve();
return 0;
} | 19.02649 | 78 | 0.516533 | [
"vector"
] |
cc4914a918379ef51b121da4870276cc85e332d3 | 6,116 | cpp | C++ | Project/Motor2D/Boo.cpp | albertllopart/SMW-Reborn | 198579b08c449544ba90d9333ad154674f05afc4 | [
"Unlicense"
] | 1 | 2020-03-19T18:08:06.000Z | 2020-03-19T18:08:06.000Z | Project/Motor2D/Boo.cpp | albertllopart/SMW-Reborn | 198579b08c449544ba90d9333ad154674f05afc4 | [
"Unlicense"
] | null | null | null | Project/Motor2D/Boo.cpp | albertllopart/SMW-Reborn | 198579b08c449544ba90d9333ad154674f05afc4 | [
"Unlicense"
] | null | null | null | #include "Boo.h"
#include "j1App.h"
#include "j1Input.h"
#include "j1Textures.h"
#include "j1Audio.h"
#include "j1Render.h"
#include "j1Window.h"
#include "j1Textures.h"
#include "j1Player.h"
#include "j1EntityModule.h"
#include "j1Map.h"
#include "j1Pathfinding.h"
#include "Brofiler\Brofiler.h"
Boo::Boo() : Entity()
{
name.create("Boo");
//animations
idle.PushBack({ 0, 0, BOO_SIZE, BOO_SIZE });
idle.PushBack({ 0, 0, BOO_SIZE, BOO_SIZE });
idle.PushBack({ 0, 0, BOO_SIZE, BOO_SIZE });
idle.PushBack({ 0, 0, BOO_SIZE, BOO_SIZE });
idle.PushBack({ 0, 0, BOO_SIZE, BOO_SIZE });
idle.PushBack({ 17, 0, BOO_SIZE, BOO_SIZE });
idle.PushBack({ 17, 0, BOO_SIZE, BOO_SIZE });
idle.PushBack({ 0, 0, BOO_SIZE, BOO_SIZE });
idle.PushBack({ 0, 0, BOO_SIZE, BOO_SIZE });
idle.PushBack({ 0, 0, BOO_SIZE, BOO_SIZE });
idle.PushBack({ 0, 0, BOO_SIZE, BOO_SIZE });
idle.PushBack({ 0, 0, BOO_SIZE, BOO_SIZE });
idle.PushBack({ 51, 0, BOO_SIZE, BOO_SIZE });
idle.PushBack({ 51, 0, BOO_SIZE, BOO_SIZE });
idle.PushBack({ 51, 0, BOO_SIZE, BOO_SIZE });
idle.PushBack({ 51, 0, BOO_SIZE, BOO_SIZE });
idle.PushBack({ 51, 0, BOO_SIZE, BOO_SIZE });
idle.PushBack({ 34, 0, BOO_SIZE, BOO_SIZE });
idle.PushBack({ 34, 0, BOO_SIZE, BOO_SIZE });
idle.PushBack({ 51, 0, BOO_SIZE, BOO_SIZE });
idle.PushBack({ 51, 0, BOO_SIZE, BOO_SIZE });
idle.PushBack({ 51, 0, BOO_SIZE, BOO_SIZE });
idle.PushBack({ 51, 0, BOO_SIZE, BOO_SIZE });
idle.PushBack({ 51, 0, BOO_SIZE, BOO_SIZE });
chase_left.PushBack({ 17, 0, BOO_SIZE, BOO_SIZE });
chase_right.PushBack({ 34, 0, BOO_SIZE, BOO_SIZE });
stop_left.PushBack({ 0, 0, BOO_SIZE, BOO_SIZE });
stop_right.PushBack({ 51, 0, BOO_SIZE, BOO_SIZE });
}
Boo::~Boo()
{}
bool Boo::Awake()
{
position.create(188, 96);
collision = App->collision->AddCollider({ (int)position.x, (int)position.y, BOO_SIZE, BOO_SIZE }, COLLIDER_BOO, this);
return true;
}
bool Boo::Start()
{
graphic = App->tex->Load("textures/Boo.png");
current_animation = &idle;
state = IDLE_LEFT;
direction = R;
//pathfinding
is_path_done = true;
path = 0;
last_path = 0;
path_size = 0;
path_stopped = false;
pathfinding = false;
find_path = true;
create_path = true;
return true;
}
bool Boo::PreUpdate()
{
return true;
}
bool Boo::Update(float dt)
{
if ((position.x - App->entitymodule->player->position.x <= 0 && App->entitymodule->player->GetDirection() == R) ||
(position.x - App->entitymodule->player->position.x >= 0 && App->entitymodule->player->GetDirection() == L))
boo_chase = true;
else
boo_chase = false;
if (boo_chase)
{
Move();
if (pathfinding)
{
// go to
if (!Find_a_Path() && find_path)
{
find_path = false;
}
else
{
//in case the enemy reaches the final of the path
pathfinding = false;
is_path_done = true;
}
}
}
Draw();
if (collision != NULL)
{
collision->SetPos(position.x, position.y);
}
pathfind_timer += dt;
return true;
}
bool Boo::PostUpdate()
{
if (App->input->GetKey(SDL_SCANCODE_0) == KEY_DOWN)
{
boo_chase = !boo_chase;
}
return true;
}
void Boo::Draw()
{
switch (state)
{
case IDLE_RIGHT:
current_animation = &idle;
break;
case IDLE_LEFT:
current_animation = &idle;
break;
case WALK_LEFT:
current_animation = &chase_left;
break;
case WALK_RIGHT:
current_animation = &chase_right;
break;
}
SDL_Rect r = current_animation->GetCurrentFrame();
App->render->Blit(graphic, position.x, position.y, &r);
}
bool Boo::Load(pugi::xml_node &)
{
return true;
}
bool Boo::Save(pugi::xml_node &) const
{
return true;
}
bool Boo::CleanUp()
{
return true;
}
void Boo::Move()
{
Pathfinding();
}
bool Boo::CreatePath(fPoint destination)
{
BROFILER_CATEGORY("Boo CreatePath", Profiler::Color::Orange)
bool ret = false;
//we call the pathfinding module and create a path, the bool we send is to know if the enmy can go in diagonal lines
if (App->pathfinding->CreatePath(App->map->WorldToMap(position.x, position.y), App->map->WorldToMap(destination.x, destination.y), true)> -1)
{
//we save the last path in a variable
last_pathfinding = App->pathfinding->GetLastPath();
path_size = last_pathfinding->Count();
path = 1;
//we clear the variable before pushing back our points
mlast_pathfinding.Clear();
for (int i = 0; i < path_size; ++i)
{
mlast_pathfinding.PushBack(*last_pathfinding->At(i));
ret = true;
}
}
return ret;
}
void Boo::Pathfinding()
{
BROFILER_CATEGORY("Boo Pathfinding", Profiler::Color::Orange)
if (is_path_done)
{
is_path_done = false;
path = 0;
last_path = 0;
path_size = 0;
path_stopped = false;
pathfinding = false;
find_path = true;
last_path = path;
create_path = true;
}
//create a path
if (pathfind_timer >= 0.2f)
{
if (create_path)
{
fPoint destination;
destination.x = App->entitymodule->player->position.x;
destination.y = App->entitymodule->player->position.y;
//if the path creates->
if (CreatePath(destination))
{
pathfinding = true;
create_path = false;
}
}
pathfind_timer = 0;
}
}
bool Boo::Find_a_Path()
{
BROFILER_CATEGORY("Boo Find_a_Path", Profiler::Color::Orange)
bool ret = true;
//when boo needs more than one step to reach player, if he doesn't then player probably dead af
if (path_size > 1)
{
iPoint go_to = App->map->MapToWorld(mlast_pathfinding[path].x, mlast_pathfinding[path].y);
//once we know where boo gotta go we send it to the function that moves him
Movement(go_to);
if (GetPositionINT() == go_to)
{
if (path < path_size - 1)
path++;
}
if (GetPositionINT() == App->map->MapToWorld(mlast_pathfinding[path_size - 1].x, mlast_pathfinding[path_size - 1].y))
ret = false;
}
else
ret = false;
return ret;
}
void Boo::Movement(iPoint go_to)
{
if (position.x < go_to.x) position.x += 5.0f, state = WALK_LEFT;
else if (position.x > go_to.x) position.x -= 5.0f, state = WALK_RIGHT;
if (position.y < go_to.y) position.y +=5.0f;
else if (position.y > go_to.y) position.y -= 5.0f;
}
iPoint Boo::GetPositionINT() const
{
return iPoint(position.x, position.y);
} | 21.089655 | 142 | 0.665141 | [
"render"
] |
cc591e047b8c17f7d60a5e29c255b4f1599fae97 | 918 | cpp | C++ | Problemset/shortest-palindrome/shortest-palindrome.cpp | Singularity0909/LeetCode | d46fb1c8ed9b16339d46d5c37f69d44e5c178954 | [
"MIT"
] | 1 | 2020-10-06T01:06:45.000Z | 2020-10-06T01:06:45.000Z | Problemset/shortest-palindrome/shortest-palindrome.cpp | Singularity0909/LeetCode | d46fb1c8ed9b16339d46d5c37f69d44e5c178954 | [
"MIT"
] | null | null | null | Problemset/shortest-palindrome/shortest-palindrome.cpp | Singularity0909/LeetCode | d46fb1c8ed9b16339d46d5c37f69d44e5c178954 | [
"MIT"
] | 1 | 2021-11-17T13:52:51.000Z | 2021-11-17T13:52:51.000Z |
// @Title: 最短回文串 (Shortest Palindrome)
// @Author: Singularity0909
// @Date: 2020-08-29 17:36:32
// @Runtime: 4 ms
// @Memory: 7.3 MB
class Solution {
public:
string shortestPalindrome(string s) {
int n = s.size();
vector<int> fail(n, -1);
for (int i = 1; i < n; ++i) {
int j = fail[i - 1];
while (j != -1 && s[j + 1] != s[i]) {
j = fail[j];
}
if (s[j + 1] == s[i]) {
fail[i] = j + 1;
}
}
int best = -1;
for (int i = n - 1; i >= 0; --i) {
while (best != -1 && s[best + 1] != s[i]) {
best = fail[best];
}
if (s[best + 1] == s[i]) {
++best;
}
}
string add = (best == n - 1 ? "" : s.substr(best + 1, n));
reverse(add.begin(), add.end());
return add + s;
}
};
| 25.5 | 66 | 0.367102 | [
"vector"
] |
7ff4837cead3e6790630a6bfbfa12f60f4b116bc | 15,680 | cpp | C++ | inetsrv/iis/admin/cnfgprts/loguictl.cpp | npocmaka/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 17 | 2020-11-13T13:42:52.000Z | 2021-09-16T09:13:13.000Z | inetsrv/iis/admin/cnfgprts/loguictl.cpp | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 2 | 2020-10-19T08:02:06.000Z | 2020-10-19T08:23:18.000Z | inetsrv/iis/admin/cnfgprts/loguictl.cpp | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 14 | 2020-11-14T09:43:20.000Z | 2021-08-28T08:59:57.000Z | // LogUICtl.cpp : Implementation of the CLogUICtrl OLE control class.
#include "stdafx.h"
#include "cnfgprts.h"
#include "LogUICtl.h"
#include "LogUIPpg.h"
#include <iiscnfg.h>
#include "initguid.h"
#include <inetcom.h>
#include <logtype.h>
#include <ilogobj.hxx>
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
IMPLEMENT_DYNCREATE(CLogUICtrl, COleControl)
/////////////////////////////////////////////////////////////////////////////
// Message map
BEGIN_MESSAGE_MAP(CLogUICtrl, COleControl)
//{{AFX_MSG_MAP(CLogUICtrl)
//}}AFX_MSG_MAP
ON_MESSAGE(OCM_COMMAND, OnOcmCommand)
ON_OLEVERB(AFX_IDS_VERB_PROPERTIES, OnProperties)
END_MESSAGE_MAP()
/////////////////////////////////////////////////////////////////////////////
// Dispatch map
BEGIN_DISPATCH_MAP(CLogUICtrl, COleControl)
//{{AFX_DISPATCH_MAP(CLogUICtrl)
DISP_FUNCTION(CLogUICtrl, "SetAdminTarget", SetAdminTarget, VT_EMPTY, VTS_BSTR VTS_BSTR)
DISP_FUNCTION(CLogUICtrl, "ApplyLogSelection", ApplyLogSelection, VT_EMPTY, VTS_NONE)
DISP_FUNCTION(CLogUICtrl, "SetComboBox", SetComboBox, VT_EMPTY, VTS_HANDLE)
DISP_FUNCTION(CLogUICtrl, "Terminate", Terminate, VT_EMPTY, VTS_NONE)
DISP_FUNCTION(CLogUICtrl, "SetUserData", SetUserData, VT_EMPTY, VTS_BSTR VTS_BSTR)
DISP_STOCKFUNC_DOCLICK()
DISP_STOCKPROP_CAPTION()
DISP_STOCKPROP_FONT()
DISP_STOCKPROP_ENABLED()
DISP_STOCKPROP_BORDERSTYLE()
//}}AFX_DISPATCH_MAP
END_DISPATCH_MAP()
/////////////////////////////////////////////////////////////////////////////
// Event map
BEGIN_EVENT_MAP(CLogUICtrl, COleControl)
//{{AFX_EVENT_MAP(CLogUICtrl)
EVENT_STOCK_CLICK()
EVENT_STOCK_KEYUP()
EVENT_STOCK_KEYDOWN()
EVENT_STOCK_KEYPRESS()
//}}AFX_EVENT_MAP
END_EVENT_MAP()
/////////////////////////////////////////////////////////////////////////////
// Property pages
BEGIN_PROPPAGEIDS(CLogUICtrl, 2)
PROPPAGEID(CLogUIPropPage::guid)
PROPPAGEID(CLSID_CFontPropPage)
END_PROPPAGEIDS(CLogUICtrl)
/////////////////////////////////////////////////////////////////////////////
// Initialize class factory and guid
IMPLEMENT_OLECREATE_EX(CLogUICtrl, "CNFGPRTS.LogUICtrl.1",
0xba634603, 0xb771, 0x11d0, 0x92, 0x96, 0, 0xc0, 0x4f, 0xb6, 0x67, 0x8b)
/////////////////////////////////////////////////////////////////////////////
// Type library ID and version
IMPLEMENT_OLETYPELIB(CLogUICtrl, _tlid, _wVerMajor, _wVerMinor)
/////////////////////////////////////////////////////////////////////////////
// Interface IDs
const IID BASED_CODE IID_DLogUI =
{ 0xba634601, 0xb771, 0x11d0, { 0x92, 0x96, 0, 0xc0, 0x4f, 0xb6, 0x67, 0x8b } };
const IID BASED_CODE IID_DLogUIEvents =
{ 0xba634602, 0xb771, 0x11d0, { 0x92, 0x96, 0, 0xc0, 0x4f, 0xb6, 0x67, 0x8b } };
/////////////////////////////////////////////////////////////////////////////
// Control type information
static const DWORD BASED_CODE _dwLogUIOleMisc =
OLEMISC_ACTIVATEWHENVISIBLE |
OLEMISC_SETCLIENTSITEFIRST |
OLEMISC_INSIDEOUT |
OLEMISC_CANTLINKINSIDE |
OLEMISC_ACTSLIKEBUTTON |
OLEMISC_RECOMPOSEONRESIZE;
IMPLEMENT_OLECTLTYPE(CLogUICtrl, IDS_LOGUI, _dwLogUIOleMisc)
/////////////////////////////////////////////////////////////////////////////
// CLogUICtrl::CLogUICtrlFactory::UpdateRegistry -
// Adds or removes system registry entries for CLogUICtrl
BOOL CLogUICtrl::CLogUICtrlFactory::UpdateRegistry(BOOL bRegister)
{
// TODO: Verify that your control follows apartment-model threading rules.
// Refer to MFC TechNote 64 for more information.
// If your control does not conform to the apartment-model rules, then
// you must modify the code below, changing the 6th parameter from
// afxRegApartmentThreading to 0.
if (bRegister)
return AfxOleRegisterControlClass(
AfxGetInstanceHandle(),
m_clsid,
m_lpszProgID,
IDS_LOGUI,
IDB_LOGUI,
afxRegApartmentThreading,
_dwLogUIOleMisc,
_tlid,
_wVerMajor,
_wVerMinor);
else
return AfxOleUnregisterClass(m_clsid, m_lpszProgID);
}
/////////////////////////////////////////////////////////////////////////////
// CLogUICtrl::CLogUICtrl - Constructor
CLogUICtrl::CLogUICtrl():
m_fUpdateFont( FALSE ),
m_fComboInit( FALSE ),
m_hAccel( NULL ),
m_cAccel( 0 )
{
InitializeIIDs(&IID_DLogUI, &IID_DLogUIEvents);
}
/////////////////////////////////////////////////////////////////////////////
// CLogUICtrl::~CLogUICtrl - Destructor
CLogUICtrl::~CLogUICtrl()
{
if ( m_hAccel )
DestroyAcceleratorTable( m_hAccel );
m_hAccel = NULL;
}
/////////////////////////////////////////////////////////////////////////////
// CLogUICtrl::OnDraw - Drawing function
void CLogUICtrl::OnDraw(CDC* pdc, const CRect& rcBounds, const CRect& rcInvalid)
{
DoSuperclassPaint(pdc, rcBounds);
}
/////////////////////////////////////////////////////////////////////////////
// CLogUICtrl::DoPropExchange - Persistence support
void CLogUICtrl::DoPropExchange(CPropExchange* pPX)
{
ExchangeVersion(pPX, MAKELONG(_wVerMinor, _wVerMajor));
COleControl::DoPropExchange(pPX);
}
/////////////////////////////////////////////////////////////////////////////
// CLogUICtrl::OnResetState - Reset control to default state
void CLogUICtrl::OnResetState()
{
COleControl::OnResetState(); // Resets defaults found in DoPropExchange
}
/////////////////////////////////////////////////////////////////////////////
// CLogUICtrl::PreCreateWindow - Modify parameters for CreateWindowEx
BOOL CLogUICtrl::PreCreateWindow(CREATESTRUCT& cs)
{
if ( cs.style & WS_CLIPSIBLINGS )
cs.style ^= WS_CLIPSIBLINGS;
cs.lpszClass = _T("BUTTON");
return COleControl::PreCreateWindow(cs);
}
/////////////////////////////////////////////////////////////////////////////
// CLogUICtrl::IsSubclassedControl - This is a subclassed control
BOOL CLogUICtrl::IsSubclassedControl()
{
return TRUE;
}
/////////////////////////////////////////////////////////////////////////////
// CLogUICtrl::OnOcmCommand - Handle command messages
LRESULT CLogUICtrl::OnOcmCommand(WPARAM wParam, LPARAM lParam)
{
#ifdef _WIN32
WORD wNotifyCode = HIWORD(wParam);
#else
WORD wNotifyCode = HIWORD(lParam);
#endif
return 0;
}
/////////////////////////////////////////////////////////////////////////////
// CLogUICtrl message handlers
//---------------------------------------------------------------------------
// OLE Interfaced Routine
void CLogUICtrl::OnClick(USHORT iButton)
{
CWaitCursor wait;
CString sz;
sz.LoadString( IDS_LOG_ERR_TITLE );
free((void*)AfxGetApp()->m_pszAppName);
AfxGetApp()->m_pszAppName = _tcsdup(sz);
if (GetSelectedStringIID(sz))
{
IID iid;
HRESULT h = CLSIDFromString((LPTSTR)(LPCTSTR)sz, &iid);
ActivateLogProperties(iid);
}
COleControl::OnClick(iButton);
}
void CLogUICtrl::OnFontChanged()
{
m_fUpdateFont = TRUE;
COleControl::OnFontChanged();
}
void CLogUICtrl::SetAdminTarget(LPCTSTR szMachineName, LPCTSTR szMetaTarget)
{
m_szMachine = szMachineName;
m_szMetaObject = szMetaTarget;
}
void CLogUICtrl::SetUserData(LPCTSTR szName, LPCTSTR szPassword)
{
m_szUserName = szName;
m_szPassword = szPassword;
}
//---------------------------------------------------------------------------
void CLogUICtrl::ActivateLogProperties(REFIID clsidUI)
{
AFX_MANAGE_STATE(::AfxGetStaticModuleState());
IClassFactory * pcsfFactory = NULL;
HRESULT hresError;
ILogUIPlugin2 * pUI = NULL;
hresError = CoGetClassObject(clsidUI, CLSCTX_INPROC, NULL, IID_IClassFactory, (void **)&pcsfFactory);
if (SUCCEEDED(hresError))
{
hresError = pcsfFactory->CreateInstance(NULL, IID_LOGGINGUI2, (void **)&pUI);
if (SUCCEEDED(hresError))
{
CString csTempPassword;
m_szPassword.CopyTo(csTempPassword);
pcsfFactory->Release();
hresError = pUI->OnPropertiesEx(
(LPTSTR)(LPCTSTR)m_szMachine,
(LPTSTR)(LPCTSTR)m_szMetaObject,
(LPTSTR)(LPCTSTR)m_szUserName,
(LPTSTR)(LPCTSTR)csTempPassword);
pUI->Release();
}
}
}
void CLogUICtrl::ApplyLogSelection()
{
CString szName;
m_comboBox.GetWindowText( szName );
// if nothing is selected, fail
if (!szName.IsEmpty())
{
CString guid;
CString csTempPassword;
m_szPassword.CopyTo(csTempPassword);
CComAuthInfo auth(m_szMachine, m_szUserName, csTempPassword);
CMetaKey mk(&auth, NULL, METADATA_PERMISSION_READ | METADATA_PERMISSION_WRITE);
if (mk.Succeeded())
{
CMetabasePath path(TRUE, _T("logging"), szName);
mk.QueryValue(MD_LOG_PLUGIN_MOD_ID, guid, NULL, path);
}
if (!guid.IsEmpty())
{
mk.SetValue(MD_LOG_PLUGIN_ORDER, guid, NULL, m_szMetaObject);
}
}
}
//---------------------------------------------------------------------------
BOOL CLogUICtrl::GetSelectedStringIID( CString &szIID )
{
if (!m_fComboInit)
return FALSE;
BOOL bRes = FALSE;
CString szName;
m_comboBox.GetWindowText( szName );
if (!szName.IsEmpty())
{
CString log_path = _T("/lm/logging"), guid;
CString csTempPassword;
m_szPassword.CopyTo(csTempPassword);
CComAuthInfo auth(m_szMachine, m_szUserName, csTempPassword);
CMetaKey mk(&auth, log_path, METADATA_PERMISSION_READ | METADATA_PERMISSION_WRITE);
if (mk.Succeeded())
{
mk.QueryValue(MD_LOG_PLUGIN_UI_ID, szIID, NULL, szName);
bRes = mk.Succeeded();
}
}
return bRes;
}
//---------------------------------------------------------------------------
// OLE Interfaced Routine
void CLogUICtrl::SetComboBox(HWND hComboBox)
{
CString szAvailableList;
CString szCurrentModGuid;
// in case there are any errors, prepare the error string
// set the name of the application correctly
szAvailableList.LoadString( IDS_LOG_ERR_TITLE );
AfxGetApp()->m_pszAppName = _tcsdup(szAvailableList);
szAvailableList.Empty();
// attach the combo box
m_comboBox.Attach(hComboBox);
m_fComboInit = TRUE;
CString csTempPassword;
m_szPassword.CopyTo(csTempPassword);
CComAuthInfo auth(m_szMachine, m_szUserName, csTempPassword);
CMetaKey mk(&auth);
if (mk.Succeeded())
{
if (FAILED(mk.QueryValue(MD_LOG_PLUGIN_ORDER, szCurrentModGuid, NULL, m_szMetaObject)))
{
AfxMessageBox( IDS_ERR_LOG_PLUGIN );
return;
}
}
CString info;
CMetabasePath::GetServiceInfoPath(m_szMetaObject, info);
if (FAILED(mk.QueryValue(MD_LOG_PLUGINS_AVAILABLE, szAvailableList, NULL, info)))
{
AfxMessageBox( IDS_ERR_LOG_PLUGIN );
return;
}
CMetaEnumerator me(FALSE, &mk);
CMetabasePath log_path(TRUE, _T("logging"));
CString key, buf;
BOOL fFoundCurrent = FALSE;
while (SUCCEEDED(me.Next(key, log_path)))
{
int idx = 0;
if ((idx = szAvailableList.Find(key)) >= 0)
{
// Log plugin name could include "Custom Logging". Check if this is part of string.
// we should have comma before and after string
BOOL bCommaAfter =
szAvailableList.GetLength() == idx + key.GetLength()
|| szAvailableList.GetAt(idx + key.GetLength()) == _T(',');
BOOL bCommaBefore = idx == 0 || szAvailableList.GetAt(idx - 1) == _T(',');
if (!fFoundCurrent)
{
CMetabasePath current_path(FALSE, log_path, key);
mk.QueryValue(MD_LOG_PLUGIN_MOD_ID, buf, NULL, current_path);
fFoundCurrent = (buf == szCurrentModGuid);
if (fFoundCurrent)
{
buf = key;
}
}
if (bCommaBefore && bCommaAfter)
{
m_comboBox.AddString(key);
}
}
}
// select the current item in the combo box
m_comboBox.SelectString(-1, buf);
}
//---------------------------------------------------------------------------
// OLE Interfaced Routine
void CLogUICtrl::Terminate()
{
if ( m_fComboInit )
m_comboBox.Detach();
m_fComboInit = FALSE;
}
//------------------------------------------------------------------------
void CLogUICtrl::OnAmbientPropertyChange(DISPID dispid)
{
BOOL flag;
UINT style;
// do the right thing depending on the dispid
switch ( dispid )
{
case DISPID_AMBIENT_DISPLAYASDEFAULT:
if ( GetAmbientProperty( DISPID_AMBIENT_DISPLAYASDEFAULT, VT_BOOL, &flag ) )
{
style = GetWindowLong(
GetSafeHwnd(), // handle of window
GWL_STYLE // offset of value to retrieve
);
if ( flag )
style |= BS_DEFPUSHBUTTON;
else
style ^= BS_DEFPUSHBUTTON;
SetWindowLong(
GetSafeHwnd(), // handle of window
GWL_STYLE, // offset of value to retrieve
style
);
Invalidate(TRUE);
}
break;
};
COleControl::OnAmbientPropertyChange(dispid);
}
//------------------------------------------------------------------------
// an important method where we tell the container how to deal with us.
// pControlInfo is passed in by the container, although we are responsible
// for maintining the hAccel structure
void CLogUICtrl::OnGetControlInfo(LPCONTROLINFO pControlInfo)
{
if ( !pControlInfo || pControlInfo->cb < sizeof(CONTROLINFO) )
return;
pControlInfo->hAccel = m_hAccel;
pControlInfo->cAccel = m_cAccel;
pControlInfo->dwFlags = CTRLINFO_EATS_RETURN;
}
//------------------------------------------------------------------------
// the ole control container object specifically filters out the space
// key so we do not get it as a OnMnemonic call. Thus we need to look
// for it ourselves
void CLogUICtrl::OnKeyUpEvent(USHORT nChar, USHORT nShiftState)
{
if ( nChar == _T(' ') )
{
OnClick((USHORT)GetDlgCtrlID());
}
COleControl::OnKeyUpEvent(nChar, nShiftState);
}
//------------------------------------------------------------------------
void CLogUICtrl::OnMnemonic(LPMSG pMsg)
{
OnClick((USHORT)GetDlgCtrlID());
COleControl::OnMnemonic(pMsg);
}
//------------------------------------------------------------------------
void CLogUICtrl::OnTextChanged()
{
// get the new text
CString sz = InternalGetText();
// set the accelerator table
SetAccelTable((LPCTSTR)sz);
if ( SetAccelTable((LPCTSTR)sz) )
// make sure the new accelerator table gets loaded
ControlInfoChanged();
// finish with the default handling.
COleControl::OnTextChanged();
}
//------------------------------------------------------------------------
BOOL CLogUICtrl::SetAccelTable( LPCTSTR pszCaption )
{
BOOL fAnswer = FALSE;
ACCEL accel;
int iAccel;
// get the new text
CString sz = pszCaption;
sz.MakeLower();
// if the handle has already been allocated, free it
if ( m_hAccel )
{
DestroyAcceleratorTable( m_hAccel );
m_hAccel = NULL;
m_cAccel = 0;
}
// if there is a & character, then declare the accelerator
iAccel = sz.Find(_T('&'));
if ( iAccel >= 0 )
{
// fill in the accererator record
accel.fVirt = FALT;
accel.key = sz.GetAt(iAccel + 1);
accel.cmd = (USHORT)GetDlgCtrlID();
m_hAccel = CreateAcceleratorTable( &accel, 1 );
if ( m_hAccel )
m_cAccel = 1;
fAnswer = TRUE;
}
// return the answer
return fAnswer;
}
| 28.56102 | 103 | 0.578954 | [
"object",
"model"
] |
7ff8a92b6ac3a17ce64935962186be924bf0a9a6 | 2,276 | hpp | C++ | src/type-safety/Xform.hpp | mikosz/type-safety | c5d30e620246c357dd97a71adca0443cb01b7064 | [
"MIT"
] | 2 | 2019-08-19T10:17:50.000Z | 2019-08-26T12:57:04.000Z | src/type-safety/Xform.hpp | mikosz/type-safety | c5d30e620246c357dd97a71adca0443cb01b7064 | [
"MIT"
] | null | null | null | src/type-safety/Xform.hpp | mikosz/type-safety | c5d30e620246c357dd97a71adca0443cb01b7064 | [
"MIT"
] | null | null | null | #pragma once
#include <type_traits>
#include <stdexcept>
#include "CompressedPair.hpp"
#include "Matrix.hpp"
#include "Point.hpp"
#include "space.hpp"
namespace type_safety {
template <class FromSpaceT, class ToSpaceT>
class Xform : CompressedPair<FromSpaceT, ToSpaceT> {
public:
template <class... SpaceParams>
Xform(SpaceParams&&... spaceParams) :
CompressedPair<FromSpaceT, ToSpaceT>(std::forward<SpaceParams>(spaceParams)...)
{
}
template <class... SpaceParams>
Xform(Matrix matrix, SpaceParams&&... spaceParams) :
CompressedPair<FromSpaceT, ToSpaceT>(std::forward<SpaceParams>(spaceParams)...),
matrix_(std::move(matrix))
{
}
Point<ToSpaceT> apply(const Point<FromSpaceT>& p) const {
checkSpacesMatch(fromSpace(), p.space());
auto result = Point<ToSpaceT>{toSpace()};
multiplyAndSet(result.vector(), matrix_, p.vector());
return result;
}
Vector<ToSpaceT> apply(const Vector<FromSpaceT>& v) const {
checkSpacesMatch(fromSpace(), v.space());
auto result = Vector<ToSpaceT>{toSpace()};
multiplyAndSet(result.vector(), matrix_, v.vector());
return result;
}
decltype(auto) fromSpace() const {
return CompressedPair<FromSpaceT, ToSpaceT>::first();
}
decltype(auto) toSpace() const {
return CompressedPair<FromSpaceT, ToSpaceT>::second();
}
Matrix& matrix() {
return matrix_;
}
const Matrix& matrix() const {
return matrix_;
}
private:
Matrix matrix_;
};
template <class FromSpace, class ToSpace>
inline auto makeXform(FromSpace fromSpace, ToSpace toSpace) {
return Xform<FromSpace, ToSpace>{std::move(fromSpace), std::move(toSpace)};
}
template <class FromSpace, class ToSpace>
inline auto makeXform(Matrix matrix, FromSpace fromSpace, ToSpace toSpace) {
return Xform<FromSpace, ToSpace>{std::move(matrix), std::move(fromSpace), std::move(toSpace)};
}
template <class LhsFromSpaceT, class LhsToSpaceT, class RhsFromSpaceT, class RhsToSpaceT>
inline auto inSequence(
const Xform<LhsFromSpaceT, LhsToSpaceT>& lhs,
const Xform<RhsFromSpaceT, RhsToSpaceT>& rhs
) {
checkSpacesMatch(lhs.toSpace(), rhs.fromSpace());
auto result = Xform<LhsFromSpaceT, RhsToSpaceT>{lhs.fromSpace(), rhs.toSpace()};
multiplyAndSet(result.matrix(), rhs.matrix(), lhs.matrix());
return result;
}
} // namespace type_safety
| 25.863636 | 95 | 0.732865 | [
"vector"
] |
7fff7bfc77bf4f2b08fe9db8cf37de1f85f2f014 | 802 | cpp | C++ | h2o_plant.cpp | antonte/terraform | 40efa22e21f3219f8ff498c13ed9a15b4ba1c114 | [
"MIT"
] | null | null | null | h2o_plant.cpp | antonte/terraform | 40efa22e21f3219f8ff498c13ed9a15b4ba1c114 | [
"MIT"
] | null | null | null | h2o_plant.cpp | antonte/terraform | 40efa22e21f3219f8ff498c13ed9a15b4ba1c114 | [
"MIT"
] | 1 | 2019-04-10T03:48:19.000Z | 2019-04-10T03:48:19.000Z | #include "h2o_plant.hpp"
#include "rend.hpp"
#include "terrain.hpp"
#include "world.hpp"
#include <shade/shader_program.hpp>
#include <shade/obj.hpp>
#define GLM_ENABLE_EXPERIMENTAL
#include <glm/gtx/transform.hpp>
H2OPlant::H2OPlant(World &world, int lifeSpan, int aProdRate, float x, float y)
: Entity(world, x, y), prodRate(aProdRate)
{
world.sched([this]() { this->world->kill(*this); }, lifeSpan);
// TODO fix rounding issue
world.h2ORate += prodRate / 100;
}
H2OPlant::~H2OPlant()
{
// TODO fix rounding issue
world->h2ORate -= prodRate / 100;
}
void H2OPlant::draw(Rend &rend)
{
rend.shad->use();
rend.mvp = glm::translate(glm::vec3(x, y, world->terrain->getZ(x, y)));
rend.mvp.update();
rend.h2OPlantObj->draw();
}
int H2OPlant::getMatter() const
{
return Matter;
}
| 21.105263 | 79 | 0.683292 | [
"transform"
] |
3d05b0a53111b55980456afc5d478b40fb2a3e97 | 1,630 | hh | C++ | construct/detail/XMLUtils.hh | celeritas-project/orange-port | 9aa2d36984a24a02ed6d14688a889d4266f7b1af | [
"Apache-2.0",
"MIT"
] | null | null | null | construct/detail/XMLUtils.hh | celeritas-project/orange-port | 9aa2d36984a24a02ed6d14688a889d4266f7b1af | [
"Apache-2.0",
"MIT"
] | null | null | null | construct/detail/XMLUtils.hh | celeritas-project/orange-port | 9aa2d36984a24a02ed6d14688a889d4266f7b1af | [
"Apache-2.0",
"MIT"
] | null | null | null | //---------------------------------*-C++-*-----------------------------------//
/*!
* \file construct/detail/XMLUtils.hh
* \brief XMLUtils class declaration
* \note Copyright (c) 2021 Oak Ridge National Laboratory, UT-Battelle, LLC.
*/
//---------------------------------------------------------------------------//
#pragma once
#include <memory>
#include <string>
#include "base/Provenance.hh"
#include "orange/Definitions.hh"
#include "orange/query/ObjectMetadata.hh"
namespace Teuchos
{
class ParameterList;
}
namespace celeritas
{
class PlacedShape;
namespace detail
{
//---------------------------------------------------------------------------//
// Build metadata from a plist (name, optional description, provenance)
ObjectMetadata build_md(const Teuchos::ParameterList& plist);
// Build a shape from the given plist
std::shared_ptr<const PlacedShape> build_shape(const Teuchos::ParameterList&);
// Get a 3-vector of doubles from a plist item
Real3 get_space_vector(const Teuchos::ParameterList&, const std::string& key);
// Get a 3-vector of indices from a plist item
Array<def::size_type, 3>
get_dim_vector(const Teuchos::ParameterList& plist, const std::string& key);
// Get a 3x3 matrix from a plist item
SpaceMatrix
get_space_matrix(const Teuchos::ParameterList&, const std::string& key);
// Construct a transform from translate/rotate
Transform build_transform(const Teuchos::ParameterList&);
//---------------------------------------------------------------------------//
} // namespace detail
} // namespace celeritas
//---------------------------------------------------------------------------//
| 31.346154 | 79 | 0.579755 | [
"shape",
"vector",
"transform"
] |
3d110353e301c0188c5554e37a6bb53bf9327b11 | 645 | cpp | C++ | Dataset/Leetcode/train/4/165.cpp | kkcookies99/UAST | fff81885aa07901786141a71e5600a08d7cb4868 | [
"MIT"
] | null | null | null | Dataset/Leetcode/train/4/165.cpp | kkcookies99/UAST | fff81885aa07901786141a71e5600a08d7cb4868 | [
"MIT"
] | null | null | null | Dataset/Leetcode/train/4/165.cpp | kkcookies99/UAST | fff81885aa07901786141a71e5600a08d7cb4868 | [
"MIT"
] | null | null | null | class Solution {
public:
double XXX(vector<int>& nums1, vector<int>& nums2) {
int m = nums1.size(), n = nums2.size();
vector<int> num(m+n);
int l = 0, r = 0;
for (int i = 0; i < m+n; ++i) {
if (l == m)
num[i] = nums2[r++];
else if (r == n)
num[i] = nums1[l++];
else if (nums1[l] < nums2[r])
num[i] = nums1[l++];
else
num[i] = nums2[r++];
}
if ((m+n)%2 == 0)
return (double)(num[(m+n)/2] + num[(m+n)/2 - 1])/2;
else
return num[(m+n)/2];
}
};
| 24.807692 | 63 | 0.362791 | [
"vector"
] |
3d18237020a582787577eae7ae06f686e3e4f11d | 13,072 | cpp | C++ | Source/Foundation/bsfCore/Network/BsNetwork.cpp | ValtoFrameworks/bsf | bb7a21e813a400dfdb8473dc3827e8e75150de99 | [
"MIT"
] | 2 | 2019-07-08T17:26:25.000Z | 2019-10-13T19:15:28.000Z | Source/Foundation/bsfCore/Network/BsNetwork.cpp | ValtoFrameworks/bsf | bb7a21e813a400dfdb8473dc3827e8e75150de99 | [
"MIT"
] | null | null | null | Source/Foundation/bsfCore/Network/BsNetwork.cpp | ValtoFrameworks/bsf | bb7a21e813a400dfdb8473dc3827e8e75150de99 | [
"MIT"
] | 4 | 2019-06-23T09:55:47.000Z | 2019-07-08T17:23:05.000Z | //************************************ bs::framework - Copyright 2019 Marko Pintera **************************************//
//*********** Licensed under the MIT license. See LICENSE.md for full terms. This notice is not to be removed. ***********//
#include "BsNetwork.h"
#include "RakNet/RakPeer.h"
#include "RakNet/MessageIdentifiers.h"
#include "Allocators/BsPoolAlloc.h"
using namespace RakNet;
namespace bs
{
static_assert(NETWORK_USER_MESSAGE_ID == ID_USER_PACKET_ENUM, "");
/** Converts a RakNet SystemAddress into the framework's NetworkAddress type. */
void systemToNetworkAddress(const SystemAddress& address, NetworkAddress& output)
{
if(address.address.addr4.sin_family == AF_INET)
{
output.ipType = IPV4;
output.port = address.address.addr4.sin_port;
memcpy(output.ip, &address.address.addr4.sin_addr, 4);
}
else
{
output.ipType = IPV6;
output.port = address.address.addr6.sin6_port;
output.ip6FlowInfo = address.address.addr6.sin6_flowinfo;
output.ip6ScopeId = address.address.addr6.sin6_scope_id;
memcpy(output.ip, &address.address.addr6.sin6_addr, 16);
}
}
/**
* Same as systemToNetworkAddress(const SystemAddress&, NetworkAddress&) except it returns a brand new NetworkAddress
* object.
*/
NetworkAddress systemToNetworkAddress(const SystemAddress& address)
{
NetworkAddress output;
systemToNetworkAddress(address, output);
return output;
}
/** Converts the framework's NetworkAddress into RakNet's SystemAddres type. */
SystemAddress networkToSystemAddress(const NetworkAddress& address)
{
SystemAddress output;
output.address.addr4.sin_port = address.port;
if(address.ipType == IPV4)
{
output.address.addr4.sin_family = AF_INET;
memcpy(&output.address.addr4.sin_addr, address.ip, 4);
}
else
{
output.address.addr6.sin6_family = AF_INET6;
output.address.addr6.sin6_flowinfo = (ULONG)address.ip6FlowInfo;
output.address.addr6.sin6_scope_id = (ULONG)address.ip6ScopeId;
memcpy(&output.address.addr6.sin6_addr, address.ip, 16);
}
return output;
}
/** Converts PacketChannel reliability, priority and ordering into equivalent RakNet enums. */
void mapChannelToRakNet(const PacketChannel& channel, ::PacketReliability& reliability, ::PacketPriority& priority)
{
switch(channel.priority)
{
case PacketPriority::Immediate:
priority = IMMEDIATE_PRIORITY;
break;
case PacketPriority::High:
priority = HIGH_PRIORITY;
break;
default:
case PacketPriority::Medium:
priority = MEDIUM_PRIORITY;
break;
case PacketPriority::Low:
priority = LOW_PRIORITY;
break;
}
if(channel.reliability == PacketReliability::Unreliable)
{
if(channel.ordering == PacketOrdering::Ordered || channel.ordering == PacketOrdering::Sequenced)
reliability = UNRELIABLE_SEQUENCED;
else
reliability = UNRELIABLE;
}
else
{
switch(channel.ordering)
{
default:
case PacketOrdering::Unordered:
reliability = RELIABLE;
break;
case PacketOrdering::Ordered:
reliability = RELIABLE_ORDERED;
break;
case PacketOrdering::Sequenced:
reliability = RELIABLE_SEQUENCED;
break;
}
}
}
NetworkAddress NetworkAddress::UNASSIGNED;
NetworkAddress::NetworkAddress(const char* address)
{
SystemAddress sysAddress(address);
systemToNetworkAddress(sysAddress, *this);
}
NetworkAddress::NetworkAddress(const char* ip, UINT16 port)
{
SystemAddress sysAddress(ip, port);
systemToNetworkAddress(sysAddress, *this);
}
String NetworkAddress::toString(bool withPort) const
{
SystemAddress sysAddress = networkToSystemAddress(*this);
return String(sysAddress.ToString(withPort, '|'));
}
bool NetworkAddress::compareIP(const NetworkAddress& other) const
{
if(ipType != other.ipType)
return false;
if(ipType == IPV4)
return memcmp(ip, other.ip, 4) == 0;
return (memcmp(ip, other.ip, sizeof(ip)) == 0 && ip6FlowInfo == other.ip6FlowInfo && ip6ScopeId == other.ip6ScopeId);
}
NetworkAddress& NetworkAddress::operator= (const NetworkAddress& rhs)
{
ipType = rhs.ipType;
port = rhs.port;
ip6FlowInfo = rhs.ip6FlowInfo;
ip6ScopeId = rhs.ip6ScopeId;
memcpy(&ip, &rhs.ip, sizeof(ip));
return *this;
}
bool NetworkAddress::operator==(const NetworkAddress& rhs) const
{
return port == rhs.port && compareIP(rhs);
}
bool NetworkAddress::operator!=(const NetworkAddress& rhs) const
{
return !(*this==rhs);
}
/** Contains information associated with a single connected peer. */
struct NetworkConnection
{
NetworkId id;
NetworkAddress networkAddress;
SystemAddress systemAddress;
RakNetGUID guid;
};
struct NetworkPeer::Pimpl
{
RakPeerInterface* peer;
Vector<NetworkConnection> networkIdMapping;
PoolAlloc<sizeof(NetworkEvent)> eventPool;
/** Maps a network ID into a RakNet system address. Returns null if the ID is not valid. */
const SystemAddress* getSystemAddress(const NetworkId& id)
{
if(id.id < 0 || id.id >= (INT32)networkIdMapping.size())
return nullptr;
return &networkIdMapping[id.id].systemAddress;
}
/** Maps a network ID into a RakNet GUID. Returns null if the ID is not valid. */
const RakNetGUID* getGUID(const NetworkId& id)
{
if(id.id < 0 || id.id >= (INT32)networkIdMapping.size())
return nullptr;
return &networkIdMapping[id.id].guid;
}
/**
* Using a RakNet address or a GUID, attempts to retrieve a network ID, or allocates a new ID if one cannot be
* found.
*/
NetworkId getOrRegisterNetworkId(const SystemAddress& address, const RakNetGUID& guid)
{
INT32 systemIndex = address.systemIndex;
assert(systemIndex >= 0 && systemIndex < (INT32)networkIdMapping.size());
NetworkConnection& connection = networkIdMapping[systemIndex];
if(connection.systemAddress != address || connection.guid != guid)
{
connection.networkAddress = systemToNetworkAddress(address);
connection.systemAddress = address;
connection.guid = guid;
}
return connection.id;
}
/** Allocates a new network event, responsible for reporting data received in @p packet. */
NetworkEvent* allocNetworkEvent(Packet* packet)
{
NetworkEvent* event = eventPool.construct<NetworkEvent>();
event->_backendData = packet;
event->sender = getOrRegisterNetworkId(packet->systemAddress, packet->guid);
switch (packet->data[0])
{
case ID_CONNECTION_REQUEST_ACCEPTED:
event->type = NetworkEventType::ConnectingDone;
break;
case ID_CONNECTION_ATTEMPT_FAILED:
event->type = NetworkEventType::ConnectingFailed;
break;
case ID_ALREADY_CONNECTED:
event->type = NetworkEventType::AlreadyConnected;
break;
case ID_NEW_INCOMING_CONNECTION:
event->type = NetworkEventType::IncomingNew;
break;
case ID_NO_FREE_INCOMING_CONNECTIONS:
event->type = NetworkEventType::IncomingNoFree;
break;
case ID_DISCONNECTION_NOTIFICATION:
event->type = NetworkEventType::Disconnected;
break;
case ID_CONNECTION_LOST:
event->type = NetworkEventType::LostConnection;
break;
default:
event->type = NetworkEventType::Data;
event->data.bytes = packet->data;
event->data.length = packet->length;
break;
}
return event;
}
/** Frees an event allocated with allocNetworkEvent(). */
void freeNetworkEvent(NetworkEvent* event)
{
Packet* packet = (Packet*)event->_backendData;
peer->DeallocatePacket(packet);
eventPool.free(event);
}
};
NetworkPeer::NetworkPeer(const NETWORK_PEER_DESC& desc)
:m(bs_new<Pimpl>())
{
m->peer = RakPeerInterface::GetInstance();
m->networkIdMapping.resize(desc.maxNumConnections);
for(INT32 i = 0; i < (INT32)m->networkIdMapping.size(); i++)
m->networkIdMapping[i].id = NetworkId(i);
UINT32 numDescriptors = (UINT32)desc.listenAddresses.size();
SocketDescriptor* descriptors = bs_stack_alloc<SocketDescriptor>(numDescriptors);
for(UINT32 i = 0; i < numDescriptors; i++)
{
const NetworkAddress& address = desc.listenAddresses[i];
if(address.compareIP(NetworkAddress::UNASSIGNED))
{
if(address.port == 0)
descriptors[i] = SocketDescriptor();
else
descriptors[i] = SocketDescriptor(address.port, nullptr);
}
else
{
if(address.ipType == IPV6)
{
LOGERR("IPV6 not supported for listener addreses on this backend");
descriptors[i] = SocketDescriptor();
}
else // IPV4
{
String addressStr = address.toString();
descriptors[i] = SocketDescriptor(address.port, addressStr.c_str());
}
}
}
StartupResult result = m->peer->Startup(desc.maxNumConnections, descriptors, numDescriptors);
bs_stack_free(descriptors);
switch(result)
{
case RAKNET_ALREADY_STARTED:
LOGWRN("Failed to start RakNet peer, RakNet already started.");
break;
case INVALID_SOCKET_DESCRIPTORS:
LOGERR("Failed to start RakNet peer, invalid socket descriptors provided.");
break;
case INVALID_MAX_CONNECTIONS:
LOGERR("Failed to start RakNet peer, invalid max. connection count provided.");
break;
case SOCKET_FAMILY_NOT_SUPPORTED:
LOGERR("Failed to start RakNet peer, socket family not supported.");
break;
case SOCKET_PORT_ALREADY_IN_USE:
LOGERR("Failed to start RakNet peer, port already in use.");
break;
case SOCKET_FAILED_TO_BIND:
LOGERR("Failed to start RakNet peer, socket failed to bind.");
break;
case SOCKET_FAILED_TEST_SEND:
LOGERR("Failed to start RakNet peer, socket failed to test send.");
break;
case PORT_CANNOT_BE_ZERO:
LOGERR("Failed to start RakNet peer, port cannot be zero.");
break;
case FAILED_TO_CREATE_NETWORK_THREAD:
LOGERR("Failed to start RakNet peer, failed to create the network thread.");
break;
case COULD_NOT_GENERATE_GUID:
LOGERR("Failed to start RakNet peer, failed to generate GUID.");
break;
case STARTUP_OTHER_FAILURE:
LOGERR("Failed to start RakNet peer, unknown failure.");
break;
default:
break;
}
if(desc.maxNumIncomingConnections > 0)
m->peer->SetMaximumIncomingConnections(desc.maxNumIncomingConnections);
}
NetworkPeer::~NetworkPeer()
{
RakPeerInterface::DestroyInstance(m->peer);
bs_delete(m);
}
bool NetworkPeer::connect(const char* host, UINT16 port)
{
ConnectionAttemptResult result = m->peer->Connect(host, port, nullptr, 0);
if(result != CONNECTION_ATTEMPT_STARTED)
{
switch(result)
{
case INVALID_PARAMETER:
LOGERR_FMT("Unable to connect to {0}|{1}, invalid parameter.", host, port);
break;
case CANNOT_RESOLVE_DOMAIN_NAME:
LOGERR_FMT("Unable to connect to {0}|{1}, domain name cannot be resolved.", host, port);
break;
case ALREADY_CONNECTED_TO_ENDPOINT:
LOGWRN_FMT("Unable to connect to {0}|{1}, already connected.", host, port);
break;
case CONNECTION_ATTEMPT_ALREADY_IN_PROGRESS:
LOGWRN_FMT("Unable to connect to {0}|{1}, connection attempt already in progress.", host, port);
break;
case SECURITY_INITIALIZATION_FAILED:
LOGERR_FMT("Unable to connect to {0}|{1}, security initialization failed.", host, port);
break;
default:
break;
}
return false;
}
return true;
}
void NetworkPeer::disconnect(const NetworkAddress& address, bool silent)
{
m->peer->CloseConnection(networkToSystemAddress(address), !silent);
}
void NetworkPeer::disconnect(const NetworkId& id, bool silent)
{
const RakNetGUID* guid = m->getGUID(id);
if(!guid)
{
LOGERR_FMT("Cannot disconnect from {0}, invalid network ID provided.", id.id);
return;
}
m->peer->CloseConnection(*guid, !silent);
}
NetworkEvent* NetworkPeer::receive() const
{
Packet* packet = m->peer->Receive();
if(!packet || packet->length == 0)
return nullptr;
return m->allocNetworkEvent(packet);
}
void NetworkPeer::free(NetworkEvent* event)
{
if(!event)
return;
m->freeNetworkEvent(event);
}
void NetworkPeer::send(const PacketData& data, const NetworkAddress& address, const PacketChannel& channel)
{
::PacketReliability reliability;
::PacketPriority priority;
mapChannelToRakNet(channel, reliability, priority);
m->peer->Send((const char*)data.bytes, (INT32)data.length, priority, reliability, 0,
networkToSystemAddress(address), false);
}
void NetworkPeer::send(const PacketData& data, const NetworkId& id, const PacketChannel& channel)
{
const RakNetGUID* guid = m->getGUID(id);
if(!guid)
{
LOGERR_FMT("Cannot send to {0}, invalid network ID provided.", id.id);
return;
}
::PacketReliability reliability;
::PacketPriority priority;
mapChannelToRakNet(channel, reliability, priority);
m->peer->Send((const char*)data.bytes, (INT32)data.length, priority, reliability, 0,
*guid, false);
}
void NetworkPeer::broadcast(const PacketData& data, const PacketChannel& channel)
{
::PacketReliability reliability;
::PacketPriority priority;
mapChannelToRakNet(channel, reliability, priority);
m->peer->Send((const char*)data.bytes, (INT32)data.length, priority, reliability, 0,
UNASSIGNED_RAKNET_GUID, true);
}
}
| 27.991435 | 124 | 0.711291 | [
"object",
"vector"
] |
3d1d945fa6c524f08e2734610fc0a2abf2bf0570 | 15,837 | cpp | C++ | src/lqr_quaternion.cpp | llanesc/lqr-tracking | 270f2f5164a668bfb77e19f5191595f1d3913a16 | [
"MIT"
] | 4 | 2020-12-17T10:00:48.000Z | 2021-08-19T22:17:36.000Z | src/lqr_quaternion.cpp | llanesc/lqr-tracking | 270f2f5164a668bfb77e19f5191595f1d3913a16 | [
"MIT"
] | 2 | 2020-11-30T18:12:36.000Z | 2021-04-28T05:08:35.000Z | src/lqr_quaternion.cpp | llanesc/lqr-tracking | 270f2f5164a668bfb77e19f5191595f1d3913a16 | [
"MIT"
] | 5 | 2020-04-22T09:00:04.000Z | 2022-03-19T09:33:58.000Z | #include "lqr_controller/lqr_quaternion.hpp"
namespace LQR {
LQR_Quaternion::LQR_Quaternion(ros::NodeHandle& nodeHandle)
: nodeHandle_(nodeHandle)
{
quadraticCost_.loadConfigFile(ros::package::getPath("lqr_controller") + "/lqrCostEuler.info", "termLQR");
Q_ = quadraticCost_.getStateWeight();
R_ = quadraticCost_.getControlWeight();
odom_sub_ = nodeHandle_.subscribe("/mavros/local_position/odom", 1, &LQR_Quaternion::topicCallback, this);
marker_pub_ = nodeHandle_.advertise<visualization_msgs::MarkerArray>("visualization_marker_array", 100);
initiated = false;
traj_index = 1;
callBack_ = ros::Time::now();
init_time_ = ros::Time::now();
}
LQR_Quaternion::~LQR_Quaternion()
{
}
void LQR_Quaternion::topicCallback(const nav_msgs::Odometry::ConstPtr& msg)
{
setStates(msg,x_);
setTrajectoryReference(xref_,uref_);
//Eigen::Vector4d static_ref(0,0,1,0);
//setStaticReference(xref_,uref_,static_ref);
setError(xref_,x_,xerror_);
marker_pub_.publish(markers_);
if ((ros::Time::now().toSec() - callBack_.toSec()) > 0.1)
{
A_ = A_quadrotor(xref_,uref_);
B_ = B_quadrotor(xref_,uref_);
if (lqrSolver_.compute(Q_, R_, A_, B_, Knew_))
{
if (!Knew_.hasNaN())
{
Kold_ = Knew_;
}
}
std::cout << "A matrix:" << std::endl << A_ << std::endl;
std::cout << "B matrix:" << std::endl << B_ << std::endl;
std::cout << "LQR gain matrix:" << std::endl << Kold_ << std::endl;
std::cout << "Reference:" << std::endl << xref_ << std::endl;
callBack_ = ros::Time::now();
}
}
state_matrix_t LQR_Quaternion::A_quadrotor(const state_vector_t& x, const control_vector_t& u)
{
double wx = u(0);
double wy = u(1);
double wz = u(2);
double norm_thrust = u(3);
Eigen::Quaternion<double> q(x(3),x(4),x(5),x(6));
Eigen::Matrix<double,4,4> q_partial_correction;
Eigen::Matrix<double,4,4> dqdot_dq;
Eigen::Matrix<double,3,4> dvdot_dq;
Eigen::Matrix<double,4,1> q_vec;
q_vec(0) = q.w();
q_vec(1) = q.x();
q_vec(2) = q.y();
q_vec(3) = q.z();
state_matrix_t A;
A.setZero();
//Position
A(0,7) = 1;
A(1,8)= 1;
A(2,9)= 1;
Eigen::Matrix<double,4,4> Identity;
//Orientation
q_partial_correction = pow(q.norm(),-1.0)*(Identity.Identity() - pow(q.norm(),-2.0)*(q_vec * q_vec.transpose()));
dqdot_dq << 0, -wx, -wy, -wz,
wx, 0, wz, -wy,
wy, -wz, 0, wx,
wz, wy, -wx, 0;
dqdot_dq = 0.5*dqdot_dq*q_partial_correction;
A(3,3) = dqdot_dq(0,0);
A(3,4) = dqdot_dq(0,1);
A(3,5) = dqdot_dq(0,2);
A(3,6) = dqdot_dq(0,3);
A(4,3) = dqdot_dq(1,0);
A(4,4) = dqdot_dq(1,1);
A(4,5) = dqdot_dq(1,2);
A(4,6) = dqdot_dq(1,3);
A(5,3) = dqdot_dq(2,0);
A(5,4) = dqdot_dq(2,1);
A(5,5) = dqdot_dq(2,2);
A(5,6) = dqdot_dq(2,3);
A(6,3) = dqdot_dq(3,0);
A(6,4) = dqdot_dq(3,1);
A(6,5) = dqdot_dq(3,2);
A(6,6) = dqdot_dq(3,3);
//Velocity
dvdot_dq << q.y(), q.z(), q.w(), q.x(),
-q.x(), -q.w(), q.z(), q.y(),
q.w(), -q.x(), -q.y(), q.z();
dvdot_dq = 2*norm_thrust*dvdot_dq*q_partial_correction;
A(7,3) = dvdot_dq(0,0);
A(7,4) = dvdot_dq(0,1);
A(7,5) = dvdot_dq(0,2);
A(7,6) = dvdot_dq(0,3);
A(8,3) = dvdot_dq(1,0);
A(8,4) = dvdot_dq(1,1);
A(8,5) = dvdot_dq(1,2);
A(8,6) = dvdot_dq(1,3);
A(9,3) = dvdot_dq(2,0);
A(9,4) = dvdot_dq(2,1);
A(9,5) = dvdot_dq(2,2);
A(9,6) = dvdot_dq(2,3);
return A;
}
control_gain_matrix_t LQR_Quaternion::B_quadrotor(const state_vector_t& x, const control_vector_t& u)
{
double wx = u(0);
double wy = u(1);
double wz = u(2);
double norm_thrust = u(3);
Eigen::Quaternion<double> q(x(3),x(4),x(5),x(6));
Eigen::Matrix<double,3,1> dvdot_dc;
Eigen::Matrix<double,4,3> dqdot_dw;
control_gain_matrix_t B;
B.setZero();
dvdot_dc << 2*(q.w()*q.y() + q.x()*q.z()),
2*(q.y()*q.z() - q.w()*q.x()),
pow(q.w(),2) - pow(q.x(),2) - pow(q.y(),2) + pow(q.z(),2);
B(7,3) = dvdot_dc(0);
B(8,3) = dvdot_dc(1);
B(9,3) = dvdot_dc(2);
dqdot_dw << -q.x(), -q.y(), -q.z(),
q.w(), -q.z(), q.y(),
q.z(), q.w(), -q.x(),
-q.y(), q.x(), q.w();
dqdot_dw = 0.5*dqdot_dw;
B(3,0) = dqdot_dw(0,0);
B(3,1) = dqdot_dw(0,1);
B(3,2) = dqdot_dw(0,2);
B(4,0) = dqdot_dw(1,0);
B(4,1) = dqdot_dw(1,1);
B(4,2) = dqdot_dw(1,2);
B(5,0) = dqdot_dw(2,0);
B(5,1) = dqdot_dw(2,1);
B(5,2) = dqdot_dw(2,2);
B(6,0) = dqdot_dw(3,0);
B(6,1) = dqdot_dw(3,1);
B(6,2) = dqdot_dw(3,2);
return B;
}
void LQR_Quaternion::setStates(const nav_msgs::Odometry::ConstPtr& msg, state_vector_t& x)
{
position_enu_ << msg->pose.pose.position.x,
msg->pose.pose.position.y,
msg->pose.pose.position.z;
q_enu_.w() = msg->pose.pose.orientation.w;
q_enu_.x() = msg->pose.pose.orientation.x;
q_enu_.y() = msg->pose.pose.orientation.y;
q_enu_.z() = msg->pose.pose.orientation.z;
velocity_enu_ << msg->twist.twist.linear.x,
msg->twist.twist.linear.y,
msg->twist.twist.linear.z;
velocity_enu_ = mavros::ftf::transform_frame_baselink_enu(velocity_enu_,q_enu_);
/*Position*/
x(0) = position_enu_(0);
x(1) = position_enu_(1);
x(2) = position_enu_(2);
/*Orientation*/
x(3) = q_enu_.w();
x(4) = q_enu_.x();
x(5) = q_enu_.y();
x(6) = q_enu_.z();
/*Linear Velocities*/
x(7) = velocity_enu_(0);
x(8) = velocity_enu_(1);
x(9) = velocity_enu_(2);
}
void LQR_Quaternion::setError(const state_vector_t& xref, const state_vector_t& x, state_vector_t& xerror)
{
/*Position error*/
xerror(0) = (x(0) - xref(0));
xerror(1) = (x(1) - xref(1));
xerror(2) = (x(2) - xref(2));
/*Orientation error*/
Eigen::Quaterniond q(x(3),x(4),x(5),x(6));
Eigen::Quaterniond qref(xref(3),xref(4),xref(5),xref(6));
Eigen::Quaterniond qerror = q.inverse() * qref;
xerror(3) = 0;
xerror(4) = qerror.x();
xerror(5) = qerror.y();
xerror(6) = qerror.z();
/*Velocity error*/
xerror(7) = (x(7) - xref(7));
xerror(8) = (x(8) - xref(8));
xerror(9) = (x(9) - xref(9));
}
bool LQR_Quaternion::setTrajectoryReference(state_vector_t& xref,control_vector_t& uref)
{
if (!initiated)
{
generateTrajectory(states_);
}
initiated = true;
Eigen::Vector3d position_ref_enu;
Eigen::Vector3d accel;
Eigen::Vector3d orient_yaw;
Eigen::Vector3d thrust;
Eigen::Vector3d thrust_dir;
Eigen::Quaterniond q_yaw;
Eigen::Vector3d rpy_ref_enu;
Eigen::Quaterniond qref_enu;
Eigen::Vector3d velocity_enu;
std::vector<double> gamma;
gamma.resize(states_.size()-1);
std::vector<double> dist_traj;
dist_traj.resize(states_.size()-1);
int i = traj_index - 1;
do {
i++;
Eigen::Vector3d distance_vec(states_[i].position_W - states_[i-1].position_W);
gamma[i-1] = (distance_vec.dot(position_enu_ - states_[i-1].position_W)/pow(distance_vec.norm(),2));
dist_traj[i-1] = ((states_[i].position_W - position_enu_).norm());
} while (i < states_.size() - 1);
if (traj_index > (states_.size() - 5))
{
traj_index = states_.size() - 1;
position_ref_enu = states_[traj_index].position_W;
/*Position*/
xref(0) = position_ref_enu.x();
xref(1) = position_ref_enu.y();
xref(2) = position_ref_enu.z();
/*Orientation*/
xref(3) = states_[traj_index].orientation_W_B.w();
xref(4) = states_[traj_index].orientation_W_B.x();
xref(5) = states_[traj_index].orientation_W_B.y();
xref(6) = states_[traj_index].orientation_W_B.z();
/*Velocity*/
xref(7) = 0;
xref(8) = 0;
xref(9) = 0;
/*Body rates*/
uref(0) = 0;
uref(1) = 0;
uref(2) = 0;
uref(3) = 9.81;
std::cout<< "xref" << xref <<std::endl;
std::cout<< "uref" << uref <<std::endl;
return true;
} else {
std::vector<double>::iterator result = std::min_element(dist_traj.begin() + traj_index,dist_traj.end());
traj_index = std::distance(dist_traj.begin(),result);
std::cout<< "traj_index" << traj_index <<std::endl;
/*Position*/
position_ref_enu = states_[traj_index-1].position_W + gamma[traj_index]*(states_[traj_index].position_W - states_[traj_index-1].position_W);
/*Orientation*/
accel = (states_[traj_index-1].acceleration_W + gamma[traj_index]*(states_[traj_index].acceleration_W - states_[traj_index-1].acceleration_W));
orient_yaw = (quaternion_to_rpy_wrap(states_[traj_index-1].orientation_W_B) + gamma[traj_index]*(quaternion_to_rpy_wrap(states_[traj_index].orientation_W_B) - quaternion_to_rpy_wrap(states_[traj_index-1].orientation_W_B)));
thrust = (Eigen::Vector3d(0,0,9.81) + accel);
thrust_dir = (thrust.normalized());
q_yaw = (Eigen::AngleAxisd(orient_yaw.z(),Eigen::Vector3d(0,0,1)));
Eigen::Vector3d interm_thrust_frame(mavros::ftf::detail::transform_frame(thrust_dir,q_yaw));
//rpy_ref_enu << atan2(-1*interm_thrust_frame.y(),sqrt(pow(interm_thrust_frame.x(),2)+pow(interm_thrust_frame.z(),2))),
// atan2(interm_thrust_frame.x(),interm_thrust_frame.z()),
// orient_yaw.z();
rpy_ref_enu = (quaternion_to_rpy_wrap(states_.at(traj_index-1).orientation_W_B) + gamma[traj_index]*(quaternion_to_rpy_wrap(states_.at(traj_index).orientation_W_B) - quaternion_to_rpy_wrap(states_.at(traj_index-1).orientation_W_B)));
qref_enu = (mavros::ftf::quaternion_from_rpy(rpy_ref_enu));
/*Velocity*/
velocity_enu << states_.at(traj_index-1).velocity_W.x() + gamma[traj_index]*(states_.at(traj_index).velocity_W.x() - states_.at(traj_index-1).velocity_W.x()),
states_.at(traj_index-1).velocity_W.y() + gamma[traj_index]*(states_.at(traj_index).velocity_W.y() - states_.at(traj_index-1).velocity_W.y()),
states_.at(traj_index-1).velocity_W.z() + gamma[traj_index]*(states_.at(traj_index).velocity_W.z() - states_.at(traj_index-1).velocity_W.z());
/*Body rates*/
Eigen::Vector3d angular_velocity_des_W;
angular_velocity_des_W << states_.at(traj_index-1).angular_velocity_W + gamma[traj_index]*(states_.at(traj_index).angular_velocity_W - states_.at(traj_index-1).angular_velocity_W);
Eigen::Vector3d angular_velocity_des_B(mavros::ftf::transform_frame_enu_baselink(angular_velocity_des_W,qref_enu));
xref(0) = position_ref_enu.x();
xref(1) = position_ref_enu.y();
xref(2) = position_ref_enu.z();
xref(3) = qref_enu.w();
xref(4) = qref_enu.x();
xref(5) = qref_enu.y();
xref(6) = qref_enu.z();
xref(6) = velocity_enu.x();
xref(7) = velocity_enu.y();
xref(8) = velocity_enu.z();
uref(0) = angular_velocity_des_B.x();
uref(1) = angular_velocity_des_B.y();
uref(2) = angular_velocity_des_B.z();
uref(3) = thrust.norm();
return false;
}
}
bool LQR_Quaternion::setStaticReference(state_vector_t& xref,control_vector_t& uref, Eigen::Vector4d& flat_states)
{
Eigen::Vector3d position_ref_enu;
position_ref_enu << flat_states(0),
flat_states(1),
flat_states(2);
Eigen::Quaterniond qref_enu(mavros::ftf::quaternion_from_rpy(0,0,flat_states(3)));
/*Position*/
xref(0) = position_ref_enu.x();
xref(1) = position_ref_enu.y();
xref(2) = position_ref_enu.z();
/*Orientation*/
xref(3) = qref_enu.w();
xref(4) = qref_enu.x();
xref(5) = qref_enu.y();
xref(6) = qref_enu.z();
/*Velocity*/
xref(7) = 0;
xref(8) = 0;
xref(9) = 0;
/*Body rates*/
uref(0) = 0;
uref(1) = 0;
uref(2) = 0;
uref(3) = 9.81;
double ref_pos_diff = sqrt(pow(x_(0)-xref(0),2)+pow(x_(1)-xref(1),2)+pow(x_(2)-xref(2),2));
double ref_yaw_diff = abs(x_(6)-xref(6));
if (ref_pos_diff < 0.05 && ref_yaw_diff < 0.05)
{
return true;
} else {
return false;
}
}
Eigen::Vector3d LQR_Quaternion::quaternion_to_rpy_wrap(const Eigen::Quaterniond& q)
{
Eigen::Vector3d rpy;
double roll = atan2(2*(q.w()*q.x()+q.y()*q.z()),1-2*(pow(q.x(),2)+pow(q.y(),2)));
double pitch = asin(2*(q.w()*q.y()-q.z()*q.x()));
double yaw = atan2(2*(q.w()*q.z()+q.x()*q.y()),1-2*(pow(q.y(),2)+pow(q.z(),2)));
rpy << roll,
pitch,
yaw;
return rpy;
}
void LQR_Quaternion::generateTrajectory(mav_msgs::EigenTrajectoryPoint::Vector& states)
{
std::vector<double> segment_times;
mav_trajectory_generation::Vertex::Vector vertices;
const int deriv_to_opt = mav_trajectory_generation::derivative_order::SNAP;
mav_trajectory_generation::Trajectory trajectory;
Eigen::Vector3d rpy_enu = (quaternion_to_rpy_wrap(q_enu_));
mav_trajectory_generation::Vertex start(dimension), interm1(dimension), interm2(dimension), interm3(dimension), interm4(dimension),end(dimension);
start.makeStartOrEnd(Eigen::Vector3d(0,0,0-0.1), deriv_to_opt);
vertices.push_back(start);
interm1.addConstraint(mav_trajectory_generation::derivative_order::POSITION, Eigen::Vector3d(0,0,1));
vertices.push_back(interm1);
interm2.addConstraint(mav_trajectory_generation::derivative_order::POSITION, Eigen::Vector3d(4,4,1));
interm2.addConstraint(mav_trajectory_generation::derivative_order::VELOCITY, Eigen::Vector3d(0,1,0));
vertices.push_back(interm2);
interm3.addConstraint(mav_trajectory_generation::derivative_order::POSITION, Eigen::Vector3d(0,8,1));
interm3.addConstraint(mav_trajectory_generation::derivative_order::VELOCITY, Eigen::Vector3d(-1,0,0));
vertices.push_back(interm3);
interm4.addConstraint(mav_trajectory_generation::derivative_order::POSITION, Eigen::Vector3d(-4,4,1));
interm4.addConstraint(mav_trajectory_generation::derivative_order::VELOCITY, Eigen::Vector3d(0,-1,0));
vertices.push_back(interm4);
end.makeStartOrEnd(Eigen::Vector3d(-4,0,1), deriv_to_opt);
vertices.push_back(end);
segment_times = estimateSegmentTimes(vertices, v_max, a_max);
// mav_trajectory_generation::NonlinearOptimizationParameters parameters;
// parameters.max_iterations = 1000;
// parameters.f_rel = 0.05;
// parameters.x_rel = 0.1;
// parameters.time_penalty = 500.0;
// parameters.initial_stepsize_rel = 0.1;
// parameters.inequality_constraint_tolerance = 0.1;
// const int N = 10;
// mav_trajectory_generation::PolynomialOptimizationNonLinear<N> opt(dimension, parameters);
// opt.setupFromVertices(vertices, segment_times, deriv_to_opt);
// opt.addMaximumMagnitudeConstraint(mav_trajectory_generation::derivative_order::VELOCITY, v_max);
// opt.addMaximumMagnitudeConstraint(mav_trajectory_generation::derivative_order::ACCELERATION, a_max);
// opt.optimize();
const int N = 10;
mav_trajectory_generation::PolynomialOptimization<N> opt(dimension);
opt.setupFromVertices(vertices, segment_times, deriv_to_opt);
opt.solveLinear();
mav_trajectory_generation::Segment::Vector segments;
opt.getSegments(&segments);
opt.getTrajectory(&trajectory);
bool success = mav_trajectory_generation::sampleWholeTrajectory(trajectory, sampling_interval, &states);
double distance = 1.0;
std::string frame_id = "local_origin";
mav_trajectory_generation::drawMavSampledTrajectory(states, distance, frame_id, &markers_);
}
state_vector_t LQR_Quaternion::getError()
{
return this->xerror_;
}
ct::core::FeedbackMatrix<nStates, nControls> LQR_Quaternion::getGain()
{
return this->Kold_;
}
void LQR_Quaternion::setOutput(double output,int j)
{
this->output_(j) = output;
}
void LQR_Quaternion::setOutput(control_vector_t output)
{
this->output_ = output;
}
control_vector_t LQR_Quaternion::getOutput()
{
return this->output_;
}
state_vector_t LQR_Quaternion::getRefStates()
{
return this->xref_;
}
control_vector_t LQR_Quaternion::getTrajectoryControl()
{
return this->uref_;
}
}/* namespace LQR */
| 30.871345 | 237 | 0.647408 | [
"vector"
] |
3d238b3dc4ea1697781f02a4647d7733210deb81 | 2,482 | cpp | C++ | src/Source/SteamImageInfo.cpp | pouwelsjochem/com.coronalabs-plugin.steamworks | d4a8e04f020d213d416ab3d77fdf34ebc09194c9 | [
"MIT"
] | null | null | null | src/Source/SteamImageInfo.cpp | pouwelsjochem/com.coronalabs-plugin.steamworks | d4a8e04f020d213d416ab3d77fdf34ebc09194c9 | [
"MIT"
] | 1 | 2020-05-22T22:53:41.000Z | 2020-07-09T14:19:17.000Z | src/Source/SteamImageInfo.cpp | pouwelsjochem/com.coronalabs-plugin.steamworks | d4a8e04f020d213d416ab3d77fdf34ebc09194c9 | [
"MIT"
] | 2 | 2020-10-22T09:44:56.000Z | 2020-10-28T17:13:41.000Z | // ----------------------------------------------------------------------------
//
// SteamImageInfo.cpp
// Copyright (c) 2016 Corona Labs Inc. All rights reserved.
// This software may be modified and distributed under the terms
// of the MIT license. See the LICENSE file for details.
//
// ----------------------------------------------------------------------------
#include "SteamImageInfo.h"
extern "C"
{
# include "lua.h"
}
SteamImageInfo::SteamImageInfo()
: fImageHandle(0),
fPixelWidth(0),
fPixelHeight(0)
{
}
SteamImageInfo::~SteamImageInfo()
{
}
bool SteamImageInfo::IsValid() const
{
if ((fImageHandle != 0) && (fImageHandle != -1))
{
if ((fPixelWidth > 0) && (fPixelHeight > 0))
{
return true;
}
}
return false;
}
bool SteamImageInfo::IsNotValid() const
{
return !IsValid();
}
int SteamImageInfo::GetImageHandle() const
{
return fImageHandle;
}
uint32 SteamImageInfo::GetPixelWidth() const
{
return fPixelWidth;
}
uint32 SteamImageInfo::GetPixelHeight() const
{
return fPixelHeight;
}
bool SteamImageInfo::PushToLua(lua_State* luaStatePointer) const
{
// Validate.
if (!luaStatePointer)
{
return false;
}
// Push this object's information to Lua.
if (IsValid())
{
// Push a table of image information to Lua.
lua_createtable(luaStatePointer, 0, 3);
lua_pushinteger(luaStatePointer, fImageHandle);
lua_setfield(luaStatePointer, -2, "imageHandle");
lua_pushnumber(luaStatePointer, (double)fPixelWidth);
lua_setfield(luaStatePointer, -2, "pixelWidth");
lua_pushnumber(luaStatePointer, (double)fPixelHeight);
lua_setfield(luaStatePointer, -2, "pixelHeight");
}
else
{
// Push nil to Lua since Steam image reference is invalid.
lua_pushnil(luaStatePointer);
}
// Returning true indicates we pushed something (table or nil) to Lua.
return true;
}
SteamImageInfo SteamImageInfo::FromImageHandle(int imageHandle)
{
// Create an invalid image info object.
SteamImageInfo imageInfo;
// Fetch referenced image's info from Steam to be copied to above object if successful.
auto steamUtilsPointer = SteamUtils();
if (steamUtilsPointer)
{
uint32 pixelWidth = 0;
uint32 pixelHeight = 0;
bool wasSuccessful = steamUtilsPointer->GetImageSize(imageHandle, &pixelWidth, &pixelHeight);
if (wasSuccessful)
{
imageInfo.fImageHandle = imageHandle;
imageInfo.fPixelWidth = pixelWidth;
imageInfo.fPixelHeight = pixelHeight;
}
}
// Return a new image info object by value.
return imageInfo;
}
| 21.964602 | 95 | 0.681708 | [
"object"
] |
3d2e0da09cfc121d02060c0a6cb08ee10d0cec4e | 8,545 | cpp | C++ | gtsam/geometry/ParallaxAnglePoint3.cpp | Ellon/gtsam-3.1.0 | 7968c07cf79ff39ffce05dd7c1aadcd97d7c3c21 | [
"BSD-3-Clause"
] | 3 | 2020-03-13T21:19:55.000Z | 2020-08-11T12:14:04.000Z | gtsam/geometry/ParallaxAnglePoint3.cpp | Ellon/gtsam-3.1.0 | 7968c07cf79ff39ffce05dd7c1aadcd97d7c3c21 | [
"BSD-3-Clause"
] | null | null | null | gtsam/geometry/ParallaxAnglePoint3.cpp | Ellon/gtsam-3.1.0 | 7968c07cf79ff39ffce05dd7c1aadcd97d7c3c21 | [
"BSD-3-Clause"
] | null | null | null | /* ----------------------------------------------------------------------------
* GTSAM Copyright 2010, Georgia Tech Research Corporation,
* Atlanta, Georgia 30332-0415
* All Rights Reserved
* Authors: Frank Dellaert, et al. (see THANKS for the full author list)
* See LICENSE for the license information
* -------------------------------------------------------------------------- */
/**
* @file ParallaxAnglePoint3.cpp
* @brief 3D Parallax Angle Point
* @author Ellon P. Mendes
*/
#include "ParallaxAnglePoint3.h"
using namespace std;
namespace gtsam {
/* ************************************************************************* */
ParallaxAnglePoint3 ParallaxAnglePoint3::FromParallaxAnglePointAndAnchors(
const ParallaxAnglePoint3 &oldPoint,
const Point3 &oldMainAnchor, const Point3 &oldAssoAnchor,
const Point3 &newMainAnchor, const Point3 &newAssoAnchor)
{
Vector3 vecFromNewMain(oldPoint.directionVectorFromOtheAnchor(oldMainAnchor, oldAssoAnchor, newMainAnchor));
Vector3 vecFromNewAsso(oldPoint.directionVectorFromOtheAnchor(oldMainAnchor, oldAssoAnchor, newAssoAnchor));
Vector2 py = vec2py(vecFromNewMain);
double pitch = py(0);
double yaw = py(1);
double parallax = vectors2angle(vecFromNewMain,vecFromNewAsso);
return ParallaxAnglePoint3(pitch,yaw,parallax);
}
/* ************************************************************************* */
void ParallaxAnglePoint3::print(const string& s) const {
cout << s << *this << endl;
}
/* ************************************************************************* */
bool ParallaxAnglePoint3::equals(const ParallaxAnglePoint3 & q, double tol) const {
return (fabs(pitch_ - q.pitch() ) < tol &&
fabs(yaw_ - q.yaw() ) < tol &&
fabs(parallax_ - q.parallax()) < tol);
}
/* ************************************************************************* */
ParallaxAnglePoint3 ParallaxAnglePoint3::operator+(const ParallaxAnglePoint3& q) const {
return ParallaxAnglePoint3(pitch_ + q.pitch_,
yaw_ + q.yaw_,
parallax_ + q.parallax_);
}
/* ************************************************************************* */
ParallaxAnglePoint3 ParallaxAnglePoint3::operator-(const ParallaxAnglePoint3& q) const {
return ParallaxAnglePoint3(pitch_ - q.pitch_,
yaw_ - q.yaw_,
parallax_ - q.parallax_);
}
/* ************************************************************************* */
ParallaxAnglePoint3 ParallaxAnglePoint3::retract(const Vector& v) const
{
ParallaxAnglePoint3 point = (*this + v);
// Force parallax to be positive
if(point.parallax_ < 1e-6)
point.parallax_ = 1e-6;
return point;
}
/* ************************************************************************* */
ostream &operator<<(ostream &os, const ParallaxAnglePoint3& p) {
os << '(' << p.pitch() << ", " << p.yaw() << ", " << p.parallax() << ')';
return os;
}
/* ************************************************************************* */
Vector3 ParallaxAnglePoint3::directionVectorFromMainAnchor(
boost::optional<gtsam::Matrix&> H) const
{
if(H)
{
Matrix VEC_p(3,1), VEC_y(3,1);
Vector3 vec = py2vec(pitch(),yaw(),VEC_p,VEC_y);
H->resize(3,3);
*H << VEC_p, VEC_y, zeros(3,1);
return vec;
}
return py2vec(pitch(), yaw());
}
/* ************************************************************************* */
Vector3 ParallaxAnglePoint3::directionVectorFromAssoAnchor(
const Point3 & mainAnchor, const Point3 & assoAnchor,
boost::optional<gtsam::Matrix&> Dpoint,
boost::optional<gtsam::Matrix&> Dmain ,
boost::optional<gtsam::Matrix&> Dasso ) const
{
if (!Dasso)
{
return directionVectorFromOtheAnchor( mainAnchor, assoAnchor, assoAnchor, Dpoint, Dmain );
}
Matrix Dothe;
Vector3 directVec = directionVectorFromOtheAnchor(
mainAnchor, assoAnchor, assoAnchor,
Dpoint, Dmain, Dasso, Dothe);
*Dasso += Dothe;
return directVec;
}
/* ************************************************************************* */
Vector3 ParallaxAnglePoint3::directionVectorFromOtheAnchor(
const Point3 & mainAnchor, const Point3 & assoAnchor, const Point3 & otheAnchor,
boost::optional<gtsam::Matrix&> Dpoint,
boost::optional<gtsam::Matrix&> Dmain ,
boost::optional<gtsam::Matrix&> Dasso ,
boost::optional<gtsam::Matrix&> Dothe ) const
{
if (!Dpoint && !Dmain && !Dasso && !Dothe)
{
// Get vector from main anchor to associated anchor
Vector3 mainToAsso( assoAnchor.vector() - mainAnchor.vector() );
// Get direction vector from main anchor to point
Vector3 dirMainToPoint(directionVectorFromMainAnchor());
// Get the angle between these vectors
double phi = vectors2angle(dirMainToPoint, mainToAsso);
// Get vector from main anchor to other anchor
Vector3 mainToOther(otheAnchor.vector() - mainAnchor.vector());
return sin(parallax_ + phi) * mainToAsso.norm() * dirMainToPoint - sin(parallax_) * mainToOther;
}
// Same computation with jacobians
// Get vector from main anchor to associated anchor
Matrix MAINTOASSO_assoanchor, MAINTOASSO_mainanchor;
Vector3 mainToAsso( assoAnchor.sub(mainAnchor, MAINTOASSO_assoanchor, MAINTOASSO_mainanchor).vector() );
// Get the lenght of the vector
Matrix NORMMAINTOASSO_maintoasso;
double normMainToAsso = norm(mainToAsso, NORMMAINTOASSO_maintoasso);
// Get direction vector from main anchor to point
// NOTE: It's already normalized
Matrix DIRMAINTOPOINT_point;
Vector3 dirMainToPoint(directionVectorFromMainAnchor(DIRMAINTOPOINT_point));
// Get the angle between these vectors
Matrix PHI_dirmaintopoint, PHI_maintoasso;
double phi = vectors2angle(dirMainToPoint, mainToAsso, PHI_dirmaintopoint, PHI_maintoasso);
// Get vector from main anchor to other anchor
Matrix MAINTOOTHER_otheanchor, MAINTOOTHER_mainanchor;
Vector3 mainToOther(otheAnchor.sub(mainAnchor, MAINTOOTHER_otheanchor, MAINTOOTHER_mainanchor).vector());
double sinParallaxPhi = sin(parallax_ + phi);
double SINPARALLAXPHI_parallax = cos(parallax_ + phi);
double SINPARALLAXPHI_phi = cos(parallax_ + phi);
Vector3 dirOtherToPoint = sinParallaxPhi * normMainToAsso * dirMainToPoint - sin(parallax_) * mainToOther;
// Chain of partial derivates
// main anchor
if(Dmain)
{
Dmain->resize(3,3);
*Dmain << dirMainToPoint*( normMainToAsso*(SINPARALLAXPHI_phi * PHI_maintoasso * MAINTOASSO_mainanchor) + sinParallaxPhi*(NORMMAINTOASSO_maintoasso * MAINTOASSO_mainanchor) ) - sin(parallax_)*MAINTOOTHER_mainanchor;
}
// associated anchor
if(Dasso)
{
Dasso->resize(3,3);
*Dasso << dirMainToPoint*( normMainToAsso*(SINPARALLAXPHI_phi * PHI_maintoasso * MAINTOASSO_assoanchor) + sinParallaxPhi*(NORMMAINTOASSO_maintoasso * MAINTOASSO_assoanchor) );
}
// other anchor
if(Dothe)
{
Dothe->resize(3,3);
*Dothe = -sin(parallax_) * MAINTOOTHER_otheanchor;
}
// parallax point
if(Dpoint)
{
Matrix DIROTHERTOPOINT_py(3,2);
DIROTHERTOPOINT_py << normMainToAsso*( dirMainToPoint*(SINPARALLAXPHI_phi * PHI_dirmaintopoint * DIRMAINTOPOINT_point.block(0,0,3,2)) + sinParallaxPhi*DIRMAINTOPOINT_point.block(0,0,3,2) );
Matrix DIROTHERTOPOINT_parallax(3,1);
DIROTHERTOPOINT_parallax << (normMainToAsso * dirMainToPoint * SINPARALLAXPHI_parallax) - (cos(parallax_) * mainToOther);
Dpoint->resize(3,3);
*Dpoint << DIROTHERTOPOINT_py, DIROTHERTOPOINT_parallax;
}
return dirOtherToPoint;
}
Point3 ParallaxAnglePoint3::toPoint3(const Point3 & mainAnchor, const Point3 & assoAnchor) const
{
Vector3 vecFromMain = directionVectorFromMainAnchor();
Point3 mainToAsso = (assoAnchor - mainAnchor);
double mainAngle = vectors2angle(vecFromMain, mainToAsso.vector());
double sinParalax = sin(parallax_);
// Guard to avoid division by zero
if(fabs(sinParalax) <= 1e-6)
{
if (sinParalax < 0) sinParalax = -1e-6;
else sinParalax = 1e-6;
}
double depthFromMain = (sin(mainAngle + parallax_)/sinParalax)*mainToAsso.norm();
return mainAnchor + Point3(vecFromMain*depthFromMain);
}
Point3 ParallaxAnglePoint3::toPoint3(const Pose3 & mainPose, const Pose3 & assoPose, boost::optional<const Pose3 &> body_P_sensor) const
{
if(body_P_sensor)
{
return toPoint3(mainPose.compose(*body_P_sensor).translation(), assoPose.compose(*body_P_sensor).translation());
}
//else
return toPoint3(mainPose.translation(), assoPose.translation());
}
}
| 34.043825 | 219 | 0.639087 | [
"vector",
"3d"
] |
3d2f50d16e9111150ffda548159d5eee2203ed39 | 2,107 | cc | C++ | tensorflow/g3doc/how_tos/adding_an_op/register_kernels.cc | vsilyaev/tensorflow | f41959ccb2d9d4c722fe8fc3351401d53bcf4900 | [
"Apache-2.0"
] | 1 | 2020-01-12T14:38:34.000Z | 2020-01-12T14:38:34.000Z | tensorflow/g3doc/how_tos/adding_an_op/register_kernels.cc | vsilyaev/tensorflow | f41959ccb2d9d4c722fe8fc3351401d53bcf4900 | [
"Apache-2.0"
] | null | null | null | tensorflow/g3doc/how_tos/adding_an_op/register_kernels.cc | vsilyaev/tensorflow | f41959ccb2d9d4c722fe8fc3351401d53bcf4900 | [
"Apache-2.0"
] | null | null | null | #include "tensorflow/core/framework/op_kernel.h"
#include "tensorflow/core/framework/register_types.h"
using namespace tensorflow;
template <typename T>
class ZeroOutOp : public OpKernel {
public:
explicit ZeroOutOp(OpKernelConstruction* context) : OpKernel(context) {}
void Compute(OpKernelContext* context) override {
// Grab the input tensor
const Tensor& input_tensor = context->input(0);
auto input = input_tensor.flat<T>();
// Create an output tensor
Tensor* output = NULL;
OP_REQUIRES_OK(context,
context->allocate_output(0, input_tensor.shape(), &output));
auto output_flat = output->template flat<T>();
// Set all the elements of the output tensor to 0
const int N = input.size();
for (int i = 0; i < N; i++) {
output_flat(i) = 0;
}
// Preserve the first input value
if (N > 0) output_flat(0) = input(0);
}
};
REGISTER_KERNEL_BUILDER(Name("ZeroOut")
.Device(DEVICE_CPU)
.TypeConstraint<float>("T"),
ZeroOutOp<float>);
REGISTER_KERNEL_BUILDER(Name("ZeroOut")
.Device(DEVICE_CPU)
.TypeConstraint<double>("T"),
ZeroOutOp<double>);
REGISTER_KERNEL_BUILDER(Name("ZeroOut")
.Device(DEVICE_CPU)
.TypeConstraint<int>("T"),
ZeroOutOp<int>);
#define REGISTER_KERNEL(type) \
REGISTER_KERNEL_BUILDER( \
Name("ZeroOut").Device(DEVICE_CPU).TypeConstraint<type>("T"), \
ZeroOutOp<type>)
REGISTER_KERNEL(float);
REGISTER_KERNEL(double);
REGISTER_KERNEL(int32);
#undef REGISTER_KERNEL
#define REGISTER_KERNEL(type) \
REGISTER_KERNEL_BUILDER( \
Name("ZeroOut").Device(DEVICE_CPU).TypeConstraint<type>("T"), \
ZeroOutOp<type>)
TF_CALL_REAL_NUMBER_TYPES(REGISTER_KERNEL);
#undef REGISTER_KERNEL
| 32.415385 | 79 | 0.573802 | [
"shape"
] |
3d3316c30c309de18a6dd045b861098ab598097b | 1,832 | cpp | C++ | tools/parser-test.cpp | b0r3dd3v/souper | 26fc1d3f59ee86885c0b073865b8c97130a9778d | [
"Apache-2.0"
] | 1,758 | 2015-01-02T13:40:08.000Z | 2022-03-30T17:24:53.000Z | tools/parser-test.cpp | b0r3dd3v/souper | 26fc1d3f59ee86885c0b073865b8c97130a9778d | [
"Apache-2.0"
] | 556 | 2015-01-02T13:11:38.000Z | 2022-03-01T20:55:11.000Z | tools/parser-test.cpp | b0r3dd3v/souper | 26fc1d3f59ee86885c0b073865b8c97130a9778d | [
"Apache-2.0"
] | 144 | 2015-01-03T07:30:58.000Z | 2022-03-08T07:41:08.000Z | // Copyright 2014 The Souper 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 "llvm/Support/raw_ostream.h"
#include "llvm/Support/MemoryBuffer.h"
#include "souper/Parser/Parser.h"
#include <unistd.h>
using namespace souper;
using namespace llvm;
int main(int argc, char **argv) {
int Arg = 1, LHSOnly = 0;
if (Arg < argc && strcmp(argv[Arg], "-LHS") == 0) {
LHSOnly = 1;
++Arg;
}
auto MB = MemoryBuffer::getFileOrSTDIN(argc >= (Arg+1) ? argv[Arg] : "-");
if (MB) {
InstContext IC;
std::string ErrStr;
std::vector<ParsedReplacement> Reps;
std::vector<ReplacementContext> Contexts;
if (LHSOnly)
Reps = ParseReplacementLHSs(IC, MB.get()->getBufferIdentifier(),
MB.get()->getBuffer(), Contexts, ErrStr);
else
Reps = ParseReplacements(IC, MB.get()->getBufferIdentifier(),
MB.get()->getBuffer(), ErrStr);
if (!ErrStr.empty()) {
llvm::errs() << ErrStr << '\n';
return 1;
}
for (const auto &R : Reps) {
if (LHSOnly) {
ReplacementContext Context;
R.printLHS(llvm::outs(), Context);
} else {
R.print(llvm::outs());
}
}
} else {
llvm::errs() << MB.getError().message() << '\n';
}
return 0;
}
| 31.050847 | 76 | 0.623362 | [
"vector"
] |
3d37175d511c965f2014acb3b5819e55bf6a11ad | 629 | cpp | C++ | codeforces/gym/2018 ACM-ICPC, Syrian Collegiate Programming Contest/i.cpp | tysm/cpsols | 262212646203e516d1706edf962290de93762611 | [
"MIT"
] | 4 | 2020-10-05T19:24:10.000Z | 2021-07-15T00:45:43.000Z | codeforces/gym/2018 ACM-ICPC, Syrian Collegiate Programming Contest/i.cpp | tysm/cpsols | 262212646203e516d1706edf962290de93762611 | [
"MIT"
] | null | null | null | codeforces/gym/2018 ACM-ICPC, Syrian Collegiate Programming Contest/i.cpp | tysm/cpsols | 262212646203e516d1706edf962290de93762611 | [
"MIT"
] | null | null | null | #include <cpplib/stdinc.hpp>
#include <cpplib/adt/point.hpp>
#include <cpplib/geometry/see.hpp>
int32_t main(){
ifstream cin("robots.in");
desync();
int t;
cin >> t;
while(t--){
int n, R, r;
cin >> n >> R >> r;
vector<point<int> > points;
point<int> p;
points.eb(p);
for(int i=0; i<n; ++i){
int dx, dy;
cin >> dx >> dy;
p.x += dx;
p.y += dy;
points.eb(p);
}
auto c = get<0>(see(points));
cout << fixed << setprecision(10) << -c.x << ' ' << -c.y << endl;
}
return 0;
}
| 22.464286 | 73 | 0.430843 | [
"geometry",
"vector"
] |
3d38cfc8ac8c4a2493e22e9f2a264c5504764384 | 4,925 | cpp | C++ | TicTacToe Game/p2x.cpp | ngocdai94/C-Projects | f62bbf635152dec6286f00e375ddb7221eb7c4cf | [
"MIT"
] | null | null | null | TicTacToe Game/p2x.cpp | ngocdai94/C-Projects | f62bbf635152dec6286f00e375ddb7221eb7c4cf | [
"MIT"
] | null | null | null | TicTacToe Game/p2x.cpp | ngocdai94/C-Projects | f62bbf635152dec6286f00e375ddb7221eb7c4cf | [
"MIT"
] | null | null | null | //Dai Nguyen
//p2.cpp
//Purpose: Create a Tic Tac Toe game with a size from 3 to 25
// for 2 users to play
//Input: row and column indexes of gameboard
//
//Output: display gameboard and result of the game
#include "tictactoex.h"
//function prototype:
//display welcome message and instruction
void welcome();
//display a goodbye message
void goodbye();
//clear screen 25 blank spaces
void clearScreen();
//display statistic of game
void displayStat(int winP1, int winP2, int countTie);
const char YES = 'y';
int main()
{
int size = 0; //get a desired game board from user
int row = 0; //get row index from player
int col = 0; //get column index from player
int winP1 = 0; //count number of wins of player 1
int winP2 = 0; //count number of wins of player 2
int countTie = 0; //count number of ties
int countGame = 0; //count number of game
char X = 'X'; //X is player 1 default character
char O = 'O'; //Y is player 2 default character
char ans = YES;
bool tie = false; //keep track if game is tie
bool turnP1 = true; //check if player 1 win
bool turnP2 = false; //check if player 2 win
bool gameOver = false; //check if gameover
//clear screen
clearScreen();
//display welcome message and instruction
welcome();
//get game board size
while (size < 3 || size > 25){
cout << "Please enter a game board size between 3 and 25: ";
cin >> size;
}
//create object game board with given size
TicTacToe game(size);
//display game board
game.displayGame();
//play until won, tie or players want to quit
while (!gameOver && ans == YES){
//display game board after reset if play more than 1 game
if (countGame >= 1){
game.displayGame();
}
//player 1 turn
if (turnP1 && !tie){
while (turnP1){
cout << "Player 1 turn!" << endl;
cout << "Which row, collumn? ";
cin >> row >> col;
//check if player 1 gives a valid location
//then switch turn
if (!game.placePiece(X, row, col)){
cout << endl << "Not a valid location." << endl;
} else {
turnP1 = false;
turnP2 = true;
}
}
game.displayGame(); //update game
//check if player 1 win or not
if (game.decideWinner(X, tie)){
cout << "Player 1 won!" << endl;
winP1++; //count number of player 1 wins
gameOver = true; //game is over if player 1 wins
turnP2 = false; //player 2 turn is disable
}
}
//player 2 turn
if (turnP2 && !tie){
while (turnP2){
cout << "Player 2 turn!" << endl;
cout << "Which row, collumn? ";
cin >> row >> col;
//check if player 2 gives a valid location
//then switch turn
if (!game.placePiece(O, row, col)){
cout << endl << "Not a valid location." << endl;
} else {
turnP2 = false;
turnP1 = true;
}
}
game.displayGame(); //update game
//check if players win or not
if (game.decideWinner(O, tie)){
cout << "Player 2 won!" << endl;
winP2++; //count number of player 2 wins
gameOver = true; //game is over if player 2 wins
turnP1 = false; //player 1 turn is disable
//tie = false;
}
}
//check if game is tie and display a tie message
if (tie) {
gameOver = true;
cout << "No one wins!" << endl;
countTie++; //update number of tie games
}
//ask players if they want to play again?
if (gameOver || tie){
//display statistic of game
displayStat(winP1, winP2, countTie);
cout << "Play again? ";
cin >> ans;
ans = tolower(ans);
//reset game board, tie status, gameover status
//activate player 1 turn
if (ans == YES) {
countGame++;
turnP1 = true;
tie = false;
gameOver = false;
game.resetBoard();
}
}
}
//Display goodbye message
goodbye();
return 0;
}
//display welcome message and instruction
void welcome()
{
cout << endl;
cout << "--------Welcome to Tic Tac Toe Game---------" << endl;
cout << "The game can play with two players." << endl;
cout << "The first player will have a default character X. " << endl;
cout << "The second player will have a default character O. " << endl;
cout << "To win this game, either player has to make a row, " << endl;
cout << "column, or diagonals with full either X or O characters. " << endl;
cout << "The game board will be between 3 and 10." << endl << endl;
}
//display goodbye message
void goodbye()
{
cout << endl << endl;
cout << "Thank you for playing!" << endl;
cout << "Bye!!!" << endl << endl << endl;
}
//clear for 25 blank spaces
void clearScreen()
{
for (int i = 0; i < 25; i++){
cout << endl;
}
}
void displayStat(int winP1, int winP2, int countTie)
{
cout << endl << endl;
//Display game statistic after finish game
cout << "Player 1 Wins: " << winP1 << endl;
cout << "Player 2 Wins: " << winP2 << endl;
cout << "Number of Tie: " << countTie << endl << endl;
}
| 25 | 78 | 0.608325 | [
"object"
] |
3d4257c6b71b451953621d59a503f91ac9699fe1 | 4,444 | cpp | C++ | RenderEngine/src/Rendering/ShaderProgram.cpp | RubenB-1643541/MarblingSimulation | 7534d7bcc4952a85a2512d354569256f8129c2cd | [
"MIT"
] | null | null | null | RenderEngine/src/Rendering/ShaderProgram.cpp | RubenB-1643541/MarblingSimulation | 7534d7bcc4952a85a2512d354569256f8129c2cd | [
"MIT"
] | null | null | null | RenderEngine/src/Rendering/ShaderProgram.cpp | RubenB-1643541/MarblingSimulation | 7534d7bcc4952a85a2512d354569256f8129c2cd | [
"MIT"
] | null | null | null | #include "pch.h"
#include "ShaderProgram.h"
RenderEngine::ShaderProgram::ShaderProgram()
{
}
RenderEngine::ShaderProgram::ShaderProgram(Shader& shader)
{
Create(shader);
}
/*
//http://www.opengl-tutorial.org/beginners-tutorials/tutorial-2-the-first-triangle/
*/
bool RenderEngine::ShaderProgram::Create(Shader& shader)
{
_shader = shader;
// Create the shaders
GLuint VertexShaderID = glCreateShader(GL_VERTEX_SHADER);
GLuint FragmentShaderID = glCreateShader(GL_FRAGMENT_SHADER);
// Read the Vertex Shader code from the file
std::string VertexShaderCode;
std::ifstream VertexShaderStream(shader.vertex, std::ios::in);
if (VertexShaderStream.is_open()) {
std::stringstream sstr;
sstr << VertexShaderStream.rdbuf();
VertexShaderCode = sstr.str();
VertexShaderStream.close();
}
else {
ENGINE_ERROR("Failed to open {}", shader.vertex);
return false;
}
// Read the Fragment Shader code from the file
std::string FragmentShaderCode;
std::ifstream FragmentShaderStream(shader.fragment, std::ios::in);
if (FragmentShaderStream.is_open()) {
std::stringstream sstr;
sstr << FragmentShaderStream.rdbuf();
FragmentShaderCode = sstr.str();
FragmentShaderStream.close();
}
else {
ENGINE_ERROR("Failed to open {}", shader.fragment);
return false;
}
GLint Result = GL_FALSE;
int InfoLogLength;
// Compile Vertex Shader
//printf("Compiling shader : %s\n", vertex_file_path);
char const* VertexSourcePointer = VertexShaderCode.c_str();
glShaderSource(VertexShaderID, 1, &VertexSourcePointer, NULL);
glCompileShader(VertexShaderID);
// Check Vertex Shader
glGetShaderiv(VertexShaderID, GL_COMPILE_STATUS, &Result);
glGetShaderiv(VertexShaderID, GL_INFO_LOG_LENGTH, &InfoLogLength);
if (InfoLogLength > 0) {
std::vector<char> VertexShaderErrorMessage(InfoLogLength + 1);
glGetShaderInfoLog(VertexShaderID, InfoLogLength, NULL, &VertexShaderErrorMessage[0]);
std::cerr << VertexShaderErrorMessage[0] << std::endl;
//printf("%s\n", &VertexShaderErrorMessage[0]);
if (!Result) {
ENGINE_ERROR("Failed to Compile VertexShader {}", &VertexShaderErrorMessage[0]);
return false;
}
else {
ENGINE_ERROR("VertexShader info: {}", &VertexShaderErrorMessage[0]);
}
}
// Compile Fragment Shader
//printf("Compiling shader : %s\n", fragment_file_path);
char const* FragmentSourcePointer = FragmentShaderCode.c_str();
glShaderSource(FragmentShaderID, 1, &FragmentSourcePointer, NULL);
glCompileShader(FragmentShaderID);
// Check Fragment Shader
glGetShaderiv(FragmentShaderID, GL_COMPILE_STATUS, &Result);
glGetShaderiv(FragmentShaderID, GL_INFO_LOG_LENGTH, &InfoLogLength);
if (InfoLogLength > 0) {
std::vector<char> FragmentShaderErrorMessage(InfoLogLength + 1);
glGetShaderInfoLog(FragmentShaderID, InfoLogLength, NULL, &FragmentShaderErrorMessage[0]);
//printf("%s\n", &FragmentShaderErrorMessage[0]);
if (!Result) {
ENGINE_ERROR("Failed to Compile FragmentShader {}", &FragmentShaderErrorMessage[0]);
return false;
}
else {
ENGINE_ERROR("FragmentShader info {}", &FragmentShaderErrorMessage[0]);
}
}
// Link the program
//printf("Linking program\n");
_id = glCreateProgram();
glAttachShader(_id, VertexShaderID);
glAttachShader(_id, FragmentShaderID);
glLinkProgram(_id);
// Check the program
glGetProgramiv(_id, GL_LINK_STATUS, &Result);
glGetProgramiv(_id, GL_INFO_LOG_LENGTH, &InfoLogLength);
if (InfoLogLength > 0) {
std::vector<char> ProgramErrorMessage(InfoLogLength + 1);
glGetProgramInfoLog(_id, InfoLogLength, NULL, &ProgramErrorMessage[0]);
if (!Result) {
ENGINE_ERROR("Failed to link VertexShader and FragmentShader {}", ProgramErrorMessage[0]);
return false;
}
else {
ENGINE_ERROR("VertexShader and FragmentShader Linking Message: {}", ProgramErrorMessage[0]);
}
}
glDetachShader(_id, VertexShaderID);
glDetachShader(_id, FragmentShaderID);
glDeleteShader(VertexShaderID);
glDeleteShader(FragmentShaderID);
return true;
}
void RenderEngine::ShaderProgram::Bind()
{
glUseProgram(_id);
}
void RenderEngine::ShaderProgram::UnBind()
{
glUseProgram(NULL);
}
void RenderEngine::ShaderProgram::UseProgram()
{
glUseProgram(_id);
}
GLuint RenderEngine::ShaderProgram::GetUniformLocation(std::string s)
{
return glGetUniformLocation(_id, s.c_str());
}
| 29.825503 | 96 | 0.724797 | [
"vector"
] |
3d44c71effe79a0a87441755582ca388e4525f83 | 14,936 | cpp | C++ | Example/Source/ExampleSDL2/Private/Main.cpp | cofenberg/unrimp | 90310657f106eb83f3a9688329b78619255a1042 | [
"MIT"
] | 187 | 2015-11-02T21:27:57.000Z | 2022-02-17T21:39:17.000Z | Example/Source/ExampleSDL2/Private/Main.cpp | cofenberg/unrimp | 90310657f106eb83f3a9688329b78619255a1042 | [
"MIT"
] | null | null | null | Example/Source/ExampleSDL2/Private/Main.cpp | cofenberg/unrimp | 90310657f106eb83f3a9688329b78619255a1042 | [
"MIT"
] | 20 | 2015-11-04T19:17:01.000Z | 2021-11-18T11:23:25.000Z | /*********************************************************\
* Copyright (c) 2012-2021 The Unrimp Team
*
* 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.
\*********************************************************/
//[-------------------------------------------------------]
//[ Includes ]
//[-------------------------------------------------------]
#include <Rhi/Public/DefaultLog.h>
#include <Rhi/Public/DefaultAssert.h>
#include <Rhi/Public/DefaultAllocator.h>
#include <Rhi/Public/RhiInstance.h>
// Disable warnings in external headers, we can't fix them
PRAGMA_WARNING_PUSH
PRAGMA_WARNING_DISABLE_MSVC(4668) // warning C4668: '__GNUC__' is not defined as a preprocessor macro, replacing with '0' for '#if/#elif'
#include <SDL.h>
#include <SDL_syswm.h>
PRAGMA_WARNING_POP
//[-------------------------------------------------------]
//[ Global variables ]
//[-------------------------------------------------------]
extern "C"
{
// NVIDIA: Force usage of NVidia GPU in case there is an integrated graphics unit as well, if we don't do this we risk getting the integrated graphics unit and hence a horrible performance
// -> See "Enabling High Performance Graphics Rendering on Optimus Systems" http://developer.download.nvidia.com/devzone/devcenter/gamegraphics/files/OptimusRenderingPolicies.pdf
_declspec(dllexport) DWORD NvOptimusEnablement = 0x00000001;
// AMD: Force usage of AMD GPU in case there is an integrated graphics unit as well, if we don't do this we risk getting the integrated graphics unit and hence a horrible performance
// -> Named "Dynamic Switchable Graphics", found no official documentation, only https://community.amd.com/message/1307599#comment-1307599 - "Can an OpenGL app default to the discrete GPU on an Enduro system?"
__declspec(dllexport) int AmdPowerXpressRequestHighPerformance = 1;
}
//[-------------------------------------------------------]
//[ Global functions ]
//[-------------------------------------------------------]
Rhi::handle getNativeWindowHandle(SDL_Window& sdlWindow)
{
Rhi::handle nativeWindowHandle = NULL_HANDLE;
SDL_SysWMinfo sdlSysWMinfo;
SDL_VERSION(&sdlSysWMinfo.version);
if (SDL_GetWindowWMInfo(&sdlWindow, &sdlSysWMinfo))
{
switch (sdlSysWMinfo.subsystem)
{
#if defined _WIN32
case SDL_SYSWM_UNKNOWN:
ASSERT(false, "Unknown subsystem")
break;
case SDL_SYSWM_WINDOWS:
nativeWindowHandle = reinterpret_cast<Rhi::handle>(sdlSysWMinfo.info.win.window);
break;
case SDL_SYSWM_X11:
case SDL_SYSWM_DIRECTFB:
case SDL_SYSWM_COCOA:
case SDL_SYSWM_UIKIT:
case SDL_SYSWM_WAYLAND:
case SDL_SYSWM_MIR:
case SDL_SYSWM_WINRT:
case SDL_SYSWM_ANDROID:
case SDL_SYSWM_VIVANTE:
case SDL_SYSWM_OS2:
ASSERT(false, "Unknown subsystem")
break;
#elif defined __ANDROID__
#warning "TODO(co) The Android support is work-in-progress"
#elif defined LINUX
case SDL_SYSWM_UNKNOWN:
case SDL_SYSWM_WINDOWS:
ASSERT(false, "Unknown subsystem")
break;
case SDL_SYSWM_X11:
nativeWindowHandle = reinterpret_cast<Rhi::handle>(sdlSysWMinfo.info.x11.window);
break;
case SDL_SYSWM_DIRECTFB:
case SDL_SYSWM_COCOA:
case SDL_SYSWM_UIKIT:
ASSERT(false, "Unknown subsystem")
break;
case SDL_SYSWM_WAYLAND:
nativeWindowHandle = reinterpret_cast<Rhi::handle>(sdlSysWMinfo.info.wl.surface);
break;
case SDL_SYSWM_MIR:
case SDL_SYSWM_WINRT:
case SDL_SYSWM_ANDROID:
case SDL_SYSWM_VIVANTE:
case SDL_SYSWM_OS2:
ASSERT(false, "Unknown subsystem")
break;
#else
#error "Unsupported platform"
#endif
}
}
// Done
return nativeWindowHandle;
}
//[-------------------------------------------------------]
//[ Platform independent program entry point ]
//[-------------------------------------------------------]
int main(int arc, char* argv[])
{
// For memory leak detection
#if defined(RHI_DEBUG) && defined(_WIN32)
// "_CrtDumpMemoryLeaks()" reports false positive memory leak with static variables, so use a memory difference instead
_CrtMemState crtMemState = { };
_CrtMemCheckpoint(&crtMemState);
#endif
// Initialize SDL 2
if (SDL_Init(0) == 0)
{
// Create SDL 2 window instance
SDL_Window* sdlWindow = SDL_CreateWindow("Example SDL2", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, 1024, 768, SDL_WINDOW_RESIZABLE | SDL_WINDOW_ALLOW_HIGHDPI);
if (nullptr != sdlWindow)
{
// Create RHI instance
Rhi::DefaultLog defaultLog;
Rhi::DefaultAssert defaultAssert;
Rhi::DefaultAllocator defaultAllocator;
#ifdef _WIN32
Rhi::Context rhiContext(defaultLog, defaultAssert, defaultAllocator, getNativeWindowHandle(*sdlWindow));
const bool loadRhiApiSharedLibrary = false;
#elif LINUX
// Under Linux the OpenGL library interacts with the library from X11 so we need to load the library ourself instead letting it be loaded by the RHI instance
// -> See http://dri.sourceforge.net/doc/DRIuserguide.html "11.5 libGL.so and dlopen()"
const bool loadRhiApiSharedLibrary = true;
Rhi::X11Context rhiContext(defaultLog, defaultAssert, defaultAllocator, getX11Display(), getNativeWindowHandle(*sdlWindow));
#endif
Rhi::RhiInstance rhiInstance((arc > 1) ? argv[1] : Rhi::DEFAULT_RHI_NAME, rhiContext, loadRhiApiSharedLibrary);
Rhi::IRhiPtr rhi = rhiInstance.getRhi();
if (nullptr != rhi && rhi->isInitialized())
{
// Create RHI resources
Rhi::ISwapChainPtr mainSwapChain;
Rhi::IBufferManagerPtr bufferManager;
Rhi::IRootSignaturePtr rootSignature;
Rhi::IGraphicsPipelineStatePtr graphicsPipelineState;
Rhi::IVertexArrayPtr vertexArray;
{
{ // Create RHI swap chain instance
const Rhi::Capabilities& capabilities = rhi->getCapabilities();
mainSwapChain = rhi->createSwapChain(
*rhi->createRenderPass(1, &capabilities.preferredSwapChainColorTextureFormat, capabilities.preferredSwapChainDepthStencilTextureFormat, 1 RHI_RESOURCE_DEBUG_NAME("Main")),
Rhi::WindowHandle{getNativeWindowHandle(*sdlWindow), nullptr, nullptr}, // TODO(co) Linux Wayland support
rhi->getContext().isUsingExternalContext()
RHI_RESOURCE_DEBUG_NAME("Main"));
}
// Create the buffer manager
bufferManager = rhi->createBufferManager();
{ // Create the root signature
// Setup
Rhi::RootSignatureBuilder rootSignatureBuilder;
rootSignatureBuilder.initialize(0, nullptr, 0, nullptr, Rhi::RootSignatureFlags::ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT);
// Create the instance
rootSignature = rhi->createRootSignature(rootSignatureBuilder RHI_RESOURCE_DEBUG_NAME("Triangle"));
}
// Vertex input layout
static constexpr Rhi::VertexAttribute vertexAttributesLayout[] =
{
{ // Attribute 0
// Data destination
Rhi::VertexAttributeFormat::FLOAT_2, // vertexAttributeFormat (Rhi::VertexAttributeFormat)
"Position", // name[32] (char)
"POSITION", // semanticName[32] (char)
0, // semanticIndex (uint32_t)
// Data source
0, // inputSlot (uint32_t)
0, // alignedByteOffset (uint32_t)
sizeof(float) * 2, // strideInBytes (uint32_t)
0 // instancesPerElement (uint32_t)
}
};
const Rhi::VertexAttributes vertexAttributes(sizeof(vertexAttributesLayout) / sizeof(Rhi::VertexAttribute), vertexAttributesLayout);
{ // Create vertex array object (VAO)
// Create the vertex buffer object (VBO)
// -> Clip space vertex positions, left/bottom is (-1,-1) and right/top is (1,1)
static constexpr float VERTEX_POSITION[] =
{ // Vertex ID Triangle on screen
0.0f, 1.0f, // 0 0
1.0f, 0.0f, // 1 . .
-0.5f, 0.0f // 2 2.......1
};
Rhi::IVertexBufferPtr vertexBuffer(bufferManager->createVertexBuffer(sizeof(VERTEX_POSITION), VERTEX_POSITION, 0, Rhi::BufferUsage::STATIC_DRAW RHI_RESOURCE_DEBUG_NAME("Triangle")));
// Create vertex array object (VAO)
// -> The vertex array object (VAO) keeps a reference to the used vertex buffer object (VBO)
// -> This means that there's no need to keep an own vertex buffer object (VBO) reference
// -> When the vertex array object (VAO) is destroyed, it automatically decreases the
// reference of the used vertex buffer objects (VBO). If the reference counter of a
// vertex buffer object (VBO) reaches zero, it's automatically destroyed.
const Rhi::VertexArrayVertexBuffer vertexArrayVertexBuffers[] = { vertexBuffer };
vertexArray = bufferManager->createVertexArray(vertexAttributes, sizeof(vertexArrayVertexBuffers) / sizeof(Rhi::VertexArrayVertexBuffer), vertexArrayVertexBuffers, nullptr RHI_RESOURCE_DEBUG_NAME("Triangle"));
}
{
// Create the graphics program
Rhi::IGraphicsProgramPtr graphicsProgram;
{
// Get the shader source code (outsourced to keep an overview)
const char* vertexShaderSourceCode = nullptr;
const char* fragmentShaderSourceCode = nullptr;
#include "ExampleSDL2_GLSL_450.h" // For Vulkan
#include "ExampleSDL2_GLSL_410.h" // macOS 10.11 only supports OpenGL 4.1 hence it's our OpenGL minimum
#include "ExampleSDL2_GLSL_ES3.h"
#include "ExampleSDL2_HLSL_D3D9_D3D10_D3D11_D3D12.h"
#include "ExampleSDL2_Null.h"
// Create the graphics program
Rhi::IShaderLanguage& shaderLanguage = rhi->getDefaultShaderLanguage();
graphicsProgram = shaderLanguage.createGraphicsProgram(
*rootSignature,
vertexAttributes,
shaderLanguage.createVertexShaderFromSourceCode(vertexAttributes, vertexShaderSourceCode, nullptr RHI_RESOURCE_DEBUG_NAME("Triangle")),
shaderLanguage.createFragmentShaderFromSourceCode(fragmentShaderSourceCode, nullptr RHI_RESOURCE_DEBUG_NAME("Triangle"))
RHI_RESOURCE_DEBUG_NAME("Triangle"));
}
// Create the graphics pipeline state object (PSO)
if (nullptr != graphicsProgram)
{
graphicsPipelineState = rhi->createGraphicsPipelineState(Rhi::GraphicsPipelineStateBuilder(rootSignature, graphicsProgram, vertexAttributes, mainSwapChain->getRenderPass()) RHI_RESOURCE_DEBUG_NAME("Triangle"));
}
}
}
// Record RHI command buffer
Rhi::CommandBuffer commandBuffer;
{
// Scoped debug event
COMMAND_SCOPED_DEBUG_EVENT_FUNCTION(commandBuffer)
// Make the graphics main swap chain to the current render target
Rhi::Command::SetGraphicsRenderTarget::create(commandBuffer, mainSwapChain);
{ // Since Direct3D 12 is command list based, the viewport and scissor rectangle must be set in every draw call to work with all supported RHI implementations
// Get the window size
uint32_t width = 1;
uint32_t height = 1;
mainSwapChain->getWidthAndHeight(width, height);
// Set the graphics viewport and scissor rectangle
Rhi::Command::SetGraphicsViewportAndScissorRectangle::create(commandBuffer, 0, 0, width, height);
}
{ // Clear the graphics color buffer of the current render target with gray, do also clear the depth buffer
const float color[4] = { 0.5f, 0.5f, 0.5f, 1.0f };
Rhi::Command::ClearGraphics::create(commandBuffer, Rhi::ClearFlag::COLOR_DEPTH, color);
}
// Set the used graphics root signature
Rhi::Command::SetGraphicsRootSignature::create(commandBuffer, rootSignature);
// Set the used graphics pipeline state object (PSO)
Rhi::Command::SetGraphicsPipelineState::create(commandBuffer, graphicsPipelineState);
// Input assembly (IA): Set the used vertex array
Rhi::Command::SetGraphicsVertexArray::create(commandBuffer, vertexArray);
// Set debug marker
// -> Debug methods: When using Direct3D <11.1, these methods map to the Direct3D 9 PIX functions
// (D3DPERF_* functions, also works directly within VisualStudio 2017 out-of-the-box)
COMMAND_SET_DEBUG_MARKER(commandBuffer, "Everyone ready for the upcoming triangle?")
{
// Scoped debug event
COMMAND_SCOPED_DEBUG_EVENT(commandBuffer, "Drawing the fancy triangle")
// Render the specified geometric primitive, based on an array of vertices
Rhi::Command::DrawGraphics::create(commandBuffer, 3);
}
}
// Main loop
bool quit = false;
SDL_Event sdlEvent;
while (!quit && SDL_WaitEvent(&sdlEvent) != 0)
{
switch (sdlEvent.type)
{
case SDL_QUIT:
// Shut down the application
quit = true;
break;
case SDL_WINDOWEVENT:
switch (sdlEvent.window.event)
{
case SDL_WINDOWEVENT_EXPOSED:
// Dispatch command buffer to the RHI implementation
commandBuffer.dispatchToRhi(*rhi);
// Present the content of the current back buffer
mainSwapChain->present();
break;
case SDL_WINDOWEVENT_SIZE_CHANGED:
// Inform the swap chain that the size of the native window was changed
// -> Required for Direct3D 9, Direct3D 10, Direct3D 11
// -> Not required for OpenGL and OpenGL ES 3
mainSwapChain->resizeBuffers();
break;
}
break;
case SDL_KEYDOWN:
// Toggle the fullscreen state
if (SDLK_RETURN == sdlEvent.key.keysym.sym && (sdlEvent.key.keysym.mod & KMOD_ALT) != 0)
{
mainSwapChain->setFullscreenState(!mainSwapChain->getFullscreenState());
}
break;
}
}
}
SDL_DestroyWindow(sdlWindow);
}
SDL_Quit();
}
// For memory leak detection
#if defined(RHI_DEBUG) && defined(_WIN32)
_CrtMemDumpAllObjectsSince(&crtMemState);
#endif
// No error
return 0;
}
| 41.373961 | 217 | 0.676018 | [
"render",
"object"
] |
3d462a700ea886972be0be20dc7919cbc1dde02a | 3,420 | hpp | C++ | nvidia_flex/common/maths.hpp | bluekyu/rpcpp_samples | dab4d21229e9793434d727b2ed8e4c5088c17218 | [
"MIT"
] | 4 | 2018-09-15T20:30:38.000Z | 2022-02-13T19:41:00.000Z | nvidia_flex/common/maths.hpp | bluekyu/rpcpp_samples | dab4d21229e9793434d727b2ed8e4c5088c17218 | [
"MIT"
] | 4 | 2017-09-05T15:18:40.000Z | 2018-08-27T01:15:46.000Z | nvidia_flex/common/maths.hpp | bluekyu/rpcpp_samples | dab4d21229e9793434d727b2ed8e4c5088c17218 | [
"MIT"
] | null | null | null | // This code contains NVIDIA Confidential Information and is disclosed to you
// under a form of NVIDIA software license agreement provided separately to you.
//
// Notice
// NVIDIA Corporation and its licensors retain all intellectual property and
// proprietary rights in and to this software and 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.
//
// ALL NVIDIA DESIGN SPECIFICATIONS, CODE ARE PROVIDED "AS IS.". NVIDIA MAKES
// NO WARRANTIES, EXPRESSED, IMPLIED, STATUTORY, OR OTHERWISE WITH RESPECT TO
// THE MATERIALS, AND EXPRESSLY DISCLAIMS ALL IMPLIED WARRANTIES OF NONINFRINGEMENT,
// MERCHANTABILITY, AND FITNESS FOR A PARTICULAR PURPOSE.
//
// Information and code furnished is believed to be accurate and reliable.
// However, NVIDIA Corporation assumes no responsibility for the consequences of use of such
// information or for any infringement of patents or other rights of third parties that may
// result from its use. No license is granted by implication or otherwise under any patent
// or patent rights of NVIDIA Corporation. Details are subject to change without notice.
// This code supersedes and replaces all information previously supplied.
// NVIDIA Corporation products are not authorized for use as critical
// components in life support devices or systems without express written approval of
// NVIDIA Corporation.
//
// Copyright (c) 2013-2016 NVIDIA Corporation. All rights reserved.
#pragma once
#include <cmath>
#include <float.h>
#include <cassert>
#include <string.h>
const float kPi = 3.141592653589f;
const float k2Pi = 2.0f*kPi;
const float kInvPi = 1.0f/kPi;
const float kInv2Pi = 0.5f/kPi;
const float kDegToRad = kPi/180.0f;
const float kRadToDeg = 180.0f/kPi;
inline float Sin(float theta)
{
return sinf(theta);
}
inline float Cos(float theta)
{
return cosf(theta);
}
// random number generator
inline uint32_t Rand(void)
{
static uint32_t seed1 = 315645664;
static uint32_t seed2 = seed1 ^ 0x13ab45fe;
seed1 = (seed2 ^ ((seed1 << 5) | (seed1 >> 27))) ^ (seed1*seed2);
seed2 = seed1 ^ ((seed2 << 12) | (seed2 >> 20));
return seed1;
}
// returns a random number in the range [min, max)
inline uint32_t Rand(uint32_t min, uint32_t max)
{
return min + Rand()%(max-min);
}
// returns random number between 0-1
inline float Randf()
{
uint32_t value = Rand();
uint32_t limit = 0xffffffff;
return (float)value*(1.0f/(float)limit);
}
// returns random number between min and max
inline float Randf(float min, float max)
{
// return Lerp(min, max, ParticleRandf());
float t = Randf();
return (1.0f-t)*min + t*(max);
}
// returns random number between 0-max
inline float Randf(float max)
{
return Randf()*max;
}
// returns a random unit vector (also can add an offset to generate around an off axis vector)
inline LVecBase3f RandomUnitVector()
{
float phi = Randf(kPi*2.0f);
float theta = Randf(kPi*2.0f);
float cosTheta = Cos(theta);
float sinTheta = Sin(theta);
float cosPhi = Cos(phi);
float sinPhi = Sin(phi);
return LVecBase3f(cosTheta*sinPhi, cosPhi, sinTheta*sinPhi);
}
inline LVecBase3f RandVec3() { return LVecBase3f(Randf(-1.0f, 1.0f), Randf(-1.0f, 1.0f), Randf(-1.0f, 1.0f)); }
| 31.376147 | 111 | 0.726901 | [
"vector"
] |
3d4987b8433e5e1199c83bc5093b31c621344b85 | 9,184 | cpp | C++ | opengl/opengl_layer_testing/source/start.cpp | h1k421/GLoat-examples | 2ec9c5669b3d36b84fd5789227664547650d982f | [
"0BSD"
] | 4 | 2019-11-16T18:06:40.000Z | 2019-11-19T14:54:19.000Z | opengl/opengl_layer_testing/source/start.cpp | h1k421/GLoat-examples | 2ec9c5669b3d36b84fd5789227664547650d982f | [
"0BSD"
] | null | null | null | opengl/opengl_layer_testing/source/start.cpp | h1k421/GLoat-examples | 2ec9c5669b3d36b84fd5789227664547650d982f | [
"0BSD"
] | null | null | null | #include <gloat.hpp>
#include <string>
#include <vector>
#include "EGL/egl.h"
#include "EGL/eglext.h"
#include "glad/glad.h"
extern bool g_opengl_core;
extern int g_opengl_major;
extern int g_opengl_minor;
void fs_free(void *ptr, size_t unk) // unk = size?
{
free(ptr);
}
void init_fs(void) {
nn::fs::SetAllocator(malloc, fs_free);
const char *mountPoint = "sdmc";
nn::Result result = nn::fs::MountSdCard(mountPoint);
if (!result.Ok()) {
debug_log("Result: 0x%08x", result.GetValue());
gloat::utils::Abort(&result);
}
nn::fs::SetEnabledAutoAbort(false);
}
nn::Result fs_write(char const *path, void *data, size_t data_size) {
nn::Result result = nn::fs::CreateFile(path, data_size);
bool need_resize = false;
if (!result.Ok()) {
if (result.GetValue() != 0x402) {
return result;
}
need_resize = true;
}
nn::fs::FileHandle handle;
result = nn::fs::OpenFile(&handle, path,
nn::fs::FileOpenMode::FileOpenMode_Writable);
if (!result.Ok()) {
return result;
}
if (need_resize) {
result = nn::fs::SetFileSize(handle, data_size);
if (!result.Ok()) {
return result;
}
}
nn::fs::WriteOption writeOption;
writeOption.mode = 1;
result = nn::fs::WriteFile(handle, 0, data, data_size, writeOption);
if (!result.Ok()) {
return result;
}
result = nn::fs::FlushFile(handle);
if (!result.Ok()) {
return result;
}
nn::fs::CloseFile(handle);
return result;
}
nn::Result fs_read(char const *path, void **data, long *data_size) {
nn::fs::FileHandle handle;
nn::Result result = nn::fs::OpenFile(
&handle, path, nn::fs::FileOpenMode::FileOpenMode_Readable);
// TODO: file not found
if (!result.Ok()) {
return result;
}
result = nn::fs::GetFileSize(data_size, handle);
if (!result.Ok()) {
return result;
}
*data = malloc(*data_size);
if (!*data) {
result.SetValue(0xBEEF);
return result;
}
result = nn::fs::ReadFile(handle, 0, *data, *data_size);
if (!result.Ok()) {
return result;
}
nn::fs::CloseFile(handle);
return result;
}
void *nv_alloc(size_t size, size_t alignment, void *unk) {
return aligned_alloc(alignment, (size + alignment - 1) & -alignment);
}
void nv_free(void *ptr, void *unk) { free(ptr); }
void *nv_realloc(void *ptr, size_t size, void *unk) {
return realloc(ptr, size);
}
void init_nv(void) {
nv::SetGraphicsAllocator(nv_alloc, nv_free, nv_realloc, nullptr);
nv::SetGraphicsDevtoolsAllocator(nv_alloc, nv_free, nv_realloc, nullptr);
// This will never be free as it is entirely unmapped from the current
// process by the nv service.
size_t graphicsMemorySize = 0x10000000; // 256MB
void *graphicsMemory = nv_alloc(graphicsMemorySize, 0x1000, nullptr);
debug_log("graphicsMemory: %p", graphicsMemory);
if (graphicsMemory == nullptr) {
nn::Result result(0xDEAD);
gloat::utils::Abort(&result);
}
nv::InitializeGraphics(graphicsMemory, graphicsMemorySize);
}
GLuint loadDDS(const char *path);
void MessageCallback(GLenum source, GLenum type, GLuint id, GLenum severity,
GLsizei length, const GLchar *message,
const void *userParam) {
debug_log("GL CALLBACK: %s type = 0x%x, severity = 0x%x, message = %s\n",
(type == GL_DEBUG_TYPE_ERROR ? "** GL ERROR **" : ""), type,
severity, message);
}
//-----------------------------------------------------------------------------
// EGL initialization
//-----------------------------------------------------------------------------
static EGLDisplay s_display;
static EGLContext s_context;
static EGLSurface s_surface;
extern bool g_opengl_core;
extern int g_opengl_major;
extern int g_opengl_minor;
static bool initEgl() {
nn::Result result(0);
nn::vi::Initialize();
nn::vi::Display *display;
nn::vi::Layer *layer;
result = nn::vi::OpenDefaultDisplay(&display);
if (!result.Ok()) {
debug_log("Could not open default display! error: %08x",
result.GetValue());
goto _fail0;
}
result = nn::vi::CreateLayer(&layer, display, 1280, 720);
if (!result.Ok()) {
debug_log("Could not create layer! error: %08x", result.GetValue());
goto _fail0;
}
// result = nn::vi::SetLayerScalingMode(layer, nn::vi::ScalingMode::Unk0);
// result = nn::vi::SetLayerScalingMode(layer, nn::vi::ScalingMode::Unk2);
if (!result.Ok()) {
debug_log("Could not set layer scaling mode! error: %08x",
result.GetValue());
goto _fail0;
}
void *nativeWindow;
result = nn::vi::GetNativeWindow(&nativeWindow, layer);
if (!result.Ok()) {
debug_log("Could not get native window! error: %08x",
result.GetValue());
goto _fail0;
}
// Connect to the EGL default display
s_display = eglGetDisplay(EGL_DEFAULT_DISPLAY);
if (!s_display) {
debug_log("Could not connect to display! error: %d", eglGetError());
goto _fail0;
}
// Initialize the EGL display connection
eglInitialize(s_display, nullptr, nullptr);
// Select OpenGL (Core) as the desired graphics API
if (eglBindAPI(EGL_OPENGL_API) == EGL_FALSE) {
debug_log("Could not set API! error: %d", eglGetError());
goto _fail1;
}
// Get an appropriate EGL framebuffer configuration
EGLConfig config;
EGLint numConfigs;
static const EGLint framebufferAttributeList[] = {EGL_RENDERABLE_TYPE,
EGL_OPENGL_BIT,
EGL_RED_SIZE,
8,
EGL_GREEN_SIZE,
8,
EGL_BLUE_SIZE,
8,
EGL_NONE};
eglChooseConfig(s_display, framebufferAttributeList, &config, 1,
&numConfigs);
if (numConfigs == 0) {
debug_log("No config found! error: %d", eglGetError());
goto _fail1;
}
// Create an EGL window surface
s_surface =
eglCreateWindowSurface(s_display, config, nativeWindow, nullptr);
if (!s_surface) {
debug_log("Surface creation failed! error: %d", eglGetError());
goto _fail1;
}
{
const EGLint profile{
g_opengl_core ? EGL_CONTEXT_OPENGL_CORE_PROFILE_BIT_KHR
: EGL_CONTEXT_OPENGL_COMPATIBILITY_PROFILE_BIT_KHR};
// Create an EGL rendering context
const EGLint contextAttributeList[] = {
EGL_CONTEXT_OPENGL_PROFILE_MASK_KHR,
profile,
EGL_CONTEXT_MAJOR_VERSION_KHR,
g_opengl_major,
EGL_CONTEXT_MINOR_VERSION_KHR,
g_opengl_minor,
EGL_NONE};
s_context = eglCreateContext(s_display, config, EGL_NO_CONTEXT,
contextAttributeList);
if (!s_context) {
debug_log("Context creation failed! error: %d", eglGetError());
goto _fail2;
}
// Connect the context to the surface
eglMakeCurrent(s_display, s_surface, s_surface, s_context);
return true;
}
_fail2:
eglDestroySurface(s_display, s_surface);
s_surface = nullptr;
_fail1:
eglTerminate(s_display);
s_display = nullptr;
_fail0:
gloat::utils::Abort(&result);
return false;
}
static void deinitEgl() {
if (s_display) {
eglMakeCurrent(s_display, EGL_NO_SURFACE, EGL_NO_SURFACE,
EGL_NO_CONTEXT);
if (s_context) {
eglDestroyContext(s_display, s_context);
s_context = nullptr;
}
if (s_surface) {
eglDestroySurface(s_display, s_surface);
s_surface = nullptr;
}
eglTerminate(s_display);
s_display = nullptr;
}
}
void init();
void render();
void quit();
void chooseLayer(int layerId);
int getLayer();
nn::hid::KeyboardState g_KeyboardState;
void updateHid() {
memset(&g_KeyboardState, 0, sizeof(g_KeyboardState));
nn::hid::GetKeyboardState(&g_KeyboardState);
}
extern "C" void nnosSleepThread(uint64_t nano);
extern "C" void nnMain(void) {
debug_log("Hello from nnMain :)");
init_fs();
init_nv();
nn::hid::InitializeKeyboard();
nn::Result result(0);
if (!initEgl()) return;
if (!gladLoadGL()) return;
init();
// TODO: wait for vsync
while (true) {
updateHid();
bool is_a_pressed = !!(g_KeyboardState.keys[0] & (1 << 0x04));
chooseLayer(!is_a_pressed);
render();
eglSwapBuffers(s_display, s_surface);
}
quit();
deinitEgl();
// NEEDED
while (true) {
}
} | 27.252226 | 79 | 0.571973 | [
"render",
"vector"
] |
3d572a1d039c941280e2cd6e1dda5ce6a3e25603 | 43,966 | cpp | C++ | src/Technosoftware/Server/Da/DaGenericServer.cpp | AkatorMr/opc-daae-server | 7d56e4603064b53476d3c0971a4d873066fba65f | [
"Info-ZIP"
] | null | null | null | src/Technosoftware/Server/Da/DaGenericServer.cpp | AkatorMr/opc-daae-server | 7d56e4603064b53476d3c0971a4d873066fba65f | [
"Info-ZIP"
] | null | null | null | src/Technosoftware/Server/Da/DaGenericServer.cpp | AkatorMr/opc-daae-server | 7d56e4603064b53476d3c0971a4d873066fba65f | [
"Info-ZIP"
] | 1 | 2021-04-15T01:08:29.000Z | 2021-04-15T01:08:29.000Z | /*
* Copyright (c) 2020 Technosoftware GmbH. All rights reserved
* Web: https://technosoftware.com
*
* The source code in this file is covered under a dual-license scenario:
* - Owner of a purchased license: SCLA 1.0
* - GPL V3: everybody else
*
* SCLA license terms accompanied with this source code.
* See https://technosoftware.com/license/Source_Code_License_Agreement.pdf
*
* GNU General Public License as published by the Free Software Foundation;
* version 3 of the License are accompanied with this source code.
* See https://technosoftware.com/license/GPLv3License.txt
*
* This source code 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.
*/
//DOM-IGNORE-BEGIN
#include "stdafx.h"
#include <process.h>
#include <stdio.h>
#include "DaGenericServer.h"
#include "UtilityFuncs.h"
#include "DaComServer.h"
#include "DaPublicGroup.h"
//=========================================================================
// Constructor
//=========================================================================
DaGenericServer::DaGenericServer()
{
m_Created = FALSE;
m_pServerHandler = NULL;
m_pCOpcSrv = NULL;
m_FilterCriteria = NULL;
m_hUpdateThread = NULL;
InitializeCriticalSection(&m_CritSec);
InitializeCriticalSection(&m_GroupsCritSec);
InitializeCriticalSection(&m_UpdateRateCritSec);
CriticalSectionCOMGroupList.Initialize();
}
//=========================================================================
// Initializer
//=========================================================================
HRESULT DaGenericServer::Create(DaBaseServer* pServerClassHandler, DaComBaseServer* pOPCServerBase)
{
HRESULT res;
_ASSERTE(pServerClassHandler != NULL);
_ASSERTE(pOPCServerBase != NULL);
if (m_Created == TRUE) {
// already created
return E_FAIL;
}
// fill position zero with no group
// so that zero won't be used as a valid group handle!
res = m_GroupList.PutElem(0, NULL);
if (FAILED(res)) {
return res;
}
// actual filter criteria
m_FilterCriteria = SysAllocString(L"");
if (m_FilterCriteria == NULL) {
return E_OUTOFMEMORY;
}
// server class handler
m_pServerHandler = pServerClassHandler;
// OPC server class base
m_pCOpcSrv = pOPCServerBase;
// get the actual update rate
// from which the groups 'tick count' information will be calculated
m_ActualBaseUpdateRate = pServerClassHandler->GetBaseUpdateRate();
m_ToKill = FALSE;
m_RefCount = 0;
// default enumeration type
m_Enum_Type = OPC_GROUPNAME_ENUM;
CoFileTimeNow(&m_StartTime);
memset(&m_LastUpdateTime, 0, sizeof(m_LastUpdateTime)); // 1.Jan 1970, 00:00:00
// automation group enumeration settings
m_Enum_Scope = OPC_ENUM_ALL;
m_Enum_Type = OPC_GROUP_ENUM;
// automation browse server address space enumerartions
m_EnumeratingItemIDs = TRUE;
// if m_EnumeratingItemIDs == FALSE => enumerating Access Paths
m_BrowseItemIDForAccessPath = FALSE;
m_BrowseFilterType = OPC_FLAT;
m_DataTypeFilter = VT_EMPTY;
m_AccessRightsFilter = 0;
// Create the update event
TCHAR szEventName[30]; // Name must be unique
_stprintf_s(szEventName, 30, _T("UpdateEvent_0x%X"), this);
m_hUpdateEvent = CreateEvent(NULL, // Cannot inherit handle.
FALSE, // Automatically reset.
FALSE, // Nonsignaled initial state.
szEventName);
if (m_hUpdateEvent == NULL) {
res = E_FAIL; // Cannot create an event.
goto CreateExit2;
}
res = CreateWaitForUpdateThread();
if (FAILED(res)) {
goto CreateExit3;
}
res = m_BrowseData.Create(pServerClassHandler);
if (FAILED(res)) {
goto CreateExit4;
}
m_Created = TRUE;
res = m_pServerHandler->AddServerToList(this);
if (FAILED(res)) {
goto CreateExit4;
}
Attach(); // Now generic Server is used
return S_OK;
CreateExit4:
m_Created = FALSE;
KillWaitForUpdateThread();
CreateExit3:
CloseHandle(m_hUpdateEvent);
m_hUpdateEvent = NULL;
CreateExit2:
SysFreeString(m_FilterCriteria);
m_FilterCriteria = NULL;
return res;
}
//=========================================================================
// Destructor
//=========================================================================
DaGenericServer::~DaGenericServer(void)
{
if (m_Created == TRUE) {
m_pServerHandler->RemoveServerFromList(this);
CloseHandle(m_hUpdateEvent);
m_hUpdateEvent = NULL;
}
if (m_FilterCriteria) {
SysFreeString(m_FilterCriteria);
}
DeleteCriticalSection(&m_GroupsCritSec);
DeleteCriticalSection(&m_CritSec);
DeleteCriticalSection(&m_UpdateRateCritSec);
}
//=====================================================================================
// Attach to class by incrementing the RefCount
// Returns the current RefCount
// or -1 if the ToKill flag is set
//=====================================================================================
int DaGenericServer::Attach(void)
{
long i;
EnterCriticalSection(&m_CritSec);
if (m_ToKill) {
return -1;
}
i = m_RefCount++;
LeaveCriticalSection(&m_CritSec);
return i;
}
//=====================================================================================
// Detach from class by decrementing the RefCount.
// Kill the class instance if request pending.
// Returns the current RefCount or -1 if it was killed.
//=====================================================================================
int DaGenericServer::Detach(void)
{
long i;
EnterCriticalSection(&m_CritSec);
_ASSERTE(m_RefCount > 0);
m_RefCount--;
if ((m_RefCount == 0) // not referenced
&& (m_ToKill == TRUE)) { // kill request
LeaveCriticalSection(&m_CritSec);
delete this; // remove from memory
return -1;
}
i = m_RefCount;
LeaveCriticalSection(&m_CritSec);
return i;
}
//=====================================================================================
// Kill the class instance.
// If the RefCount is > 0 then only the kill request flag is set.
// Returns the current RefCount or -1 if it was killed.
//=====================================================================================
int DaGenericServer::Kill(BOOL WithDetach)
{
long i;
HRESULT res;
DaGenericGroup* theGroup;
KillWaitForUpdateThread();
EnterCriticalSection(&m_CritSec);
// kill the groups of this server
EnterCriticalSection(&m_GroupsCritSec);
res = m_GroupList.First(&i);
while (SUCCEEDED(res)) {
res = m_GroupList.GetElem(i, &theGroup);
if (theGroup->Killed() == FALSE) {
theGroup->Kill();
}
res = m_GroupList.Next(i, &i);
}
LeaveCriticalSection(&m_GroupsCritSec);
// !!!??? ev. force delete of all COM groups!
// so that the server will shutdown even if there are
// bad clients
//
if (WithDetach) {
if (m_RefCount > 0)
--m_RefCount;
}
if (m_RefCount) { // still referenced
m_ToKill = TRUE; // set kill request flag
}
else {
LeaveCriticalSection(&m_CritSec);
delete this;
return -1;
}
i = m_RefCount;
LeaveCriticalSection(&m_CritSec);
return i;
}
//=========================================================================
// Killed()
// tells whether the class instance was killed (with Kill()) or not
//=========================================================================
BOOL DaGenericServer::Killed(void)
{
BOOL b;
EnterCriticalSection(&m_CritSec);
b = m_ToKill;
LeaveCriticalSection(&m_CritSec);
return b;
}
//=========================================================================
// GetGenericGroup
// returns the group associated with handle
// if handle not valid (maybe group was deleted)
// then return NULL
//=========================================================================
HRESULT DaGenericServer::GetGenericGroup(
long ServerGroupHandle,
DaGenericGroup **group)
{
long res;
long pgh;
DaPublicGroup *pg;
DaPublicGroupManager *pgHandler;
pgHandler = &(m_pServerHandler->publicGroups_);
EnterCriticalSection(&m_GroupsCritSec);
res = m_GroupList.GetElem(ServerGroupHandle, group);
if (FAILED(res)) {
res = OPC_E_INVALIDHANDLE; // invalid handle
goto GetGenericGroupExit0;
}
if ((*group)->Killed() == TRUE) {
res = E_FAIL; // group has to be removed
goto GetGenericGroupExit0;
}
// check if group is public
if ((*group)->GetPublicInfo(&pgh) == TRUE) {
// check if this public group still exists
// !!!??? maybe this instruction can create DEADLOCK! control!
res = pgHandler->GetGroup(pgh, &pg);
if (FAILED(res)) {
// public group isn't there
// remove DaGenericGroup from server list and kill
(*group)->Kill();
res = OPC_E_INVALIDHANDLE;
goto GetGenericGroupExit0;
}
pgHandler->ReleaseGroup(pgh);
}
// increment ref count so that group cannot be deleted
// during access
(*group)->Attach();
res = S_OK;
GetGenericGroupExit0:
LeaveCriticalSection(&m_GroupsCritSec);
return res;
}
//=========================================================================
// ReleaseGenericGroup
//
//=========================================================================
HRESULT DaGenericServer::ReleaseGenericGroup(
long ServerGroupHandle)
{
DaGenericGroup *group;
long res;
EnterCriticalSection(&m_GroupsCritSec);
res = m_GroupList.GetElem(ServerGroupHandle, &group);
if (FAILED(res)) {
res = OPC_E_INVALIDHANDLE;
goto ReleaseGenericGroupExit0;
}
if (group->Detach() < 0) { // killed due to request
res = m_GroupList.PutElem(ServerGroupHandle, NULL);
}
res = S_OK;
ReleaseGenericGroupExit0:
LeaveCriticalSection(&m_GroupsCritSec);
return res;
}
//=========================================================================
// RemoveGenericGroup
//=========================================================================
HRESULT DaGenericServer::RemoveGenericGroup(
long ServerGroupHandle)
{
HRESULT hres = S_OK;
DaGenericGroup* pGGroup;
EnterCriticalSection(&m_GroupsCritSec);
m_GroupList.GetElem(ServerGroupHandle, &pGGroup);
if ((pGGroup == NULL) || pGGroup->Killed()) {
hres = OPC_E_INVALIDHANDLE;
}
else {
pGGroup->Kill();
}
LeaveCriticalSection(&m_GroupsCritSec);
return hres;
}
//=========================================================================
// SearchGroup
// searches a group between public or private groups
// this function expects external
// collision control through the m_GroupsCritSec critical section
//=========================================================================
HRESULT DaGenericServer::SearchGroup(
BOOL Public,
LPCWSTR theName,
DaGenericGroup **theGroup,
long *sgh)
{
long i, size;
long pgh;
DaGenericGroup *group;
HRESULT res;
if (theName != NULL) {
size = m_GroupList.Size();
for (i = 0; i < size; i++) {
res = m_GroupList.GetElem(i, &group);
if ((SUCCEEDED(res))
&& (group->Killed() == FALSE)
&& (group->GetPublicInfo(&pgh) == Public)
&& (wcscmp(theName, group->m_Name) == 0)) {
*sgh = i;
*theGroup = group;
return S_OK;
}
}
}
*theGroup = NULL;
return E_FAIL;
}
//=========================================================================
// ChangePrivateGroupName
//=========================================================================
HRESULT DaGenericServer::ChangePrivateGroupName(
DaGenericGroup *group,
LPWSTR Name
)
{
HRESULT res;
long sgh;
long pgh;
DaGenericGroup *foundGroup;
if (group->GetPublicInfo(&pgh) == TRUE) {
res = OPC_E_PUBLIC;
goto ChangePrivateGroupNameExit0;
}
if (!Name || *Name == L'\0') {
LOGFMTE("ChangePrivateGroupName() failed with invalid argument(s): Name is a NULL-Pointer or a NULL-String");
res = E_INVALIDARG;
goto ChangePrivateGroupNameExit0;
}
EnterCriticalSection(&m_GroupsCritSec);
res = SearchGroup(FALSE, Name, &foundGroup, &sgh);
if (SUCCEEDED(res)) {
if (foundGroup == group) { // Also succeeded bause it's the name
goto ChangePrivateGroupNameExit1; // of the own group.
}
res = OPC_E_DUPLICATENAME;
goto ChangePrivateGroupNameExit1;
}
res = group->set_Name(Name);
ChangePrivateGroupNameExit1:
LeaveCriticalSection(&(m_GroupsCritSec));
ChangePrivateGroupNameExit0:
return res;
}
//=================================================================
// GetCOMGroup
// Gets an interface of the associated COM group. If there
// is no COM object then it will be created.
//=================================================================
HRESULT DaGenericServer::GetCOMGroup(
DaGenericGroup* pGGroup,
REFIID riid,
LPUNKNOWN* ppUnk)
{
HRESULT hr;
CComObject<DaGroup>* pCOMGroup;
*ppUnk = NULL;
CriticalSectionCOMGroupList.BeginReading(); // Lock reading COM list
hr = m_COMGroupList.GetElem(pGGroup->m_hServerGroupHandle, &pCOMGroup);
if (SUCCEEDED(hr)) { // there already is a COM group
hr = pCOMGroup->QueryInterface(riid, (LPVOID *)ppUnk);
CriticalSectionCOMGroupList.EndReading(); // Unlock reading COM list
return hr;
}
CriticalSectionCOMGroupList.EndReading(); // Unlock reading COM list
CriticalSectionCOMGroupList.BeginWriting(); // Lock writing COM list
hr = m_COMGroupList.GetElem(pGGroup->m_hServerGroupHandle, &pCOMGroup);
if (SUCCEEDED(hr)) { // there already is a COM group
hr = pCOMGroup->QueryInterface(riid, (LPVOID *)ppUnk);
}
else {
// create the COM Group
hr = CComObject<DaGroup>::CreateInstance(&pCOMGroup);
if (FAILED(hr)) {
goto GetCOMGroupExit1;
}
// initialize the COM group
hr = pCOMGroup->Create(this, pGGroup->m_hServerGroupHandle, pGGroup);
if (FAILED(hr)) { // failed
delete pCOMGroup;
goto GetCOMGroupExit1;
}
// get the requested interface
hr = pCOMGroup->QueryInterface(riid, (LPVOID *)ppUnk);
if (FAILED(hr)) {
delete pCOMGroup;
goto GetCOMGroupExit1;
}
// store the created COM group in the list
hr = m_COMGroupList.PutElem(pGGroup->m_hServerGroupHandle, pCOMGroup);
if (FAILED(hr)) { // probably out of memory
pCOMGroup->Release(); // release interface and destroy object
goto GetCOMGroupExit1;
}
// all succeeded
}
GetCOMGroupExit1:
CriticalSectionCOMGroupList.EndWriting(); // Unlock writing COM list
return hr;
}
//=================================================================
// Internal Enumeration Helper Method to get an array of
// Interface-Ptrs to the requested groups.
//
// Parameters:
// riid: Interface type requested: IID_IEnumUnknown or IID_IEnumString
// scope: Indicates the class of groups to be enumerated
// OPC_ENUM_PRIVATE_CONNECTIONS
// enumerates the private groups the client is connected to.
// OPC_ENUM_PUBLIC_CONNECTIONS
// enumerates the public groups the client is connected to.
// OPC_ENUM_ALL_CONNECTIONS
// enumerates all of the groups the client is connected to.
// OPC_ENUM_PRIVATE
// enumerates all of the private groups created by the client (whether connected or not)
// OPC_ENUM_PUBLIC
// enumerates all of the public groups available in the server (whether connected or not)
// OPC_ENUM_ALL
// enumerates all private groups and all public groups (whether connected or not)
//
// GroupList: returned array of Interface Ptrs
//
// GroupCount: Number of returned ptrs
//
//=================================================================
//-----------------------------------------------------------------
// Notes:
// m_GroupsCritSec locking is done outside!
//-----------------------------------------------------------------
HRESULT DaGenericServer::GetGrpList(
REFIID riid,
OPCENUMSCOPE scope,
LPUNKNOWN **GroupList,
int *GroupCount)
{
long sh, size, count;
LPUNKNOWN pUnk;
DaGenericGroup *group;
CComObject<DaGroup> *pCOMGroup;
HRESULT res;
BOOL bPublic;
long pgh;
_ASSERTE((riid == IID_IEnumUnknown) || (riid == IID_IEnumString));
if ((scope != OPC_ENUM_PRIVATE)
&& (scope != OPC_ENUM_ALL)
&& (scope != OPC_ENUM_PUBLIC)
&& (scope != OPC_ENUM_PRIVATE_CONNECTIONS)
&& (scope != OPC_ENUM_ALL_CONNECTIONS)
&& (scope != OPC_ENUM_PUBLIC_CONNECTIONS)) {
goto GetGrpListExit0;
}
// First public group list must be refreshed
RefreshPublicGroups();
size = m_GroupList.TotElem(); // highest group index
if (size == 0) { // no groups
res = S_OK;
goto GetGrpListExit0;
}
*GroupList = new LPUNKNOWN[size];
if (*GroupList == NULL) {
res = E_OUTOFMEMORY;
goto GetGrpListExit0;
}
// go through all generic groups
// and if enumerating connections
// look if there is the corresponding COM group
count = 0;
res = m_GroupList.First(&sh);
while (SUCCEEDED(res)) {
res = m_GroupList.GetElem(sh, &group);
if ((SUCCEEDED(res))
&& (group->Killed() == FALSE)) {
bPublic = group->GetPublicInfo(&pgh);
CriticalSectionCOMGroupList.BeginReading(); // Lock reading COM list
res = m_COMGroupList.GetElem(sh, &pCOMGroup);
if (((scope == OPC_ENUM_PRIVATE) && (bPublic == FALSE))
|| ((scope == OPC_ENUM_PUBLIC) && (bPublic == TRUE))
|| (scope == OPC_ENUM_ALL)
|| ((SUCCEEDED(res)) && (scope == OPC_ENUM_PRIVATE_CONNECTIONS) && (bPublic == FALSE))
|| ((SUCCEEDED(res)) && (scope == OPC_ENUM_PUBLIC_CONNECTIONS) && (bPublic == TRUE))
|| ((SUCCEEDED(res)) && (scope == OPC_ENUM_ALL_CONNECTIONS))) {
if (riid == IID_IEnumUnknown) {
// create a new COM group for this group
// and get a new interface for this group
res = GetCOMGroup(group, IID_IUnknown, &pUnk);
if (FAILED(res)) { // error, ignore group
goto GetGrpListExit1;
}
(*GroupList)[count] = pUnk;
}
else { // IID_IEnumString
(*GroupList)[count] = (LPUNKNOWN)WSTRClone(group->m_Name, NULL);
}
// count the group
++count;
}
CriticalSectionCOMGroupList.EndReading(); // Unlock reading COM list
}
res = m_GroupList.Next(sh, &sh);
}
*GroupCount = count;
return S_OK;
GetGrpListExit1:
// release the COM items
CriticalSectionCOMGroupList.EndReading(); // Unlock reading COM list
count--;
while (count >= 0) {
(*GroupList)[count]->Release();
count--;
}
delete GroupList;
GetGrpListExit0:
*GroupList = NULL; // init results
*GroupCount = 0;
return res;
}
//=================================================================
// free the group list allocated with GetGrpList
//=================================================================
HRESULT DaGenericServer::FreeGrpList(
REFIID riid,
LPUNKNOWN *GroupList,
int count)
{
int sh;
if ((count == 0) && (GroupList == NULL)) {
return S_OK;
}
if (riid == IID_IEnumString) {
// free the strings
for (sh = 0; sh < count; sh++) {
//delete ( LPOLESTR ) ( GroupList[sh] );
WSTRFree((LPWSTR)(GroupList[sh]), NULL);
}
}
else {
sh = 0;
while (sh < count) {
GroupList[sh]->Release();
sh++;
}
}
delete GroupList; // free the list
return S_OK;
}
//=================================================================
// refreshes m_GroupList deleting no more existing public groups
// and inserting newly created ones!
// This proc assumes m_GroupList is already locked by the caller
//=================================================================
HRESULT DaGenericServer::RefreshPublicGroups()
{
long sh;
long res;
DaGenericGroup *group, *theGroup;
DaPublicGroupManager *pgHandler;
DaPublicGroup *pPG;
long pgh;
int found;
long thePGh;
BOOL bPublic;
// start to enumerate all the groups
// except 0 which is the invalid handle
pgHandler = &(m_pServerHandler->publicGroups_);
res = m_GroupList.Next(0, &sh);
while (SUCCEEDED(res)) {
// found a group
res = m_GroupList.GetElem(sh, &group);
if (group->Killed() == FALSE) {
bPublic = group->GetPublicInfo(&pgh);
if (bPublic == TRUE) {
res = pgHandler->GetGroup(pgh, &pPG);
if (FAILED(res)) {
// public group isn't there
// remove DaGenericGroup from server list and delete
m_GroupList.PutElem(sh, NULL);
// invalid handle or group has to be removed
group->Kill();
}
else {
// there is a public group
pgHandler->ReleaseGroup(pgh);
}
}
}
res = m_GroupList.Next(sh, &sh);
}
// search in the public group list
// if there is some group not in the servers m_GroupList create and add it!
res = pgHandler->First(&pgh);
while (SUCCEEDED(res)) {
// get and nail the public group
res = pgHandler->GetGroup(pgh, &pPG);
if (SUCCEEDED(res)) {
found = FALSE;
res = m_GroupList.Next(0, &sh);
while ((SUCCEEDED(res)) && (found == FALSE)) {
res = m_GroupList.GetElem(sh, &group);
bPublic = group->GetPublicInfo(&thePGh);
if ((bPublic == TRUE) && (thePGh == pgh)) {
found = TRUE;
}
res = m_GroupList.Next(sh, &sh);
}
if (found == FALSE) {
// there is a public group without a corresponding DaGenericGroup:
// so we have to create the DaGenericGroup for this client
// create the group from the DaPublicGroup
theGroup = new DaGenericGroup();
if (theGroup == NULL) {
// unnail the public group
pgHandler->ReleaseGroup(pgh);
res = E_OUTOFMEMORY;
goto RefreshPublicGroupsExit0;
}
// create the group from the DaPublicGroup
res = theGroup->Create(
this,
pPG->m_Name,
pPG->m_InitialActive,
&pPG->m_InitialTimeBias,
pPG->m_InitialUpdateRate,
0, // client group handle: default
&pPG->m_PercentDeadband,
0, // LCID
TRUE, // Public group
pgh,
&sh
);
if (FAILED(res)) {
delete theGroup;
// unnail the public group
pgHandler->ReleaseGroup(pgh);
res = E_OUTOFMEMORY;
goto RefreshPublicGroupsExit0;
}
}
// unnail the public group
pgHandler->ReleaseGroup(pgh);
} // couldn't get the group
// get the next in the list
res = pgHandler->Next(pgh, &pgh);
}
res = S_OK;
RefreshPublicGroupsExit0:
return res;
}
//=================================================================
// GetGroupUniqueName
// old: "returns a unique name for a private or public group"
// V1.0a: returns a unique name among private and public groups!
// the server group handle is used as a starting point ( to build the name )
// This proc assumes m_GroupList is already locked by the caller
//=================================================================
HRESULT DaGenericServer::GetGroupUniqueName(long ServerGroupHandle, WCHAR **theName, BOOL bPublic)
{
WCHAR wc[15];
long i;
long sgh;
DaGenericGroup *foundGroup;
i = ServerGroupHandle;
*theName = new WCHAR[32];
if (*theName == NULL) {
return E_OUTOFMEMORY;
}
wcscpy(*theName, L"Group_");
_itow(i, wc, 10);
wcscat(*theName, wc);
while ((SUCCEEDED(SearchGroup(TRUE, *theName, &foundGroup, &sgh)))
|| (SUCCEEDED(SearchGroup(FALSE, *theName, &foundGroup, &sgh)))) {
// it's already a public or private group name
// generate another
wcscpy(*theName, L"Group_");
_itow(i, wc, 10);
wcscat(*theName, wc);
i++;
}
return S_OK;
}
//=================================================================================
// Thread waiting for Update Event from server class handler
// ---------------------------------------------------------
//=================================================================================
unsigned __stdcall WaitForUpdateThread(void* pArg)
{
DaGenericServer* serv = static_cast<DaGenericServer *>(pArg);
_ASSERTE(serv != NULL);
long idx;
HRESULT res;
DaGenericGroup *group;
while (serv->m_UpdateThreadToKill == FALSE) {
// wait ServerClassHandler sends me update event
WaitForSingleObject(serv->m_hUpdateEvent, INFINITE);
// check if base update rate has changend
// and if so recalc tick counts of groups
serv->CheckBaseUpdateRateChanged();
// update all groups belonging to this server instance
// all access to the group list is protected by crit sec
EnterCriticalSection(&serv->m_GroupsCritSec);
res = serv->m_GroupList.First(&idx);
while (SUCCEEDED(res)) {
// get and nail the group
res = serv->GetGenericGroup(idx, &group);
LeaveCriticalSection(&serv->m_GroupsCritSec);
if (SUCCEEDED(res)) {
if (group->GetActiveState() == TRUE) {
// only active groups enter into account for update
EnterCriticalSection(&group->m_UpdateRateCritSec);
// recalc ticks if base update rate changed
serv->RecalcTicks(group);
// update only active groups
group->m_TickCount--;
if (group->m_TickCount == 0) {
// restart tick counter
group->m_TickCount = group->m_Ticks;
LeaveCriticalSection(&group->m_UpdateRateCritSec);
// it's group turn to update
res = group->UpdateNotify();
}
else {
LeaveCriticalSection(&group->m_UpdateRateCritSec);
}
//
// Keep Alive
//
if (group->m_fCallbackEnable) {
group->m_csKeepAlive.Lock();
if (group->KeepAliveTime()) { // Activated keep-alive callbacks
CComObject<DaGroup>* pCOMGroup = NULL;
IUnknown** ppCallback = NULL;
serv->CriticalSectionCOMGroupList.BeginReading(); // lock reading
if (SUCCEEDED(serv->m_COMGroupList.GetElem(group->m_hServerGroupHandle, &pCOMGroup))) {
ppCallback = pCOMGroup->m_vec.begin(); // Check if there is a registered callback function
if (*ppCallback) { // Enabled Callback exist
group->m_dwKeepAliveCount--;
if (group->m_dwKeepAliveCount == 0) {
group->ResetKeepAliveCounter();
HRESULT hrErr = S_OK;
pCOMGroup->FireOnDataChange(0, NULL, &hrErr);
}
}
}
serv->CriticalSectionCOMGroupList.EndReading(); // unlock reading
}
group->m_csKeepAlive.Unlock();
}
//
// Keep Alive
//
}
// unnail the group
serv->ReleaseGenericGroup(idx);
}
// get the index of the next group in the list
EnterCriticalSection(&serv->m_GroupsCritSec);
res = serv->m_GroupList.Next(idx, &idx);
}
LeaveCriticalSection(&serv->m_GroupsCritSec);
}
_endthreadex(0);
return 0;
} // WaitForUpdateThread
//=================================================================================
// Create Update Thread
// --------------------
//=================================================================================
HRESULT DaGenericServer::CreateWaitForUpdateThread(void)
{
unsigned uThreadID; // Thread identifier
m_UpdateThreadToKill = FALSE;
m_hUpdateThread = (HANDLE)_beginthreadex(
NULL, // No thread security attributes
0, // Default stack size
WaitForUpdateThread, // Pointer to thread function
this, // Pass class to new thread for access to the AppHandler
0, // Run thread immediately
&uThreadID); // Thread identifier
if (m_hUpdateThread == 0) { // Cannot create the thread
return HRESULT_FROM_WIN32(GetLastError());
}
return S_OK;
}
//=================================================================================
// Kill Update Thread
// ------------------
//=================================================================================
HRESULT DaGenericServer::KillWaitForUpdateThread(void)
{
if (m_hUpdateThread) {
m_UpdateThreadToKill = TRUE;
// give a chance to exit if the thread is waiting
SetEvent(m_hUpdateEvent);
// Wait max 60 secs until the update thread has terminated.
if (WaitForSingleObject(m_hUpdateThread, 60000) == WAIT_TIMEOUT) {
TerminateThread(m_hUpdateThread, 1);
}
CloseHandle(m_hUpdateThread);
m_hUpdateThread = NULL;
}
return S_OK;
}
//=================================================================================
// Check Base Update Rate
// ----------------------
//=================================================================================
BOOL DaGenericServer::CheckBaseUpdateRateChanged(void)
{
DWORD newrate;
newrate = m_pServerHandler->GetBaseUpdateRate();
EnterCriticalSection(&m_UpdateRateCritSec);
if (newrate != m_ActualBaseUpdateRate) {
// base update rate has changed!
m_ActualBaseUpdateRate = newrate;
LeaveCriticalSection(&m_UpdateRateCritSec);
return TRUE;
}
LeaveCriticalSection(&m_UpdateRateCritSec);
return FALSE;
}
//=================================================================================
// Recalculate Tick Count information for group
// --------------------------------------------
//=================================================================================
HRESULT DaGenericServer::RecalcTicks(DaGenericGroup *group)
{
HRESULT res;
DWORD rate;
_ASSERTE(group != NULL);
rate = GetActualBaseUpdateRate();
if (rate != group->GetActualBaseUpdateRate()) {
// set the new update rate
group->SetActualBaseUpdateRate(rate);
// recalc tick information
res = group->ReviseUpdateRate(group->m_RequestedUpdateRate);
}
else {
res = S_OK;
}
return res;
}
//=================================================================================
// returns the actual base update rate
//=================================================================================
DWORD DaGenericServer::GetActualBaseUpdateRate(void)
{
DWORD rate;
EnterCriticalSection(&m_UpdateRateCritSec);
rate = m_ActualBaseUpdateRate;
LeaveCriticalSection(&m_UpdateRateCritSec);
return rate;
}
//=================================================================================
// sets the actual base update rate
//=================================================================================
HRESULT DaGenericServer::SetActualBaseUpdateRate(DWORD BaseUpdateRate)
{
EnterCriticalSection(&m_UpdateRateCritSec);
m_ActualBaseUpdateRate = BaseUpdateRate;
LeaveCriticalSection(&m_UpdateRateCritSec);
return S_OK;
}
//=================================================================================
// Fires a 'Shutdown Request' to the subscribed client
//=================================================================================
void DaGenericServer::FireShutdownRequest(LPCWSTR szReason)
{
_ASSERTE(m_Created);
_ASSERTE(m_pCOpcSrv);
m_pCOpcSrv->FireShutdownRequest(szReason);
}
//=================================================================================
// Calls the OnRefreshOutputDevices() function in the server specific part.
// The current client name is provided as 'Actor ID'.
// This function returns only S_OK or S_FALSE.
//=================================================================================
HRESULT DaGenericServer::OnRefreshOutputDevices(
/* [in] */ DWORD dwNumOfItems,
/* [in][dwNumOfItems] */ DaDeviceItem ** ppDItems,
/* [in][out][dwNumOfItems] */ OPCITEMVQT * pVQTs,
/* [in][out][dwNumOfItems] */ HRESULT * errors)
{
_ASSERTE(m_Created);
_ASSERTE(m_pCOpcSrv);
LPWSTR szActorID;
HRESULT hrActorID = m_pCOpcSrv->GetClientName(&szActorID);
if (FAILED(hrActorID)) {
szActorID = L"Unknown"; // Must not be NULL
}
HRESULT hrRefresh = m_pServerHandler->OnRefreshOutputDevices(
OPC_REFRESH_CLIENT, szActorID,
dwNumOfItems,
ppDItems,
pVQTs,
errors);
_ASSERTE(SUCCEEDED(hrRefresh)); // Must return S_OK or S_FALSE
if (SUCCEEDED(hrActorID)) { // Release ActorID if successfully returned
ComFree(szActorID);
}
return hrRefresh;
}
//=========================================================================
// InternalReadMaxAge
// ------------------
// Read the given array of items. The MaxAge value will determine
// where the data is obtained.
//
// This method is called from multiple threads
// - serving different clients
// - handling sync/async read, refresh, update for the same client
// Non-reentrant parts must therefore be protected !
//
// Note :
// - ppDItems may contain NULL values ...
// these are the items eliminated before read ...
// - pItemValues[x].vDataValue.vt contains the requested data type
// or VT_EMPTY if the canonical data type should be used.
// - Since this function must return S_OK or S_FALSE a
// temporary buffer (ppTemporaryBuffer) and the current time
// (pftNow) must be allocated/specified outside of this function
// by the caller.
// - The size of the ppTemporaryBuffer must be identically with the
// size of the ppDItems buffer.
//
// return:
// S_OK if succeeded for all items; otherwise S_FALSE.
// Do not return other codes !
//=========================================================================
HRESULT DaGenericServer::InternalReadMaxAge(
/* [in] */ LPFILETIME pftNow,
/* [in] */ DWORD dwNumOfItems,
/* [in][dwNumOfItems] */ DaDeviceItem ** ppDItems, // Contains the Device Item pointers, Arrays size is dwNumOfItems
/* [in][dwNumOfItems] */ DaDeviceItem ** ppTemporaryBuffer, // A temporary buffer, must be provided by the caller
/* [in][dwNumOfItems] */ DWORD * pdwMaxAges,
/* [in][out][dwNumOfItems] */ VARIANT * pvValues,
/* [in][out][dwNumOfItems] */ WORD * pwQualities,
/* [in][out][dwNumOfItems] */ FILETIME * pftTimeStamps,
/* [in][out][dwNumOfItems] */ HRESULT * errors,
/* [in][dwNumOfItems] */ BOOL * pfPhyval /* = NULL */)
{
// Contains the pointers to the Device Items for
// which the value needs to be updated from the Device.
DaDeviceItem** pDItemsToReadFromDevice = ppTemporaryBuffer;
HRESULT hrRet = S_OK;
DWORD i;
DWORD dwNumOfItemsToReadFromDevice = 0;
for (i = 0; i < dwNumOfItems; i++) { // Check each requested Item
pDItemsToReadFromDevice[i] = NULL;
DaDeviceItem* pDItem = ppDItems[i];
if (pDItem) {
// Max Age Handling
if (pdwMaxAges[i] == 0) { // Read always from device
pDItemsToReadFromDevice[i] = pDItem;
dwNumOfItemsToReadFromDevice++;
}
else if (pdwMaxAges[i] != 0xFFFFFFFF) {
// Compare Max Age if not disabled
// Subtract Max Age from the current time
ULONGLONG* pulNow = (ULONGLONG*)pftNow;
ULONGLONG* pulAge = (ULONGLONG*)&pdwMaxAges[i];
ULONGLONG ulCompareTime = *pulNow - *pulAge;
if (pDItem->IsTimeStampOlderThan((FILETIME*)&ulCompareTime)) {
pDItemsToReadFromDevice[i] = pDItem;
dwNumOfItemsToReadFromDevice++;
}
}
}
}
//
// Read from the Device for those Items which it's required.
//
if (dwNumOfItemsToReadFromDevice) {
HRESULT hrRefresh = m_pServerHandler->OnRefreshInputCache(
OPC_REFRESH_CLIENT,
dwNumOfItems,
pDItemsToReadFromDevice,
errors);
_ASSERTE(SUCCEEDED(hrRefresh)); // Must return S_OK or S_FALSE
}
//
// Now the Data Cache is up to date and the values can be read
//
m_pServerHandler->readWriteLock_.BeginReading();
for (i = 0; i < dwNumOfItems; i++) { // Check each requested Item
if (ppDItems[i]) { // Valid Item
if (FAILED(errors[i])) { // Read from Device failed
hrRet = S_FALSE;
}
else {
// Use the canonical data type if requested data
// type is VT_EMPTY.
if (V_VT(&pvValues[i]) == VT_EMPTY) {
V_VT(&pvValues[i]) = ppDItems[i]->get_CanonicalDataType();
}
// Read from Cache
errors[i] = ppDItems[i]->get_ItemValue(
&pvValues[i], // Value
&pwQualities[i], // Quality
&pftTimeStamps[i]); // Timestamp
if (FAILED(errors[i])) {
hrRet = S_FALSE;
}
}
}
}
m_pServerHandler->readWriteLock_.EndReading();
_ASSERTE(SUCCEEDED(hrRet)); // Must return S_OK or S_FALSE
return hrRet;
}
//=========================================================================
// InternalWriteVQT
// ----------------
// See comments of DaGenericGroup::InternalWrite() in
// module DaGenericGroup.cpp.
//=========================================================================
HRESULT DaGenericServer::InternalWriteVQT(
/* [in] */ DWORD dwNumOfItems,
/* [in][dwNumOfItems] */ DaDeviceItem ** ppDItems,
/* [in][out][dwNumOfItems] */ OPCITEMVQT * pVQTs,
/* [in][out][dwNumOfItems] */ HRESULT * errors,
/* [in][dwNumOfItems] */ BOOL * pfPhyval /* = NULL */,
/* [in] */ long hServerGroupHandle /* = -1 */)
{
DaDeviceItem* pDItem = NULL;
HRESULT hr = S_OK;
HRESULT hrRet = S_OK;
DWORD dwNumOfItemsToWrite = 0; // Counts the number of valid item pointers in ppItems[]
for (DWORD i = 0; i < dwNumOfItems; ++i) { // Write value into cache
pDItem = ppDItems[i];
if (pDItem == NULL) { // No refresh requested for this item
continue;
}
hr = S_OK;
OPCITEMVQT* pVQT = &pVQTs[i];
if (V_VT(&pVQT->vDataValue) != VT_EMPTY) {
// The value to be written must have the format required by the HW (indicated by
// the canonical data type)
hr = pDItem->ChangeValueToCanonicalType(&pVQT->vDataValue);
}
else if (!pVQT->bQualitySpecified && !pVQT->bTimeStampSpecified) {
hr = OPC_E_BADTYPE; // At least one value should be specified
}
if (FAILED(hr)) {
errors[i] = hr;
ppDItems[i] = NULL;
pDItem->Detach(); // Do not refresh output for this item
hrRet = S_FALSE;
}
else {
dwNumOfItemsToWrite++;
}
}
if (dwNumOfItemsToWrite) {
HRESULT hrRefresh = OnRefreshOutputDevices(
dwNumOfItems,
ppDItems,
pVQTs,
errors
);
if (hrRefresh == S_FALSE && hrRet == S_OK) {
hrRet = S_FALSE;
}
}
else {
hrRet = S_FALSE;
}
_ASSERTE(SUCCEEDED(hrRet)); // Must return S_OK or S_FALSE
return hrRet;
}
//DOM-IGNORE-END
| 32.02185 | 139 | 0.508256 | [
"object"
] |
3d5d636b99c4fff7b06e1e9f71dae0461ae4107a | 10,024 | cc | C++ | extensions/html_flash_element/html_flash_element.cc | suzhe/google-gadgets-for-linux | b58baabd8458c8515c9902b8176151a08d240983 | [
"Apache-2.0"
] | 175 | 2015-01-01T12:40:33.000Z | 2019-05-24T22:33:59.000Z | extensions/html_flash_element/html_flash_element.cc | suzhe/google-gadgets-for-linux | b58baabd8458c8515c9902b8176151a08d240983 | [
"Apache-2.0"
] | 11 | 2015-01-19T16:30:56.000Z | 2018-04-25T01:06:52.000Z | extensions/html_flash_element/html_flash_element.cc | suzhe/google-gadgets-for-linux | b58baabd8458c8515c9902b8176151a08d240983 | [
"Apache-2.0"
] | 97 | 2015-01-19T15:35:29.000Z | 2019-05-15T05:48:02.000Z | /*
Copyright 2008 Google 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.
*/
#include <ggadget/common.h>
#include <ggadget/element_factory.h>
#include <ggadget/view.h>
#include <ggadget/basic_element.h>
#include <ggadget/scriptable_helper.h>
#include <ggadget/string_utils.h>
namespace ggadget {
namespace internal {
static const char kHtmlFlashCode[] =
"<html>\n"
"<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\">\n"
"<style>*{ margin:0px; padding:0px }</style>\n"
"<body oncontextmenu=\"return false;\">\n"
"<embed src=\"%s\" "
"quality=\"high\" bgcolor=\"#ffffff\" width=\"100%\" play=\"true\" "
"height=\"100%\" type=\"application/x-shockwave-flash\" "
"swLiveConnect=\"true\" wmode=\"transparent\" name=\"movieObject\" "
"pluginspage=\"http://www.adobe.com/go/getflashplayer\"/>\n"
"</body>\n"
"<script language=\"JavaScript\">\n"
"window.external.movieObject = window.document.movieObject;\n"
"</script>\n"
"</html>";
static const char *kFlashMethods[] = {
"GetVariable",
"GotoFrame",
"IsPlaying",
"LoadMovie",
"Pan",
"PercentLoaded",
"Play",
"Rewind",
"SetVariable",
"SetZoomRect",
"StopPlay",
"TotalFrames",
"Zoom",
"TCallFrame",
"TCallLabel",
"TCurrentFrame",
"TCurrentLabel",
"TGetProperty",
"TGetPropertyAsNumber",
"TGotoFrame",
"TGotoLabel",
"TPlay",
"TSetProperty",
"TStopPlay"
};
class HtmlFlashElement : public BasicElement {
class ExternalObject : public ScriptableHelperNativeOwnedDefault {
public:
DEFINE_CLASS_ID(0x64eaa63bd2cc4efb, ScriptableInterface);
ExternalObject(HtmlFlashElement *owner) : owner_(owner) { }
protected:
virtual void DoRegister() {
RegisterProperty("movieObject", NULL,
NewSlot(owner_, &HtmlFlashElement::SetMovieObject));
}
private:
HtmlFlashElement *owner_;
};
class MethodCaller : public Slot {
public:
MethodCaller(HtmlFlashElement *owner, const char *name)
: owner_(owner), name_(name) {
}
virtual ResultVariant Call(ScriptableInterface *object,
int argc, const Variant argv[]) const {
GGL_UNUSED(object);
if (owner_ && name_ && owner_->movie_object_.Get()) {
Slot *slot = NULL;
ResultVariant prop = owner_->movie_object_.Get()->GetProperty(name_);
if (prop.v().type() == Variant::TYPE_SCRIPTABLE) {
ScriptableInterface *obj =
VariantValue<ScriptableInterface *>()(prop.v());
if (obj) {
ResultVariant slot_prop = obj->GetProperty("");
if (slot_prop.v().type() == Variant::TYPE_SLOT) {
slot = VariantValue<Slot *>()(slot_prop.v());
}
}
} else if (prop.v().type() == Variant::TYPE_SLOT) {
slot = VariantValue<Slot *>()(prop.v());
}
if (slot) {
return slot->Call(owner_->movie_object_.Get(), argc, argv);
}
}
return ResultVariant();
}
virtual bool HasMetadata() const {
return false;
}
virtual Variant::Type GetReturnType() const {
return Variant::TYPE_VARIANT;
}
virtual bool operator==(const Slot &another) const {
return owner_ == down_cast<const MethodCaller *>(&another)->owner_ &&
name_ == down_cast<const MethodCaller *>(&another)->name_;
}
private:
HtmlFlashElement *owner_;
const char *name_;
};
public:
DEFINE_CLASS_ID(0x2613c535747940a6, BasicElement);
HtmlFlashElement(View *view, const char *name)
: BasicElement(view, "flash", name, false),
browser_(view->GetElementFactory()->CreateElement("_browser", view, "")),
external_(this) {
SetPixelX(0);
SetPixelY(0);
SetRelativeWidth(1.0);
SetRelativeHeight(1.0);
if (browser_) {
browser_->SetParentElement(this);
browser_->SetPixelX(0);
browser_->SetPixelY(0);
browser_->SetRelativeWidth(1.0);
browser_->SetRelativeHeight(1.0);
browser_->SetEnabled(true);
// Force the browser window to be loaded.
browser_->RecursiveLayout();
if (!browser_->SetProperty("external", Variant(&external_))) {
DLOG("Invalid browser element.");
delete browser_;
browser_ = NULL;
}
} else {
DLOG("Failed to create _browser element.");
}
}
virtual ~HtmlFlashElement() {
movie_object_.Reset(NULL);
delete browser_;
}
static BasicElement *CreateInstance(View *view, const char *name) {
return new HtmlFlashElement(view, name);
}
public:
virtual void Layout() {
BasicElement::Layout();
if (browser_)
browser_->RecursiveLayout();
}
protected:
virtual void DoClassRegister() {
// It's not necessary to call BasicElement::DoClassRegister(),
// if it's loaded in object element.
BasicElement::DoClassRegister();
RegisterProperty("movie",
NewSlot(&HtmlFlashElement::GetSrc),
NewSlot(&HtmlFlashElement::SetSrc));
RegisterProperty("src",
NewSlot(&HtmlFlashElement::GetSrc),
NewSlot(&HtmlFlashElement::SetSrc));
}
virtual void DoRegister() {
if (browser_) {
for (size_t i = 0; i < arraysize(kFlashMethods); ++i) {
RegisterMethod(kFlashMethods[i],
new MethodCaller(this, kFlashMethods[i]));
}
SetDynamicPropertyHandler(NewSlot(this, &HtmlFlashElement::GetProperty),
NewSlot(this, &HtmlFlashElement::SetProperty));
}
}
virtual void DoDraw(CanvasInterface *canvas) {
if (browser_)
browser_->Draw(canvas);
}
virtual EventResult HandleMouseEvent(const MouseEvent &event) {
BasicElement *fired, *in;
ViewInterface::HitTest hittest;
return browser_ ?
browser_->OnMouseEvent(event, true, &fired, &in, &hittest) :
EVENT_RESULT_UNHANDLED;
}
virtual EventResult HandleDragEvent(const DragEvent &event) {
BasicElement *fired;
return browser_ ? browser_->OnDragEvent(event, true, &fired) :
EVENT_RESULT_UNHANDLED;
}
virtual EventResult HandleKeyEvent(const KeyboardEvent &event) {
return browser_ ? browser_->OnKeyEvent(event) : EVENT_RESULT_UNHANDLED;
}
virtual EventResult HandleOtherEvent(const Event &event) {
return browser_ ? browser_->OnOtherEvent(event) : EVENT_RESULT_UNHANDLED;
}
virtual void AggregateMoreClipRegion(const Rectangle &boundary,
ClipRegion *region) {
if (browser_) {
browser_->AggregateClipRegion(boundary, region);
}
}
private:
Variant GetProperty(const std::string &name) {
if (movie_object_.Get()) {
Variant value;
ScriptableInterface *scriptable = NULL;
{ // Life scope of ResultVariant result.
ResultVariant result = movie_object_.Get()->GetProperty(name.c_str());
value = result.v();
if (value.type() == Variant::TYPE_SCRIPTABLE) {
scriptable = VariantValue<ScriptableInterface *>()(value);
// Add a reference to prevent ResultVariant from deleting the object.
if (scriptable)
scriptable->Ref();
}
}
// Release the temporary reference but don't delete the object.
if (scriptable)
scriptable->Unref(true);
return value;
}
return Variant();
}
bool SetProperty(const std::string &name, const Variant &value) {
if (movie_object_.Get())
return movie_object_.Get()->SetProperty(name.c_str(), value);
return false;
}
void SetSrc(const char *src) {
DLOG("SetSrc: %s", src);
if (browser_) {
movie_object_.Reset(NULL);
src_ = src ? src : "";
std::string content = StringPrintf(kHtmlFlashCode, src_.c_str());
browser_->SetProperty("innerText", Variant(content));
}
}
std::string GetSrc() {
return src_;
}
void SetMovieObject(ScriptableInterface *movie_object) {
DLOG("SetMovieObject: %p, Id=%jx",
movie_object, movie_object ? movie_object->GetClassId() : 0);
movie_object_.Reset(movie_object);
}
private:
DISALLOW_EVIL_CONSTRUCTORS(HtmlFlashElement);
BasicElement *browser_;
ScriptableHolder<ScriptableInterface> movie_object_;
ExternalObject external_;
std::string src_;
};
} // namespace internal
} // namespace ggadget
#define Initialize html_flash_element_LTX_Initialize
#define Finalize html_flash_element_LTX_Finalize
#define RegisterElementExtension html_flash_element_LTX_RegisterElementExtension
extern "C" {
bool Initialize() {
LOGI("Initialize html_flash_element extension.");
return true;
}
void Finalize() {
LOGI("Finalize html_flash_element extension.");
}
bool RegisterElementExtension(ggadget::ElementFactory *factory) {
if (factory) {
LOGI("Register html_flash_element extension, using name \"flash\".");
factory->RegisterElementClass(
"clsid:D27CDB6E-AE6D-11CF-96B8-444553540000",
&ggadget::internal::HtmlFlashElement::CreateInstance);
factory->RegisterElementClass(
"progid:ShockwaveFlash.ShockwaveFlash.9",
&ggadget::internal::HtmlFlashElement::CreateInstance);
factory->RegisterElementClass(
"progid:ShockwaveFlash.ShockwaveFlash",
&ggadget::internal::HtmlFlashElement::CreateInstance);
factory->RegisterElementClass(
"flash",
&ggadget::internal::HtmlFlashElement::CreateInstance);
}
return true;
}
}
| 29.922388 | 80 | 0.650539 | [
"object"
] |
3d5d9578cacd67d91f9334f3e00c1089b6f1b9a0 | 5,432 | cpp | C++ | src/graph/DataLayerVisitor.cpp | MaximMilashchenko/ComputeLibrary | 91ee4d0a9ef128b16936921470a0e3ffef347536 | [
"MIT"
] | 2,313 | 2017-03-24T16:25:28.000Z | 2022-03-31T03:00:30.000Z | src/graph/DataLayerVisitor.cpp | MaximMilashchenko/ComputeLibrary | 91ee4d0a9ef128b16936921470a0e3ffef347536 | [
"MIT"
] | 952 | 2017-03-28T07:05:58.000Z | 2022-03-30T09:54:02.000Z | src/graph/DataLayerVisitor.cpp | MaximMilashchenko/ComputeLibrary | 91ee4d0a9ef128b16936921470a0e3ffef347536 | [
"MIT"
] | 714 | 2017-03-24T22:21:51.000Z | 2022-03-18T19:49:57.000Z | /*
* Copyright (c) 2021 Arm Limited.
*
* SPDX-License-Identifier: MIT
*
* 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 "arm_compute/graph/DataLayerVisitor.h"
#include "arm_compute/core/Error.h"
#include "arm_compute/graph/Graph.h"
#include "arm_compute/graph/TypePrinter.h"
#include "arm_compute/graph/nodes/Nodes.h"
namespace arm_compute
{
namespace graph
{
namespace
{
template <typename T>
void add_convolution_layer_data(DataLayerVisitor::LayerData &layer_data, T &node)
{
PadStrideInfo ps_info = node.convolution_info();
DataLayout layout = node.output(0)->desc().layout;
// Add data layout
layer_data["data_layout"] = to_string(layout);
// Add padding info
std::ostringstream padding;
padding << "[" << to_string(ps_info.pad_left()) << ","
<< to_string(ps_info.pad_top()) << ","
<< to_string(ps_info.pad_bottom()) << ","
<< to_string(ps_info.pad_right()) << "]";
layer_data["pad"] = padding.str();
// Add stride info
std::ostringstream stride;
stride << "[" << to_string(ps_info.stride().first) << ","
<< to_string(ps_info.stride().second) << "]";
layer_data["stride"] = stride.str();
// Add dilation info
// graph api does not support dilation > 1
layer_data["dilation"] = "[1,1]";
// Add bias enabled?
// Assumes three inputs (input, weights, bias)
std::string bias_enabled = node.input(2) == nullptr ? "0" : "1";
layer_data["bias_enabled"] = bias_enabled;
// Change input names for weights / bias (if applicable)
// Assumes input(1) is weights and input(2) is bias
if(layer_data.count("input_shape1"))
{
layer_data["weights_shape"] = layer_data["input_shape1"];
layer_data.erase("input_shape1");
}
if(layer_data.count("input_shape2"))
{
layer_data["bias_shape"] = layer_data["input_shape2"];
layer_data.erase("input_shape2");
}
}
template <typename T>
void add_convolution_layer_method(DataLayerVisitor::LayerData &layer_data, T &node)
{
std::ostringstream method;
method << node.convolution_method();
layer_data["convolution_method"] = method.str();
}
template <typename T>
void add_generic_layer_data(DataLayerVisitor::LayerData &layer_data, T &node)
{
// Loop over each input tensor
for(size_t tensor_no = 0; tensor_no < node.num_inputs(); ++tensor_no)
{
// Add input tensor shapes
if(node.input(tensor_no) != nullptr)
{
layer_data["input_shape" + to_string(tensor_no)] = "[" + to_string(node.input(tensor_no)->desc().shape) + "]";
}
}
// Add output tensor shape
if(node.output(0) != nullptr)
{
layer_data["output_shape0"] = "[" + to_string(node.output(0)->desc().shape) + "]";
}
}
} // namespace
void DataLayerVisitor::visit(ConvolutionLayerNode &n)
{
_layer_data.clear();
add_generic_layer_data<ConvolutionLayerNode>(_layer_data, n);
add_convolution_layer_data<ConvolutionLayerNode>(_layer_data, n);
add_convolution_layer_method<ConvolutionLayerNode>(_layer_data, n);
}
void DataLayerVisitor::visit(DepthwiseConvolutionLayerNode &n)
{
_layer_data.clear();
add_generic_layer_data<DepthwiseConvolutionLayerNode>(_layer_data, n);
add_convolution_layer_data<DepthwiseConvolutionLayerNode>(_layer_data, n);
}
void DataLayerVisitor::visit(FusedConvolutionBatchNormalizationNode &n)
{
_layer_data.clear();
add_generic_layer_data<FusedConvolutionBatchNormalizationNode>(_layer_data, n);
add_convolution_layer_data<FusedConvolutionBatchNormalizationNode>(_layer_data, n);
add_convolution_layer_method<FusedConvolutionBatchNormalizationNode>(_layer_data, n);
}
void DataLayerVisitor::visit(FusedDepthwiseConvolutionBatchNormalizationNode &n)
{
_layer_data.clear();
add_generic_layer_data<FusedDepthwiseConvolutionBatchNormalizationNode>(_layer_data, n);
add_convolution_layer_data<FusedDepthwiseConvolutionBatchNormalizationNode>(_layer_data, n);
}
void DataLayerVisitor::visit(OutputNode &n)
{
_layer_data.clear();
ARM_COMPUTE_UNUSED(n);
}
void DataLayerVisitor::default_visit(INode &n)
{
_layer_data.clear();
add_generic_layer_data<INode>(_layer_data, n);
}
const DataLayerVisitor::LayerData &DataLayerVisitor::layer_data() const
{
return _layer_data;
}
} // namespace graph
} // namespace arm_compute
| 34.163522 | 122 | 0.713733 | [
"shape"
] |
87ce0013c3a24e8963d995935dbe88ddd5f73fe0 | 7,874 | cpp | C++ | GameObject.cpp | Maknee/WeirdSnake | 6f79f0ea7161fd0af433f1934fbcd50901f0c851 | [
"MIT"
] | null | null | null | GameObject.cpp | Maknee/WeirdSnake | 6f79f0ea7161fd0af433f1934fbcd50901f0c851 | [
"MIT"
] | null | null | null | GameObject.cpp | Maknee/WeirdSnake | 6f79f0ea7161fd0af433f1934fbcd50901f0c851 | [
"MIT"
] | null | null | null | #include "GameObject.h"
#include "GraphicsEngine.h"
GameObject::GameObject(Shader & shader)
{
this->shader = shader;
this->initRenderData();
}
GameObject::~GameObject()
{
glDeleteVertexArrays(1, &this->VAO);
glDeleteBuffers(1, &this->VBO);
motionState.reset();
rigidBody.reset();
shape.reset();
}
void GameObject::SetRigidBody(std::unique_ptr<btDiscreteDynamicsWorld>& dynamicsWorld, std::unique_ptr<btCollisionShape> &shape,
std::string name,
btVector3 &position, btQuaternion &rotation,
btScalar mass, btVector3 &inertia)
{
this->shape = std::move(shape);
this->motionState = std::unique_ptr<btDefaultMotionState>(new btDefaultMotionState(btTransform(rotation, position)));
btRigidBody::btRigidBodyConstructionInfo rigidBodyConstructionInfo(mass, this->motionState.get(), this->shape.get(), inertia);
this->rigidBody = std::shared_ptr<btRigidBody>(new btRigidBody(rigidBodyConstructionInfo));
this->name = name;
this->rigidBody->setUserPointer(this);
dynamicsWorld->addRigidBody(this->rigidBody.get());
};
void Box::initRenderData()
{
// Configure VAO/EBO/VBO
GLfloat vertices[] = {
// Positions // Normals // Texture Coords
-0.5f, -0.5f, -0.5f, 0.0f, 0.0f, -1.0f, 0.0f, 0.0f,
0.5f, -0.5f, -0.5f, 0.0f, 0.0f, -1.0f, 1.0f, 0.0f,
0.5f, 0.5f, -0.5f, 0.0f, 0.0f, -1.0f, 1.0f, 1.0f,
0.5f, 0.5f, -0.5f, 0.0f, 0.0f, -1.0f, 1.0f, 1.0f,
-0.5f, 0.5f, -0.5f, 0.0f, 0.0f, -1.0f, 0.0f, 1.0f,
-0.5f, -0.5f, -0.5f, 0.0f, 0.0f, -1.0f, 0.0f, 0.0f,
-0.5f, -0.5f, 0.5f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f,
0.5f, -0.5f, 0.5f, 0.0f, 0.0f, 1.0f, 1.0f, 0.0f,
0.5f, 0.5f, 0.5f, 0.0f, 0.0f, 1.0f, 1.0f, 1.0f,
0.5f, 0.5f, 0.5f, 0.0f, 0.0f, 1.0f, 1.0f, 1.0f,
-0.5f, 0.5f, 0.5f, 0.0f, 0.0f, 1.0f, 0.0f, 1.0f,
-0.5f, -0.5f, 0.5f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f,
-0.5f, 0.5f, 0.5f, -1.0f, 0.0f, 0.0f, 1.0f, 0.0f,
-0.5f, 0.5f, -0.5f, -1.0f, 0.0f, 0.0f, 1.0f, 1.0f,
-0.5f, -0.5f, -0.5f, -1.0f, 0.0f, 0.0f, 0.0f, 1.0f,
-0.5f, -0.5f, -0.5f, -1.0f, 0.0f, 0.0f, 0.0f, 1.0f,
-0.5f, -0.5f, 0.5f, -1.0f, 0.0f, 0.0f, 0.0f, 0.0f,
-0.5f, 0.5f, 0.5f, -1.0f, 0.0f, 0.0f, 1.0f, 0.0f,
0.5f, 0.5f, 0.5f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f,
0.5f, 0.5f, -0.5f, 1.0f, 0.0f, 0.0f, 1.0f, 1.0f,
0.5f, -0.5f, -0.5f, 1.0f, 0.0f, 0.0f, 0.0f, 1.0f,
0.5f, -0.5f, -0.5f, 1.0f, 0.0f, 0.0f, 0.0f, 1.0f,
0.5f, -0.5f, 0.5f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f,
0.5f, 0.5f, 0.5f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f,
-0.5f, -0.5f, -0.5f, 0.0f, -1.0f, 0.0f, 0.0f, 1.0f,
0.5f, -0.5f, -0.5f, 0.0f, -1.0f, 0.0f, 1.0f, 1.0f,
0.5f, -0.5f, 0.5f, 0.0f, -1.0f, 0.0f, 1.0f, 0.0f,
0.5f, -0.5f, 0.5f, 0.0f, -1.0f, 0.0f, 1.0f, 0.0f,
-0.5f, -0.5f, 0.5f, 0.0f, -1.0f, 0.0f, 0.0f, 0.0f,
-0.5f, -0.5f, -0.5f, 0.0f, -1.0f, 0.0f, 0.0f, 1.0f,
-0.5f, 0.5f, -0.5f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f,
0.5f, 0.5f, -0.5f, 0.0f, 1.0f, 0.0f, 1.0f, 1.0f,
0.5f, 0.5f, 0.5f, 0.0f, 1.0f, 0.0f, 1.0f, 0.0f,
0.5f, 0.5f, 0.5f, 0.0f, 1.0f, 0.0f, 1.0f, 0.0f,
-0.5f, 0.5f, 0.5f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f,
-0.5f, 0.5f, -0.5f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f
};
glGenVertexArrays(1, &this->VAO);
glGenBuffers(1, &VBO);
glBindBuffer(GL_ARRAY_BUFFER, VBO);
glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);
glBindVertexArray(this->VAO);
glEnableVertexAttribArray(0);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 8 * sizeof(GLfloat), (GLvoid*)0);
glEnableVertexAttribArray(1);
glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 8 * sizeof(GLfloat), (GLvoid*)(3 * sizeof(GLfloat)));
glEnableVertexAttribArray(2);
glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, 8 * sizeof(GLfloat), (GLvoid*)(6 * sizeof(GLfloat)));
glBindBuffer(GL_ARRAY_BUFFER, 0);
glBindVertexArray(0);
}
void Box::DrawSprite()
{
// Prepare transformations
glm::mat4 model;
model = glm::scale(model, scale);
model = model * glm::toMat4(rotation);
model = glm::translate(model, this->position);
glm::mat4 view;
view = glm::lookAt(GraphicsEngine::cameraPos,
GraphicsEngine::cameraPos + GraphicsEngine::cameraFront,
GraphicsEngine::cameraUp);
glm::mat4 projection;
projection = glm::perspective(GraphicsEngine::fov,
static_cast<GLfloat>(GraphicsEngine::WIDTH) / static_cast<GLfloat>(GraphicsEngine::HEIGHT),
0.1f, 100.0f);
this->shader.Use();
this->shader.SetMatrix4("model", model);
this->shader.SetMatrix4("view", view);
this->shader.SetMatrix4("projection", projection);
this->shader.SetVector3f("objectColor", this->color);
this->shader.SetVector3f("viewPos", GraphicsEngine::cameraPos);
glBindTexture(GL_TEXTURE_2D, 0);
glBindVertexArray(this->VAO);
glDrawArrays(GL_TRIANGLES, 0, 36);
glBindVertexArray(0);
}
void Box::DrawSprite(glm::mat4 &model)
{
// Prepare transformations
glm::mat4 view;
view = glm::lookAt(GraphicsEngine::cameraPos,
GraphicsEngine::cameraPos + GraphicsEngine::cameraFront,
GraphicsEngine::cameraUp);
glm::mat4 projection;
projection = glm::perspective(GraphicsEngine::fov,
static_cast<GLfloat>(GraphicsEngine::WIDTH) / static_cast<GLfloat>(GraphicsEngine::HEIGHT),
0.1f, 100.0f);
this->shader.Use();
this->shader.SetMatrix4("model", model);
this->shader.SetMatrix4("view", view);
this->shader.SetMatrix4("projection", projection);
this->shader.SetVector3f("objectColor", this->color);
this->shader.SetVector3f("viewPos", GraphicsEngine::cameraPos);
glBindVertexArray(this->VAO);
glDrawArrays(GL_TRIANGLES, 0, 36);
glBindVertexArray(0);
glBindTexture(GL_TEXTURE_2D, 0);
}
void Box::DrawSprite(Texture2D &texture)
{
// Prepare transformations
glm::mat4 model;
model = glm::scale(model, scale);
model = model * glm::toMat4(rotation);
model = glm::translate(model, this->position);
glm::mat4 view;
view = glm::lookAt(GraphicsEngine::cameraPos,
GraphicsEngine::cameraPos + GraphicsEngine::cameraFront,
GraphicsEngine::cameraUp);
glm::mat4 projection;
projection = glm::perspective(GraphicsEngine::fov,
static_cast<GLfloat>(GraphicsEngine::WIDTH) / static_cast<GLfloat>(GraphicsEngine::HEIGHT),
0.1f, 100.0f);
this->shader.Use();
this->shader.SetMatrix4("model", model);
this->shader.SetMatrix4("view", view);
this->shader.SetMatrix4("projection", projection);
this->shader.SetVector3f("objectColor", this->color);
this->shader.SetVector3f("viewPos", GraphicsEngine::cameraPos);
glActiveTexture(GL_TEXTURE0);
texture.Bind();
this->shader.SetTexture("bodyTexture", 0);
glBindVertexArray(this->VAO);
glDrawArrays(GL_TRIANGLES, 0, 36);
glBindVertexArray(0);
glBindTexture(GL_TEXTURE_2D, 0);
}
void Box::DrawSprite(Texture2D &texture, glm::mat4 &model)
{
// Prepare transformations
glm::mat4 view;
view = glm::lookAt(GraphicsEngine::cameraPos,
GraphicsEngine::cameraPos + GraphicsEngine::cameraFront,
GraphicsEngine::cameraUp);
glm::mat4 projection;
projection = glm::perspective(GraphicsEngine::fov,
static_cast<GLfloat>(GraphicsEngine::WIDTH) / static_cast<GLfloat>(GraphicsEngine::HEIGHT),
0.1f, 100.0f);
this->shader.Use();
this->shader.SetMatrix4("model", model);
this->shader.SetMatrix4("view", view);
this->shader.SetMatrix4("projection", projection);
this->shader.SetVector3f("objectColor", this->color);
this->shader.SetVector3f("viewPos", GraphicsEngine::cameraPos);
glActiveTexture(GL_TEXTURE0);
texture.Bind();
this->shader.SetTexture("bodyTexture", 0);
glBindVertexArray(this->VAO);
glDrawArrays(GL_TRIANGLES, 0, 36);
glBindVertexArray(0);
glBindTexture(GL_TEXTURE_2D, 0);
} | 33.506383 | 129 | 0.633985 | [
"shape",
"model"
] |
87d127d1eab95cbedaeb1b21a018da2ea31805b8 | 21,488 | hpp | C++ | GViewCore/include/GView.hpp | gdt050579/GView | e5b8f286ee9a5e3bf11510c3aa9c21baeacee723 | [
"MIT"
] | 7 | 2021-12-28T23:42:07.000Z | 2022-03-27T17:29:58.000Z | GViewCore/include/GView.hpp | gdt050579/GView | e5b8f286ee9a5e3bf11510c3aa9c21baeacee723 | [
"MIT"
] | 25 | 2021-11-11T19:32:00.000Z | 2022-03-31T11:54:02.000Z | GViewCore/include/GView.hpp | gdt050579/GView | e5b8f286ee9a5e3bf11510c3aa9c21baeacee723 | [
"MIT"
] | 1 | 2021-11-24T15:11:35.000Z | 2021-11-24T15:11:35.000Z | #pragma once
// Version MUST be in the following format <Major>.<Minor>.<Patch>
#define GVIEW_VERSION "0.40.0"
#include <AppCUI/include/AppCUI.hpp>
using namespace AppCUI::Controls;
using namespace AppCUI::Utils;
using namespace AppCUI::Graphics;
using namespace AppCUI;
#ifdef CORE_EXPORTABLE
# ifdef BUILD_FOR_WINDOWS
# define CORE_EXPORT __declspec(dllexport)
# else
# define CORE_EXPORT
# endif
#else
# define CORE_EXPORT
#endif
#ifdef BUILD_FOR_WINDOWS
# define PLUGIN_EXPORT __declspec(dllexport)
#else
# define PLUGIN_EXPORT
#endif
namespace GView
{
class CORE_EXPORT Object;
struct CORE_EXPORT TypeInterface
{
Object* obj;
virtual std::string_view GetTypeName() = 0;
virtual ~TypeInterface(){};
template <typename T>
Reference<T> To()
{
return static_cast<T*>(this);
}
};
namespace Utils
{
constexpr uint64 INVALID_OFFSET = 0xFFFFFFFFFFFFFFFFULL;
constexpr int INVALID_SELECTION_INDEX = -1;
class CORE_EXPORT ErrorList
{
void* data;
public:
ErrorList();
~ErrorList();
void Clear();
bool AddError(const char* format, ...);
bool AddWarning(const char* format, ...);
bool Empty() const;
uint32 GetErrorsCount() const;
uint32 GetWarningsCount() const;
std::string_view GetError(uint32 index) const;
std::string_view GetWarning(uint32 index) const;
void PopulateListView(AppCUI::Utils::Reference<AppCUI::Controls::ListView> listView) const;
};
class CORE_EXPORT DataCache
{
AppCUI::OS::DataObject* fileObj;
uint64 fileSize, start, end, currentPos;
uint8* cache;
uint32 cacheSize;
bool CopyObject(void* buffer, uint64 offset, uint32 requestedSize);
public:
DataCache();
DataCache(DataCache&& obj);
~DataCache();
bool Init(std::unique_ptr<AppCUI::OS::DataObject> file, uint32 cacheSize);
BufferView Get(uint64 offset, uint32 requestedSize, bool failIfRequestedSizeCanNotBeRead);
inline BufferView GetEntireFile()
{
return fileSize < 0xFFFFFFFF ? Get(0, (uint32) fileSize, true) : BufferView();
}
Buffer CopyToBuffer(uint64 offset, uint32 requestedSize, bool failIfRequestedSizeCanNotBeRead = true);
inline Buffer CopyEntireFile(bool failIfRequestedSizeCanNotBeRead = true)
{
return CopyToBuffer(0, (uint32) fileSize, failIfRequestedSizeCanNotBeRead);
}
inline uint8 GetFromCache(uint64 offset, uint8 defaultValue = 0) const
{
if ((offset >= start) && (offset < end))
return cache[offset - start];
return defaultValue;
}
inline uint32 GetCacheSize() const
{
return cacheSize;
}
inline uint64 GetSize() const
{
return fileSize;
}
inline uint64 GetCurrentPos() const
{
return currentPos;
}
inline void SetCurrentPos(uint64 value)
{
currentPos = value;
}
template <typename T>
inline bool Copy(uint64 offset, T& object)
{
return CopyObject(&object, offset, sizeof(T));
}
bool WriteTo(Reference<AppCUI::OS::DataObject> output, uint64 offset, uint32 size);
};
enum class DemangleKind : uint8
{
Auto,
Microsoft,
Itanium,
Rust,
};
CORE_EXPORT bool Demangle(std::string_view input, String& output, DemangleKind format = DemangleKind::Auto);
} // namespace Utils
namespace Hashes
{
class CORE_EXPORT Adler32
{
private:
uint16 a;
uint16 b;
bool init;
public:
bool Init();
bool Update(const unsigned char* input, uint32 length);
bool Update(const Buffer& buffer);
bool Update(const BufferView& buffer);
bool Final(uint32& hash);
static std::string_view GetName();
const std::string_view GetHexValue();
public:
inline static const uint32 ResultBytesLength = sizeof(a) + sizeof(b);
private:
char hexDigest[ResultBytesLength * 2];
};
class CORE_EXPORT CRC16
{
private:
uint32 value;
bool init;
public:
bool Init();
bool Update(const unsigned char* input, uint32 length);
bool Update(const Buffer& buffer);
bool Update(const BufferView& buffer);
bool Final(uint16& hash);
static std::string_view GetName();
const std::string_view GetHexValue();
public:
inline static const uint32 ResultBytesLength = sizeof(value);
private:
char hexDigest[ResultBytesLength * 2];
};
enum class CRC32Type : uint32
{
JAMCRC = 0xFFFFFFFF,
JAMCRC_0 = 0x00000000
};
class CORE_EXPORT CRC32
{
private:
uint32 value;
CRC32Type type;
bool init;
public:
bool Init(CRC32Type type);
bool Update(const unsigned char* input, uint32 length);
bool Update(const Buffer& buffer);
bool Update(const BufferView& buffer);
bool Final(uint32& hash);
static std::string_view GetName(CRC32Type type);
const std::string_view GetHexValue();
public:
inline static const uint32 ResultBytesLength = sizeof(value);
private:
char hexDigest[ResultBytesLength * 2];
};
enum class CRC64Type : uint64
{
WE = 0xFFFFFFFFFFFFFFFF,
ECMA_182 = 0x0000000000000000
};
class CORE_EXPORT CRC64
{
private:
uint64 value;
CRC64Type type;
bool init;
private:
bool Final();
public:
bool Init(CRC64Type type);
bool Update(const unsigned char* input, uint32 length);
bool Update(const Buffer& buffer);
bool Update(const BufferView& buffer);
bool Final(uint64& hash);
static std::string_view GetName(CRC64Type type);
const std::string_view GetHexValue();
public:
inline static const uint32 ResultBytesLength = sizeof(value);
private:
char hexDigest[ResultBytesLength * 2];
};
class CORE_EXPORT MD2
{
private:
uint8 m[16];
uint8 x[48];
uint8 c[16];
uint32 size;
bool init;
private:
bool Final();
public:
bool Init();
bool Update(const unsigned char* input, uint32 length);
bool Update(const Buffer& buffer);
bool Update(const BufferView& buffer);
bool Final(uint8 hash[16]);
static std::string_view GetName();
const std::string_view GetHexValue();
public:
inline static const uint32 ResultBytesLength = sizeof(m) / sizeof(m[0]);
private:
char hexDigest[ResultBytesLength * 2];
};
enum class OpenSSLHashKind : uint8
{
Md4,
Md5,
Blake2s256,
Blake2b512,
Sha1,
Sha224,
Sha256,
Sha384,
Sha512,
Sha512_224,
Sha512_256,
Sha3_224,
Sha3_256,
Sha3_384,
Sha3_512,
Shake128,
Shake256
};
class CORE_EXPORT OpenSSLHash
{
public:
OpenSSLHash(OpenSSLHashKind kind);
~OpenSSLHash();
bool Update(const void* input, uint32 length);
bool Final();
std::string_view GetHexValue();
const uint8* Get() const;
uint32 GetSize() const;
private:
void* handle;
uint8 hash[64];
uint32 size;
private:
char hexDigest[(sizeof(hash) / sizeof(hash[0])) * 2];
};
} // namespace Hashes
namespace DigitalSignature
{
enum class ASN1TYPE
{
EOC = 0,
BOOLEAN = 1,
INTEGER = 2,
BIT_STRING = 3,
OCTET_STRING = 4,
NULL_ASN = 5,
OBJECT = 6,
OBJECT_DESCRIPTOR = 7,
EXTERNAL = 8,
REAL = 9,
ENUMERATED = 10,
UTF8STRING = 12,
SEQUENCE = 16,
SET = 17,
NUMERICSTRING = 18,
PRINTABLESTRING = 19,
T61STRING = 20,
TELETEXSTRING = 20,
VIDEOTEXSTRING = 21,
IA5STRING = 22,
UTCTIME = 23,
GENERALIZEDTIME = 24,
GRAPHICSTRING = 25,
ISO64STRING = 26,
VISIBLESTRING = 26,
GENERALSTRING = 27,
UNIVERSALSTRING = 28,
BMPSTRING = 30
};
struct CORE_EXPORT Certificate
{
int32 version;
String serialNumber;
String signatureAlgorithm;
String publicKeyAlgorithm;
String validityNotBefore;
String validityNotAfter;
String issuer;
String subject;
int32 verify;
String errorVerify;
int32 signerVerify; // compares the certificate cert against the signer identifier si
String errorSignerVerify;
};
constexpr auto MAX_SIZE_IN_CONTAINER = 32U;
struct CORE_EXPORT SignerAttributes
{
String name;
ASN1TYPE types[MAX_SIZE_IN_CONTAINER]; // usually one value unless (attribute.contentType == "1.2.840.113635.100.9.2") //
// V_ASN1_SEQUENCE
String contentType;
String contentTypeData;
int32 count;
String CDHashes[MAX_SIZE_IN_CONTAINER]; // optional -> (attribute.contentType == "1.2.840.113635.100.9.2") // V_ASN1_SEQUENCE
};
struct CORE_EXPORT Signer
{
int32 count;
SignerAttributes attributes[MAX_SIZE_IN_CONTAINER];
uint32 attributesCount;
};
struct CORE_EXPORT Signature
{
int32 isDetached;
String sn;
Buffer snContent;
Certificate certificates[MAX_SIZE_IN_CONTAINER];
uint32 certificatesCount = 0;
Signer signers[MAX_SIZE_IN_CONTAINER];
uint32 signersCount = 0;
String errorMessage;
bool error = true;
};
CORE_EXPORT bool CMSToHumanReadable(const Buffer& buffer, String& ouput);
CORE_EXPORT bool CMSToPEMCerts(const Buffer& buffer, String output[32], uint32& count);
CORE_EXPORT bool CMSToStructure(const Buffer& buffer, Signature& output);
} // namespace DigitalSignature
namespace Compression
{
namespace LZXPRESS
{
namespace Huffman
{
CORE_EXPORT bool Decompress(const BufferView& compressed, Buffer& uncompressed);
}
} // namespace LZXPRESS
} // namespace Compression
/*
* Object can be:
* - a file
* - a folder
* - a process
* - a memory buffer
*/
class CORE_EXPORT Object
{
public:
enum class Type : uint32
{
File,
Folder,
MemoryBuffer,
Process
};
private:
Utils::DataCache cache;
TypeInterface* contentType;
AppCUI::Utils::UnicodeStringBuilder name;
AppCUI::Utils::UnicodeStringBuilder filePath;
uint32 PID;
Type objectType;
public:
Object(Type objType, Utils::DataCache&& dataCache, TypeInterface* contType, ConstString objName, ConstString objFilePath, uint32 pid)
: cache(std::move(dataCache)), contentType(contType), name(objName), filePath(objFilePath), PID(pid), objectType(objType)
{
if (contentType)
contentType->obj = this;
}
inline Utils::DataCache& GetData()
{
return cache;
}
inline u16string_view GetName() const
{
return name.ToStringView();
}
inline u16string_view GetPath() const
{
return filePath.ToStringView();
}
inline Reference<TypeInterface> GetContentType() const
{
return contentType;
}
template <typename T>
inline Reference<T> GetContentType() const
{
return (T*) contentType;
}
inline uint32 GetPID() const
{
return PID;
}
inline Type GetObjectType() const
{
return objectType;
}
};
namespace View
{
typedef uint8 MethodID;
struct CORE_EXPORT ViewControl : public AppCUI::Controls::UserControl, public AppCUI::Utils::PropertiesInterface
{
protected:
const AppCUI::Application::Config& Cfg;
public:
virtual bool GoTo(uint64 offset) = 0;
virtual bool Select(uint64 offset, uint64 size) = 0;
virtual bool ShowGoToDialog() = 0;
virtual bool ShowFindDialog() = 0;
virtual std::string_view GetName() = 0;
virtual void PaintCursorInformation(AppCUI::Graphics::Renderer& renderer, uint32 width, uint32 height) = 0;
int WriteCursorInfo(AppCUI::Graphics::Renderer& renderer, int x, int y, int width, std::string_view key, std::string_view value);
void WriteCusorInfoLine(AppCUI::Graphics::Renderer& renderer, int x, int y, std::string_view key, const ConstString& value);
ViewControl(UserControlFlags flags = UserControlFlags::None) : UserControl("d:c", flags), Cfg(this->GetConfig())
{
}
};
namespace BufferViewer
{
struct BufferColor
{
uint64 start;
uint64 end;
ColorPair color;
constexpr inline void Reset()
{
start = end = GView::Utils::INVALID_OFFSET;
}
constexpr inline bool IsValue() const
{
return start != GView::Utils::INVALID_OFFSET;
}
constexpr inline bool Empty() const
{
return start == GView::Utils::INVALID_OFFSET;
}
};
struct CORE_EXPORT PositionToColorInterface
{
virtual bool GetColorForBuffer(uint64 offset, BufferView buf, BufferColor& result) = 0;
};
struct CORE_EXPORT OffsetTranslateInterface
{
virtual uint64_t TranslateToFileOffset(uint64 value, uint32 fromTranslationIndex) = 0;
virtual uint64_t TranslateFromFileOffset(uint64 value, uint32 toTranslationIndex) = 0;
};
struct CORE_EXPORT Settings
{
void* data;
Settings();
void AddZone(uint64 start, uint64 size, ColorPair col, std::string_view name);
void AddBookmark(uint8 bookmarkID, uint64 fileOffset);
void SetOffsetTranslationList(std::initializer_list<std::string_view> list, Reference<OffsetTranslateInterface> cbk);
void SetPositionToColorCallback(Reference<PositionToColorInterface> cbk);
void SetEntryPointOffset(uint64_t offset);
};
}; // namespace BufferViewer
namespace ImageViewer
{
struct CORE_EXPORT LoadImageInterface
{
virtual bool LoadImageToObject(Image& img, uint32 index) = 0;
};
struct CORE_EXPORT Settings
{
void* data;
Settings();
void SetLoadImageCallback(Reference<LoadImageInterface> cbk);
void AddImage(uint64 offset, uint64 size);
};
}; // namespace ImageViewer
namespace ContainerViewer
{
struct CORE_EXPORT EnumerateInterface
{
virtual bool BeginIteration(std::u16string_view path, AppCUI::Controls::TreeViewItem parent) = 0;
virtual bool PopulateItem(AppCUI::Controls::TreeViewItem item) = 0;
};
struct CORE_EXPORT OpenItemInterface
{
virtual void OnOpenItem(std::u16string_view path, AppCUI::Controls::TreeViewItem item) = 0;
};
struct CORE_EXPORT Settings
{
void* data;
Settings();
bool SetIcon(string_view imageStringFormat16x16);
bool SetPathSeparator(char16 separator);
bool AddProperty(string_view name, const ConstString& value, ListViewItem::Type itemType = ListViewItem::Type::Normal);
void SetColumns(std::initializer_list<ConstString> columns);
void SetEnumerateCallback(Reference<EnumerateInterface> callback);
void SetOpenItemCallback(Reference<OpenItemInterface> callback);
};
}; // namespace ContainerViewer
namespace TextViewer
{
enum class WrapMethod : uint8
{
None = 0,
LeftMargin = 1,
Padding = 2,
Bullets = 3,
};
struct CORE_EXPORT Settings
{
void* data;
Settings();
void SetWrapMethod(WrapMethod method);
void SetTabSize(uint32 tabSize);
void ShowTabCharacter(bool show);
void HightlightCurrentLine(bool highlight);
};
}; // namespace TextViewer
namespace GridViewer
{
struct CORE_EXPORT Settings
{
void* data;
Settings();
void SetSeparator(char separator[2]);
};
}; // namespace GridViewer
// namespace ImageViewer
namespace DissasmViewer // StructureViewer
{
using TypeID = uint32;
enum class DissamblyLanguage : uint32
{
Default,
x86,
x64,
JavaByteCode,
IL,
Count
};
enum class VariableType : uint32
{
UInt8,
UInt16,
UInt32,
UInt64,
Int8,
Int16,
Int32,
Int64,
AsciiZ,
Utf16Z,
Utf32Z
};
struct CORE_EXPORT Settings
{
void* data;
void SetDefaultDissasemblyLanguage(DissamblyLanguage lang);
void ReserverZonesCapacity(uint32 reserved_size);
void AddDissasemblyZone(uint64 start, uint64 size, DissamblyLanguage lang = DissamblyLanguage::Default);
void AddMemmoryMapping(uint64 address, std::string_view name);
/**
* Add a new data type with its definition. Default data types: UInt8-64,Int8-64, float,double, asciiZ, Unicode16Z,Unicode32Z
*
*
* @param[in] name Name of the new type
* @param[in] definition Multiple statements in the form DataType variableName followed by semicolon. Example: name="Point",
* definition="UInt32 x;UInt32 y;"
* @returns The id of the new data type generated.
*/
TypeID AddType(std::string_view name, std::string_view definition);
// structure view
void AddVariable(uint64 offset, std::string_view name, VariableType type);
void AddArray(uint64 offset, std::string_view name, VariableType type, uint32 count);
void AddBiDiminesionalArray(uint64 offset, std::string_view name, VariableType type, uint32 width, uint32 height);
void AddVariable(uint64 offset, std::string_view name, TypeID type);
void AddArray(uint64 offset, std::string_view name, TypeID type, uint32 count);
void AddBiDiminesionalArray(uint64 offset, std::string_view name, TypeID type, uint32 width, uint32 height);
/*
* types: uin8-64,int8-64, float,double, char* (asciiZ), Unicode16Z,Unicode32Z
* auto point_id = AddType("Point","struct Point{ uint32 x;uint32 y };");
* AddVariable(0x1234, "MyPoint", point_id);
*/
Settings();
};
}; // namespace DissasmViewer
struct CORE_EXPORT WindowInterface
{
virtual Reference<Object> GetObject() = 0;
virtual bool AddPanel(Pointer<TabPage> page, bool vertical) = 0;
virtual bool CreateViewer(const std::string_view& name, BufferViewer::Settings& settings) = 0;
virtual bool CreateViewer(const std::string_view& name, ImageViewer::Settings& settings) = 0;
virtual bool CreateViewer(const std::string_view& name, GridViewer::Settings& settings) = 0;
virtual bool CreateViewer(const std::string_view& name, DissasmViewer::Settings& settings) = 0;
virtual bool CreateViewer(const std::string_view& name, TextViewer::Settings& settings) = 0;
virtual bool CreateViewer(const std::string_view& name, ContainerViewer::Settings& settings) = 0;
virtual Reference<ViewControl> GetCurrentView() = 0;
};
}; // namespace View
namespace App
{
bool CORE_EXPORT Init();
void CORE_EXPORT Run();
bool CORE_EXPORT ResetConfiguration();
void CORE_EXPORT OpenFile(const std::filesystem::path& path);
void CORE_EXPORT OpenBuffer(BufferView buf, const ConstString& name, string_view typeExtension = "");
Reference<GView::Object> CORE_EXPORT GetObject(uint32 index);
uint32 CORE_EXPORT GetObjectsCount();
}; // namespace App
}; // namespace GView
| 29.638621 | 137 | 0.585397 | [
"object"
] |
87d22f24ca82ef931884a643735779debb27f0e3 | 4,667 | hpp | C++ | allium/mesh/range.hpp | hrittich/allium | d2691f51f9dc5ccaf808dd11fb28d251eb00b15d | [
"Apache-2.0"
] | 1 | 2022-03-20T15:52:32.000Z | 2022-03-20T15:52:32.000Z | allium/mesh/range.hpp | BuboniK666/allium | d2691f51f9dc5ccaf808dd11fb28d251eb00b15d | [
"Apache-2.0"
] | null | null | null | allium/mesh/range.hpp | BuboniK666/allium | d2691f51f9dc5ccaf808dd11fb28d251eb00b15d | [
"Apache-2.0"
] | 1 | 2022-03-20T15:54:06.000Z | 2022-03-20T15:54:06.000Z | // Copyright 2020 Hannah Rittich
//
// 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.
#ifndef ALLIUM_MESH_RANGE_HPP
#define ALLIUM_MESH_RANGE_HPP
#include <iterator>
#include "point.hpp"
namespace allium {
template <int> class RangeIterator;
/**
@brief An n-d range.
*/
template <int D>
class Range {
public:
Range() = default;
Range(Point<int, D> begin_pos, Point<int, D> end_pos)
: m_begin_pos(begin_pos),
m_end_pos(end_pos)
{}
bool operator== (const Range& other) const {
return m_begin_pos == other.m_begin_pos
&& m_end_pos == other.m_end_pos;
}
/** True if the given point p is inside the range. */
bool in(Point<int, D> p) {
for (int i = 0; i < D; ++i) {
if (p[i] < m_begin_pos[i] || p[i] >= m_end_pos[i])
return false;
}
return true;
}
int index(Point<int, D> p) {
int idx = p[0] - m_begin_pos[0];
for (int i = 1; i < D; ++i) {
int dim_size = m_end_pos[i] - m_begin_pos[i];
idx = (p[i] - m_begin_pos[i]) + dim_size * idx;
}
return idx;
}
/** Returns true if the two ranges intersect. */
bool intersects(const Range<D>& other) {
for (size_t i = 0; i < D; ++i) {
if (other.m_begin_pos[i] >= m_end_pos[i]
|| other.m_end_pos[i] <= m_begin_pos[i]) {
return false;
}
}
return true;
}
Point<int, D> begin_pos() const { return m_begin_pos; }
Point<int, D> end_pos() const { return m_end_pos; }
RangeIterator<D> begin() const;
RangeIterator<D> end() const;
/**
The number of points per dimension.
*/
Point<int, D> shape() const { return m_end_pos - m_begin_pos; }
/**
The total number of points.
*/
size_t size() const {
return shape().prod();
}
private:
Point<int, D> m_begin_pos, m_end_pos;
};
/// @cond INTERNAL
template <int D, int I = D>
struct next_in_range {
static void exec(const Range<D>& r, Point<int, D>& p, bool& overflow) {
++p[I-1];
if (p[I-1] >= r.end_pos()[I-1]) {
p[I-1] = r.begin_pos()[I-1];
next_in_range<D, I-1>::exec(r, p, overflow);
}
}
};
template <int D>
struct next_in_range<D, 0> {
static void exec(const Range<D>& r, Point<int, D>& p, bool& overflow) {
overflow = true;
}
};
/// @endcond
/**
@brief Iterator over the points in an n-d range (allium::Range).
*/
template <int D>
class RangeIterator {
public:
using iterator_category = std::input_iterator_tag;
using value_type = Point<int, D>;
//using difference_type Distance
using pointer = Point<int, D>*;
using reference = Point<int, D>&;
RangeIterator(Point<int, D> start, const Range<D>* range)
: m_range(range),
m_value(start),
m_overflow(false)
{}
/* Out of range position. */
RangeIterator() : m_overflow(true) {}
RangeIterator(const RangeIterator&) = delete;
RangeIterator& operator= (const RangeIterator&) = delete;
RangeIterator(RangeIterator&&) = default;
bool operator==(const RangeIterator& rhs) const {
return m_overflow && rhs.m_overflow;
}
bool operator!=(const RangeIterator& rhs) const {
return !(*this == rhs);
}
RangeIterator& operator++ () {
next_in_range<D>::exec(*m_range, m_value, m_overflow);
return *this;
}
Point<int, D> operator* () {
return m_value;
}
private:
const Range<D>* m_range;
Point<int, D> m_value;
bool m_overflow;
};
template <int D>
RangeIterator<D> Range<D>::begin() const {
return RangeIterator<D>(begin_pos(), this);
}
template <int D>
RangeIterator<D> Range<D>::end() const {
return RangeIterator<D>();
}
template <int D>
std::ostream& operator<< (std::ostream& os, Range<D> r)
{
os << "Range(" << r.begin_pos() << ", " << r.end_pos() << ")";
return os;
}
}
#endif
| 25.927778 | 75 | 0.57403 | [
"shape"
] |
87dfae5153f5c60a7dd61ff37f8839190fcc91c2 | 22,794 | cpp | C++ | PSME/agent/network/src/discovery/discovery_manager.cpp | opencomputeproject/HWMgmt-DeviceMgr-PSME | 2a00188aab6f4bef3776987f0842ef8a8ea972ac | [
"Apache-2.0"
] | 5 | 2021-10-07T15:36:37.000Z | 2022-03-01T07:21:49.000Z | PSME/agent/network/src/discovery/discovery_manager.cpp | opencomputeproject/HWMgmt-DeviceMgr-PSME | 2a00188aab6f4bef3776987f0842ef8a8ea972ac | [
"Apache-2.0"
] | null | null | null | PSME/agent/network/src/discovery/discovery_manager.cpp | opencomputeproject/HWMgmt-DeviceMgr-PSME | 2a00188aab6f4bef3776987f0842ef8a8ea972ac | [
"Apache-2.0"
] | 1 | 2022-03-01T07:21:51.000Z | 2022-03-01T07:21:51.000Z | /*!
* @copyright
* Copyright (c) 2015-2017 Intel Corporation
*
* @copyright
* 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
*
* @copyright
* http://www.apache.org/licenses/LICENSE-2.0
*
* @copyright
* 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 discovery_manager.cpp
* @brief Initial discovery implementation.
* */
#include "discovery/discovery_manager.hpp"
#include "loader/network_config.hpp"
#include "agent-framework/module/network_components.hpp"
#include "agent-framework/module/common_components.hpp"
#include "network_config.hpp"
#include "api/netlink/sysfs.hpp"
#include "api/acl.hpp"
#include "api/switch_info.hpp"
#include "api/static_mac.hpp"
#include "utils/utils.hpp"
#include <safe-string/safe_lib.hpp>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <linux/if_ether.h>
using namespace agent::network;
using namespace agent::network::loader;
using namespace agent::network::api::netlink;
using namespace agent::network::discovery;
using namespace agent::network::utils;
using namespace agent_framework::module;
using namespace agent_framework::model;
using namespace agent_framework::model::enums;
using namespace agent_framework::model::attribute;
using std::string;
namespace {
constexpr uint32_t SERIAL_DEFAULT_BITRATE = 115200;
constexpr uint32_t SERIAL_DEFAULT_DATABITS = 8;
constexpr uint32_t SERIAL_DEFAULT_STOPBIT = 1;
constexpr uint32_t SWITCH_DEFAULT_LOCATION = 1;
static constexpr char MESH_PORT_ENV_NAME[] = "MESH_PORTS";
static void update_manager_info(const string& uuid) {
/* get module reference */
auto manager = CommonComponents::get_instance()->
get_module_manager().get_entry_reference(uuid);
/* update serial information */
SerialConsole serial{manager->get_serial_console()};
serial.set_bitrate(SERIAL_DEFAULT_BITRATE);
serial.set_data_bits(SERIAL_DEFAULT_DATABITS);
serial.set_flow_control(SerialConsoleFlowControl::None);
serial.set_parity(SerialConsoleParity::None);
serial.set_pin_out(SerialConsolePinOut::Cisco);
serial.set_stop_bits(SERIAL_DEFAULT_STOPBIT);
serial.set_signal_type(SerialConsoleSignalType::Rs232);
/* add collections */
manager->set_serial_console(std::move(serial));
manager->add_collection({CollectionName::Switches,
CollectionType::EthernetSwitches, ""});
manager->add_collection({CollectionName::Chassis,
CollectionType::Chassis, ""});
}
static string get_switch_uuid(const string& uuid) {
auto uuids = NetworkComponents::get_instance()->
get_switch_manager().get_keys(uuid);
if (uuids.empty()) {
throw std::runtime_error("No ethernet switches found");
}
return uuids.front();
}
static void update_switch_info(const string& switch_uuid) {
/* get switch reference */
auto switch_module = NetworkComponents::get_instance()->
get_switch_manager().get_entry_reference(switch_uuid);
/* TODO how do we know the location ? */
switch_module->set_location(SWITCH_DEFAULT_LOCATION);
switch_module->add_collection({CollectionName::EthernetSwitchPorts,
CollectionType::EthernetSwitchPorts, ""});
switch_module->add_collection({CollectionName::Neighbors,
CollectionType::NeighborSwitches, ""});
switch_module->add_collection({CollectionName::Acls,
CollectionType::Acls, ""});
}
static inline bool is_mesh_port(const string& port_identifier) {
auto env = std::getenv(MESH_PORT_ENV_NAME);
if (!env) {
return false;
}
std::stringstream ss{env};
std::istream_iterator<std::string> eos{};
std::istream_iterator<std::string> iit{ss};
return (std::find(iit, eos, port_identifier) != eos);
}
static void add_physical_port(const string& switch_uuid,
const string& port_identifier) {
/* add port into network manager */
auto network_components = NetworkComponents::get_instance();
auto& port_manager = network_components->get_port_manager();
EthernetSwitchPort port_model{switch_uuid};
port_model.add_collection({CollectionName::Vlans,
CollectionType::EthernetSwitchPortVlans, ""});
port_model.add_collection({CollectionName::PortAcls,
CollectionType::Acls, ""});
port_model.add_collection({CollectionName::StaticMacs,
CollectionType::StaticMacs, ""});
port_model.set_link_technology(LinkTechnology::Ethernet);
port_model.set_port_class(PortClass::Physical);
port_model.set_port_type(is_mesh_port(port_identifier) ?
PortType::MeshPort : PortType::Upstream);
port_model.set_port_mode(PortMode::Unknown);
port_model.set_port_identifier(port_identifier);
port_model.set_vlan_enable(true);
port_model.set_status({State::Enabled, Health::OK});
port_manager.add_entry(port_model);
}
static void discover_switch_ports(const string& switch_uuid) {
SysFs sysfs{};
/* discover physical & logical ports */
auto network_components = NetworkComponents::get_instance();
auto& port_manager = network_components->get_port_manager();
try {
/* physical ports */
const auto& port_list = sysfs.get_port_list();
for (const auto& port_identifier : port_list) {
string port_uuid{};
if (get_port_uuid_by_identifier(port_identifier, port_uuid)) {
log_debug(GET_LOGGER("network-agent"), "Updating port " +
port_identifier);
auto port = port_manager.get_entry_reference(port_uuid);
/* add port collections */
port->add_collection({CollectionName::Vlans,
CollectionType::EthernetSwitchPortVlans, ""});
port->add_collection({CollectionName::PortAcls,
CollectionType::Acls, ""});
port->add_collection({CollectionName::StaticMacs,
CollectionType::StaticMacs, ""});
/* update port link technology attribute */
if (LinkTechnology::Unknown == port->get_link_technology()) {
port->set_link_technology(LinkTechnology::Ethernet);
}
/* update port type attribute */
if (PortType::Unknown == port->get_port_type()) {
port->set_port_type(PortType::Upstream);
}
/* update port static attributes */
port->set_port_class(PortClass::Physical);
port->set_port_mode(PortMode::Unknown);
port->set_vlan_enable(true);
port->set_status({State::Enabled, Health::OK});
}
else {
log_debug(GET_LOGGER("network-agent"), "Adding physical port " +
port_identifier);
add_physical_port(switch_uuid, port_identifier);
}
}
/* logical ports */
const auto lag_list = sysfs.get_team_list();
for (const auto& lag_identifier : lag_list) {
log_debug(GET_LOGGER("network-agent"), "Adding LAG " + lag_identifier);
add_logical_port(lag_identifier, switch_uuid);
}
}
catch (const std::runtime_error& e) {
log_error(GET_LOGGER("network-agent"), e.what());
throw;
}
}
static inline void init_forward_port (const string port_identifier,
AclRule& model_rule) {
if (!port_identifier.empty()) {
string port_uuid{};
if (get_port_uuid_by_identifier(port_identifier, port_uuid)) {
model_rule.set_forward_mirror_port(port_uuid);
}
}
}
static inline void init_mirrored_ports (const api::Acl::Strings& ports,
AclRule& model_rule) {
AclRule::MirroredPorts port_uuids{};
for (const auto& port_identifier : ports) {
string port_uuid{};
if (get_port_uuid_by_identifier(port_identifier, port_uuid)) {
port_uuids.add_entry(port_uuid);
}
}
model_rule.set_mirrored_ports(port_uuids);
}
static inline void init_acl_action (const api::Acl::Rule& rule,
AclRule& model_rule) {
switch(rule.get_action()) {
case api::Acl::ActionType::ACTION_DENY:
model_rule.set_action(enums::AclAction::Deny);
break;
case api::Acl::ActionType::ACTION_PERMIT:
model_rule.set_action(enums::AclAction::Permit);
break;
case api::Acl::ActionType::ACTION_FORWARD:
model_rule.set_action(enums::AclAction::Forward);
break;
case api::Acl::ActionType::ACTION_MIRROR:
model_rule.set_action(enums::AclAction::Mirror);
break;
default:
break;
}
}
static inline void init_acl_mirror_type (const api::Acl::Rule& rule,
AclRule& model_rule) {
switch(rule.get_mirror_type()) {
case api::Acl::MirrorType::MIRROR_INGRESS:
model_rule.set_mirror_type(enums::AclMirrorType::Ingress);
break;
case api::Acl::MirrorType::MIRROR_EGRESS:
model_rule.set_mirror_type(enums::AclMirrorType::Egress);
break;
case api::Acl::MirrorType::MIRROR_BIDIRECTIONAL:
model_rule.set_mirror_type(enums::AclMirrorType::Bidirectional);
break;
case api::Acl::MirrorType::MIRROR_REDIRECT:
model_rule.set_mirror_type(enums::AclMirrorType::Redirect);
break;
case api::Acl::MirrorType::MIRROR_NA:
default:
break;
}
}
static inline void get_condition_ip(const api::Acl::Condition& condition,
AclRule::Ip& ip) {
in_addr addr{};
addr.s_addr = uint32_t(condition.value);
ip.set_address(inet_ntoa(addr));
if (condition.mask) {
addr.s_addr = uint32_t(condition.mask);
ip.set_mask(inet_ntoa(addr));
}
}
static inline void get_condition_mac(const api::Acl::Condition& condition,
AclRule::Mac& mac) {
uint8_t octets[ETH_ALEN]{};
if (EOK != memcpy_s(octets, ETH_ALEN, &condition.value, ETH_ALEN)) {
throw std::runtime_error("Cannot copy memory with MAC address.");
}
std::reverse(octets, octets + ETH_ALEN);
mac.set_address(api::SwitchInfo::format_mac_address(octets));
if (condition.mask) {
if (EOK != memcpy_s(octets, ETH_ALEN, &condition.mask, ETH_ALEN)) {
throw std::runtime_error("Cannot copy memory with MAC address mask.");
};
std::reverse(octets, octets + ETH_ALEN);
mac.set_mask(api::SwitchInfo::format_mac_address(octets));
}
}
static inline void get_condition_vlan(const api::Acl::Condition& condition,
AclRule::VlanId& vlan_id) {
vlan_id.set_id(uint32_t(condition.value));
if (condition.mask) {
vlan_id.set_mask(uint32_t(condition.mask));
}
}
static inline void get_condition_port(const api::Acl::Condition& condition,
AclRule::Port& port) {
port.set_port(uint32_t(condition.value));
if (condition.mask) {
port.set_mask(uint32_t(condition.mask));
}
}
static inline void init_acl_conditions (const api::Acl::Rule& rule,
AclRule& model_rule) {
for (const auto& condition : rule.get_conditions()) {
AclRule::Ip ip{};
AclRule::Mac mac{};
AclRule::VlanId vlan_id{};
AclRule::Port port{};
switch(condition.type) {
case api::Acl::ConditionType::CONDITION_IP_SRC:
get_condition_ip(condition, ip);
model_rule.set_source_ip(ip);
break;
case api::Acl::ConditionType::CONDITION_IP_DEST:
get_condition_ip(condition, ip);
model_rule.set_destination_ip(ip);
break;
case api::Acl::ConditionType::CONDITION_MAC_SRC:
get_condition_mac(condition, mac);
model_rule.set_source_mac(mac);
break;
case api::Acl::ConditionType::CONDITION_MAC_DEST:
get_condition_mac(condition, mac);
model_rule.set_destination_mac(mac);
break;
case api::Acl::ConditionType::CONDITION_VLAN:
get_condition_vlan(condition, vlan_id);
model_rule.set_vlan_id(vlan_id);
break;
case api::Acl::ConditionType::CONDITION_PROTOCOL:
model_rule.set_protocol(condition.value);
break;
case api::Acl::ConditionType::CONDITION_L4_PORT_SRC:
get_condition_port(condition, port);
model_rule.set_source_port(port);
break;
case api::Acl::ConditionType::CONDITION_L4_PORT_DEST:
get_condition_port(condition, port);
model_rule.set_destination_port(port);
break;
default:
break;
}
}
}
static inline void init_acl_rule (const api::Acl::Rule& rule,
AclRule& model_rule) {
model_rule.set_rule_id(rule.get_rule_id());
init_acl_action(rule, model_rule);
init_forward_port(rule.get_destination_port(), model_rule);
init_mirrored_ports(rule.get_mirrored_ports(), model_rule);
init_acl_mirror_type(rule, model_rule);
init_acl_conditions(rule, model_rule);
}
static inline void init_acl_rules (const string& acl_uuid,
const api::Acl::Rules& rules) {
auto network_manager = NetworkComponents::get_instance();
auto& acl_rule_manager = network_manager->get_acl_rule_manager();
for (const auto& rule : rules) {
AclRule model_rule{acl_uuid};
init_acl_rule(rule, model_rule);
model_rule.set_status({enums::State::Enabled, enums::Health::OK});
acl_rule_manager.add_entry(std::move(model_rule));
}
}
static inline void read_acl_rules(const string& acl_uuid) {
api::Acl acl{};
try {
acl.read_acl_rule_list(api::Acl::get_acl_name(acl_uuid));
}
catch (const std::runtime_error& e) {
log_error(GET_LOGGER("fm10000"),
string("Failed reading ACL rule list from switch: ") +
e.what());
return;
}
init_acl_rules(acl_uuid, acl.get_rules());
}
static inline void init_acls_with_ports (const string& switch_uuid,
api::Acl& acl) {
auto network_manager = NetworkComponents::get_instance();
auto& acl_manager = network_manager->get_acl_manager();
auto& acl_port_manager = network_manager->get_acl_port_manager();
for (const auto& acl_name : acl.get_acls()) {
Acl acl_model{switch_uuid};
const auto acl_uuid = acl_model.get_uuid();
acl_model.set_status({enums::State::Enabled,
enums::Health::OK});
acl_model.add_collection({CollectionName::AclRules,
CollectionType::Rules, ""});
acl_model.add_collection({CollectionName::AclPorts,
CollectionType::EthernetSwitchPorts, ""});
acl_model.set_name(acl_name);
// keep ACL UUID -> ACL name mapping
api::Acl::add_acl_name(acl_uuid, acl_name);
acl_manager.add_entry(acl_model);
for (const auto& port_identifier : acl.get_bound_ports(acl_name)) {
string port_uuid{};
if (get_port_uuid_by_identifier(port_identifier, port_uuid)) {
acl_port_manager.add_entry(acl_uuid, port_uuid, "");
}
}
read_acl_rules(acl_uuid);
}
}
static void discover_acls(const string& switch_uuid) {
api::Acl acl{};
try {
acl.read_acl_list();
}
catch (const std::runtime_error& e) {
log_error(GET_LOGGER("network-agent"),
string("Failed reading ACL list from switch: ") + e.what());
return;
}
init_acls_with_ports(switch_uuid, acl);
}
void add_static_macs_to_model(const string& port_uuid,
const api::StaticMac::Table& macs) {
auto network_manager = NetworkComponents::get_instance();
auto& static_mac_manager = network_manager->get_static_mac_manager();
for (const auto& pair : macs) {
StaticMac static_mac{port_uuid};
static_mac.set_address(pair.first);
static_mac.set_vlan_id(pair.second);
static_mac.set_status({enums::State::Enabled, enums::Health::OK});
static_mac_manager.add_entry(static_mac);
}
}
void init_static_macs_on_port(const string& port_uuid) {
auto network_manager = NetworkComponents::get_instance();
auto& port_manager = network_manager->get_port_manager();
auto port = port_manager.get_entry(port_uuid);
try {
api::StaticMac::Table macs{};
api::StaticMac::get_macs(port.get_port_identifier(), macs);
add_static_macs_to_model(port_uuid, macs);
}
catch (const std::runtime_error& e) {
log_error(GET_LOGGER("fm10000"),
string("Failed reading static MAC list on port ")
+ port_uuid + " : " + e.what());
}
}
static void discover_static_macs(const string& switch_uuid) {
auto network_manager = NetworkComponents::get_instance();
auto& port_manager = network_manager->get_port_manager();
for (const auto& port_uuid : port_manager.get_keys(switch_uuid)) {
::init_static_macs_on_port(port_uuid);
}
}
static void discover_switch_vlan_ports(const string&) {
/* add port-vlan pair to the network manager */
auto network_components = NetworkComponents::get_instance();
auto& port_manager = network_components->get_port_manager();
for (const auto& port_uuid : port_manager.get_keys()) {
auto port = port_manager.get_entry(port_uuid);
if (is_member_port(port.get_port_identifier())) {
/* getting vlan list isn't allowed on member port */
continue;
}
if (PortClass::Logical == port.get_port_class()) {
if (is_logical_port_empty(port.get_port_identifier())) {
/* it's not possible to get vlan list on empty lag */
continue;
}
}
/* get vlan list on the port */
init_switch_vlan_port(port.get_port_identifier());
}
}
static void show_network_modules() {
auto network_components = NetworkComponents::get_instance();
auto common_components = CommonComponents::get_instance();
auto& module_manager = common_components->get_module_manager();
auto& switch_manager = network_components->get_switch_manager();
auto& port_manager = network_components->get_port_manager();
auto& port_vlan_manager = network_components->get_port_vlan_manager();
for (const auto& uuid : module_manager.get_keys()) {
log_debug(GET_LOGGER("network-agent"), "Manager UUID: " + uuid);
for (const auto& switch_uuid : switch_manager.get_keys(uuid)) {
log_debug(GET_LOGGER("network-agent"), "Switch UUID: " + switch_uuid);
for (const auto& port_uuid : port_manager.get_keys(switch_uuid)) {
log_debug(GET_LOGGER("network-agent"), "Port UUID: " + port_uuid);
for (const auto& port_vlan_uuid :
port_vlan_manager.get_keys(port_uuid)) {
log_debug(GET_LOGGER("network-agent"), "Port-vlan UUID: "
+ port_vlan_uuid);
}
}
}
}
}
}
DiscoveryManager::DiscoveryManager() {}
DiscoveryManager::~DiscoveryManager() {}
void DiscoveryManager::wait_for_complete() {
std::unique_lock<std::mutex> lock{m_mutex};
m_cv.wait(lock);
}
void DiscoveryManager::discovery(const std::string& uuid) {
/* start discovery */
::update_manager_info(uuid);
auto switch_uuid = get_switch_uuid(uuid);
::update_switch_info(switch_uuid);
::discover_switch_ports(switch_uuid);
::discover_switch_vlan_ports(switch_uuid);
::discover_acls(switch_uuid);
::discover_static_macs(switch_uuid);
::show_network_modules();
/* notify discovery done */
m_cv.notify_all();
}
| 43.007547 | 87 | 0.584101 | [
"model"
] |
87e100ae92b64d6fe85549b7de1ba2ccb8a7c739 | 6,632 | cpp | C++ | ndlk/ortogon_u-2/source/exact_cover_u.cpp | tomasbrod/tbboinc | c125cc355b2dc9a1e536b5e5ded028d4e7f4613a | [
"MIT"
] | null | null | null | ndlk/ortogon_u-2/source/exact_cover_u.cpp | tomasbrod/tbboinc | c125cc355b2dc9a1e536b5e5ded028d4e7f4613a | [
"MIT"
] | 4 | 2020-09-07T15:54:45.000Z | 2020-09-27T16:47:16.000Z | ndlk/ortogon_u-2/source/exact_cover_u.cpp | tomasbrod/tbboinc | c125cc355b2dc9a1e536b5e5ded028d4e7f4613a | [
"MIT"
] | null | null | null | #include "exact_cover_u.h"
std::vector<transver> baza_trans;
std::vector<exact_cover::data*> exact_cover::O;
std::vector<exact_cover::data> exact_cover::heads;
std::vector<exact_cover::data> exact_cover::nodes;
bool is_dlk(const kvadrat& kvad){
long long flag, t;
for(int i = 0; i < raz; i += por){
flag = 0;
for(int j = 0; j < por; j++){
if(flag & (t = 1ll << kvad[i + j])) return false;
flag |= t;
}
}
for(int i = 0; i < por; i++){
flag = 0;
for(int j = 0; j < raz; j += por){
if(flag & (t = 1ll << kvad[i + j])) return false;
flag |= t;
}
}
flag = 0;
for(int j = 0; j < raz + por; j += por + 1){
if(flag & (t = 1ll << kvad[j])) return false;
flag |= t;
}
flag = 0;
for(int j = por - 1; j <= raz - por; j += por - 1){
if(flag & (t = 1ll << kvad[j])) return false;
flag |= t;
}
return true;
}
void exact_cover::search(std::list<kvadrat_m>& templ){
data* c;
data* r;
int l = 0;
forward:
c = choose_column();
if(!c->size) goto backtrack;
cover_column(c);
r = O[l] = c->down;
advance:
if(r == c) goto backup;
if(l == por - 1){
save_solution(templ);
goto recover;
}
for(data* j = r->right; j != r; j = j->right) cover_column(heads.data() + (j->column & modul));
l++;
goto forward;
backup:
uncover_column(c);
backtrack:
if(l == 0) return;
r = O[--l];
c = heads.data() + (r->column & modul);
for(data* j = r->left; j != r; j = j->left) uncover_column(heads.data() + (j->column & modul));
recover:
r = O[l] = r->down;
goto advance;
}
void exact_cover::init(int ch_trans){
nodes.resize(ch_trans * por);
for(int i = 0; i <= raz; i++){
heads[i].right = heads.data() + i + 1;
heads[i].left = heads.data() + i - 1;
heads[i].down = heads[i].up = heads.data() + i;
heads[i].size = 0;
}
heads[0].left += raz + 1;
heads[raz].right = heads.data();
for(int i = 0, count = 0; i < ch_trans; count += por, i++){
for(int j = 0, k = 0, t; j < por; k += por, j++){
nodes[count + j].column = (i << sdvig) | (t = baza_trans[i][j] + k + 1);
nodes[count + j].right = nodes.data() + count + j + 1;
nodes[count + j].left = nodes.data() + count + j - 1;
nodes[count + j].down = heads.data() + t;
nodes[count + j].up = heads[t].up;
heads[t].up = heads[t].up->down = nodes.data() + count + j;
heads[t].size++;
}
nodes[count].left += por;
nodes[count + por - 1].right -= por;
}
}
void exact_cover::search_mates(const kvadrat& dlk){
baza_trans.clear();
search_trans(dlk);
int ch_trans = baza_trans.size();
if(ch_trans < por) return;
init(ch_trans);
std::list<kvadrat_m> templ;
search(templ);
if(templ.empty()) return;
kvadrat_m tempk(raz_kvm);
char* p = tempk.data();
for(int i = 0; i < raz; i += por){
*p++ = dlk[i] + (dlk[i] < 10 ? '0' : 'A' - 10);
for(int j = 1; j < por; j++){
*p++ = ' ';
*p++ = dlk[i + j] + (dlk[i + j] < 10 ? '0' : 'A' - 10);
}
*p++ = '\r';
*p++ = '\n';
}
extern std::map<kvadrat_m,std::list<kvadrat_m>> baza_mar;
baza_mar.insert(std::make_pair(tempk, templ));
}
void exact_cover::search_trans(const kvadrat& dlk){
init_trans(dlk);
transver tempt(por);
data* c;
data* r;
int l = 0, count = 0;
forward:
c = choose_column();
if(!c->size) goto backtrack;
cover_column(c);
r = O[l] = c->down;
advance:
if(r == c) goto backup;
if(l == por - 1){
for(int i = 0, t; i < por; i++){
t = O[i]->column >> sdvig;
tempt[t >> 8] = t & 0xff;
}
baza_trans.push_back(tempt);
if(++count > max_trans){
std::cerr << "Число диагональных трансверсалей ДЛК" << por << ":\n\n";
for(int i = 0; i < raz; i++) std::cerr << char(dlk[i] + (dlk[i] < 10 ? '0' : 'A' - 10)) << (i % por != por - 1 ? ' ' : '\n');
std::cerr << "\nпревышает максимум " << max_trans << std::endl << std::endl;
extern bool mute;
if(!mute){
std::cout << "Для выхода нажмите любую клавишу: ";
system("pause > nul");
std::cout << std::endl;
}
exit(3);
}
goto recover;
}
for(data* j = r->right; j != r; j = j->right) cover_column(heads.data() + (j->column & modul));
l++;
goto forward;
backup:
uncover_column(c);
backtrack:
if(l == 0) return;
r = O[--l];
c = heads.data() + (r->column & modul);
for(data* j = r->left; j != r; j = j->left) uncover_column(heads.data() + (j->column & modul));
recover:
r = O[l] = r->down;
goto advance;
}
void exact_cover::init_trans(const kvadrat& dlk){
nodes.resize(raz * 3 + (por << 1));
int dl = 3 * por + 2;
for(int i = 0; i <= dl; i++){
heads[i].right = heads.data() + i + 1;
heads[i].left = heads.data() + i - 1;
heads[i].down = heads[i].up = heads.data() + i;
heads[i].size = 0;
}
heads[0].left = heads.data() + dl;
heads[dl].right = heads.data();
int temp[4];
for(int i = 0, count = 0, r, c; i < raz; i++){
temp[0] = (r = i / por) + 1;
temp[1] = (c = i % por) + por + 1;
temp[2] = dlk[i] + (por << 1) + 1;
temp[3] = 0;
if(r == c) temp[3] = 1;
if(r == por - 1 - c) temp[3] |= 2;
int t;
for(int j = 0, t; j < 3; j++){
nodes[count + j].column = (r << (sdvig + 8)) | (c << sdvig) | (t = temp[j]);
nodes[count + j].right = nodes.data() + count + j + 1;
nodes[count + j].left = nodes.data() + count + j - 1;
nodes[count + j].down = heads.data() + t;
nodes[count + j].up = heads[t].up;
heads[t].up = heads[t].up->down = nodes.data() + count + j;
heads[t].size++;
}
switch(temp[3]){
case 0:
nodes[count].left += 3;
nodes[count + 2].right -= 3;
count += 3;
break;
case 1:
case 2:
nodes[count + 3].column = (r << (sdvig + 8)) | (c << sdvig) | (t = dl - 2 + temp[3]);
nodes[count + 3].right = nodes.data() + count;
nodes[count + 3].left = nodes.data() + count + 2;
nodes[count + 3].down = heads.data() + t;
nodes[count + 3].up = heads[t].up;
heads[t].up = heads[t].up->down = nodes.data() + count + 3;
heads[t].size++;
nodes[count].left += 4;
count += 4;
break;
case 3:
for(int j = 0; j < 2; j++){
nodes[count + 3 + j].column = (r << (sdvig + 8)) | (c << sdvig) | (t = dl - 1 + j);
nodes[count + 3 + j].right = nodes.data() + count + j + 4;
nodes[count + 3 + j].left = nodes.data() + count + j + 2;
nodes[count + 3 + j].down = heads.data() + t;
nodes[count + 3 + j].up = heads[t].up;
heads[t].up = heads[t].up->down = nodes.data() + count + 3 + j;
heads[t].size++;
}
nodes[count].left += 5;
nodes[count + 4].right -= 5;
count += 5;
}
}
}
| 29.215859 | 129 | 0.518094 | [
"vector"
] |
87e1f316e5b4bf74cd6da034e8ec0748373dc48d | 3,386 | cc | C++ | src/oryol-conv3d/AssimpLoader.cc | 13rac1/oryol-tools | 9f0719343718d379d0cb52838260da78466e4ba7 | [
"MIT"
] | null | null | null | src/oryol-conv3d/AssimpLoader.cc | 13rac1/oryol-tools | 9f0719343718d379d0cb52838260da78466e4ba7 | [
"MIT"
] | null | null | null | src/oryol-conv3d/AssimpLoader.cc | 13rac1/oryol-tools | 9f0719343718d379d0cb52838260da78466e4ba7 | [
"MIT"
] | null | null | null | //------------------------------------------------------------------------------
// AssimpLoader.cc
//------------------------------------------------------------------------------
#include "AssimpLoader.h"
#include "ExportUtil/Log.h"
#include "assimp/scene.h"
#include "assimp/postprocess.h"
using namespace OryolTools;
//------------------------------------------------------------------------------
void
AssimpLoader::Load(const std::string& path, IRep& irep) {
Log::FailIf(path.empty(), "path to 3D file required!");
this->importer.SetPropertyInteger(AI_CONFIG_PP_RVC_FLAGS, aiComponent_LIGHTS|aiComponent_CAMERAS);
this->importer.SetPropertyInteger(AI_CONFIG_PP_SBP_REMOVE, aiPrimitiveType_POINT|aiPrimitiveType_LINE);
this->importer.SetPropertyInteger(AI_CONFIG_PP_SLM_VERTEX_LIMIT, (1<<16));
const uint32_t procFlags =
aiProcess_CalcTangentSpace|
aiProcess_JoinIdenticalVertices|
aiProcess_Triangulate|
aiProcess_GenNormals| // only if mesh doesn't already have normals
aiProcess_ImproveCacheLocality|
aiProcess_SplitLargeMeshes|
aiProcess_RemoveRedundantMaterials|
aiProcess_SortByPType|
aiProcess_FindDegenerates|
aiProcess_FindInvalidData|
aiProcess_GenUVCoords|
aiProcess_TransformUVCoords|
aiProcess_OptimizeMeshes|
aiProcess_OptimizeGraph|
aiProcess_FlipWindingOrder;
this->scene = importer.ReadFile(path, procFlags);
Log::FailIf(!this->scene, "Failed to import file '%s' via assimp: %s\n", path.c_str(), importer.GetErrorString());
this->toIRep(irep);
}
//------------------------------------------------------------------------------
void
AssimpLoader::toIRep(IRep& irep) {
this->writeVertexComponents(irep);
// FIXME
}
//------------------------------------------------------------------------------
void
AssimpLoader::writeVertexComponents(IRep& irep) {
std::array<VertexFormat::Code, VertexAttr::Num> comps;
comps.fill(VertexFormat::Invalid);
for (uint32_t meshIndex = 0; meshIndex < this->scene->mNumMeshes; meshIndex++) {
const aiMesh* msh = scene->mMeshes[meshIndex];
if (msh->HasPositions()) {
comps[VertexAttr::Position] = VertexFormat::Float3;
}
if (msh->HasNormals()) {
comps[VertexAttr::Normal] = VertexFormat::Float3;
}
if (msh->HasTangentsAndBitangents()) {
comps[VertexAttr::Tangent] = VertexFormat::Float3;
comps[VertexAttr::Binormal] = VertexFormat::Float3;
}
for (uint32_t i = 0; i < 4; i++) {
if (msh->HasTextureCoords(i)) {
comps[VertexAttr::TexCoord0+i] = VertexFormat::Float2;
}
}
for (uint32_t i = 0; i < 2; i++) {
if (msh->HasVertexColors(i)) {
comps[VertexAttr::Color0+i] = VertexFormat::Float4;
}
}
if (msh->HasBones()) {
comps[VertexAttr::Weights] = VertexFormat::Float4;
comps[VertexAttr::Indices] = VertexFormat::Float4;
}
}
for (int i = 0; i < VertexAttr::Num; i++) {
if (comps[i] != VertexFormat::Invalid) {
IRep::VertexComponent c;
c.Attr = (VertexAttr::Code) i;
c.Format = comps[i];
irep.VertexComponents.push_back(c);
}
}
}
| 37.622222 | 118 | 0.560248 | [
"mesh",
"3d"
] |
87e4329f2b324b2edb11955e4e97887c0e7d6b48 | 37,428 | cpp | C++ | src/CryptoNoteCore/Currency.cpp | Camellia73/BlackRoseCoin_Diamond_V2 | f155f7f9eb7f8db711b9e3a0d417038321a92abe | [
"BSD-3-Clause"
] | null | null | null | src/CryptoNoteCore/Currency.cpp | Camellia73/BlackRoseCoin_Diamond_V2 | f155f7f9eb7f8db711b9e3a0d417038321a92abe | [
"BSD-3-Clause"
] | null | null | null | src/CryptoNoteCore/Currency.cpp | Camellia73/BlackRoseCoin_Diamond_V2 | f155f7f9eb7f8db711b9e3a0d417038321a92abe | [
"BSD-3-Clause"
] | null | null | null | // Copyright (c) 2012-2017, The CryptoNote developers, The Bytecoin developers
// Copyright (c) 2017-2019, The Iridium developers
// Copyright (c) 2018-2019, The MonetaVerde developers
//
// This file is part of Bytecoin.
//
// Bytecoin is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Bytecoin 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 Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with Bytecoin. If not, see <http://www.gnu.org/licenses/>.
#include "Currency.h"
#include <cctype>
#include <boost/algorithm/string/trim.hpp>
#include <boost/lexical_cast.hpp>
#include "../Common/Math.h"
#include "../Common/Base58.h"
#include "../Common/int-util.h"
#include "../Common/StringTools.h"
#include "Account.h"
#include "CryptoNoteBasicImpl.h"
#include "CryptoNoteFormatUtils.h"
#include "CryptoNoteTools.h"
#include "TransactionExtra.h"
#include "UpgradeDetector.h"
#undef ERROR
using namespace Logging;
using namespace Common;
namespace CryptoNote {
/* BLACKROSEDIAMONDV2 COMPATIBILITY */
#if defined(_MSC_VER)
/* #define NOMINMAX 1
#include <windows.h>
#include <winnt.h>
static inline void mul(uint64_t a, uint64_t b, uint64_t &low, uint64_t &high) {
low = mul128(a, b, &high);
}
*/
#include <intrin.h>
#pragma intrinsic(_umul128)
static inline void mul(uint64_t a, uint64_t b, uint64_t &low, uint64_t &high) {
low = _umul128(a, b, &high);
}
#else
static inline void mul(uint64_t a, uint64_t b, uint64_t &low, uint64_t &high) {
typedef unsigned __int128 uint128_t;
uint128_t res = (uint128_t) a * (uint128_t) b;
low = (uint64_t) res;
high = (uint64_t) (res >> 64);
}
#endif
uint64_t log2_fix(uint64_t x, size_t log_fix_precision)
{
assert(x != 0);
assert(1 <= log_fix_precision && log_fix_precision < sizeof(uint64_t) * 8 / 2 - 1); // "Invalid log precision"
uint64_t b = UINT64_C(1) << (log_fix_precision - 1);
uint64_t y = 0;
while (x >= (UINT64_C(2) << log_fix_precision))
{
x >>= 1;
y += UINT64_C(1) << log_fix_precision;
}
// 64 bits are enough, because of x < 2 * (1 << log_fix_precision) <= 2^32
uint64_t z = x;
for (size_t i = 0; i < log_fix_precision; i++)
{
z = (z * z) >> log_fix_precision;
if (z >= (UINT64_C(2) << log_fix_precision))
{
z >>= 1;
y += b;
}
b >>= 1;
}
return y;
}
/* /END BLACKROSEDIAMONDV2 */
const std::vector<uint64_t> Currency::PRETTY_AMOUNTS = {
1, 2, 3, 4, 5, 6, 7, 8, 9,
10, 20, 30, 40, 50, 60, 70, 80, 90,
100, 200, 300, 400, 500, 600, 700, 800, 900,
1000, 2000, 3000, 4000, 5000, 6000, 7000, 8000, 9000,
10000, 20000, 30000, 40000, 50000, 60000, 70000, 80000, 90000,
100000, 200000, 300000, 400000, 500000, 600000, 700000, 800000, 900000,
1000000, 2000000, 3000000, 4000000, 5000000, 6000000, 7000000, 8000000, 9000000,
10000000, 20000000, 30000000, 40000000, 50000000, 60000000, 70000000, 80000000, 90000000,
100000000, 200000000, 300000000, 400000000, 500000000, 600000000, 700000000, 800000000, 900000000,
1000000000, 2000000000, 3000000000, 4000000000, 5000000000, 6000000000, 7000000000, 8000000000, 9000000000,
10000000000, 20000000000, 30000000000, 40000000000, 50000000000, 60000000000, 70000000000, 80000000000, 90000000000,
100000000000, 200000000000, 300000000000, 400000000000, 500000000000, 600000000000, 700000000000, 800000000000, 900000000000,
1000000000000, 2000000000000, 3000000000000, 4000000000000, 5000000000000, 6000000000000, 7000000000000, 8000000000000, 9000000000000,
10000000000000, 20000000000000, 30000000000000, 40000000000000, 50000000000000, 60000000000000, 70000000000000, 80000000000000, 90000000000000,
100000000000000, 200000000000000, 300000000000000, 400000000000000, 500000000000000, 600000000000000, 700000000000000, 800000000000000, 900000000000000,
1000000000000000, 2000000000000000, 3000000000000000, 4000000000000000, 5000000000000000, 6000000000000000, 7000000000000000, 8000000000000000, 9000000000000000,
10000000000000000, 20000000000000000, 30000000000000000, 40000000000000000, 50000000000000000, 60000000000000000, 70000000000000000, 80000000000000000, 90000000000000000,
100000000000000000, 200000000000000000, 300000000000000000, 400000000000000000, 500000000000000000, 600000000000000000, 700000000000000000, 800000000000000000, 900000000000000000,
1000000000000000000, 2000000000000000000, 3000000000000000000, 4000000000000000000, 5000000000000000000, 6000000000000000000, 7000000000000000000, 8000000000000000000, 9000000000000000000,
10000000000000000000ull
};
bool Currency::init() {
if (!generateGenesisBlock()) {
logger(ERROR, BRIGHT_RED) << "Failed to generate genesis block";
return false;
}
try {
cachedGenesisBlock->getBlockHash();
} catch (std::exception& e) {
logger(ERROR, BRIGHT_RED) << "Failed to get genesis block hash: " << e.what();
return false;
}
if (isTestnet()) {
m_upgradeHeightV2 = m_testnetUpgradeHeightV2;
m_upgradeHeightV3 = m_testnetUpgradeHeightV3;
m_upgradeHeightV4 = m_testnetUpgradeHeightV4;
m_difficultyTarget = m_testnet_DifficultyTarget;
m_blocksFileName = "testnet_" + m_blocksFileName;
m_blockIndexesFileName = "testnet_" + m_blockIndexesFileName;
m_txPoolFileName = "testnet_" + m_txPoolFileName;
logger(INFO, RED) << "V2 Height : " << m_upgradeHeightV2;
logger(INFO, RED) << "V3 Height : " << m_upgradeHeightV3;
logger(INFO, RED) << "V4 Height : " << m_upgradeHeightV4;
logger(INFO, RED) << "Target : " << m_difficultyTarget << "s";
}
return true;
}
bool Currency::generateGenesisBlock() {
genesisBlockTemplate = boost::value_initialized<BlockTemplate>();
//account_public_address ac = boost::value_initialized<AccountPublicAddress>();
//std::vector<size_t> sz;
//constructMinerTx(0, 0, 0, 0, 0, ac, m_genesisBlock.baseTransaction); // zero fee in genesis
//BinaryArray txb = toBinaryArray(m_genesisBlock.baseTransaction);
//std::string hex_tx_represent = Common::toHex(txb);
// Hard code coinbase tx in genesis block, because through generating tx use random, but genesis should be always the same
// This is the BlackRoseDiamondV2 genesis transaction
std::string genesisCoinbaseTxHex = GENESIS_COINBASE_TX_HEX;
BinaryArray minerTxBlob;
bool r =
fromHex(genesisCoinbaseTxHex, minerTxBlob) &&
fromBinaryArray(genesisBlockTemplate.baseTransaction, minerTxBlob);
if (!r) {
logger(ERROR, BRIGHT_RED) << "failed to parse coinbase tx from hard coded blob";
return false;
}
genesisBlockTemplate.majorVersion = BLOCK_MAJOR_VERSION_1;
genesisBlockTemplate.minorVersion = BLOCK_MINOR_VERSION_0;
genesisBlockTemplate.timestamp = 0;
genesisBlockTemplate.nonce = 10000;
if (m_testnet) {
++genesisBlockTemplate.nonce;
}
//miner::find_nonce_for_given_block(bl, 1, 0);
cachedGenesisBlock.reset(new CachedBlock(genesisBlockTemplate));
return true;
}
size_t Currency::difficultyWindowByBlockVersion(uint8_t blockMajorVersion) const {
if (blockMajorVersion >= BLOCK_MAJOR_VERSION_3) {
return CryptoNote::parameters::DIFFICULTY_WINDOW_V3;
} else {
return CryptoNote::parameters::DIFFICULTY_WINDOW;
}
}
size_t Currency::difficultyLagByBlockVersion(uint8_t blockMajorVersion) const {
if (blockMajorVersion >= BLOCK_MAJOR_VERSION_2) {
return CryptoNote::parameters::DIFFICULTY_LAG_V2; // lag = 0 since V2
} else {
return CryptoNote::parameters::DIFFICULTY_LAG;
}
}
size_t Currency::difficultyCutByBlockVersion(uint8_t blockMajorVersion) const {
return CryptoNote::parameters::DIFFICULTY_CUT;
}
size_t Currency::difficultyBlocksCountByBlockVersion(uint8_t blockMajorVersion) const {
if (blockMajorVersion >= BLOCK_MAJOR_VERSION_2) {
return DIFFICULTY_BLOCKS_COUNT;
} else {
return difficultyWindowByBlockVersion(blockMajorVersion) + difficultyLagByBlockVersion(blockMajorVersion);
}
}
size_t Currency::blockGrantedFullRewardZoneByBlockVersion(uint8_t blockMajorVersion) const {
if (blockMajorVersion >= BLOCK_MAJOR_VERSION_2) {
return CryptoNote::parameters::CRYPTONOTE_BLOCK_GRANTED_FULL_REWARD_ZONE_CURRENT; // does not change since V2
} else {
return CryptoNote::parameters::CRYPTONOTE_BLOCK_GRANTED_FULL_REWARD_ZONE_V1;
}
}
uint32_t Currency::upgradeHeight(uint8_t majorVersion) const {
if (majorVersion == BLOCK_MAJOR_VERSION_4) {
return m_upgradeHeightV4;
} else if (majorVersion == BLOCK_MAJOR_VERSION_3) {
return m_upgradeHeightV3;
} else if (majorVersion == BLOCK_MAJOR_VERSION_2) {
return m_upgradeHeightV2;
} else {
return static_cast<uint32_t>(-1);
}
}
bool Currency::getBlockReward(uint8_t blockMajorVersion, size_t medianSize, size_t currentBlockSize, uint64_t alreadyGeneratedCoins,
uint64_t fee, uint64_t& reward, int64_t& emissionChange, const Difficulty diff) const {
size_t log_fix_precision = blockMajorVersion > BLOCK_MAJOR_VERSION_2? (parameters::BLOCK_REWARD_LOG_FIX_PRECISION_V3):(parameters::BLOCK_REWARD_LOG_FIX_PRECISION);
assert(diff != 0);
assert(static_cast<uint64_t>(diff) < (UINT64_C(1) << (sizeof(uint64_t) * 8 - log_fix_precision)));
uint64_t baseReward = log2_fix(diff << log_fix_precision, log_fix_precision) << 20;
// logger(Logging::INFO, Logging::BRIGHT_GREEN) << "baseReward: " << baseReward << ", con diff " << (int)diff << ", log fix: " << log_fix_precision << ", b.majorv: " << (int)blockMajorVersion;
// assert(alreadyGeneratedCoins <= m_moneySupply);
assert(m_emissionSpeedFactor > 0 && m_emissionSpeedFactor <= 8 * sizeof(uint64_t));
// Tail emission
/*
uint64_t baseReward = (m_moneySupply - alreadyGeneratedCoins) >> m_emissionSpeedFactor;
if (alreadyGeneratedCoins + CryptoNote::parameters::TAIL_EMISSION_REWARD >= m_moneySupply || baseReward < CryptoNote::parameters::TAIL_EMISSION_REWARD)
{
baseReward = CryptoNote::parameters::TAIL_EMISSION_REWARD;
}
*/
size_t blockGrantedFullRewardZone = blockGrantedFullRewardZoneByBlockVersion(blockMajorVersion);
medianSize = std::max(medianSize, blockGrantedFullRewardZone);
if (currentBlockSize > UINT64_C(2) * medianSize) {
logger(TRACE) << "Block cumulative size is too big: " << currentBlockSize << ", expected less than " << 2 * medianSize;
return false;
}
uint64_t penalizedBaseReward = getPenalizedAmount(baseReward, medianSize, currentBlockSize);
uint64_t penalizedFee = blockMajorVersion >= BLOCK_MAJOR_VERSION_4 ? getPenalizedAmount(fee, medianSize, currentBlockSize) : fee;
if (parameters::CRYPTONOTE_COIN_VERSION == 1) {
penalizedFee = getPenalizedAmount(fee, medianSize, currentBlockSize);
}
// logger(Logging::INFO, Logging::BRIGHT_GREEN) << "[getBlockReward] baseReward: " << baseReward << ", con diff " << (int)diff << ", log fix: " << log_fix_precision << ", b.majorv: " << (int)blockMajorVersion << ", penalizedBaseReward: " << penalizedBaseReward << ", penalizedFee: " << penalizedFee << ", fee:" << fee;
//std::cout << "BlockSize: " << currentBlockSize << ", medianSize:" << medianSize << ", baseReward: " << formatAmount(baseReward) << ", penalizedBaseReward: " << formatAmount(penalizedBaseReward) << ", fee: " << formatAmount(fee)
// << ", penalizedFee: " << formatAmount(penalizedFee) << std::endl;
emissionChange = penalizedBaseReward - (fee - penalizedFee);
reward = penalizedBaseReward + penalizedFee;
return true;
}
/*
bool Currency::getBlockReward(uint8_t blockMajorVersion, size_t medianSize, size_t currentBlockSize, uint64_t alreadyGeneratedCoins,
uint64_t fee, uint64_t& reward, int64_t& emissionChange) const {
assert(alreadyGeneratedCoins <= m_moneySupply);
assert(m_emissionSpeedFactor > 0 && m_emissionSpeedFactor <= 8 * sizeof(uint64_t));
uint64_t baseReward = (m_moneySupply - alreadyGeneratedCoins) >> m_emissionSpeedFactor;
size_t blockGrantedFullRewardZone = blockGrantedFullRewardZoneByBlockVersion(blockMajorVersion);
medianSize = std::max(medianSize, blockGrantedFullRewardZone);
if (currentBlockSize > UINT64_C(2) * medianSize) {
logger(TRACE) << "Block cumulative size is too big: " << currentBlockSize << ", expected less than " << 2 * medianSize;
return false;
}
uint64_t penalizedBaseReward = getPenalizedAmount(baseReward, medianSize, currentBlockSize);
uint64_t penalizedFee = blockMajorVersion >= BLOCK_MAJOR_VERSION_2 ? getPenalizedAmount(fee, medianSize, currentBlockSize) : fee;
emissionChange = penalizedBaseReward - (fee - penalizedFee);
reward = penalizedBaseReward + penalizedFee;
return true;
}
*/
size_t Currency::maxBlockCumulativeSize(uint64_t height) const {
assert(height <= std::numeric_limits<uint64_t>::max() / m_maxBlockSizeGrowthSpeedNumerator);
size_t maxSize = static_cast<size_t>(m_maxBlockSizeInitial +
(height * m_maxBlockSizeGrowthSpeedNumerator) / m_maxBlockSizeGrowthSpeedDenominator);
assert(maxSize >= m_maxBlockSizeInitial);
return maxSize;
}
bool Currency::constructMinerTx(uint8_t blockMajorVersion, uint32_t height, size_t medianSize, uint64_t alreadyGeneratedCoins, size_t currentBlockSize,
uint64_t fee, const AccountPublicAddress& minerAddress, Transaction& tx, const BinaryArray& extraNonce/* = BinaryArray()*/, size_t maxOuts/* = 1*/,
const Difficulty diff/* = 0*/) const {
tx.inputs.clear();
tx.outputs.clear();
tx.extra.clear();
KeyPair txkey = generateKeyPair();
addTransactionPublicKeyToExtra(tx.extra, txkey.publicKey);
if (!extraNonce.empty()) {
if (!addExtraNonceToTransactionExtra(tx.extra, extraNonce)) {
return false;
}
}
BaseInput in;
in.blockIndex = height;
uint64_t blockReward;
int64_t emissionChange;
if (!getBlockReward(blockMajorVersion, medianSize, currentBlockSize, alreadyGeneratedCoins, fee, blockReward, emissionChange, diff)) {
logger(INFO) << "Block is too big";
return false;
}
std::vector<uint64_t> outAmounts;
decompose_amount_into_digits(blockReward, m_defaultDustThreshold,
[&outAmounts](uint64_t a_chunk) { outAmounts.push_back(a_chunk); },
[&outAmounts](uint64_t a_dust) { outAmounts.push_back(a_dust); });
if (!(1 <= maxOuts)) { logger(ERROR, BRIGHT_RED) << "max_out must be non-zero"; return false; }
while (maxOuts < outAmounts.size()) {
outAmounts[outAmounts.size() - 2] += outAmounts.back();
outAmounts.resize(outAmounts.size() - 1);
}
uint64_t summaryAmounts = 0;
for (size_t no = 0; no < outAmounts.size(); no++) {
Crypto::KeyDerivation derivation = boost::value_initialized<Crypto::KeyDerivation>();
Crypto::PublicKey outEphemeralPubKey = boost::value_initialized<Crypto::PublicKey>();
bool r = Crypto::generate_key_derivation(minerAddress.viewPublicKey, txkey.secretKey, derivation);
if (!(r)) {
logger(ERROR, BRIGHT_RED)
<< "while creating outs: failed to generate_key_derivation("
<< minerAddress.viewPublicKey << ", " << txkey.secretKey << ")";
return false;
}
r = Crypto::derive_public_key(derivation, no, minerAddress.spendPublicKey, outEphemeralPubKey);
if (!(r)) {
logger(ERROR, BRIGHT_RED)
<< "while creating outs: failed to derive_public_key("
<< derivation << ", " << no << ", "
<< minerAddress.spendPublicKey << ")";
return false;
}
KeyOutput tk;
tk.key = outEphemeralPubKey;
TransactionOutput out;
summaryAmounts += out.amount = outAmounts[no];
out.target = tk;
tx.outputs.push_back(out);
}
if (!(summaryAmounts == blockReward)) {
logger(ERROR, BRIGHT_RED) << "Failed to construct miner tx, summaryAmounts = " << summaryAmounts << " not equal blockReward = " << blockReward;
return false;
}
tx.version = CURRENT_TRANSACTION_VERSION;
//lock
tx.unlockTime = height + m_minedMoneyUnlockWindow;
tx.inputs.push_back(in);
return true;
}
bool Currency::isFusionTransaction(const std::vector<uint64_t>& inputsAmounts, const std::vector<uint64_t>& outputsAmounts, size_t size) const {
if (size > fusionTxMaxSize()) {
return false;
}
if (inputsAmounts.size() < fusionTxMinInputCount()) {
return false;
}
if (inputsAmounts.size() < outputsAmounts.size() * fusionTxMinInOutCountRatio()) {
return false;
}
uint64_t inputAmount = 0;
for (auto amount: inputsAmounts) {
if (amount < defaultDustThreshold()) {
return false;
}
inputAmount += amount;
}
std::vector<uint64_t> expectedOutputsAmounts;
expectedOutputsAmounts.reserve(outputsAmounts.size());
decomposeAmount(inputAmount, defaultDustThreshold(), expectedOutputsAmounts);
std::sort(expectedOutputsAmounts.begin(), expectedOutputsAmounts.end());
return expectedOutputsAmounts == outputsAmounts;
}
bool Currency::isFusionTransaction(const Transaction& transaction, size_t size) const {
assert(getObjectBinarySize(transaction) == size);
std::vector<uint64_t> outputsAmounts;
outputsAmounts.reserve(transaction.outputs.size());
for (const TransactionOutput& output : transaction.outputs) {
outputsAmounts.push_back(output.amount);
}
return isFusionTransaction(getInputsAmounts(transaction), outputsAmounts, size);
}
bool Currency::isFusionTransaction(const Transaction& transaction) const {
return isFusionTransaction(transaction, getObjectBinarySize(transaction));
}
bool Currency::isAmountApplicableInFusionTransactionInput(uint64_t amount, uint64_t threshold) const {
uint8_t ignore;
return isAmountApplicableInFusionTransactionInput(amount, threshold, ignore);
}
bool Currency::isAmountApplicableInFusionTransactionInput(uint64_t amount, uint64_t threshold, uint8_t& amountPowerOfTen) const {
if (amount >= threshold) {
return false;
}
if (amount < defaultDustThreshold()) {
return false;
}
auto it = std::lower_bound(PRETTY_AMOUNTS.begin(), PRETTY_AMOUNTS.end(), amount);
if (it == PRETTY_AMOUNTS.end() || amount != *it) {
return false;
}
amountPowerOfTen = static_cast<uint8_t>(std::distance(PRETTY_AMOUNTS.begin(), it) / 9);
return true;
}
std::string Currency::accountAddressAsString(const AccountBase& account) const {
return getAccountAddressAsStr(m_publicAddressBase58Prefix, account.getAccountKeys().address);
}
std::string Currency::accountAddressAsString(const AccountPublicAddress& accountPublicAddress) const {
return getAccountAddressAsStr(m_publicAddressBase58Prefix, accountPublicAddress);
}
bool Currency::parseAccountAddressString(const std::string& str, AccountPublicAddress& addr) const {
uint64_t prefix;
if (!CryptoNote::parseAccountAddressString(prefix, addr, str)) {
return false;
}
if (prefix != m_publicAddressBase58Prefix) {
logger(DEBUGGING) << "Wrong address prefix: " << prefix << ", expected " << m_publicAddressBase58Prefix;
return false;
}
return true;
}
std::string Currency::formatAmount(uint64_t amount) const {
std::string s = std::to_string(amount);
if (s.size() < m_numberOfDecimalPlaces + 1) {
s.insert(0, m_numberOfDecimalPlaces + 1 - s.size(), '0');
}
s.insert(s.size() - m_numberOfDecimalPlaces, ".");
return s;
}
std::string Currency::formatAmount(int64_t amount) const {
std::string s = formatAmount(static_cast<uint64_t>(std::abs(amount)));
if (amount < 0) {
s.insert(0, "-");
}
return s;
}
bool Currency::parseAmount(const std::string& str, uint64_t& amount) const {
std::string strAmount = str;
boost::algorithm::trim(strAmount);
size_t pointIndex = strAmount.find_first_of('.');
size_t fractionSize;
if (std::string::npos != pointIndex) {
fractionSize = strAmount.size() - pointIndex - 1;
while (m_numberOfDecimalPlaces < fractionSize && '0' == strAmount.back()) {
strAmount.erase(strAmount.size() - 1, 1);
--fractionSize;
}
if (m_numberOfDecimalPlaces < fractionSize) {
return false;
}
strAmount.erase(pointIndex, 1);
} else {
fractionSize = 0;
}
if (strAmount.empty()) {
return false;
}
if (!std::all_of(strAmount.begin(), strAmount.end(), ::isdigit)) {
return false;
}
if (fractionSize < m_numberOfDecimalPlaces) {
strAmount.append(m_numberOfDecimalPlaces - fractionSize, '0');
}
return Common::fromString(strAmount, amount);
}
Difficulty Currency::nextDifficulty(
uint8_t version,
uint32_t blockIndex,
std::vector<uint64_t> timestamps,
std::vector<Difficulty> cumulativeDifficulties
) const {
Difficulty nextDiff;
if (version >= BLOCK_MAJOR_VERSION_3) {
nextDiff = nextDifficultyLWMA4(version, timestamps, cumulativeDifficulties);
} else {
nextDiff = nextDifficultyOriginal(timestamps,cumulativeDifficulties);
}
if(nextDiff < 1) {
nextDiff = 1;
}
return nextDiff;
}
/**
* Original cryptonote difficulty algo
*/
Difficulty Currency::nextDifficultyOriginal(
std::vector<uint64_t> timestamps,
std::vector<Difficulty> cumulativeDifficulties
) const {
uint64_t target_seconds = static_cast<int64_t>(m_difficultyTarget); //CryptoNote::parameters::DIFFICULTY_TARGET;
size_t m_difficultyWindow_2 = CryptoNote::parameters::DIFFICULTY_WINDOW;
assert(m_difficultyWindow_2 >= 2);
if (timestamps.size() > m_difficultyWindow_2) {
timestamps.resize(m_difficultyWindow_2);
cumulativeDifficulties.resize(m_difficultyWindow_2);
}
size_t length = timestamps.size();
assert(length == cumulativeDifficulties.size());
assert(length <= m_difficultyWindow_2);
if (length <= 1) {
return 1;
}
static_assert(CryptoNote::parameters::DIFFICULTY_WINDOW >= 2, "Window is too small");
assert(length <= CryptoNote::parameters::DIFFICULTY_WINDOW);
sort(timestamps.begin(), timestamps.end());
size_t cut_begin, cut_end;
static_assert(2 * CryptoNote::parameters::DIFFICULTY_CUT <= CryptoNote::parameters::DIFFICULTY_WINDOW - 2, "Cut length is too large");
if (length <= CryptoNote::parameters::DIFFICULTY_WINDOW - 2 * CryptoNote::parameters::DIFFICULTY_CUT) {
cut_begin = 0;
cut_end = length;
} else {
cut_begin = (length - (CryptoNote::parameters::DIFFICULTY_WINDOW - 2 * CryptoNote::parameters::DIFFICULTY_CUT) + 1) / 2;
cut_end = cut_begin + (CryptoNote::parameters::DIFFICULTY_WINDOW - 2 * CryptoNote::parameters::DIFFICULTY_CUT);
}
assert(/*cut_begin >= 0 &&*/ cut_begin + 2 <= cut_end && cut_end <= length);
uint64_t time_span = timestamps[cut_end - 1] - timestamps[cut_begin];
if (time_span == 0) {
time_span = 1;
}
Difficulty total_work = cumulativeDifficulties[cut_end - 1] - cumulativeDifficulties[cut_begin];
assert(total_work > 0);
uint64_t low, high;
mul(total_work, target_seconds, low, high);
if (high != 0 || low + time_span - 1 < low) {
return 0;
}
return (low + time_span - 1) / time_span;
}
// LWMA difficulty algorithm Hard fork v3
// Copyright (c) 2017-2018 Zawy
// MIT license http://www.opensource.org/licenses/mit-license.php.
// Tom Harding, Karbowanec, Masari, Bitcoin Gold, and Bitcoin Candy have contributed.
// https://github.com/zawy12/difficulty-algorithms/issues/3
// Zawy's LWMA difficulty algorithm implementation V4 (60 solvetimes limits -7T/7T)
// (60 solvetimes - limits -7T/7T - adjust = 0.9909)
Difficulty Currency::nextDifficultyLWMA4(uint8_t &version,
std::vector<uint64_t> ×tamps,
std::vector<Difficulty> &cumulativeDifficulties
) const {
const size_t c_difficultyWindow = difficultyWindowByBlockVersion(version); // 61
const int64_t c_difficultyTarget = static_cast<int64_t>(m_difficultyTarget);
if (timestamps.size() > c_difficultyWindow) {
timestamps.resize(c_difficultyWindow);
cumulativeDifficulties.resize(c_difficultyWindow);
}
size_t length = timestamps.size();
assert(length == cumulativeDifficulties.size());
assert(length <= c_difficultyWindow);
if (length <= 1) {
return 1;
}
int64_t solveTime(0),LWMA(0),minWST(0);
uint64_t aimedTarget(0),low,high;
Difficulty totalWork(0),nextDiff(0);
const double_t adjust = 0.9909;
for (int64_t i = 1; i < length; i++) { // lenght = 61
solveTime = static_cast<int64_t>(timestamps[i]) - static_cast<int64_t>(timestamps[i-1]);
solveTime = std::max<int64_t>(- blockFutureTimeLimit(), solveTime);
LWMA += solveTime * i;
}
// Keep LWMA sane in case something unforeseen occurs.if ( LWMA < T*N*(N+1)/8 ) { LWMA = T*N*(N+1)/8; N=lenght-1}
minWST = c_difficultyTarget * length*(length-1)/8;
if(LWMA < minWST){
LWMA = minWST;
}
totalWork = cumulativeDifficulties.back() - cumulativeDifficulties.front();
aimedTarget = adjust * (length / 2.0) * c_difficultyTarget ;
assert(totalWork > 0);
low = mul128(totalWork, aimedTarget, &high);
if (high != 0) {
return 0;
}
nextDiff = low/LWMA;
return nextDiff;
}
bool Currency::checkProofOfWorkV1(Crypto::cn_context& context, const CachedBlock& block, Difficulty currentDifficulty) const {
if (BLOCK_MAJOR_VERSION_1 != block.getBlock().majorVersion) {
return false;
}
return check_hash(block.getBlockLongHash(context), currentDifficulty);
}
bool Currency::checkProofOfWorkV2(Crypto::cn_context& context, const CachedBlock& cachedBlock, Difficulty currentDifficulty) const {
const auto& block = cachedBlock.getBlock();
if (block.majorVersion < BLOCK_MAJOR_VERSION_2) {
return false;
}
if (!check_hash(cachedBlock.getBlockLongHash(context), currentDifficulty)) {
return false;
}
TransactionExtraMergeMiningTag mmTag;
if (!getMergeMiningTagFromExtra(block.parentBlock.baseTransaction.extra, mmTag)) {
logger(ERROR) << "merge mining tag wasn't found in extra of the parent block miner transaction";
return false;
}
if (8 * sizeof(cachedGenesisBlock->getBlockHash()) < block.parentBlock.blockchainBranch.size()) {
return false;
}
Crypto::Hash auxBlocksMerkleRoot;
Crypto::tree_hash_from_branch(block.parentBlock.blockchainBranch.data(), block.parentBlock.blockchainBranch.size(),
cachedBlock.getAuxiliaryBlockHeaderHash(), &cachedGenesisBlock->getBlockHash(), auxBlocksMerkleRoot);
if (auxBlocksMerkleRoot != mmTag.merkleRoot) {
logger(ERROR, BRIGHT_YELLOW) << "Aux block hash wasn't found in merkle tree";
return false;
}
return true;
}
bool Currency::checkProofOfWork(Crypto::cn_context& context, const CachedBlock& block, Difficulty currentDiffic) const {
switch (block.getBlock().majorVersion) {
case BLOCK_MAJOR_VERSION_1:
return checkProofOfWorkV1(context, block, currentDiffic);
case BLOCK_MAJOR_VERSION_2:
case BLOCK_MAJOR_VERSION_3:
case BLOCK_MAJOR_VERSION_4:
return checkProofOfWorkV2(context, block, currentDiffic);
}
logger(ERROR, BRIGHT_RED) << "Unknown block major version: " << block.getBlock().majorVersion << "." << block.getBlock().minorVersion;
return false;
}
size_t Currency::getApproximateMaximumInputCount(size_t transactionSize, size_t outputCount, size_t mixinCount) const {
const size_t KEY_IMAGE_SIZE = sizeof(Crypto::KeyImage);
const size_t OUTPUT_KEY_SIZE = sizeof(decltype(KeyOutput::key));
const size_t AMOUNT_SIZE = sizeof(uint64_t) + 2; //varint
const size_t GLOBAL_INDEXES_VECTOR_SIZE_SIZE = sizeof(uint8_t);//varint
const size_t GLOBAL_INDEXES_INITIAL_VALUE_SIZE = sizeof(uint32_t);//varint
const size_t GLOBAL_INDEXES_DIFFERENCE_SIZE = sizeof(uint32_t);//varint
const size_t SIGNATURE_SIZE = sizeof(Crypto::Signature);
const size_t EXTRA_TAG_SIZE = sizeof(uint8_t);
const size_t INPUT_TAG_SIZE = sizeof(uint8_t);
const size_t OUTPUT_TAG_SIZE = sizeof(uint8_t);
const size_t PUBLIC_KEY_SIZE = sizeof(Crypto::PublicKey);
const size_t TRANSACTION_VERSION_SIZE = sizeof(uint8_t);
const size_t TRANSACTION_UNLOCK_TIME_SIZE = sizeof(uint64_t);
const size_t outputsSize = outputCount * (OUTPUT_TAG_SIZE + OUTPUT_KEY_SIZE + AMOUNT_SIZE);
const size_t headerSize = TRANSACTION_VERSION_SIZE + TRANSACTION_UNLOCK_TIME_SIZE + EXTRA_TAG_SIZE + PUBLIC_KEY_SIZE;
const size_t inputSize = INPUT_TAG_SIZE + AMOUNT_SIZE + KEY_IMAGE_SIZE + SIGNATURE_SIZE + GLOBAL_INDEXES_VECTOR_SIZE_SIZE + GLOBAL_INDEXES_INITIAL_VALUE_SIZE +
mixinCount * (GLOBAL_INDEXES_DIFFERENCE_SIZE + SIGNATURE_SIZE);
return (transactionSize - headerSize - outputsSize) / inputSize;
}
Currency::Currency(Currency&& currency) :
m_maxBlockHeight(currency.m_maxBlockHeight),
m_maxBlockBlobSize(currency.m_maxBlockBlobSize),
m_maxTxSize(currency.m_maxTxSize),
m_publicAddressBase58Prefix(currency.m_publicAddressBase58Prefix),
m_minedMoneyUnlockWindow(currency.m_minedMoneyUnlockWindow),
m_timestampCheckWindow(currency.m_timestampCheckWindow),
m_timestampCheckWindowV3(currency.m_timestampCheckWindowV3),
m_blockFutureTimeLimit(currency.m_blockFutureTimeLimit),
m_moneySupply(currency.m_moneySupply),
m_emissionSpeedFactor(currency.m_emissionSpeedFactor),
m_rewardBlocksWindow(currency.m_rewardBlocksWindow),
m_blockGrantedFullRewardZone(currency.m_blockGrantedFullRewardZone),
m_minerTxBlobReservedSize(currency.m_minerTxBlobReservedSize),
m_minMixin(currency.m_minMixin),
m_maxMixin(currency.m_maxMixin),
m_mandatoryMixinBlockVersion(currency.m_mandatoryMixinBlockVersion),
m_numberOfDecimalPlaces(currency.m_numberOfDecimalPlaces),
m_coin(currency.m_coin),
m_mininumFee(currency.m_mininumFee),
m_defaultDustThreshold(currency.m_defaultDustThreshold),
m_difficultyTarget(currency.m_difficultyTarget),
m_testnet_DifficultyTarget(currency.m_testnet_DifficultyTarget),
m_difficultyWindow(currency.m_difficultyWindow),
m_difficultyLag(currency.m_difficultyLag),
m_difficultyCut(currency.m_difficultyCut),
m_maxBlockSizeInitial(currency.m_maxBlockSizeInitial),
m_maxBlockSizeGrowthSpeedNumerator(currency.m_maxBlockSizeGrowthSpeedNumerator),
m_maxBlockSizeGrowthSpeedDenominator(currency.m_maxBlockSizeGrowthSpeedDenominator),
m_lockedTxAllowedDeltaSeconds(currency.m_lockedTxAllowedDeltaSeconds),
m_lockedTxAllowedDeltaBlocks(currency.m_lockedTxAllowedDeltaBlocks),
m_mempoolTxLiveTime(currency.m_mempoolTxLiveTime),
m_numberOfPeriodsToForgetTxDeletedFromPool(currency.m_numberOfPeriodsToForgetTxDeletedFromPool),
m_fusionTxMaxSize(currency.m_fusionTxMaxSize),
m_fusionTxMinInputCount(currency.m_fusionTxMinInputCount),
m_fusionTxMinInOutCountRatio(currency.m_fusionTxMinInOutCountRatio),
m_upgradeHeightV2(currency.m_upgradeHeightV2),
m_upgradeHeightV3(currency.m_upgradeHeightV3),
m_upgradeHeightV4(currency.m_upgradeHeightV4),
m_testnetUpgradeHeightV2(currency.m_testnetUpgradeHeightV2),
m_testnetUpgradeHeightV3(currency.m_testnetUpgradeHeightV3),
m_testnetUpgradeHeightV4(currency.m_testnetUpgradeHeightV4),
m_upgradeVotingThreshold(currency.m_upgradeVotingThreshold),
m_upgradeVotingWindow(currency.m_upgradeVotingWindow),
m_upgradeWindow(currency.m_upgradeWindow),
m_blocksFileName(currency.m_blocksFileName),
m_blockIndexesFileName(currency.m_blockIndexesFileName),
m_txPoolFileName(currency.m_txPoolFileName),
m_testnet(currency.m_testnet),
genesisBlockTemplate(std::move(currency.genesisBlockTemplate)),
cachedGenesisBlock(new CachedBlock(genesisBlockTemplate)),
logger(currency.logger) {
}
CurrencyBuilder::CurrencyBuilder(Logging::ILogger& log) : m_currency(log) {
maxBlockNumber(parameters::CRYPTONOTE_MAX_BLOCK_NUMBER);
maxBlockBlobSize(parameters::CRYPTONOTE_MAX_BLOCK_BLOB_SIZE);
maxTxSize(parameters::CRYPTONOTE_MAX_TX_SIZE);
publicAddressBase58Prefix(parameters::CRYPTONOTE_PUBLIC_ADDRESS_BASE58_PREFIX);
minedMoneyUnlockWindow(parameters::CRYPTONOTE_MINED_MONEY_UNLOCK_WINDOW);
timestampCheckWindow(parameters::BLOCKCHAIN_TIMESTAMP_CHECK_WINDOW);
timestampCheckWindowV3(parameters::BLOCKCHAIN_TIMESTAMP_CHECK_WINDOW_V3);
blockFutureTimeLimit(parameters::CRYPTONOTE_BLOCK_FUTURE_TIME_LIMIT);
moneySupply(parameters::MONEY_SUPPLY);
emissionSpeedFactor(parameters::EMISSION_SPEED_FACTOR);
rewardBlocksWindow(parameters::CRYPTONOTE_REWARD_BLOCKS_WINDOW);
minMixin(parameters::MIN_MIXIN);
maxMixin(parameters::MAX_MIXIN);
mandatoryMixinBlockVersion(parameters::MANDATORY_MIXIN_BLOCK_VERSION);
blockGrantedFullRewardZone(parameters::CRYPTONOTE_BLOCK_GRANTED_FULL_REWARD_ZONE);
minerTxBlobReservedSize(parameters::CRYPTONOTE_COINBASE_BLOB_RESERVED_SIZE);
numberOfDecimalPlaces(parameters::CRYPTONOTE_DISPLAY_DECIMAL_POINT);
mininumFee(parameters::MINIMUM_FEE);
defaultDustThreshold(parameters::DEFAULT_DUST_THRESHOLD);
difficultyTarget(parameters::DIFFICULTY_TARGET);
testnetDifficultyTarget(parameters::TESTNET_DIFFICULTY_TARGET);
difficultyWindow(parameters::DIFFICULTY_WINDOW);
difficultyLag(parameters::DIFFICULTY_LAG);
difficultyCut(parameters::DIFFICULTY_CUT);
maxBlockSizeInitial(parameters::MAX_BLOCK_SIZE_INITIAL);
maxBlockSizeGrowthSpeedNumerator(parameters::MAX_BLOCK_SIZE_GROWTH_SPEED_NUMERATOR);
maxBlockSizeGrowthSpeedDenominator(parameters::MAX_BLOCK_SIZE_GROWTH_SPEED_DENOMINATOR);
lockedTxAllowedDeltaSeconds(parameters::CRYPTONOTE_LOCKED_TX_ALLOWED_DELTA_SECONDS);
lockedTxAllowedDeltaBlocks(parameters::CRYPTONOTE_LOCKED_TX_ALLOWED_DELTA_BLOCKS);
mempoolTxLiveTime(parameters::CRYPTONOTE_MEMPOOL_TX_LIVETIME);
mempoolTxFromAltBlockLiveTime(parameters::CRYPTONOTE_MEMPOOL_TX_FROM_ALT_BLOCK_LIVETIME);
numberOfPeriodsToForgetTxDeletedFromPool(parameters::CRYPTONOTE_NUMBER_OF_PERIODS_TO_FORGET_TX_DELETED_FROM_POOL);
fusionTxMaxSize(parameters::FUSION_TX_MAX_SIZE);
fusionTxMinInputCount(parameters::FUSION_TX_MIN_INPUT_COUNT);
fusionTxMinInOutCountRatio(parameters::FUSION_TX_MIN_IN_OUT_COUNT_RATIO);
upgradeHeightV2(parameters::UPGRADE_HEIGHT_V2);
upgradeHeightV3(parameters::UPGRADE_HEIGHT_V3);
upgradeHeightV4(parameters::UPGRADE_HEIGHT_V4);
testnetUpgradeHeightV2(parameters::TESTNET_UPGRADE_HEIGHT_V2);
testnetUpgradeHeightV3(parameters::TESTNET_UPGRADE_HEIGHT_V3);
testnetUpgradeHeightV4(parameters::TESTNET_UPGRADE_HEIGHT_V4);
upgradeVotingThreshold(parameters::UPGRADE_VOTING_THRESHOLD);
upgradeVotingWindow(parameters::UPGRADE_VOTING_WINDOW);
upgradeWindow(parameters::UPGRADE_WINDOW);
blocksFileName(parameters::CRYPTONOTE_BLOCKS_FILENAME);
blockIndexesFileName(parameters::CRYPTONOTE_BLOCKINDEXES_FILENAME);
txPoolFileName(parameters::CRYPTONOTE_POOLDATA_FILENAME);
testnet(false);
}
CurrencyBuilder& CurrencyBuilder::emissionSpeedFactor(unsigned int val) {
if (val <= 0 || val > 8 * sizeof(uint64_t)) {
throw std::invalid_argument("val at emissionSpeedFactor()");
}
m_currency.m_emissionSpeedFactor = val;
return *this;
}
CurrencyBuilder& CurrencyBuilder::numberOfDecimalPlaces(size_t val) {
m_currency.m_numberOfDecimalPlaces = val;
m_currency.m_coin = 1;
for (size_t i = 0; i < m_currency.m_numberOfDecimalPlaces; ++i) {
m_currency.m_coin *= 10;
}
return *this;
}
CurrencyBuilder& CurrencyBuilder::difficultyWindow(size_t val) {
if (val < 2) {
throw std::invalid_argument("val at difficultyWindow()");
}
m_currency.m_difficultyWindow = val;
return *this;
}
CurrencyBuilder& CurrencyBuilder::upgradeVotingThreshold(unsigned int val) {
if (val <= 0 || val > 100) {
throw std::invalid_argument("val at upgradeVotingThreshold()");
}
m_currency.m_upgradeVotingThreshold = val;
return *this;
}
CurrencyBuilder& CurrencyBuilder::upgradeWindow(uint32_t val) {
if (val <= 0) {
throw std::invalid_argument("val at upgradeWindow()");
}
m_currency.m_upgradeWindow = val;
return *this;
}
}
| 41.356906 | 322 | 0.723122 | [
"vector"
] |
87e5007d3dd3ca9c0acb41929d610a7f26f4ce88 | 2,254 | hpp | C++ | pomdog/graphics/gl4/render_target2d_gl4.hpp | mogemimi/pomdog | 6dc6244d018f70d42e61c6118535cf94a9ee0618 | [
"MIT"
] | 163 | 2015-03-16T08:42:32.000Z | 2022-01-11T21:40:22.000Z | pomdog/graphics/gl4/render_target2d_gl4.hpp | mogemimi/pomdog | 6dc6244d018f70d42e61c6118535cf94a9ee0618 | [
"MIT"
] | 17 | 2015-04-12T20:57:50.000Z | 2020-10-10T10:51:45.000Z | pomdog/graphics/gl4/render_target2d_gl4.hpp | mogemimi/pomdog | 6dc6244d018f70d42e61c6118535cf94a9ee0618 | [
"MIT"
] | 21 | 2015-04-12T20:45:11.000Z | 2022-01-14T20:50:16.000Z | // Copyright mogemimi. Distributed under the MIT license.
#pragma once
#include "pomdog/basic/conditional_compilation.hpp"
#include "pomdog/graphics/forward_declarations.hpp"
#include "pomdog/graphics/gl4/opengl_prerequisites.hpp"
#include "pomdog/graphics/gl4/texture2d_gl4.hpp"
#include "pomdog/graphics/render_target2d.hpp"
#include "pomdog/graphics/surface_format.hpp"
#include "pomdog/utility/errors.hpp"
#include "pomdog/utility/tagged.hpp"
POMDOG_SUPPRESS_WARNINGS_GENERATED_BY_STD_HEADERS_BEGIN
#include <optional>
POMDOG_SUPPRESS_WARNINGS_GENERATED_BY_STD_HEADERS_END
namespace pomdog::detail::gl4 {
using RenderBuffer2DGL4 = Tagged<GLuint, RenderTarget2D>;
class RenderTarget2DGL4 final : public RenderTarget2D {
public:
~RenderTarget2DGL4() override;
[[nodiscard]] std::unique_ptr<Error>
Initialize(
std::int32_t pixelWidth,
std::int32_t pixelHeight,
std::int32_t levelCount,
SurfaceFormat format,
std::int32_t multiSampleCount) noexcept;
/// Gets the width of the texture data, in pixels.
std::int32_t GetWidth() const noexcept override;
/// Gets the height of the texture data, in pixels.
std::int32_t GetHeight() const noexcept override;
/// Gets the mipmap level.
std::int32_t GetLevelCount() const noexcept override;
/// Gets the format of the pixel data in the render target.
SurfaceFormat GetFormat() const noexcept override;
/// Gets the size of the texture resource.
Rectangle GetBounds() const noexcept override;
/// Copies the pixel data from texture to memory.
void GetData(void* result, std::size_t offsetInBytes, std::size_t sizeInBytes) const override;
void BindToFramebuffer(GLuint frameBuffer, GLenum attachmentPoint);
void UnbindFromFramebuffer(GLuint frameBuffer, GLenum attachmentPoint);
/// Gets the handle of the native texture resource.
Texture2DObjectGL4 GetTextureHandle() const noexcept;
private:
Texture2DGL4 texture;
std::int32_t pixelWidth = 0;
std::int32_t pixelHeight = 0;
std::int32_t levelCount = 0;
SurfaceFormat format = SurfaceFormat::A8_UNorm;
bool generateMipmap = false;
bool multiSampleEnabled = false;
};
} // namespace pomdog::detail::gl4
| 32.2 | 98 | 0.748004 | [
"render"
] |
87ead99702027bc7f38ddc92a8ec6ddbc882cf00 | 436 | cpp | C++ | UVa/10055 - Hashmat the Brave Warrior/file.cpp | s1nisteR/CPSolutions | b840f1f1c7283b4bb581d1d5d54c27a828f5601d | [
"MIT"
] | 1 | 2022-02-05T10:54:11.000Z | 2022-02-05T10:54:11.000Z | UVa/10055 - Hashmat the Brave Warrior/file.cpp | s1nisteR/CPSolutions | b840f1f1c7283b4bb581d1d5d54c27a828f5601d | [
"MIT"
] | null | null | null | UVa/10055 - Hashmat the Brave Warrior/file.cpp | s1nisteR/CPSolutions | b840f1f1c7283b4bb581d1d5d54c27a828f5601d | [
"MIT"
] | null | null | null | #include <iostream>
#include <string>
#include <algorithm>
#include <array>
#include <vector>
#include <utility>
#include <cmath>
#include <bitset>
using namespace std;
int main()
{
//Fast IO
ios_base::sync_with_stdio(false);
cin.tie(NULL);
#ifndef ONLINE_JUDGE
freopen("inputf.in","r",stdin);
freopen("outputf.in","w",stdout);
#endif
long long a, b;
while(cin >> a >> b)
{
cout << abs(a - b) << "\n";
}
return 0;
}
| 12.823529 | 34 | 0.642202 | [
"vector"
] |
87ee4dd5cc02a7bf036cda40394764dbb3414a31 | 5,092 | hpp | C++ | stapl_release/stapl/runtime/this_context.hpp | parasol-ppl/PPL_utils | 92728bb89692fda1705a0dee436592d97922a6cb | [
"BSD-3-Clause"
] | null | null | null | stapl_release/stapl/runtime/this_context.hpp | parasol-ppl/PPL_utils | 92728bb89692fda1705a0dee436592d97922a6cb | [
"BSD-3-Clause"
] | null | null | null | stapl_release/stapl/runtime/this_context.hpp | parasol-ppl/PPL_utils | 92728bb89692fda1705a0dee436592d97922a6cb | [
"BSD-3-Clause"
] | null | null | null | /*
// Copyright (c) 2000-2009, Texas Engineering Experiment Station (TEES), a
// component of the Texas A&M University System.
// All rights reserved.
// The information and source code contained herein is the exclusive
// property of TEES and may not be disclosed, examined or reproduced
// in whole or in part without explicit written authorization from TEES.
*/
#ifndef STAPL_RUNTIME_THIS_CONTEXT_HPP
#define STAPL_RUNTIME_THIS_CONTEXT_HPP
#include "context_id.hpp"
#include <boost/optional.hpp>
namespace stapl {
namespace runtime {
class context;
class location_md;
//////////////////////////////////////////////////////////////////////
/// @brief STAPL Runtime System RMI execution context management.
//////////////////////////////////////////////////////////////////////
namespace this_context {
//////////////////////////////////////////////////////////////////////
/// @brief Pushes a base @ref context on the stack.
///
/// @ingroup runtimeMetadata
//////////////////////////////////////////////////////////////////////
void push_base(context&);
//////////////////////////////////////////////////////////////////////
/// @brief Pops the base @ref context from the stack.
///
/// @ingroup runtimeMetadata
//////////////////////////////////////////////////////////////////////
void pop_base(context&);
//////////////////////////////////////////////////////////////////////
/// @brief Pushes a placeholder for a new @ref context on the stack.
///
/// @see gang
/// @ingroup runtimeMetadata
//////////////////////////////////////////////////////////////////////
void push_placeholder(boost::optional<context>&);
//////////////////////////////////////////////////////////////////////
/// @brief Pops the placeholder from the stack.
///
/// @ingroup runtimeMetadata
//////////////////////////////////////////////////////////////////////
void pop_placeholder(void);
//////////////////////////////////////////////////////////////////////
/// @brief Switches to the base @ref context of @p l.
///
/// The location metadata @p l will be used to either create a new base context
/// or to switch to an existing one.
///
/// @see gang
/// @ingroup runtimeMetadata
//////////////////////////////////////////////////////////////////////
void switch_to(location_md&, boost::optional<context>&);
//////////////////////////////////////////////////////////////////////
/// @brief Unswitches from the @ref context on the stack.
///
/// @see gang
/// @ingroup runtimeMetadata
//////////////////////////////////////////////////////////////////////
void unswitch(void);
//////////////////////////////////////////////////////////////////////
/// @brief Returns the current @ref context from the stack.
///
/// If the @ref context creation was deferred (e.g. one location gangs defer
/// the creation of all metadata) then this function will create all the
/// required metadata and return the associated @ref context object.
///
/// @ingroup runtimeMetadata
//////////////////////////////////////////////////////////////////////
context& get(void);
//////////////////////////////////////////////////////////////////////
/// @brief Returns the @ref base context of the context at the top of
/// the stack.
///
/// @ingroup runtimeMetadata
//////////////////////////////////////////////////////////////////////
context& base_of_top(void);
//////////////////////////////////////////////////////////////////////
/// @brief Returns a pointer to the current @ref context from the stack.
///
/// If the @ref context creation was deferred, then it returns @c nullptr.
///
/// @ingroup runtimeMetadata
//////////////////////////////////////////////////////////////////////
context* try_get(void) noexcept;
//////////////////////////////////////////////////////////////////////
/// @brief Returns the current context id from the stack.
///
/// If the @ref context creation was deferred (e.g. one location gangs defer
/// the creation of all metadata) then this function will create all the
/// required metadata and return the associated @ref context object.
///
/// @see this_context::get()
/// @ingroup runtimeMetadata
//////////////////////////////////////////////////////////////////////
context_id const& get_id(void);
//////////////////////////////////////////////////////////////////////
/// @brief Returns a pointer to the location metadata of the given gang id if
/// it is in the stack, otherwise @c nullptr.
///
/// @ingroup runtimeMetadata
//////////////////////////////////////////////////////////////////////
location_md* try_get_location_md(const gang_id) noexcept;
//////////////////////////////////////////////////////////////////////
/// @brief Returns @c true if the execution can be restored for location @p l.
///
/// @warning This is an expensive operation that restores an SPMD section, used
/// in @ref restore().
///
/// @ingroup runtimeMetadata
//////////////////////////////////////////////////////////////////////
bool can_restore(location_md& l);
} // namespace this_context
} // namespace runtime
} // namespace stapl
#endif
| 32.851613 | 79 | 0.459741 | [
"object"
] |
87ef65677b75706d21cb2ab08e274458b959f964 | 13,221 | cpp | C++ | examples/interpreter/physl.cpp | NK-Nikunj/phylanx | 6898992513a122c49d26947d877f329365486665 | [
"BSL-1.0"
] | null | null | null | examples/interpreter/physl.cpp | NK-Nikunj/phylanx | 6898992513a122c49d26947d877f329365486665 | [
"BSL-1.0"
] | null | null | null | examples/interpreter/physl.cpp | NK-Nikunj/phylanx | 6898992513a122c49d26947d877f329365486665 | [
"BSL-1.0"
] | null | null | null | // Copyright (c) 2018 Parsa Amini
// Copyright (c) 2018 Hartmut Kaiser
//
// 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)
#include <phylanx/phylanx.hpp>
#include <phylanx/execution_tree/compiler/primitive_name.hpp>
#include <hpx/hpx_main.hpp>
#include <cstddef>
#include <fstream>
#include <iostream>
#include <sstream>
#include <string>
#include <utility>
#include <vector>
#include <boost/program_options.hpp>
#include <boost/filesystem.hpp>
namespace fs = boost::filesystem;
namespace po = boost::program_options;
std::string read_user_code(std::string const& path)
{
std::ifstream code_stream(path);
if (!code_stream.good())
{
HPX_THROW_EXCEPTION(hpx::filesystem_error,
"read_user_code",
"Failed to open the specified file: " + path);
}
// Read the file
std::ostringstream str_stream;
if (!(str_stream << code_stream.rdbuf()))
{
HPX_THROW_EXCEPTION(hpx::filesystem_error,
"read_user_code",
"Failed to read code from the specified file: " + path);
}
return str_stream.str();
}
void dump_ast(std::vector<phylanx::ast::expression> const& ast, std::string path)
{
std::ofstream ast_stream(path, std::ios::binary);
if (!ast_stream.good())
{
HPX_THROW_EXCEPTION(hpx::filesystem_error,
"dump_ast",
"Failed to open the specified file: " + path);
}
// Serialize the AST into a byte array
std::vector<char> bytes = phylanx::util::serialize(ast);
// char is 1 byte
ast_stream.write(bytes.data(), bytes.size());
}
std::vector<phylanx::ast::expression> load_ast_dump(std::string const& path)
{
std::ifstream ast_stream(path, std::ios::binary | std::ios::ate);
if (!ast_stream.good())
{
HPX_THROW_EXCEPTION(hpx::filesystem_error,
"dump_ast",
"Failed to open the specified file: " + path);
}
// Size of the data
auto const data_size = ast_stream.tellg();
if (data_size == decltype(data_size)(0) || !ast_stream.seekg(0, std::ios::beg))
{
HPX_THROW_EXCEPTION(hpx::filesystem_error,
"load_ast",
"Failed to read the specified file: " + path);
}
// Allocate all the memory needed to load the AST upfront
std::vector<char> bytes;
bytes.reserve(data_size);
return phylanx::util::unserialize<std::vector<phylanx::ast::expression>>(
std::move(bytes));
}
std::vector<phylanx::execution_tree::primitive_argument_type>
read_arguments(std::vector<std::string> const& args)
{
std::vector<phylanx::execution_tree::primitive_argument_type> result(
args.size());
std::transform(args.begin(), args.end(), result.begin(),
[](std::string const& s) { return phylanx::ast::generate_ast(s); });
return result;
}
///////////////////////////////////////////////////////////////////////////////
void print_performance_counter_data_csv()
{
// CSV Header
std::cout << "primitive_instance,display_name,count,time,eval_direct\n";
// List of existing primitive instances
std::vector<std::string> existing_primitive_instances;
// Retrieve all primitive instances
for (auto const& entry :
hpx::agas::find_symbols(hpx::launch::sync, "/phylanx/*$*"))
{
existing_primitive_instances.push_back(entry.first);
}
// Print performance data
std::vector<std::string> const counter_names{
"count/eval", "time/eval", "eval_direct"
};
for (auto const& entry : phylanx::util::retrieve_counter_data(
existing_primitive_instances, counter_names))
{
std::cout << "\"" << entry.first << "\",\""
<< phylanx::execution_tree::compiler::primitive_display_name(
entry.first)
<< "\"";
for (auto const& counter_value : entry.second)
{
std::cout << "," << counter_value;
}
std::cout << "\n";
}
std::cout << "\n";
}
///////////////////////////////////////////////////////////////////////////////
int handle_command_line(int argc, char* argv[], po::variables_map& vm)
{
try
{
po::options_description cmdline_options(
"Usage: physl <physl_script> [options] [arguments...]");
cmdline_options.add_options()
("help,h", "print out program usage")
("docs","Print out all primitives/plugins and descriptions")
("code,c", po::value<std::string>(),
"Execute the PhySL code given in argument")
("print,p", "Print the result of evaluation of the last "
"PhySL expression encountered in the input")
("performance", "Print the topology of the created execution "
"tree and the corresponding performance counter results")
("transform,t", po::value<std::string>(),
"file to read transformation rules from")
("dump-ast,d", po::value<std::string>()->implicit_value("<none>"),
"file to dump AST to")
("load-ast,l", po::value<std::string>(),
"file to dump AST to. If none path is provided, use the base "
"file name of the input file replacing the extension to .ast")
;
po::positional_options_description pd;
pd.add("positional", -1);
po::options_description positional_options;
positional_options.add_options()
("positional", po::value<std::vector<std::string> >(),
"positional options")
;
po::options_description all_options;
all_options.add(cmdline_options).add(positional_options);
po::parsed_options const opts(
po::command_line_parser(argc, argv)
.options(all_options)
.positional(pd)
.style(po::command_line_style::unix_style)
.run()
);
po::store(opts, vm);
if (vm.count("help") != 0)
{
std::cout << cmdline_options << std::endl;
return 1;
}
}
catch (std::exception const& e)
{
std::cerr << "physl: command line handling: exception caught: "
<< e.what() << "\n";
return -1;
}
return 0;
}
std::string get_dump_file(po::variables_map const& vm,
fs::path code_source_path, bool code_is_file)
{
std::string dump_file = vm["dump-ast"].as<std::string>();
// If no dump file is specified but PhySL code is read from a
// file then use the file name with .ast extension
if (dump_file == "<none>")
{
if (!code_is_file)
{
HPX_THROW_EXCEPTION(hpx::commandline_option_error, "get_ast()",
"the required path argument for option '--dump-ast' is "
"missing");
}
return code_source_path.replace_extension("ast").string();
}
return dump_file;
}
std::vector<phylanx::ast::expression> ast_from_code_or_dump(po::variables_map const& vm,
std::vector<std::string>& positional_args, std::string& code_source_name)
{
// Return value
std::vector<phylanx::ast::expression> ast;
// Set to true if PhySL code was read from a file, used to generate a file
// name for the AST dump file, if requested and a name is not provided
bool code_is_file = false;
fs::path code_source_path;
// Determine if an AST dump is to be loaded
if (vm.count("load-ast") != 0)
{
if (vm.count("code"))
{
HPX_THROW_EXCEPTION(hpx::commandline_option_error,
"get_ast()",
"'--dump-ast' and '--code' options cannot be used "
"simultaneously");
}
std::string ast_dump_file = vm["load-ast"].as<std::string>();
ast = load_ast_dump(ast_dump_file);
code_source_name = fs::path(ast_dump_file).filename().string();
}
// Read PhySL source code from a file or the provided argument
else
{
// PhySL source code
std::string user_code;
if (vm.count("code") != 0)
{
// Execute code as given directly on the command line
user_code = vm["code"].as<std::string>();
code_source_name = "<command_line>";
}
else if (!positional_args.empty() && !positional_args[0].empty())
{
// Interpret first argument as the file name for the PhySL code
user_code = read_user_code(positional_args[0]);
code_source_path = fs::path(positional_args[0]);
code_source_name = code_source_path.filename().string();
// The rest of the positional arguments are arguments for the script
positional_args.erase(positional_args.begin());
code_is_file = true;
}
else
{
HPX_THROW_EXCEPTION(hpx::commandline_option_error, "get_ast()",
"No code was provided.");
}
// Compile the given code into AST
ast = phylanx::ast::generate_ast(user_code);
}
// Apply transformation rules to AST, if requested
if (vm.count("transform") != 0)
{
std::string const transform_rules =
read_user_code(vm["transform"].as<std::string>());
ast = phylanx::ast::transform_ast(
ast, phylanx::ast::generate_transform_rules(transform_rules));
}
// Dump the AST to a file, if requested
if (vm.count("dump-ast") != 0)
{
std::string dump_file =
get_dump_file(vm, std::move(code_source_path), code_is_file);
dump_ast(ast, std::move(dump_file));
}
return ast;
}
phylanx::execution_tree::compiler::result_type compile_and_run(
std::vector<phylanx::ast::expression> const ast,
std::vector<std::string> const positional_args,
phylanx::execution_tree::compiler::function_list& snippets,
std::string const& code_source_name)
{
// Collect the arguments for running the code
auto const args = read_arguments(positional_args);
// Now compile AST into expression tree (into actual executable code);
phylanx::execution_tree::compiler::environment env =
phylanx::execution_tree::compiler::default_environment();
phylanx::execution_tree::define_variable(code_source_name,
phylanx::execution_tree::compiler::primitive_name_parts{
"sys_argv", -1, 0, 0},
snippets, env,
phylanx::execution_tree::primitive_argument_type{std::move(args)});
auto const code = phylanx::execution_tree::compile(
code_source_name, ast, snippets, env);
// Re-init all performance counters to guarantee correct measurement
// results if those are requested on the command line.
hpx::reinit_active_counters();
// Evaluate user code using the read data
return code();
}
void print_performance_profile(
phylanx::execution_tree::compiler::function_list& snippets,
std::string const code_source_name)
{
auto topology = snippets.snippets_.back().get_expression_topology();
std::cout << "\n"
<< phylanx::execution_tree::dot_tree(code_source_name, topology)
<< "\n";
std::cout << "\n"
<< phylanx::execution_tree::newick_tree(code_source_name, topology)
<< "\n\n";
print_performance_counter_data_csv();
}
///////////////////////////////////////////////////////////////////////////////
void interpreter(po::variables_map vm)
{
// Collect positional arguments
std::vector<std::string> positional_args;
if (vm.count("positional") != 0)
{
positional_args = vm["positional"].as<std::vector<std::string>>();
}
// Origin of PhySL code. It is either file name or <command_line>
std::string code_source_name;
// The AST that is either generated from PhySL code or loaded from an AST dump
std::vector<phylanx::ast::expression> ast =
ast_from_code_or_dump(vm, positional_args, code_source_name);
phylanx::execution_tree::compiler::function_list snippets;
auto const result = compile_and_run(
std::move(ast), std::move(positional_args), snippets, code_source_name);
// Print the result of the last PhySL expression, if requested
if (vm.count("print") != 0)
{
std::cout << result << "\n";
}
// Print auxiliary information at exit: topology of the execution tree
// and the associate performance counter data
if (vm.count("performance") != 0)
{
print_performance_profile(snippets, std::move(code_source_name));
}
}
int main(int argc, char* argv[])
{
po::variables_map vm;
int const cmdline_result = handle_command_line(argc, argv, vm);
if (cmdline_result != 0)
{
return cmdline_result > 0 ? 0 : cmdline_result;
}
if(vm.count("docs") != 0) {
phylanx::execution_tree::show_patterns();
return 0;
}
try
{
interpreter(std::move(vm));
}
catch (std::exception const& e)
{
std::cout << "physl: exception caught:\n" << e.what() << "\n";
return -1;
}
return 0;
}
| 32.484029 | 88 | 0.606308 | [
"vector",
"transform"
] |
87ff5140fc553ad481deba8de55e95654f0d701a | 5,975 | hpp | C++ | ui-cpp/thirdparty/Lyra/include/lyra/cli_parser.hpp | bck2302000/spirit | 14ed7782bd23f4828bf23ab8136ae31a21037bb3 | [
"MIT"
] | 92 | 2016-10-02T16:17:27.000Z | 2022-02-22T11:23:49.000Z | ui-cpp/thirdparty/Lyra/include/lyra/cli_parser.hpp | bck2302000/spirit | 14ed7782bd23f4828bf23ab8136ae31a21037bb3 | [
"MIT"
] | 590 | 2016-09-24T12:46:36.000Z | 2022-03-24T18:27:18.000Z | ui-cpp/thirdparty/Lyra/include/lyra/cli_parser.hpp | bck2302000/spirit | 14ed7782bd23f4828bf23ab8136ae31a21037bb3 | [
"MIT"
] | 46 | 2016-09-26T07:20:17.000Z | 2022-02-17T19:55:17.000Z | // Copyright 2018-2019 Rene Rivera
// Copyright 2017 Two Blue Cubes Ltd. All rights reserved.
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
#ifndef LYRA_CLI_PARSER_HPP
#define LYRA_CLI_PARSER_HPP
#include "lyra/exe_name.hpp"
#include "lyra/parser.hpp"
namespace lyra
{
/* tag::reference[]
= `lyra::cli_parser`
A Combined parser made up of any two or more other parsers. Creating and using
one of these as a basis one can incrementally compose other parsers into this
one. For example:
[source]
----
auto cli = lyra::cli_parser();
std::string what;
float when = 0;
cli |= lyra::opt(what, "what")["--make-it-so"]("Make it so.").required();
cli |= lyra::opt(when. "when")["--time"]("When to do <what>.").optional();
----
*/ // end::reference[]
class cli_parser : parser_base
{
public:
cli_parser() = default;
// Copy construction, needs to copy the exe name and the composed parsers.
cli_parser(const cli_parser& other)
: m_exeName(other.m_exeName)
{
for (auto& other_parser : other.m_parsers)
{
m_parsers.push_back(other_parser->clone());
}
}
// Compose the `exe_name` parser.
cli_parser& operator|=(exe_name const& exe_name)
{
m_exeName = exe_name;
return *this;
}
// Compose a regular parser.
cli_parser& operator|=(parser_base const& p)
{
m_parsers.push_back(p.clone());
return *this;
}
// Compose the parsers from another `cli_parser`.
cli_parser& operator|=(cli_parser const& other)
{
for (auto& p : other.m_parsers)
{
m_parsers.push_back(p->clone());
}
return *this;
}
// Concat composition.
template <typename T>
cli_parser operator|(T const& other) const
{
return cli_parser(*this) |= other;
}
// Return a container of the individual help text for the composed parsers.
virtual help_text get_help_text() const override
{
help_text text;
for (auto const& p : m_parsers)
{
auto child_help = p->get_help_text();
text.insert(text.end(), child_help.begin(), child_help.end());
}
return text;
}
friend auto operator<<(std::ostream& os, cli_parser const& parser)
-> std::ostream&
{
parser.writeToStream(os);
return os;
}
auto validate() const -> result override
{
for (auto const& p : m_parsers)
{
auto result = p->validate();
if (!result) return result;
}
return result::ok();
}
parse_result parse(
args const& args,
parser_customization const& customize
= default_parser_customization()) const;
parse_result parse(
std::string const& exe_name, detail::token_iterator const& tokens,
parser_customization const& customize) const override
{
struct ParserInfo
{
parser_base const* parser = nullptr;
size_t count = 0;
};
std::vector<ParserInfo> parseInfos(m_parsers.size());
{
size_t i = 0;
for (auto const& p : m_parsers) parseInfos[i++].parser = p.get();
}
m_exeName.set(exe_name);
auto result = parse_result::ok(
detail::parse_state(parser_result_type::no_match, tokens));
while (result.value().remainingTokens())
{
bool tokenParsed = false;
for (auto& parseInfo : parseInfos)
{
auto parser_cardinality = parseInfo.parser->cardinality();
if (parser_cardinality.is_unbounded()
|| parseInfo.count < parser_cardinality.maximum)
{
result = parseInfo.parser->parse(
exe_name, result.value().remainingTokens(), customize);
if (!result) return result;
if (result.value().type() != parser_result_type::no_match)
{
tokenParsed = true;
++parseInfo.count;
break;
}
}
}
if (result.value().type() == parser_result_type::short_circuit_all)
return result;
if (!tokenParsed)
return parse_result::runtimeError(
"Unrecognized token: "
+ result.value().remainingTokens()->name);
}
// Check missing required options.
for (auto& parseInfo : parseInfos)
{
auto parser_cardinality = parseInfo.parser->cardinality();
if (parser_cardinality.is_bounded()
&& (parseInfo.count < parser_cardinality.minimum
|| parser_cardinality.maximum < parseInfo.count))
{
return parse_result::runtimeError(
"Expected: " + parseInfo.parser->get_usage_text());
}
}
return result;
}
virtual std::unique_ptr<parser_base> clone() const override
{
return std::unique_ptr<parser_base>(new cli_parser(*this));
}
private:
mutable exe_name m_exeName;
std::vector<std::unique_ptr<parser_base>> m_parsers;
void writeToStream(std::ostream& os) const
{
if (!m_exeName.name().empty())
{
os << "Usage:\n"
<< " " << m_exeName.name();
for (auto const& p : m_parsers)
{
std::string usage_test = p->get_usage_text();
if (usage_test.size() > 0)
{
os << " ";
if (p->is_optional()) os << "[";
os << usage_test;
if (p->is_optional()) os << "]";
}
}
os << "\n\n";
}
os << "Options, arguments:";
for (auto const& cols : get_help_text())
{
os << "\n " << cols.option << "\n\n " << cols.description << "\n";
}
}
};
template <typename DerivedT, typename T>
cli_parser operator|(composable_parser<DerivedT> const& thing, T const& other)
{
return cli_parser() | static_cast<DerivedT const&>(thing) | other;
}
/* tag::reference[]
[source]
----
cli_parser::parse_result cli_parser::parse(
args const& args, parser_customization const& customize) const;
----
Parses given arguments `args` and optional parser customization `customize`.
The result indicates success or failure, and if failure what kind of failure
it was. The state of variables bound to options is unspecified and any bound
callbacks may have been called.
end::reference[] */
inline cli_parser::parse_result
cli_parser::parse(args const& args, parser_customization const& customize) const
{
return parse(
args.exe_name(),
detail::token_iterator(
args, customize.token_delimiters(), customize.option_prefix()),
customize);
}
} // namespace lyra
#endif
| 24.387755 | 80 | 0.678494 | [
"vector"
] |
e2125754449b241fd9b902f1a110cc8fb796b41b | 2,606 | cpp | C++ | src/kalman_filter.cpp | dan-fern/CarND-Extended-Kalman-Filter-Project | 025679863b5f93470cd13c6f965ec6b39770f149 | [
"MIT"
] | null | null | null | src/kalman_filter.cpp | dan-fern/CarND-Extended-Kalman-Filter-Project | 025679863b5f93470cd13c6f965ec6b39770f149 | [
"MIT"
] | null | null | null | src/kalman_filter.cpp | dan-fern/CarND-Extended-Kalman-Filter-Project | 025679863b5f93470cd13c6f965ec6b39770f149 | [
"MIT"
] | null | null | null | #include "kalman_filter.h"
using Eigen::MatrixXd;
using Eigen::VectorXd;
// NOTE: Eigen lib does not initialize VectorXd or MatrixXd objects with zeros.
/** Constructor */
KalmanFilter::KalmanFilter( )
{
}
/** Destructor */
KalmanFilter::~KalmanFilter( )
{
}
/** Init Initializes Kalman filter
* @param x_in Initial state
* @param P_in Initial state covariance
* @param F_in Transition matrix
* @param H_in Measurement matrix
* @param R_in Measurement covariance matrix
* @param Q_in Process covariance matrix
*/
void KalmanFilter::Init( VectorXd &x_in,
MatrixXd &P_in,
MatrixXd &F_in,
MatrixXd &H_in,
MatrixXd &R_in,
MatrixXd &Q_in )
{
x_ = x_in;
P_ = P_in;
F_ = F_in;
H_ = H_in;
R_ = R_in;
Q_ = Q_in;
}
/** Predicts the state and state covariance using the process model
* @param delta_T Time between k and k+1 in s
*/
void KalmanFilter::Predict( )
{
//MatrixXd Ft = F_.transpose( );
x_ = F_ * x_;
P_ = F_ * P_ * F_.transpose( ) + Q_;
}
/** Updates the state by using standard Kalman Filter equations
* @param z The measurement at k+1
*/
void KalmanFilter::Update( const VectorXd &z )
{
VectorXd y = z - ( H_ * x_ );
MatrixXd S = H_ * P_ * H_.transpose() + R_;
MatrixXd K = P_ * H_.transpose( ) * S.inverse( );
//new estimate
x_ = x_ + ( K * y );
MatrixXd I = MatrixXd::Identity( x_.size( ), x_.size( ) );
P_ = ( I - K * H_ ) * P_;
}
/** Updates the state by using Extended Kalman Filter equations
* @param z The measurement at k+1
*/
void KalmanFilter::UpdateEKF( const VectorXd &z )
{
//state parameters
float px = x_(0);
float py = x_(1);
float vx = x_(2);
float vy = x_(3);
float rho = sqrt( px * px + py * py );
if( fabs( rho ) < 0.00001 )
{
px += 0.001;
py += 0.001;
rho = sqrt( px * px + py * py );
}
float phi = atan2( py, px );
float rho_dot = ( px * vx + py * vy ) / rho;
VectorXd z_pred( 3 );
z_pred << rho, phi, rho_dot;
VectorXd y = z - z_pred;
//normalize angle
while( y( 1 ) > M_PI )
{
y( 1 ) -= 2 * M_PI;
}
while( y( 1 ) < -M_PI )
{
y( 1 ) += 2 * M_PI;
}
MatrixXd S = H_ * P_ * H_.transpose( ) + R_;
MatrixXd K = P_ * H_.transpose( ) * S.inverse( );
//new estimate
x_ = x_ + ( K * y );
MatrixXd I = MatrixXd::Identity( x_.size( ), x_.size( ) );
P_ = ( I - K * H_ ) * P_;
}
| 19.021898 | 79 | 0.537989 | [
"model"
] |
e219fec048fdb859e727ac16dcdc9e8c998c5781 | 8,568 | cpp | C++ | openbabel-2.4.1/src/formats/freefracformat.cpp | sxhexe/reaction-route-search | f7694c84ca1def4a133ade3e1e2e09705cd28312 | [
"MIT"
] | 1 | 2017-09-16T07:36:29.000Z | 2017-09-16T07:36:29.000Z | openbabel-2.4.1/src/formats/freefracformat.cpp | sxhexe/reaction-route-search | f7694c84ca1def4a133ade3e1e2e09705cd28312 | [
"MIT"
] | null | null | null | openbabel-2.4.1/src/formats/freefracformat.cpp | sxhexe/reaction-route-search | f7694c84ca1def4a133ade3e1e2e09705cd28312 | [
"MIT"
] | null | null | null | /**********************************************************************
Copyright (C) 2005-2006 by Geoffrey R. Hutchison
Some portions Copyright (C) 2004 by Chris Morley
This program 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 version 2 of the License.
This program 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.
***********************************************************************/
#include <openbabel/babelconfig.h>
#include <openbabel/obmolecformat.h>
#include <openbabel/math/matrix3x3.h>
using namespace std;
namespace OpenBabel
{
class FreeFormFractionalFormat : public OBMoleculeFormat
{
public:
//Register this format type ID
FreeFormFractionalFormat()
{
OBConversion::RegisterFormat("fract",this);
}
virtual const char* Description() //required
{
return
"Free Form Fractional format\n"
"General purpose crystallographic format\n"
"The \"free-form\" fractional format attempts to allow for input from a\n"
"range of fractional / crystallography file formats. As such, it has only\n"
"a few restrictions on input:\n\n"
"- Line one of the file contains a title or comment.\n"
"- Line two of the file contains the unit cell parameters separated by\n"
" whitespace and/or commas (i.e. \"a b c alpha beta gamma\").\n"
"- Any remaining lines are parsed for atom information. Lines start with\n"
" the element symbol, followed by fractional X, Y, and Z coordinates\n"
" (in angstroms) separated by whitespace.\n\n"
"Any numeric input (i.e., unit cell parameters, XYZ coordinates) can include\n"
"designations of errors, although this is currently ignored. For example::\n\n"
" C 1.00067(3) 2.75(2) 3.0678(12)\n\n"
"will be parsed as::\n\n"
" C 1.00067 2.75 3.0678\n\n"
"When used as an **output** format, The first line written is the title of the\n"
"molecule or the filename if no title is defined. If a molecule has a defined\n"
"unit cell, then the second line will be formatted as::\n\n"
" a b c alpha beta gamma\n\n"
"where a, b, c are the unit cell vector lengths, and alpha, beta, and gamma are\n"
"the angles between them. These numbers are formatted as \"10.5\", which means that\n"
"5 decimal places will be output for all numbers. In the case where no unit cell\n"
"is defined for the molecule, the vector lengths will be defined as 1.0, and the\n"
"angles to 90.0 degrees.\n\n"
"Remaining lines define the atoms in the file. The first column is the atomic\n"
"symbol, followed by the XYZ coordinates in 10.5 format (in angstroms).\n\n"
"Here is an example file::\n\n"
" ZnO test file\n"
" 3.14 3.24 5.18 90.0 90.0 120.0\n"
" O 0.66667 0.33333 0.3750\n"
" O 0.33333 0.66667 0.8750\n"
" Zn 0.66667 0.33333 0.0000\n"
" Zn 0.33333 0.66667 0.5000\n\n"
"Read Options e.g. -as\n"
" s Output single bonds only\n"
" b Disable bonding entirely\n\n";
};
virtual const char* SpecificationURL()
{return "http://openbabel.org/wiki/Free_Form_Fractional";}; //optional
//*** This section identical for most OBMol conversions ***
////////////////////////////////////////////////////
/// The "API" interface functions
virtual bool ReadMolecule(OBBase* pOb, OBConversion* pConv);
virtual bool WriteMolecule(OBBase* pOb, OBConversion* pConv);
};
//***
//Make an instance of the format class
FreeFormFractionalFormat theFreeFormFractionalFormat;
/* const char * TrimErrors(const std::string data)
{
string temp = data;
size_t stdErr = temp.rfind("(");
if(stdErr!=string::npos)
temp.erase(stdErr);
return temp.c_str();
}
*/
/////////////////////////////////////////////////////////////////
bool FreeFormFractionalFormat::ReadMolecule(OBBase* pOb, OBConversion* pConv)
{
OBMol* pmol = pOb->CastAndClear<OBMol>();
if(pmol==NULL)
return false;
//Define some references so we can use the old parameter names
istream &ifs = *pConv->GetInStream();
OBMol &mol = *pmol;
const char* title = pConv->GetTitle();
char buffer[BUFF_SIZE];
if (!ifs.getline(buffer,BUFF_SIZE))
{
obErrorLog.ThrowError(__FUNCTION__,
"Problems reading a free form fractional file: Could not read the first line (title/comments).", obWarning);
return(false);
}
if (strlen(buffer) != 0)
mol.SetTitle(buffer);
else
mol.SetTitle(title);
if (!ifs.getline(buffer,BUFF_SIZE))
{
obErrorLog.ThrowError(__FUNCTION__,
"Problems reading a free form fractional file: Could not read the second line (unit cell parameters a b c alpha beta gamma).",
obWarning);
return(false);
}
vector<string> vs;
tokenize(vs,buffer," \n\t,");
if (vs.size() != 6)
return(false);
//parse cell values
double A, B, C, Alpha, Beta, Gamma;
string temp; // used to trim ending (xx) data from strings
A = atof(vs[0].c_str());
B = atof(vs[1].c_str());
C = atof(vs[2].c_str());
Alpha = atof(vs[3].c_str());
Beta = atof(vs[4].c_str());
Gamma = atof(vs[5].c_str());
OBUnitCell *uc = new OBUnitCell;
uc->SetOrigin(fileformatInput);
uc->SetData(A, B, C, Alpha, Beta, Gamma);
mol.SetData(uc);
mol.BeginModify();
string str;
double x,y,z;
vector3 v;
int atomicNum;
OBAtom *atom;
while(ifs.getline(buffer,BUFF_SIZE))
{
if (strlen(buffer) == 0 || *buffer == 0x0D) //incl Windows kludge
// blank line -- consider it the end of this molecule
break;
tokenize(vs,buffer);
if (vs.size() != 4)
return(false);
atom = mol.NewAtom();
// check to see if first column is number or element symbol
// (PCModel has files of the form X Y Z symbol)
atomicNum = etab.GetAtomicNum(vs[0].c_str());
if (atomicNum == 0 && (isdigit(vs[0][0]) || ispunct(vs[0][0])))
{
x = atof(vs[0].c_str());
y = atof(vs[1].c_str());
z = atof(vs[2].c_str());
atomicNum = etab.GetAtomicNum(vs[3].c_str());
}
else
{
x = atof(vs[1].c_str());
y = atof(vs[2].c_str());
z = atof(vs[3].c_str());
}
v.Set(x, y, z);
v = uc->FractionalToCartesian(v);
atom->SetVector(v);
atom->SetAtomicNum(atomicNum);
}
// clean out any remaining blank lines
while(ifs.peek() != EOF && ifs.good() &&
(ifs.peek() == '\n' || ifs.peek() == '\r'))
ifs.getline(buffer,BUFF_SIZE);
if (!pConv->IsOption("b",OBConversion::INOPTIONS))
mol.ConnectTheDots();
if (!pConv->IsOption("s",OBConversion::INOPTIONS)
&& !pConv->IsOption("b",OBConversion::INOPTIONS))
mol.PerceiveBondOrders();
mol.EndModify();
return(true);
}
////////////////////////////////////////////////////////////////
bool FreeFormFractionalFormat::WriteMolecule(OBBase* pOb, OBConversion* pConv)
{
OBMol* pmol = dynamic_cast<OBMol*>(pOb);
if(pmol==NULL)
return false;
//Define some references so we can use the old parameter names
ostream &ofs = *pConv->GetOutStream();
OBMol &mol = *pmol;
char buffer[BUFF_SIZE];
OBUnitCell *uc = NULL;
ofs << mol.GetTitle() << endl;
if (!mol.HasData(OBGenericDataType::UnitCell))
ofs << " 1.00000 1.00000 1.00000 90.00000 90.00000 90.00000\n";
else
{
uc = (OBUnitCell*)mol.GetData(OBGenericDataType::UnitCell);
snprintf(buffer, BUFF_SIZE,
"%10.5f%10.5f%10.5f%10.5f%10.5f%10.5f",
uc->GetA(), uc->GetB(), uc->GetC(),
uc->GetAlpha() , uc->GetBeta(), uc->GetGamma());
ofs << buffer << "\n";
}
vector3 v;
FOR_ATOMS_OF_MOL(atom, mol)
{
v = atom->GetVector();
if (uc != NULL)
v = uc->CartesianToFractional(v);
snprintf(buffer, BUFF_SIZE, "%s %10.5f%10.5f%10.5f",
etab.GetSymbol(atom->GetAtomicNum()),
v.x(),
v.y(),
v.z());
ofs << buffer << endl;
}
ofs << endl; // add a blank line between molecules
return(true);
}
} //namespace OpenBabel
| 31.733333 | 156 | 0.595355 | [
"vector"
] |
e2225bafe1f18dff78a68f59e1b1447e0f38676f | 13,609 | cpp | C++ | src/planning/scenario_planning/lane_driving/behavior_planning/behavior_velocity_planner/src/scene_module/blind_spot/scene.cpp | zqw-hooper/AutowareArchitectureProposal | 93ca87fd7255be697219a100a97a639a56f6c4a7 | [
"Apache-2.0"
] | null | null | null | src/planning/scenario_planning/lane_driving/behavior_planning/behavior_velocity_planner/src/scene_module/blind_spot/scene.cpp | zqw-hooper/AutowareArchitectureProposal | 93ca87fd7255be697219a100a97a639a56f6c4a7 | [
"Apache-2.0"
] | null | null | null | src/planning/scenario_planning/lane_driving/behavior_planning/behavior_velocity_planner/src/scene_module/blind_spot/scene.cpp | zqw-hooper/AutowareArchitectureProposal | 93ca87fd7255be697219a100a97a639a56f6c4a7 | [
"Apache-2.0"
] | 4 | 2021-06-21T11:58:51.000Z | 2021-08-06T08:25:54.000Z | /*
* Copyright 2020 Tier IV, Inc. 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 <scene_module/blind_spot/scene.h>
#include "utilization/boost_geometry_helper.h"
#include "utilization/util.h"
namespace bg = boost::geometry;
using Point = bg::model::d2::point_xy<double>;
using Polygon = bg::model::polygon<Point, false>;
BlindSpotModule::BlindSpotModule(
const int64_t module_id, const int64_t lane_id, const std::string & turn_direction)
: SceneModuleInterface(module_id), lane_id_(lane_id), turn_direction_(turn_direction)
{
constexpr double state_change_margin_time = 2.0;
state_machine_.setMarginTime(state_change_margin_time); // [sec]
}
bool BlindSpotModule::modifyPathVelocity(autoware_planning_msgs::PathWithLaneId * path)
{
debug_data_ = {};
const auto input_path = *path;
debug_data_.path_raw = input_path;
State current_state = state_machine_.getState();
ROS_DEBUG_COND(
show_debug_info_, "[BlindSpotModule]: run: state_machine_.getState() = %d", (int)current_state);
/* get current pose */
geometry_msgs::PoseStamped current_pose = planner_data_->current_pose;
/* check if the current_pose is ahead from judgement line */
int closest = -1;
if (!planning_utils::calcClosestIndex(input_path, current_pose.pose, closest)) {
ROS_WARN_DELAYED_THROTTLE(1.0, "[BlindSpotModule::run] calcClosestIndex fail");
return false;
}
/* set judge line dist */
double current_velocity = planner_data_->current_velocity->twist.linear.x;
double max_accel = planner_data_->max_stop_acceleration_threshold_;
judge_line_dist_ = planning_utils::calcJudgeLineDist(current_velocity, max_accel, 0.0);
/* set stop-line and stop-judgement-line */
if (!setStopLineIdx(closest, judge_line_dist_, *path, stop_line_idx_, judge_line_idx_)) {
ROS_WARN_DELAYED_THROTTLE(1.0, "[BlindSpotModule::run] setStopLineIdx fail");
return false;
}
if (stop_line_idx_ <= 0 || judge_line_idx_ <= 0) {
ROS_INFO_COND(
show_debug_info_,
"[BlindSpotModule::run] the stop line or judge line is at path[0], ignore "
"planning. Maybe it is far behind the current position.");
return true;
}
if (current_state == State::STOP) {
// visualize virtual_wall at vehicle front position
debug_data_.virtual_wall_pose =
getAheadPose(stop_line_idx_, planner_data_->base_link2front, *path);
}
debug_data_.stop_point_pose = path->points.at(stop_line_idx_).point.pose;
debug_data_.judge_point_pose = path->points.at(judge_line_idx_).point.pose;
debug_data_.path_with_judgeline = *path;
if (current_state == State::GO) {
const auto p = planning_utils::transformRelCoordinate2D(
current_pose.pose, path->points.at(judge_line_idx_).point.pose);
// current_pose is ahead of judge_line
if (p.position.x > 0.0) {
ROS_INFO_COND(
show_debug_info_, "[BlindSpotModule::run] no plan needed. skip collision check.");
return true; // no plan needed.
}
}
/* get detection area */
if (turn_direction_.compare("right") != 0 && turn_direction_.compare("left") != 0) {
ROS_WARN(
"blind spot detector is running, turn_direction_ = not right or left. (%s)",
turn_direction_.c_str());
return false;
}
const auto detection_area = generateDetectionArea(current_pose.pose);
debug_data_.detection_area = detection_area;
/* get dynamic object */
const auto objects_ptr = planner_data_->dynamic_objects;
/* calculate dynamic collision around detection area */
const bool is_collision = checkCollision(*path, detection_area, objects_ptr, path_expand_width_);
if (is_collision) {
state_machine_.setStateWithMarginTime(State::STOP);
} else {
state_machine_.setStateWithMarginTime(State::GO);
}
/* set stop speed */
if (state_machine_.getState() == State::STOP) {
constexpr double stop_vel = 0.0;
setVelocityFrom(stop_line_idx_, stop_vel, *path);
}
return true;
}
std::vector<geometry_msgs::Point> BlindSpotModule::generateDetectionArea(
const geometry_msgs::Pose & current_pose)
{
std::vector<geometry_msgs::Point> blind_spot;
double detection_width = 5.0;
double detection_length_forward = 5.0;
double detection_length_backward = 15.0;
double vehicle_width = 3.0;
double vw = vehicle_width * 0.5;
if (turn_direction_.compare("right") == 0) {
vw *= -1.0;
detection_width *= -1.0;
} else if (turn_direction_.compare("left") == 0) {
// nothing to do.
}
geometry_msgs::Pose fl;
fl.position.x = detection_length_forward;
fl.position.y = vw;
blind_spot.push_back(planning_utils::transformAbsCoordinate2D(fl, current_pose).position);
geometry_msgs::Pose fr;
fr.position.x = detection_length_forward;
fr.position.y = vw + detection_width;
blind_spot.push_back(planning_utils::transformAbsCoordinate2D(fr, current_pose).position);
geometry_msgs::Pose rr;
rr.position.x = -detection_length_backward;
rr.position.y = vw + detection_width;
blind_spot.push_back(planning_utils::transformAbsCoordinate2D(rr, current_pose).position);
geometry_msgs::Pose rl;
rl.position.x = -detection_length_backward;
rl.position.y = vw;
blind_spot.push_back(planning_utils::transformAbsCoordinate2D(rl, current_pose).position);
return blind_spot;
}
bool BlindSpotModule::setStopLineIdx(
const int current_pose_closest, const double judge_line_dist,
autoware_planning_msgs::PathWithLaneId & path, int & stop_line_idx, int & judge_line_idx)
{
// TEMP: return first assigned_lane_id point's index
stop_line_idx = -1;
for (size_t i = 0; i < path.points.size(); ++i) {
for (const auto & id : path.points.at(i).lane_ids) {
if (id == lane_id_) {
stop_line_idx = i;
}
if (stop_line_idx != -1) break;
}
if (stop_line_idx != -1) break;
}
if (stop_line_idx == -1) {
ROS_ERROR(
"[BlindSpotModule::setStopLineIdx]: cannot set the stop line. something wrong. please "
"check code. ");
return false; // cannot find stop line.
}
// TEMP: should use interpolation (points distance may be very long)
double curr_dist = 0.0;
double prev_dist = curr_dist;
judge_line_idx = -1;
for (size_t i = stop_line_idx; i > 0; --i) {
const geometry_msgs::Pose p0 = path.points.at(i).point.pose;
const geometry_msgs::Pose p1 = path.points.at(i - 1).point.pose;
curr_dist += planning_utils::calcDist2d(p0, p1);
if (curr_dist > judge_line_dist) {
const double dl = std::max(curr_dist - prev_dist, 0.0001 /* avoid 0 divide */);
const double w_p0 = (curr_dist - judge_line_dist) / dl;
const double w_p1 = (judge_line_dist - prev_dist) / dl;
autoware_planning_msgs::PathPointWithLaneId p = path.points.at(i);
p.point.pose.position.x = w_p0 * p0.position.x + w_p1 * p1.position.x;
p.point.pose.position.y = w_p0 * p0.position.y + w_p1 * p1.position.y;
p.point.pose.position.z = w_p0 * p0.position.z + w_p1 * p1.position.z;
tf2::Quaternion q0_tf, q1_tf;
tf2::fromMsg(p0.orientation, q0_tf);
tf2::fromMsg(p1.orientation, q1_tf);
p.point.pose.orientation = tf2::toMsg(q0_tf.slerp(q1_tf, w_p1));
auto itr = path.points.begin();
itr += i;
path.points.insert(itr, p);
judge_line_idx = i;
++stop_line_idx;
break;
}
prev_dist = curr_dist;
}
if (judge_line_idx == -1) {
ROS_DEBUG(
"[BlindSpotModule::setStopLineIdx]: cannot set the stop judgement line. path is too short, "
"or "
"the vehicle is already ahead of the stop line. stop_line_id = %d",
stop_line_idx);
}
return true;
}
geometry_msgs::Pose BlindSpotModule::getAheadPose(
const size_t start_idx, const double ahead_dist,
const autoware_planning_msgs::PathWithLaneId & path) const
{
if (path.points.size() == 0) {
return geometry_msgs::Pose{};
}
double curr_dist = 0.0;
double prev_dist = 0.0;
for (size_t i = start_idx; i < path.points.size() - 1 && i >= 0; ++i) {
const geometry_msgs::Pose p0 = path.points.at(i).point.pose;
const geometry_msgs::Pose p1 = path.points.at(i + 1).point.pose;
curr_dist += planning_utils::calcDist2d(p0, p1);
if (curr_dist > ahead_dist) {
const double dl = std::max(curr_dist - prev_dist, 0.0001 /* avoid 0 divide */);
const double w_p0 = (curr_dist - ahead_dist) / dl;
const double w_p1 = (ahead_dist - prev_dist) / dl;
geometry_msgs::Pose p;
p.position.x = w_p0 * p0.position.x + w_p1 * p1.position.x;
p.position.y = w_p0 * p0.position.y + w_p1 * p1.position.y;
p.position.z = w_p0 * p0.position.z + w_p1 * p1.position.z;
tf2::Quaternion q0_tf, q1_tf;
tf2::fromMsg(p0.orientation, q0_tf);
tf2::fromMsg(p1.orientation, q1_tf);
p.orientation = tf2::toMsg(q0_tf.slerp(q1_tf, w_p1));
return p;
}
prev_dist = curr_dist;
}
return path.points.back().point.pose;
}
bool BlindSpotModule::setVelocityFrom(
const size_t idx, const double vel, autoware_planning_msgs::PathWithLaneId & input)
{
for (size_t i = idx; i < input.points.size(); ++i) {
input.points.at(i).point.twist.linear.x =
std::min(vel, input.points.at(i).point.twist.linear.x);
}
}
bool BlindSpotModule::checkCollision(
const autoware_planning_msgs::PathWithLaneId & path,
const std::vector<geometry_msgs::Point> & detection_area,
const autoware_perception_msgs::DynamicObjectArray::ConstPtr objects_ptr, const double path_width)
{
/* generates side edge line */
autoware_planning_msgs::PathWithLaneId path_r; // right side edge line
autoware_planning_msgs::PathWithLaneId path_l; // left side edge line
generateEdgeLine(path, path_width, path_r, path_l);
debug_data_.path_right_edge = path_r;
debug_data_.path_left_edge = path_l;
/* check collision for each objects and detection area */
for (const auto & object : objects_ptr->objects) {
const auto object_pose = object.state.pose_covariance.pose;
// Ignore objects outside detection area
const auto detection_area_polygon = linestring2polygon(to_bg2d(detection_area));
if (!bg::within(to_bg2d(object_pose.position), detection_area_polygon)) {
continue;
}
if (checkPathCollision(path_r, object) || checkPathCollision(path_l, object)) {
return true;
}
}
return false;
}
bool BlindSpotModule::checkPathCollision(
const autoware_planning_msgs::PathWithLaneId & path,
const autoware_perception_msgs::DynamicObject & object)
{
bool is_collision = false;
bg::model::linestring<Point> bg_ego_path;
for (const auto & p : path.points) {
bg_ego_path.push_back(Point{p.point.pose.position.x, p.point.pose.position.y});
}
std::vector<bg::model::linestring<Point>> bg_object_path_arr;
for (size_t i = 0; i < object.state.predicted_paths.size(); ++i) {
bg::model::linestring<Point> bg_object_path;
for (const auto & p : object.state.predicted_paths.at(i).path) {
bg_object_path.push_back(Point{p.pose.pose.position.x, p.pose.pose.position.y});
}
bg_object_path_arr.push_back(bg_object_path);
}
for (size_t i = 0; i < object.state.predicted_paths.size(); ++i) {
bool is_intersects = bg::intersects(bg_ego_path, bg_object_path_arr.at(i));
is_collision = is_collision || is_intersects;
}
return is_collision;
}
bool BlindSpotModule::generateEdgeLine(
const autoware_planning_msgs::PathWithLaneId & path, const double path_width,
autoware_planning_msgs::PathWithLaneId & path_r, autoware_planning_msgs::PathWithLaneId & path_l)
{
path_r = path;
path_l = path;
for (int i = 0; i < path.points.size(); ++i) {
const double yaw = tf2::getYaw(path.points.at(i).point.pose.orientation);
path_r.points.at(i).point.pose.position.x += path_width * std::sin(yaw);
path_r.points.at(i).point.pose.position.y -= path_width * std::cos(yaw);
path_l.points.at(i).point.pose.position.x -= path_width * std::sin(yaw);
path_l.points.at(i).point.pose.position.y += path_width * std::cos(yaw);
}
}
void BlindSpotModule::StateMachine::setStateWithMarginTime(State state)
{
/* same state request */
if (state_ == state) {
start_time_ = nullptr; // reset timer
return;
}
/* GO -> STOP */
if (state == State::STOP) {
state_ = State::STOP;
start_time_ = nullptr; // reset timer
return;
}
/* STOP -> GO */
if (state == State::GO) {
if (start_time_ == nullptr) {
start_time_ = std::make_shared<ros::Time>(ros::Time::now());
return;
} else {
const double duration = (ros::Time::now() - *start_time_).toSec();
if (duration > margin_time_) {
state_ = State::GO;
start_time_ = nullptr; // reset timer
}
return;
}
}
ROS_ERROR(
"[StateMachine::setStateWithMarginTime()] : Unsuitable state. ignore "
"request.");
return;
}
void BlindSpotModule::StateMachine::setState(State state) { state_ = state; }
void BlindSpotModule::StateMachine::setMarginTime(const double t) { margin_time_ = t; }
BlindSpotModule::State BlindSpotModule::StateMachine::getState() { return state_; }
| 35.440104 | 100 | 0.699758 | [
"geometry",
"object",
"vector",
"model"
] |
e223f86407f313b37c2e67df2c1e74454c8854d7 | 397 | cpp | C++ | RaccoonPythonLibrary/RPL/Object.cpp | KamikazeRaccoons/RaccoonPythonInterpreter | a4cb6595669a1bdea5c4e56158566cb9c1a6d162 | [
"Apache-2.0"
] | 1 | 2016-02-15T23:08:11.000Z | 2016-02-15T23:08:11.000Z | RaccoonPythonLibrary/RPL/Object.cpp | KamikazeRaccoons/RaccoonPythonInterpreter | a4cb6595669a1bdea5c4e56158566cb9c1a6d162 | [
"Apache-2.0"
] | null | null | null | RaccoonPythonLibrary/RPL/Object.cpp | KamikazeRaccoons/RaccoonPythonInterpreter | a4cb6595669a1bdea5c4e56158566cb9c1a6d162 | [
"Apache-2.0"
] | null | null | null | #include "Object.h"
namespace rpl
{
Object::~Object()
{
delete m_pMutex;
}
void Object::lock()
{
m_pMutex->lock();
}
void Object::unlock()
{
m_pMutex->unlock();
}
void Object::destroy() const
{
delete this;
}
Object::ScopedLock::ScopedLock(Object* parent)
{
m_pParent = parent;
m_pParent->lock();
}
Object::ScopedLock::~ScopedLock()
{
m_pParent->unlock();
}
} | 11.342857 | 47 | 0.622166 | [
"object"
] |
e225461fb4cdeefd2a1e9df065851e908ad1b424 | 4,018 | cpp | C++ | Gems/AtomTressFX/External/Code/src/SDF.cpp | whywhywhyw/o3de | 8e09f66799d4c8f188d45861d821e8656a554cb1 | [
"Apache-2.0",
"MIT"
] | 678 | 2016-01-26T13:39:34.000Z | 2022-03-22T09:12:05.000Z | Gems/AtomTressFX/External/Code/src/SDF.cpp | RoddieKieley/o3de | e804fd2a4241b039a42d9fa54eaae17dc94a7a92 | [
"Apache-2.0",
"MIT"
] | 36 | 2016-01-26T15:30:17.000Z | 2021-09-14T11:44:23.000Z | Gems/AtomTressFX/External/Code/src/SDF.cpp | RoddieKieley/o3de | e804fd2a4241b039a42d9fa54eaae17dc94a7a92 | [
"Apache-2.0",
"MIT"
] | 131 | 2016-01-26T12:53:31.000Z | 2022-02-17T04:23:22.000Z |
///---------------------------------------------------------------------------------------
// Example code for managing objects for signed-distance fields (SDFs)
//
// This includes the TressFXSDFCollision objects. Associated with each is a system
// for skinning the model on the GPU (since that is input to TressFXSDFCollision) and
// visualizing the SDFs using marching cubes. The GPU skinning and marching cubes
// systems could be packaged as library code as well, but are not there yet.
//
// The skinned meshes are loaded through this interface as well.
//-------------------------------------------------------------------------------------
//
// Copyright (c) 2019 Advanced Micro Devices, Inc. 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 "SDF.h"
#include "TressFXBoneSkinning.h"
#include "TressFXSDFMarchingCubes.h"
#include "TressFXSDFCollision.h"
#include "EngineInterface.h"
CollisionMesh::CollisionMesh(
EI_Scene * gltfImplementation,
EI_RenderTargetSet * renderPass,
const char * name,
const char * tfxmeshFilePath,
int numCellsInXAxis,
float SDFCollMargin,
int skinNumber,
const char * followBone)
{
m_pBoneSkinning.reset(new TressFXBoneSkinning);
m_pSDFMachingCubes.reset(new TressFXSDFMarchingCubes);
EI_Device* pDevice = GetDevice();
EI_CommandContext& uploadCommandContext = GetDevice()->GetCurrentCommandContext();
m_pBoneSkinning->LoadTressFXCollisionMeshData(gltfImplementation, tfxmeshFilePath, skinNumber, followBone);
m_pBoneSkinning->Initialize(renderPass, pDevice, uploadCommandContext, name);
m_pCollisionMesh.reset(new TressFXSDFCollision(pDevice, m_pBoneSkinning.get(), name, numCellsInXAxis, SDFCollMargin));
#if ENABLE_MARCHING_CUBES
m_pSDFMachingCubes->SetSDF(m_pCollisionMesh.get());
m_pSDFMachingCubes->SetSDFIsoLevel(m_pCollisionMesh->GetSDFCollisionMargin());
m_pSDFMachingCubes->Initialize(name, gltfImplementation, renderPass);
#endif
}
void CollisionMesh::SkinTheMesh(EI_CommandContext& context, double fTime)
{
m_pBoneSkinning->Update(context, fTime);
}
void CollisionMesh::AccumulateSDF(EI_CommandContext& context, TressFXSDFCollisionSystem& sdfCollisionSystem)
{
m_pCollisionMesh->Update(context, sdfCollisionSystem);
}
void CollisionMesh::ApplySDF(EI_CommandContext& context, TressFXSDFCollisionSystem& sdfCollisionSystem, TressFXHairObject* strands)
{
m_pCollisionMesh->CollideWithHair(context, sdfCollisionSystem, *strands);
}
void CollisionMesh::GenerateIsoSurface(EI_CommandContext& context)
{
m_pSDFMachingCubes->Update(context);
}
void CollisionMesh::DrawIsoSurface(EI_CommandContext& context)
{
(void)context;
m_pSDFMachingCubes->Draw();
}
void CollisionMesh::DrawMesh(EI_CommandContext& context)
{
m_pBoneSkinning->DrawMesh(context);
} | 41.854167 | 132 | 0.715281 | [
"model"
] |
e22958a833ba30675d2b2f6f8dfabfe72a445cf1 | 3,739 | hpp | C++ | ThirdParty/oglplus-develop/include/oglplus/bound.hpp | vif/3D-STG | 721402e76a9b9b99b88ba3eb06beb6abb17a9254 | [
"MIT"
] | null | null | null | ThirdParty/oglplus-develop/include/oglplus/bound.hpp | vif/3D-STG | 721402e76a9b9b99b88ba3eb06beb6abb17a9254 | [
"MIT"
] | null | null | null | ThirdParty/oglplus-develop/include/oglplus/bound.hpp | vif/3D-STG | 721402e76a9b9b99b88ba3eb06beb6abb17a9254 | [
"MIT"
] | null | null | null | /**
* @file oglplus/bound.hpp
* @brief OGLplus bound objects
*
* @author Matus Chochlik
*
* Copyright 2010-2013 Matus Chochlik. 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)
*/
#pragma once
#ifndef OGLPLUS_BOUND_1201190831_HPP
#define OGLPLUS_BOUND_1201190831_HPP
#include <oglplus/object.hpp>
namespace oglplus {
/// A common base class for Bound objects
/**
* @note Do not use this class directly, use Bound or Bind() instead.
*
* @ingroup modifier_classes
*/
template <class Bindable, class BindableOps>
class BoundBase
{
private:
typename Bindable::Target _bind_target;
protected:
BoundBase(const Bindable& bindable, typename Bindable::Target target)
: _bind_target(target)
{
bindable.Bind(target);
}
public:
/// Returns the target to which the object is bound
typename Bindable::Target BindTarget(void) const
{
return _bind_target;
}
};
#if OGLPLUS_DOCUMENTATION_ONLY
/// Specializations of this template wrap functions of Bindable with bind target
/**
* @note Do not use this class directly, use Bound or Bind() instead.
*
* @see Bind()
* @see Bound
*
* @ingroup utility_classes
*/
template <template <class, class> class Base, class BaseParam, class BindableOps>
class BoundTemplate
: public Base<BaseParam, BindableOps>
{
};
#else
template <template <class, class> class Base, class BaseParam, class Bindable>
class BoundTemplate;
#endif
/// A wraper that binds @ref oglplus_object "objects" to a specified target
/**
* @ref bound_objects make the usage of @ref oglplus_object "objects" that
* can be bound to a OpenGL binding point or "target" easier.
* This includes objects like @ref oglplus::Buffer "Buffer,"
* @ref oglplus::Texture "Texture", @ref oglplus::Renderbuffer "Renderbuffer"
* or @ref oglplus::Framebuffer "Framebuffer"
* which have a target to which individual
* instances can be bound and operated on through the binding point.
* Generally @c Bound<Object> classes re-implement those functions of @c Object
* which have a @c target parameter of the @c Object::Target type. These
* re-implemented functions have all the other parameters of the original
* member functions, but lack the @c target parameter and supply it to the
* original function call automatically.
*
* @see Bind()
*
* @ingroup modifier_classes
*/
template <class Bindable>
class Bound
: public BoundTemplate<BoundBase, Bindable, Bindable>
{
public:
/// Creates a new object bound to @p target from a @p bindable object
/**
* @see Bind
*/
Bound(
const Bindable& bindable,
typename Bindable::Target target
): BoundTemplate<oglplus::BoundBase, Bindable, Bindable>(bindable, target)
{ }
};
#if OGLPLUS_DOCUMENTATION_ONLY
/// Function constructing Bound objects
/** This function is the preferred way to construct instances of objects
* Bound to a target (binding point).
*/
template <class Object>
inline Bound<Object> Bind(
const Object& bindable,
typename Object::Target target
)
{
return Bound<ObjectOps>(bindable, target);
}
#else
template <class ObjectOps>
inline Bound<ObjectOps> Bind(
const Object<ObjectOps>& bindable,
typename ObjectOps::Target target
)
{
return Bound<ObjectOps>(bindable, target);
}
template <class ObjectOps>
inline Bound<ObjectOps> Bind(
const Managed<ObjectOps>& bindable,
typename ObjectOps::Target target
)
{
return Bound<ObjectOps>(bindable, target);
}
template <class ObjectOps>
inline Bound<ObjectOps> Bind(
const Managed<Object<ObjectOps> >& bindable,
typename ObjectOps::Target target
)
{
return Bound<ObjectOps>(bindable, target);
}
#endif
} // namespace oglplus
#endif // include guard
| 25.609589 | 81 | 0.740572 | [
"object"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.