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
65561835cc7963d47ab21762835e443aac3faaa7
16,388
cpp
C++
tests/2d_tests.cpp
wildmeshing/wildmeshing-toolkit
7f4c60e5a6d366d9c3850b720b42b610e10600c2
[ "MIT" ]
8
2021-12-10T08:26:45.000Z
2022-03-24T00:19:41.000Z
tests/2d_tests.cpp
wildmeshing/wildmeshing-toolkit
7f4c60e5a6d366d9c3850b720b42b610e10600c2
[ "MIT" ]
86
2021-12-03T01:46:30.000Z
2022-03-23T19:33:17.000Z
tests/2d_tests.cpp
wildmeshing/wildmeshing-toolkit
7f4c60e5a6d366d9c3850b720b42b610e10600c2
[ "MIT" ]
2
2021-11-26T08:29:38.000Z
2022-01-03T22:10:42.000Z
#include <wmtk/TriMesh.h> #include <igl/read_triangle_mesh.h> #include <stdlib.h> #include <catch2/catch.hpp> #include <iostream> #include "wmtk/ConcurrentTriMesh.h" using namespace wmtk; TEST_CASE("load mesh and create TriMesh", "[test_mesh_creation]") { TriMesh m; std::vector<std::array<size_t, 3>> tris = {{{0, 1, 2}}}; m.create_mesh(3, tris); REQUIRE(m.tri_capacity() == tris.size()); REQUIRE(m.vert_capacity() == 3); } TEST_CASE("test generate tuples with 1 triangle", "[test_tuple_generation]") { TriMesh m; std::vector<std::array<size_t, 3>> tris = {{{0, 1, 2}}}; m.create_mesh(3, tris); SECTION("test generation from vertics") { auto vertices_tuples = m.get_vertices(); REQUIRE(vertices_tuples.size() == 3); REQUIRE(vertices_tuples[0].vid(m) == 0); REQUIRE(vertices_tuples[1].vid(m) == 1); REQUIRE(vertices_tuples[2].vid(m) == 2); } SECTION("test generation from faces") { auto faces_tuples = m.get_faces(); REQUIRE(faces_tuples.size() == 1); // to test vid initialized correctly REQUIRE(faces_tuples[0].vid(m) == tris[0][0]); // // to test the fid is a triangle touching this vertex // std::vector<size_t> tris = m_vertex_connectivity[faces_tuples[0].vid(*this)].m_conn_tris; // REQUIRE(std::find(tris.begin(), tris.end(), faces_tuples[0].fid(*this)) != tris.end()); } SECTION("test generation from edges") { auto edges_tuples = m.get_edges(); REQUIRE(edges_tuples.size() == 3); } } TEST_CASE("test generate tuples with 2 triangle", "[test_tuple_generation]") { // v3 // / \ // /f1 \ // v2 -----v1 // \f0 / // \ / // v0 TriMesh m; std::vector<std::array<size_t, 3>> tris = {{{0, 1, 2}}, {{2, 1, 3}}}; m.create_mesh(4, tris); SECTION("test generation from vertics") { auto vertices_tuples = m.get_vertices(); REQUIRE(vertices_tuples.size() == 4); REQUIRE(vertices_tuples[0].vid(m) == 0); REQUIRE(vertices_tuples[1].vid(m) == 1); REQUIRE(vertices_tuples[2].vid(m) == 2); REQUIRE(vertices_tuples[3].vid(m) == 3); // test the faces are assigned correctly REQUIRE(vertices_tuples[1].fid(m) == 0); REQUIRE(vertices_tuples[2].fid(m) == 0); } SECTION("test generation from faces") { auto faces_tuples = m.get_faces(); REQUIRE(faces_tuples.size() == 2); // std::vector<size_t> conn_tris = // m_vertex_connectivity[faces_tuples[0].vid(*this)].m_conn_tris; // REQUIRE( // std::find(conn_tris.begin(), conn_tris.end(), faces_tuples[0].fid(*this)) != // conn_tris.end()); } SECTION("test generation from edges") { auto edges_tuples = m.get_edges(); REQUIRE(edges_tuples.size() == 5); REQUIRE(edges_tuples[0].fid(m) == 0); REQUIRE(edges_tuples[1].fid(m) == 0); REQUIRE(edges_tuples[2].fid(m) == 0); REQUIRE(edges_tuples[3].fid(m) == 1); REQUIRE(edges_tuples[4].fid(m) == 1); } } // for every quiry do a require TEST_CASE("random 10 switches on 2 traingles", "[tuple_operation]") { TriMesh m; std::vector<std::array<size_t, 3>> tris = {{{0, 1, 2}}, {{1, 2, 3}}}; m.create_mesh(4, tris); SECTION("test all tuples generated using vertices") { auto vertices_tuples = m.get_vertices(); for (int i = 0; i < vertices_tuples.size(); i++) { TriMesh::Tuple v_tuple = vertices_tuples[i]; for (int j = 0; j < 10; j++) { size_t test = rand() % 3; switch (test) { case 0: v_tuple = v_tuple.switch_vertex(m); case 1: v_tuple = v_tuple.switch_edge(m); case 2: v_tuple = v_tuple.switch_face(m).value_or(v_tuple); default:; } } REQUIRE(v_tuple.is_valid(m)); } } SECTION("test all tuples generated using edges") { auto edges_tuples = m.get_edges(); for (int i = 0; i < edges_tuples.size(); i++) { TriMesh::Tuple e_tuple = edges_tuples[i]; for (int j = 0; j < 10; j++) { size_t test = rand() % 3; switch (test) { case 0: e_tuple = e_tuple.switch_vertex(m); case 1: e_tuple = e_tuple.switch_edge(m); case 2: e_tuple = e_tuple.switch_face(m).value_or(e_tuple); default:; } } REQUIRE(e_tuple.is_valid(m)); } } SECTION("test all tuples generated using faces") { auto faces_tuples = m.get_faces(); for (int i = 0; i < faces_tuples.size(); i++) { TriMesh::Tuple f_tuple = faces_tuples[i]; for (int j = 0; j < 10; j++) { size_t test = rand() % 3; switch (test) { case 0: f_tuple = f_tuple.switch_vertex(m); case 1: f_tuple = f_tuple.switch_edge(m); case 2: f_tuple = f_tuple.switch_face(m).value_or(f_tuple); default:; } } REQUIRE(f_tuple.is_valid(m)); } } } TriMesh::Tuple double_switch_vertex(TriMesh::Tuple t, TriMesh& m) { TriMesh::Tuple t_after = t.switch_vertex(m); t_after = t_after.switch_vertex(m); return t_after; } TriMesh::Tuple double_switch_edge(TriMesh::Tuple t, TriMesh& m) { TriMesh::Tuple t_after = t.switch_edge(m); t_after = t_after.switch_edge(m); return t_after; } TriMesh::Tuple double_switch_face(TriMesh::Tuple t, TriMesh& m) { TriMesh::Tuple t_after = t.switch_face(m).value_or(t); t_after = t_after.switch_face(m).value_or(t); return t_after; } bool tuple_equal(const TriMesh& m, TriMesh::Tuple t1, TriMesh::Tuple t2) { return (t1.fid(m) == t2.fid(m)) && (t1.eid(m) == t2.eid(m)) && (t1.vid(m) == t2.vid(m)); } // checking for every tuple t: // (1) t.switch_vertex().switch_vertex() == t // (2) t.switch_edge().switch_edge() == t // (3) t.switch_tri().switch_tri() == t TEST_CASE("double switches is identity", "[tuple_operation]") { TriMesh m; std::vector<std::array<size_t, 3>> tris = {{{0, 1, 2}}, {{1, 2, 3}}}; m.create_mesh(4, tris); SECTION("test all tuples generated using vertices") { TriMesh::Tuple v_tuple_after; auto vertices_tuples = m.get_vertices(); for (int i = 0; i < vertices_tuples.size(); i++) { TriMesh::Tuple v_tuple = vertices_tuples[i]; v_tuple_after = double_switch_vertex(v_tuple, m); REQUIRE(tuple_equal(m, v_tuple_after, v_tuple)); v_tuple_after = double_switch_edge(v_tuple, m); REQUIRE(tuple_equal(m, v_tuple_after, v_tuple)); v_tuple_after = double_switch_face(v_tuple, m); REQUIRE(tuple_equal(m, v_tuple_after, v_tuple)); } } SECTION("test all tuples generated using edges") { TriMesh::Tuple e_tuple_after; auto edges_tuples = m.get_edges(); for (int i = 0; i < edges_tuples.size(); i++) { TriMesh::Tuple e_tuple = edges_tuples[i]; e_tuple_after = double_switch_vertex(e_tuple, m); REQUIRE(tuple_equal(m, e_tuple_after, e_tuple)); e_tuple_after = double_switch_edge(e_tuple, m); REQUIRE(tuple_equal(m, e_tuple_after, e_tuple)); e_tuple_after = double_switch_face(e_tuple, m); REQUIRE(tuple_equal(m, e_tuple_after, e_tuple)); } } SECTION("test all tuples generated using faces") { TriMesh::Tuple f_tuple_after; auto faces_tuples = m.get_faces(); for (int i = 0; i < faces_tuples.size(); i++) { TriMesh::Tuple f_tuple = faces_tuples[i]; f_tuple_after = double_switch_vertex(f_tuple, m); REQUIRE(tuple_equal(m, f_tuple_after, f_tuple)); f_tuple_after = double_switch_edge(f_tuple, m); REQUIRE(tuple_equal(m, f_tuple_after, f_tuple)); f_tuple_after = double_switch_face(f_tuple, m); REQUIRE(tuple_equal(m, f_tuple_after, f_tuple)); } } } // check for every t // t.switch_vertex().switchedge().switchvertex().switchedge().switchvertex().switchedge() == t TEST_CASE("vertex_edge switches equals indentity", "[tuple_operation]") { TriMesh m; std::vector<std::array<size_t, 3>> tris = {{{0, 1, 2}}, {{1, 2, 3}}}; m.create_mesh(4, tris); SECTION("test all tuples generated using vertices") { TriMesh::Tuple v_tuple_after; auto vertices_tuples = m.get_vertices(); for (int i = 0; i < vertices_tuples.size(); i++) { TriMesh::Tuple v_tuple = vertices_tuples[i]; v_tuple_after = v_tuple.switch_vertex(m); v_tuple_after = v_tuple_after.switch_edge(m); v_tuple_after = v_tuple_after.switch_vertex(m); v_tuple_after = v_tuple_after.switch_edge(m); v_tuple_after = v_tuple_after.switch_vertex(m); v_tuple_after = v_tuple_after.switch_edge(m); REQUIRE(tuple_equal(m, v_tuple, v_tuple_after)); } } SECTION("test all tuples generated using edges") { TriMesh::Tuple e_tuple_after; auto edges_tuples = m.get_edges(); for (int i = 0; i < edges_tuples.size(); i++) { TriMesh::Tuple e_tuple = edges_tuples[i]; e_tuple_after = e_tuple.switch_vertex(m); e_tuple_after = e_tuple_after.switch_edge(m); e_tuple_after = e_tuple_after.switch_vertex(m); e_tuple_after = e_tuple_after.switch_edge(m); e_tuple_after = e_tuple_after.switch_vertex(m); e_tuple_after = e_tuple_after.switch_edge(m); REQUIRE(tuple_equal(m, e_tuple, e_tuple_after)); } } SECTION("test all tuples generated using faces") { TriMesh::Tuple f_tuple_after; auto faces_tuples = m.get_faces(); for (int i = 0; i < faces_tuples.size(); i++) { TriMesh::Tuple f_tuple = faces_tuples[i]; f_tuple_after = f_tuple.switch_vertex(m); f_tuple_after = f_tuple_after.switch_edge(m); f_tuple_after = f_tuple_after.switch_vertex(m); f_tuple_after = f_tuple_after.switch_edge(m); f_tuple_after = f_tuple_after.switch_vertex(m); f_tuple_after = f_tuple_after.switch_edge(m); REQUIRE(tuple_equal(m, f_tuple, f_tuple_after)); } } } TEST_CASE("test_link_check", "[test_pre_check]") { TriMesh m; SECTION("extra_face_after_collapse") { std::vector<std::array<size_t, 3>> tris = {{{1, 2, 3}}, {{0, 1, 4}}, {{0, 2, 5}}, {{0, 1, 6}}, {{0, 2, 6}}, {{1, 2, 6}}}; m.create_mesh(7, tris); TriMesh::Tuple edge(1, 2, 0, m); REQUIRE_FALSE(m.check_link_condition(edge)); } SECTION("one_triangle") { std::vector<std::array<size_t, 3>> tris = {{{0, 1, 2}}}; m.create_mesh(3, tris); TriMesh::Tuple edge(0, 2, 0, m); assert(edge.is_valid(m)); REQUIRE_FALSE(m.check_link_condition(edge)); } SECTION("one_tet") { std::vector<std::array<size_t, 3>> tris = { {{0, 1, 2}}, {{1, 3, 2}}, {{0, 2, 3}}, {{3, 0, 1}}}; m.create_mesh(4, tris); TriMesh::Tuple edge(1, 0, 0, m); assert(edge.is_valid(m)); REQUIRE_FALSE(m.check_link_condition(edge)); } SECTION("non_manifold_after_collapse") { std::vector<std::array<size_t, 3>> tris = { {{0, 1, 5}}, {{1, 2, 5}}, {{2, 3, 5}}, {{5, 3, 4}}}; m.create_mesh(6, tris); TriMesh::Tuple fail_edge(5, 0, 1, m); REQUIRE_FALSE(m.check_link_condition(fail_edge)); TriMesh::Tuple pass_edge(0, 2, 0, m); REQUIRE(m.check_link_condition(pass_edge)); } } // test manifold (eid uniqueness) TEST_CASE("test unique edge", "[test_2d_operation]") { std::vector<std::array<size_t, 3>> tris = {{{0, 1, 2}}, {{1, 3, 2}}, {{4, 1, 0}}, {{0, 2, 5}}}; auto m = TriMesh(); m.create_mesh(6, tris); REQUIRE(m.check_edge_manifold()); } TEST_CASE("edge_collapse", "[test_2d_operation]") { std::vector<std::array<size_t, 3>> tris = {{{0, 1, 2}}, {{1, 3, 2}}, {{4, 1, 0}}, {{0, 2, 5}}}; SECTION("rollback") { class NoCollapseMesh : public TriMesh { bool collapse_edge_before(const TriMesh::Tuple& loc) override { return true; }; bool collapse_edge_after(const TriMesh::Tuple& loc) override { return false; }; }; auto m = NoCollapseMesh(); m.create_mesh(6, tris); const auto tuple = NoCollapseMesh::Tuple(1, 0, 0, m); REQUIRE(tuple.is_valid(m)); std::vector<TriMesh::Tuple> dummy; REQUIRE_FALSE(m.collapse_edge(tuple, dummy)); REQUIRE(tuple.is_valid(m)); } SECTION("collapse") { class Collapse : public TriMesh { bool collapse_edge_before(const TriMesh::Tuple& loc) override { return true; }; bool collapse_edge_after(const TriMesh::Tuple& loc) override { return true; }; }; auto m = Collapse(); m.create_mesh(6, tris); const auto tuple = Collapse::Tuple(1, 0, 0, m); REQUIRE(tuple.is_valid(m)); std::vector<TriMesh::Tuple> dummy; REQUIRE(m.collapse_edge(tuple, dummy)); // fail at check manifold REQUIRE_FALSE(tuple.is_valid(m)); } } TEST_CASE("swap_operation", "[test_2d_operation]") { const std::string root(WMT_DATA_DIR); const std::string path = root + "/fan.obj"; Eigen::MatrixXd V; Eigen::MatrixXi F; bool ok = igl::read_triangle_mesh(path, V, F); REQUIRE(ok); std::vector<std::array<size_t, 3>> tri(F.rows()); for (int i = 0; i < F.rows(); i++) { for (int j = 0; j < 3; j++) tri[i][j] = (size_t)F(i, j); } TriMesh m; m.create_mesh(V.rows(), tri); SECTION("swap") { TriMesh::Tuple swap_e = TriMesh::Tuple(1, 0, 0, m); REQUIRE(swap_e.is_valid(m)); std::vector<TriMesh::Tuple> new_e; REQUIRE(m.swap_edge(swap_e, new_e)); REQUIRE_FALSE(swap_e.is_valid(m)); REQUIRE(new_e.front().is_valid(m)); REQUIRE(m.vert_capacity() == 8); REQUIRE(m.tri_capacity() == 8); std::vector<size_t> m_indices; for (auto edge : m.get_one_ring_edges_for_vertex(new_e.front())) { m_indices.push_back(edge.vid(m)); } vector_unique(m_indices); std::vector<size_t> tru_indices = {1, 3, 4, 5}; REQUIRE(std::equal(m_indices.begin(), m_indices.end(), tru_indices.begin())); } SECTION("swap_on_boundary_edge") { TriMesh::Tuple swap_e = TriMesh::Tuple(0, 2, 0, m); REQUIRE(swap_e.is_valid(m)); std::vector<TriMesh::Tuple> dummy; REQUIRE_FALSE(m.swap_edge(swap_e, dummy)); } SECTION("swap_on_connected_vertices") { TriMesh m2; std::vector<std::array<size_t, 3>> tris = {{{0, 1, 2}}, {{1, 0, 3}}, {{1, 3, 2}}}; m2.create_mesh(4, tris); TriMesh::Tuple edge(0, 2, 0, m); assert(edge.is_valid(m)); std::vector<TriMesh::Tuple> dummy; REQUIRE_FALSE(m.swap_edge(edge, dummy)); } } TEST_CASE("split_operation", "[test_2d_operation]") { TriMesh m; SECTION("1_tri_split") { std::vector<std::array<size_t, 3>> tris = {{{0, 1, 2}}}; m.create_mesh(3, tris); auto edges = m.get_edges(); TriMesh::Tuple edge(0, 1, 0, m); std::vector<TriMesh::Tuple> dummy; assert(edge.is_valid(m)); REQUIRE(m.split_edge(edge, dummy)); REQUIRE_FALSE(edges[0].is_valid(m)); } SECTION("2_tris_split") { std::vector<std::array<size_t, 3>> tris = {{{0, 1, 2}}, {{1, 3, 2}}}; m.create_mesh(4, tris); auto edges = m.get_edges(); TriMesh::Tuple edge(1, 0, 0, m); std::vector<TriMesh::Tuple> dummy; assert(edge.is_valid(m)); REQUIRE(m.split_edge(edge, dummy)); for (auto e : edges) REQUIRE_FALSE(e.is_valid(m)); } }
34
100
0.571333
[ "mesh", "vector" ]
655827bfb4b2d376d4c56a0555f9aeb524c6db3c
2,724
cpp
C++
source/menu.cpp
duylee/duy
b803278fdd553b2d8bcabebd085a60d018f9f8d8
[ "MIT" ]
9
2016-03-07T10:36:24.000Z
2017-04-12T14:27:32.000Z
source/menu.cpp
duylee/duy
b803278fdd553b2d8bcabebd085a60d018f9f8d8
[ "MIT" ]
1
2016-04-11T10:58:21.000Z
2016-04-13T03:43:17.000Z
source/menu.cpp
duylee/duy
b803278fdd553b2d8bcabebd085a60d018f9f8d8
[ "MIT" ]
6
2016-03-07T10:38:50.000Z
2021-11-27T14:43:05.000Z
#include "menu.h" #include "d3d.h" #include "memory.h" Menu::Menu() { this->width_ = 190; } Menu::~Menu() { } void Menu::AddItem(int32_t *status, char item_description[32], char *status_description[], int32_t num_status_descriptions) { // better not look at this code this->items_[this->num_items_].status = status; this->items_[this->num_items_].num_status_descriptions = num_status_descriptions; junkasm strcpy_s(this->items_[this->num_items_].item_description, item_description); for (int32_t i = 0; i < num_status_descriptions; i++) { junkasm memcpy_s(reinterpret_cast<void*>(this->items_[this->num_items_].status_description + i * 16), 16, reinterpret_cast<void*>(status_description[i]), 16); } this->num_items_++; this->height_ = this->num_items_ * 20 + 30; } void Menu::Render(LPDIRECT3DDEVICE9 device) { // if menu is hidden, simply don't draw it if (this->hidden_) return; if (this->font_) { this->font_->Release(); this->font_ = nullptr; } if (!this->font_) D3DXCreateFont(device, 15, 0, FW_BOLD, 0, FALSE, DEFAULT_CHARSET, OUT_DEFAULT_PRECIS, ANTIALIASED_QUALITY, DEFAULT_PITCH | FF_DONTCARE, L"Arial", &this->font_); DrawBox(10, 10, this->width_, this->height_, 0xC0000000, COLOR_RED, device); DrawBorder(10, 10, this->width_, 25, 1, COLOR_RED, device); WriteText(90, 15, COLOR_YELLOW, "Biesi's Public Hack", DT_CENTER, this->font_); junkasm for (int32_t i = 0; i < this->num_items_; i++) { DWORD color = COLOR_WHITE; if (i == this->current_index_) color = COLOR_YELLOW; WriteText(20, 40 + i * 20, color, this->items_[i].item_description, DT_LEFT, this->font_); junkasm // this is pure magic char* status_desc = reinterpret_cast<char*>(this->items_[i].status_description + *this->items_[i].status * 16); WriteText(this->width_, 40 + i * 20, color, status_desc, DT_RIGHT, this->font_); } } void Menu::Navigate() { junkasm if (GetAsyncKeyState(VK_INSERT) & 1) this->hidden_ = !this->hidden_; // arrow down if (GetAsyncKeyState(VK_DOWN) & 1) { // fancy calculation of next element this->current_index_ = (this->current_index_ + 1) % this->num_items_; } // arrow up if (GetAsyncKeyState(VK_UP) & 1) { if (this->current_index_ > 0) this->current_index_ -= 1; else this->current_index_ = this->num_items_ - 1; } junkasm // arrow right if (GetAsyncKeyState(VK_RIGHT) & 1) { if (*this->items_[this->current_index_].status < this->items_[this->current_index_].num_status_descriptions - 1) *this->items_[this->current_index_].status += 1; } // arrow left if (GetAsyncKeyState(VK_LEFT) & 1) { junkasm if (*this->items_[this->current_index_].status > 0) *this->items_[this->current_index_].status -= 1; } }
25.942857
162
0.694934
[ "render" ]
6558324a271a1e19175c7573c64a0dc7b8a76275
717
cpp
C++
LeetCode/InterviewSchool/179. Largest Number.cpp
Sowmik23/All-Codes
212ef0d940fa84624bb2972a257768a830a709a3
[ "MIT" ]
5
2021-02-14T17:48:21.000Z
2022-01-24T14:29:44.000Z
LeetCode/InterviewSchool/179. Largest Number.cpp
Sowmik23/All-Codes
212ef0d940fa84624bb2972a257768a830a709a3
[ "MIT" ]
null
null
null
LeetCode/InterviewSchool/179. Largest Number.cpp
Sowmik23/All-Codes
212ef0d940fa84624bb2972a257768a830a709a3
[ "MIT" ]
null
null
null
class Solution { public: string largestNumber(vector<int>& nums) { vector<string> str; for(auto i: nums){ str.push_back(to_string(i)); } //sort(str.begin(), str.end(), compare); sort(str.begin(),str.end(), [](string &s1, string &s2){ return s1+s2>s2+s1; }); //sort(begin(str), end(str), [](string &s1, string &s2){ return s1+s2>s2+s1; }); // for(auto i: str) cout<<i<<" "; string res = ""; for(auto i: str) res+=i; if(res[0]=='0') return "0"; return res; } private: static bool compare(string a, string b){ return a+b>b+a; } };
23.9
88
0.46304
[ "vector" ]
655aa3664ad3acce3c41046cb27003911ed0adf8
3,622
hpp
C++
OpenSimRoot/src/modules/Soil/Swms3d.hpp
nb-e/OpenRootSim
aaa1cd18e94ebf613c28737842401daba3b8d5ef
[ "BSD-3-Clause" ]
1
2021-08-03T00:52:58.000Z
2021-08-03T00:52:58.000Z
OpenSimRoot/src/modules/Soil/Swms3d.hpp
nb-e/OpenRootSim
aaa1cd18e94ebf613c28737842401daba3b8d5ef
[ "BSD-3-Clause" ]
null
null
null
OpenSimRoot/src/modules/Soil/Swms3d.hpp
nb-e/OpenRootSim
aaa1cd18e94ebf613c28737842401daba3b8d5ef
[ "BSD-3-Clause" ]
1
2021-08-03T00:52:59.000Z
2021-08-03T00:52:59.000Z
/* Copyright © 2016 Forschungszentrum Jülich GmbH All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted under the GNU General Public License v3 and provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. Disclaimer 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. You should have received the GNU GENERAL PUBLIC LICENSE v3 with this file in license.txt but can also be found at http://www.gnu.org/licenses/gpl-3.0.en.html NOTE: The GPL.v3 license requires that all derivative work is distributed under the same license. That means that if you use this source code in any other program, you can only distribute that program with the full source code included and licensed under a GPL license. */ #ifndef SWMS3D_HPP_ #define SWMS3D_HPP_ #include "Output.hpp" #include "Solute.hpp" #include "Watflow.hpp" //todo: to behave nicely, this should have been declared as an integration class. //todo: now dt for water and nutrients are coupled class Swms3d: public DerivativeBase { public: Swms3d(SimulaDynamic* const pSD); ~Swms3d(){ // close Output Files if(outputVTK){ delete outputVTK; outputVTK=nullptr; } delete water; for(auto it:solute) delete it; } static void terminate(){ if(outputVTK) { delete outputVTK; outputVTK=nullptr; } }; void calculate(const Time &time, double &dt); std::string getName()const; void addObject(SimulaBase *rootNode); static Watflow* getWaterPointer() {return primaryWater_;} protected: static std::deque<SimulaBase *> rootNodeQueue_; private: void initialize_(); void getTimeStepSWMS(double & deltaT, const int& Iter,const double& tPrint,const double& tAtm,const double& lastTime,const double& dtMaxC); static Watflow* primaryWater_; Watflow *water; double dt; std::vector<Solute *> solute; //all the solute models static OutputSoilVTK *outputVTK; tIndex ItCum; std::size_t Iter; std::size_t TLevel; std::size_t PLevel; double cumMineralisation; double dtOpt; double dtOld; double tOld; double tAtm; std::size_t MaxIt; Time TPrint, pdt; bool printVTU; }; class GetValuesFromSWMS:public DerivativeBase{ public: GetValuesFromSWMS(SimulaDynamic* pSD); std::string getName()const; protected: void calculate(const Time &t,double &var); SimulaBase *link; }; #endif
35.861386
756
0.765047
[ "vector" ]
655c73b802de9843c5d46aa9170d9d654d5da473
5,329
cpp
C++
solutions-CODEUP/100000621-02.cpp
Ki-Seki/solutions
e4329712d664180d850e0a48d7d0f637215f13d0
[ "MIT" ]
1
2022-02-26T10:33:24.000Z
2022-02-26T10:33:24.000Z
solutions-CODEUP/100000621-02.cpp
Ki-Seki/solutions
e4329712d664180d850e0a48d7d0f637215f13d0
[ "MIT" ]
null
null
null
solutions-CODEUP/100000621-02.cpp
Ki-Seki/solutions
e4329712d664180d850e0a48d7d0f637215f13d0
[ "MIT" ]
1
2021-12-01T14:54:33.000Z
2021-12-01T14:54:33.000Z
/* * hint: * 本题使用了两种方法: * 1. 硬核模拟:优先队列 + 快速幂 + 迪杰斯特拉算法。由于每条路径的幂指数都是不同的,所以用一个队列保存路径上所有的指数。 * 2. 逻辑上的简化:并查集 + 迪杰斯特拉算法。每条路径长度指数式增长,因此先出现的一定是最小的。 */ // 方法一 #include <cstdio> #include <algorithm> #include <queue> #include <vector> #include <cstring> #define MAXN 105 #define MOD 100000 struct cmp { bool operator ()(int a, int b) { return a < b; } }; // use queue to store path length // eg. queue [4, 2, 1] is (2 ^ 4 + 2 ^ 2 + 2 ^ 1) = 22 // esp. [] means INF, [-1] means 0 typedef std::priority_queue<int, std::vector<int>, cmp> Exps; // while implementing fast power algorithm, // some intermediaries should be long long type typedef long long LL; int n, m; Exps graph[MAXN][MAXN]; bool is_visited[MAXN] = {}; Exps dist[MAXN]; void clear(Exps* start, Exps* end) { while (start < end) { while (start->size()) start->pop(); start++; } } bool operator < (Exps a, Exps b) { if (!a.empty() && b.empty()) return true; else if (!a.empty() && !b.empty()) { while (a.size() && b.size()) { if (a.top() < b.top()) return true; else if (a.top() > b.top()) return false; a.pop(); b.pop(); } if (a.size() && a.top()) return true; } return false; } Exps operator + (Exps &a, Exps &b) { Exps sum = a; while (b.size()) { sum.push(b.top()); b.pop(); } return sum; } // start from 0 void dijkstra() { // init dist[0].push(-1); // n loops for (int i = 0; i < n; i++) { // find unvisited u with min dist between 0 and u int u = -1; Exps min; for (int j = 0; j < n; j++) if (dist[j] < min && is_visited[j] == false) { u = j; min = dist[j]; } // end if (u == -1) break; // mark u as visited is_visited[u] = true; // update u's neighbors for (int j = 0; j < n; j++) if (!graph[u][j].empty() && !is_visited[j]) { Exps tmp = dist[u] + graph[u][j]; if (tmp < dist[j]) dist[j] = tmp; } } } // return n ^ m % p int fast_power(int n, int m, int p) { if (m == 0) return 1; n %= p; if (m & 1) return n * fast_power(n, m-1, p) % p; else { LL tmp = fast_power(n, m/2, p) % p; return tmp * tmp % p; } } int cal(Exps &a) { if (a.empty()) return -1; LL ans = 0; while (a.size()) { if (a.top() != -1) ans = (ans + fast_power(2, a.top(), MOD)) % MOD; a.pop(); } return ans; } int main() { while (scanf("%d %d", &n, &m) != EOF) { // init clear(graph[0], graph[0] + MAXN * MAXN); memset(is_visited, false, sizeof(is_visited)); clear(dist, dist + MAXN); // input for (int i = 0; i < m; i++) { int city1, city2; scanf("%d %d", &city1, &city2); graph[city1][city2].push(i); graph[city2][city1].push(i); } // dijkstra dijkstra(); // output for (int i = 1; i < n; i++) printf("%d\n", cal(dist[i])); } return 0; } // // 方法二: // // 版权声明:本文为CSDN博主「weixin_43886377」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。 // // 原文链接:https://blog.csdn.net/weixin_43886377/article/details/104361142 // #include <iostream> // #include<bits/stdc++.h> // using namespace std; // int g[101][101]; // bool visit[101]; // int father[101],d[101]; // int n; // int INF=0x3fffffff; // int f(int k) // { // int s=1; // for(int i=1; i<=k; i++) // { // s=(s*2)%100000; // } // return s; // } // void dij(int s) // { // int i,j; // fill(visit,visit+101,false); // fill(d,d+101,INF); // for(i=0; i<n; i++) // { // d[i]=g[s][i]; // } // d[s]=0; // visit[s]=true; // for(i=1; i<n; i++) // { // int Min=INF; // int u=-1; // for(j=0; j<n; j++) // { // if(visit[j]==false&&d[j]<Min) // { // Min=d[j]; // u=j; // } // } // if(u==-1)return; // visit[u]=true; // for(j=0; j<n; j++) // { // if(visit[j]==false&&g[u][j]+d[u]<d[j]) // d[j]=d[u]+g[u][j]; // } // } // } // int findFather(int x) // { // while(x!=father[x]) // x=father[x]; // return x; // } // int main() // { // int m,i,a,b; // while(scanf("%d %d",&n,&m)!=EOF) // { // for(i=0; i<n; i++)father[i]=i; // fill(g[0],g[0]+101*101,INF); // for(i=0; i<m; i++) // { // scanf("%d %d",&a,&b); // int fatherA=findFather(a); // int fatherB=findFather(b); // if(fatherA!=fatherB) // { // father[fatherA]=fatherB; // g[a][b]=g[b][a]=f(i); // } // else continue; // } // dij(0); // for(i=1; i<n; i++) // { // if(d[i]==INF)printf("-1\n"); // else printf("%d\n",d[i]%100000); // } // } // return 0; // }
21.487903
78
0.42128
[ "vector" ]
655cfaf4b9a422e32f1a7cb527b7de47eafe20a5
1,517
cpp
C++
Compiler.cpp
FatalEagle/Crowbot
33157e68bc126745693678a556c74c1634ea66a0
[ "Apache-2.0" ]
1
2017-04-08T04:22:49.000Z
2017-04-08T04:22:49.000Z
Compiler.cpp
FatalEagle/Crowbot
33157e68bc126745693678a556c74c1634ea66a0
[ "Apache-2.0" ]
null
null
null
Compiler.cpp
FatalEagle/Crowbot
33157e68bc126745693678a556c74c1634ea66a0
[ "Apache-2.0" ]
null
null
null
#include "resource.h" #define SHOW_TOKENS std::function<void()> Compiler::compile(Lexxer lexxer, Robot *robot) { if(lexxer.getNextToken()=="__BEGIN") { #ifdef SHOW_TOKENS printf("<Token: [__BEGIN]>\n"); #endif std::vector<std::function<void()>> lines; std::string tok; while(tok!="__END") { tok=lexxer.getNextToken(); #ifdef SHOW_TOKENS printf("<Token: [%s]>\n", tok.c_str()); #endif if(tok=="__FUNC") { tok=lexxer.getNextToken(); #ifdef SHOW_TOKENS printf("<Function Token: [%s]>\n", tok.c_str()); #endif lines.push_back([robot, tok]() { robot->executeFunction(tok); } ); } else if(tok=="output") { tok=lexxer.getNextToken(); #ifdef SHOW_TOKENS printf("<Output Token: [%s]>\n", tok.c_str()); #endif lines.push_back([tok]() { std::cout<<tok; } ); } } return [lines]() { for(auto it : lines) { it(); } }; } return [](){}; }
27.581818
68
0.355966
[ "vector" ]
6569ddc7acab8ca19258a22826562f41792d63b4
15,311
cpp
C++
dialog.cpp
NixonSiagian/samp-client
7a10dfeddc806e199688c645b12f3bf37eaa4f61
[ "FSFAP" ]
null
null
null
dialog.cpp
NixonSiagian/samp-client
7a10dfeddc806e199688c645b12f3bf37eaa4f61
[ "FSFAP" ]
null
null
null
dialog.cpp
NixonSiagian/samp-client
7a10dfeddc806e199688c645b12f3bf37eaa4f61
[ "FSFAP" ]
null
null
null
#include "main.h" #include "game/game.h" #include "net/netgame.h" #include "gui/gui.h" #include "dialog.h" #include "vendor/imgui/imgui_internal.h" #include "keyboard.h" #include "gui/util.h" extern CGUI *pGUI; extern CGame *pGame; extern CNetGame *pNetGame; extern CKeyBoard *pKeyBoard; char szCDialogInputBuffer[100]; char utf8CDialogInputBuffer[100*3]; CDialogWindow::CDialogWindow() { m_bIsActive = false; m_putf8Info = nullptr; m_pszInfo = nullptr; } void CDialogWindow::Show(bool bShow) { if(pGame) pGame->FindPlayerPed()->TogglePlayerControllable(!bShow); m_bIsActive = bShow; } void DialogWindowInputHandler(const char* str) { if(!str || *str == '\0') return; strcpy(szCDialogInputBuffer, str); cp1251_to_utf8(utf8CDialogInputBuffer, str); } void CDialogWindow::Clear() { if(m_putf8Info) { free(m_putf8Info); m_putf8Info = nullptr; } if(m_pszInfo) { free(m_pszInfo); m_pszInfo = nullptr; } m_bIsActive = false; m_byteDialogStyle = 0; m_wDialogID = -1; m_utf8Title[0] = 0; m_utf8Button1[0] = 0; m_utf8Button2[0] = 0; memset(szCDialogInputBuffer, 0, 100); memset(utf8CDialogInputBuffer, 0, 100*3); } void CDialogWindow::SetInfo(char* szInfo, int length) { if(!szInfo || !length) return; if(m_putf8Info) { free(m_putf8Info); m_putf8Info = nullptr; } if(m_pszInfo) { free(m_pszInfo); m_pszInfo = nullptr; } m_putf8Info = (char*)malloc((length * 3) + 1); if(!m_putf8Info) return; m_pszInfo = (char*)malloc((length * 3) + 1); if(!m_pszInfo) return; cp1251_to_utf8(m_putf8Info, szInfo); // ========= char szNonColorEmbeddedMsg[4200]; int iNonColorEmbeddedMsgLen = 0; for (size_t pos = 0; pos < strlen(szInfo) && szInfo[pos] != '\0'; pos++) { if(pos+7 < strlen(szInfo)) { if (szInfo[pos] == '{' && szInfo[pos+7] == '}') { pos += 7; continue; } } szNonColorEmbeddedMsg[iNonColorEmbeddedMsgLen] = szInfo[pos]; iNonColorEmbeddedMsgLen++; } szNonColorEmbeddedMsg[iNonColorEmbeddedMsgLen] = 0; // ======== cp1251_to_utf8(m_pszInfo, szNonColorEmbeddedMsg); } bool CDialogWindow::IsDialogList() { if(m_bIsActive) { if(m_byteDialogStyle == DIALOG_STYLE_LIST || m_byteDialogStyle == DIALOG_STYLE_TABLIST || m_byteDialogStyle == DIALOG_STYLE_TABLIST_HEADERS) return true; } return false; } void dialogKeyboardEvent(const char* str) { if(!str || *str == '\0') return; strcpy(szCDialogInputBuffer, str); cp1251_to_utf8(utf8CDialogInputBuffer, str); } void CDialogWindow::Draw() { if(m_bIsActive) { if(m_byteDialogStyle == DIALOG_STYLE_MSGBOX || m_byteDialogStyle == DIALOG_STYLE_INPUT || m_byteDialogStyle == DIALOG_STYLE_PASSWORD) { DrawDefault(); } else { DrawList(); } } } void CDialogWindow::DrawList() { std::string strUtf8 = m_putf8Info; int size = strUtf8.length(); int iTabsCount = 0; std::vector<std::string> vLines; std::vector<std::string> firstTabs; ImVec2 fTabSize[4]; int tmplineid; std::stringstream ssLine(strUtf8); std::string tmpLine; while(std::getline(ssLine, tmpLine, '\n')) { if(tmpLine[0] != 0) { vLines.push_back(tmpLine); int tmpTabId = 0; if(m_byteDialogStyle != DIALOG_STYLE_LIST) { std::stringstream ssTabLine(tmpLine); std::string tmpTabLine; while(std::getline(ssTabLine, tmpTabLine, '\t')) { if(tmpTabId > 4) continue; //if(vLines.size() == 1 && iTabsCount <= 4) if(tmpTabId >= iTabsCount && iTabsCount <= 4) iTabsCount++; //0 >= 0 = 1 //1 >= 1 = 2 // ImVec2 tabSize; tabSize = CalcTextSizeWithoutTags((char*)tmpTabLine.c_str()); if(tmpTabId == 0) firstTabs.push_back(removeColorTags(tmpTabLine)); if(tabSize.x > fTabSize[tmpTabId].x) fTabSize[tmpTabId].x = tabSize.x; tmpTabId++; } } else { ImVec2 tabSize; tabSize = CalcTextSizeWithoutTags((char*)tmpLine.c_str()); if(tmpTabId == 0) firstTabs.push_back(removeColorTags(tmpLine)); if(tabSize.x > fTabSize[tmpTabId].x) fTabSize[tmpTabId].x = tabSize.x; } tmplineid++; } } float buttonFactor = pGUI->ScaleX(187.5f) * 2 + pGUI->GetFontSize(); ImVec2 vecWinSize; if(m_byteDialogStyle != DIALOG_STYLE_LIST) { for(uint8_t i = 0; i < iTabsCount; i++) vecWinSize.x += fTabSize[i].x * (i == iTabsCount - 1 ? 1.25 : 1.5); } else vecWinSize.x += fTabSize[0].x * 1.25; if(buttonFactor > vecWinSize.x) { vecWinSize.x = 0.0f; if(m_byteDialogStyle != DIALOG_STYLE_LIST) { buttonFactor /= iTabsCount; for(uint8_t i = 0; i < iTabsCount; i++) vecWinSize.x += fTabSize[i].x + buttonFactor; } else vecWinSize.x += fTabSize[0].x + buttonFactor; } else buttonFactor = 0; vecWinSize.x += 93.5f; vecWinSize.y = 720; ImGuiStyle style; ImGuiIO &io = ImGui::GetIO(); ImGui::Begin("###tablist", nullptr, ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoDecoration | ImGuiWindowFlags_NoMove); ImVec2 cursor = ImGui::GetCursorScreenPos(); cursor.x -= 32; cursor.y -= 3; ImGui::GetWindowDrawList()->AddRectFilled(cursor, ImVec2(cursor.x + ImGui::GetWindowWidth() + 32, cursor.y + ImGui::GetFontSize() + 5 + 3), ImColor(ImVec4(0.0f, 0.0f, 0.0f, 1.0f))); TextWithColors(m_utf8Title); ImGui::SetCursorPosY(ImGui::GetCursorPosY() + 5); ImGui::ItemSize(ImVec2(0, pGUI->GetFontSize() / 2 + 2.75f)); ImVec2 cursonPosition; cursonPosition = ImGui::GetCursorPos(); if(m_byteDialogStyle == DIALOG_STYLE_TABLIST_HEADERS) { style.Colors[ImGuiCol_ChildBg] = ImGui::GetStyle().Colors[ImGuiCol_ChildBg]; ImGui::GetStyle().Colors[ImGuiCol_ChildBg] = ImVec4(0.0f, 0.0f, 0.0f, 0.0f); ImGui::BeginChild("###headers", ImVec2(-1, pGUI->GetFontSize()), false); ImGui::Columns(iTabsCount, "###tablistHeader", false); for(uint16_t i = 0; i < iTabsCount; i++) { ImGui::SetColumnWidth(-1, fTabSize[i].x * (i == iTabsCount - 1 ? 1.25 : 1.5) + buttonFactor); ImGui::NextColumn(); } std::stringstream ssTabLine(vLines[0]); std::string tmpTabLine; int tmpTabId = 0; while(std::getline(ssTabLine, tmpTabLine, '\t')) { if(tmpTabId > iTabsCount) continue; tmpTabLine.insert(0, "{a9c4e4}"); if(tmpTabId == 0) { cursonPosition = ImGui::GetCursorPos(); ImGui::SetCursorPosX(cursonPosition.x + pGUI->GetFontSize() / 3); } TextWithColors(tmpTabLine.c_str()); ImGui::NextColumn(); tmpTabId++; } ImGui::Columns(1); ImGui::EndChild(); ImGui::GetStyle().Colors[ImGuiCol_ChildBg] = style.Colors[ImGuiCol_ChildBg]; } ImGui::BeginChild("###tablist", ImVec2(-1, pGUI->ScaleY(vecWinSize.y)-pGUI->ScaleY(95.0f*2)), false, ImGuiWindowFlags_NoScrollbar); if(m_byteDialogStyle != DIALOG_STYLE_LIST) { ImGui::Columns(iTabsCount, "###tablistColumn", false); for(uint16_t i = 0; i < iTabsCount; i++) { ImGui::SetColumnWidth(-1, fTabSize[i].x * (i == iTabsCount - 1 ? 1.25 : 1.5) + buttonFactor); ImGui::NextColumn(); } } for(uint32_t line = m_byteDialogStyle == DIALOG_STYLE_TABLIST_HEADERS ? 1 : 0; line < vLines.size(); line++) { std::stringstream ssTabLine(vLines[line]); std::string tmpTabLine; int tmpTabId = 0; ImVec2 differentOffsets; if(tmpTabId == 0) { ImGui::PushID(tmpTabId+line); std::stringstream ss; ss << line+tmpTabId; std::string s = ss.str(); std::string itemid = "##" + s; bool is_selected = (m_iSelectedItem == line); cursonPosition = ImGui::GetCursorPos(); if(ImGui::Selectable(itemid.c_str(), is_selected, ImGuiSelectableFlags_SpanAllColumns | ImGuiSelectableFlags_AllowDoubleClick)) { if(ImGui::IsMouseDoubleClicked(0)) { Show(false); if(pNetGame) { if(m_byteDialogStyle == DIALOG_STYLE_TABLIST_HEADERS) m_iSelectedItem--; pNetGame->SendDialogResponse(m_wDialogID, 1, m_iSelectedItem, (char*)firstTabs[m_iSelectedItem].c_str()); } } } if(ImGui::IsItemHovered()) m_iSelectedItem = line; ss.clear(); ss << line + tmpTabId + 1; s = ss.str(); itemid = "##" + s; if(ImGui::Selectable(itemid.c_str(), is_selected, ImGuiSelectableFlags_SpanAllColumns | ImGuiSelectableFlags_AllowDoubleClick)) { if(ImGui::IsMouseDoubleClicked(0)) { Show(false); if(pNetGame) { if(m_byteDialogStyle == DIALOG_STYLE_TABLIST_HEADERS) m_iSelectedItem--; pNetGame->SendDialogResponse(m_wDialogID, 1, m_iSelectedItem, (char*)firstTabs[m_iSelectedItem].c_str()); } } } if(ImGui::IsItemHovered()) m_iSelectedItem = line; ImVec2 cursonPositionLast; cursonPositionLast = ImGui::GetCursorPos(); differentOffsets.x = cursonPositionLast.x - cursonPosition.x; differentOffsets.y = cursonPositionLast.y - cursonPosition.y; if(is_selected) ImGui::SetItemDefaultFocus(); if(m_byteDialogStyle != DIALOG_STYLE_LIST) ImGui::SameLine(); } if(m_byteDialogStyle != DIALOG_STYLE_LIST) { while(std::getline(ssTabLine, tmpTabLine, '\t')) { if(tmpTabId > iTabsCount) continue; ImVec2 cursonPos; cursonPos = ImGui::GetCursorPos(); if(tmpTabId == 0) { if(line == m_iSelectedItem) m_strSelectedItemText = tmpTabLine; ImGui::SetCursorPos(ImVec2(cursonPos.x, cursonPos.y - differentOffsets.y / 4)); } else ImGui::SetCursorPos(ImVec2(cursonPos.x, cursonPos.y + differentOffsets.y / 4)); tmpTabLine.insert(0, "{ffffff}"); TextWithColors((char*)tmpTabLine.c_str()); ImGui::SetCursorPos(ImVec2(cursonPos.x, cursonPos.y + differentOffsets.y / 2)); if(m_byteDialogStyle != DIALOG_STYLE_LIST) ImGui::NextColumn(); tmpTabId++; } while(tmpTabId < iTabsCount) { TextWithColors("{ffffff}"); ImGui::NextColumn(); tmpTabId++; } } else { ImVec2 cursonPos; cursonPos = ImGui::GetCursorPos(); if(line == m_iSelectedItem) m_strSelectedItemText = vLines[line]; ImGui::SetCursorPos(ImVec2(cursonPos.x+pGUI->GetFontSize(), cursonPos.y - differentOffsets.y + pGUI->GetFontSize() / 2)); vLines[line].insert(0, "{ffffff}"); TextWithColors((char*)vLines[line].c_str()); ImGui::SetCursorPos(ImVec2(cursonPos.x, cursonPos.y)); } } if(m_byteDialogStyle != DIALOG_STYLE_LIST) ImGui::Columns(1); ScrollWhenDraggingOnVoid(); ImGui::EndChild(); if(m_utf8Button1[0] != 0 && m_utf8Button2[0] != 0) ImGui::SetCursorPosX((ImGui::GetWindowWidth() - pGUI->ScaleX(417.0f) + ImGui::GetStyle().ItemSpacing.x + pGUI->GetFontSize()) / 2); else ImGui::SetCursorPosX((ImGui::GetWindowWidth() - pGUI->ScaleX(230.0f) + ImGui::GetStyle().ItemSpacing.x + pGUI->GetFontSize()) / 2); if(m_utf8Button1[0] != 0) { if(ImGui::Button(m_utf8Button1, ImVec2(pGUI->ScaleX(187.5f), pGUI->ScaleY(60.0f)))) { Show(false); if(pNetGame) { if(m_byteDialogStyle == DIALOG_STYLE_TABLIST_HEADERS) m_iSelectedItem--; pNetGame->SendDialogResponse(m_wDialogID, 1, m_iSelectedItem, (char*)firstTabs[m_iSelectedItem].c_str()); } } } if(m_utf8Button1[0] != 0 && m_utf8Button2[0] != 0) ImGui::SameLine(0, pGUI->GetFontSize()); if(m_utf8Button2[0] != 0) { if(ImGui::Button(m_utf8Button2, ImVec2(pGUI->ScaleX(187.5f), pGUI->ScaleY(60.0f)))) { Show(false); if(pNetGame) { if(firstTabs.size() <= m_iSelectedItem) { m_iSelectedItem = firstTabs.size(); m_iSelectedItem--; } pNetGame->SendDialogResponse(m_wDialogID, 0, m_iSelectedItem, (char*)firstTabs[m_iSelectedItem].c_str()); } } } ImGui::SetWindowSize(ImVec2(vecWinSize.x, pGUI->ScaleY(vecWinSize.y + m_byteDialogStyle == DIALOG_STYLE_TABLIST_HEADERS ? pGUI->ScaleY(187.5f) / 2 : 0))); ImVec2 winsize = ImGui::GetWindowSize(); ImGui::SetWindowPos(ImVec2(((io.DisplaySize.x - winsize.x) / 2), ((io.DisplaySize.y - winsize.y) / 2))); ImGui::End(); } void CDialogWindow::DrawDefault() { if(!m_bIsActive || !m_putf8Info) return; ImGuiIO &io = ImGui::GetIO(); ImGui::Begin("###dialogDefault", nullptr, ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoScrollbar); // title ImVec2 cursor = ImGui::GetCursorScreenPos(); cursor.x -= 32; cursor.y -= 3; ImGui::GetWindowDrawList()->AddRectFilled(cursor, ImVec2(cursor.x + ImGui::GetWindowWidth() + 32, cursor.y + ImGui::GetFontSize() + 5 + 3), ImColor(ImVec4(0.0f, 0.0f, 0.0f, 1.0f))); TextWithColors(m_utf8Title); ImGui::SetCursorPosY(ImGui::GetCursorPosY() + 5); ImGui::ItemSize(ImVec2(0, pGUI->GetFontSize() / 2 + 2.75f)); switch(m_byteDialogStyle) { case DIALOG_STYLE_MSGBOX: TextWithColors(m_putf8Info); ImGui::SetCursorPosX(ImGui::GetCursorPosX()+pGUI->GetFontSize()*1.5); ImGui::ItemSize(ImVec2(0, pGUI->GetFontSize() / 2)); break; case DIALOG_STYLE_INPUT: TextWithColors(m_putf8Info); ImGui::SetCursorPosX(ImGui::GetCursorPosX()+pGUI->GetFontSize()*1.5); ImGui::ItemSize(ImVec2(0, pGUI->GetFontSize() / 2)); ImGui::PushStyleVar(ImGuiStyleVar_ButtonTextAlign, ImVec2(0.0f, 0.5f)); if(ImGui::Button(utf8CDialogInputBuffer, ImVec2(pGUI->ScaleX(500 * 2), pGUI->ScaleY(35 * 2)))) { if(!pKeyBoard->IsOpen()) pKeyBoard->Open(&DialogWindowInputHandler, false); } ImGui::PopStyleVar(1); ImGui::ItemSize(ImVec2(0, pGUI->GetFontSize() / 2)); break; case DIALOG_STYLE_PASSWORD: TextWithColors(m_putf8Info); ImGui::SetCursorPosX(ImGui::GetCursorPosX()+pGUI->GetFontSize()*1.5); ImGui::ItemSize(ImVec2(0, pGUI->GetFontSize() / 2)); char _utf8CDialogInputBuffer[100*3+1]; strcpy(_utf8CDialogInputBuffer, utf8CDialogInputBuffer); for(int i = 0; i < strlen(_utf8CDialogInputBuffer); i++) { if(_utf8CDialogInputBuffer[i] == '\0') break; _utf8CDialogInputBuffer[i] = '*'; } ImGui::PushStyleVar(ImGuiStyleVar_ButtonTextAlign, ImVec2(0.0f, 0.5f)); if(ImGui::Button(_utf8CDialogInputBuffer, ImVec2(ImGui::CalcTextSize(m_pszInfo).x+pGUI->GetFontSize(), pGUI->ScaleY(70.0f)))) { if(!pKeyBoard->IsOpen()) pKeyBoard->Open(&DialogWindowInputHandler, true); } ImGui::PopStyleVar(1); ImGui::ItemSize(ImVec2(0, pGUI->GetFontSize() / 2)); break; } if(m_utf8Button1[0] != 0 && m_utf8Button2[0] != 0) ImGui::SetCursorPosX((ImGui::GetWindowWidth() - pGUI->ScaleX(417.0f) + ImGui::GetStyle().ItemSpacing.x + pGUI->GetFontSize()) / 2); else ImGui::SetCursorPosX((ImGui::GetWindowWidth() - pGUI->ScaleX(230.0f) + ImGui::GetStyle().ItemSpacing.x + pGUI->GetFontSize()) / 2); if(m_utf8Button1[0] != 0) { if(ImGui::Button(m_utf8Button1, ImVec2(pGUI->ScaleX(187.5f), pGUI->ScaleY(60.0f)))) { Show(false); if(pNetGame) pNetGame->SendDialogResponse(m_wDialogID, 1, 0, szCDialogInputBuffer); memset(szCDialogInputBuffer, 0, 100); } } if(m_utf8Button1[0] != 0 && m_utf8Button2[0] != 0) ImGui::SameLine(0, pGUI->GetFontSize()); if(m_utf8Button2[0] != 0) { if(ImGui::Button(m_utf8Button2, ImVec2(pGUI->ScaleX(187.5f), pGUI->ScaleY(60.0f)))) { Show(false); if(pNetGame) pNetGame->SendDialogResponse(m_wDialogID, 0, -1, szCDialogInputBuffer); memset(szCDialogInputBuffer, 0, 100); } } ScrollWhenDraggingOnVoid(); ImVec2 size = ImGui::GetWindowSize(); ImGui::SetWindowPos(ImVec2(((io.DisplaySize.x - size.x) / 2), ((io.DisplaySize.y - size.y) / 2))); ImGui::End(); }
26.908612
182
0.677487
[ "vector" ]
6574fccf9ccbc146b4f03154b6710179abf53343
4,195
cpp
C++
volentixfutr/src/volentixfutr.cpp
Volentix/volentix_contracts
d6680b933804310df3d219885e60bafd8f646cef
[ "MIT" ]
1
2019-10-14T16:45:04.000Z
2019-10-14T16:45:04.000Z
volentixfutr/src/volentixfutr.cpp
Volentix/volentix-contracts
d6680b933804310df3d219885e60bafd8f646cef
[ "MIT" ]
null
null
null
volentixfutr/src/volentixfutr.cpp
Volentix/volentix-contracts
d6680b933804310df3d219885e60bafd8f646cef
[ "MIT" ]
1
2019-05-06T15:33:01.000Z
2019-05-06T15:33:01.000Z
#include "volentixfutr.hpp" void volentixfutr::txfds( name account ) { require_auth( txfds_treasury ); require_auth( account ); facilitators_index facilitators(_self, _self.value); auto iterator = facilitators.find(account.value); eosio_assert(iterator != facilitators.end(), "facilitator doesn't exist"); time_point_sec tps = time_point_sec(); uint32_t sse = tps.sec_since_epoch(); asset already_allocated = iterator->already_allocated; asset total_allocation = iterator->allocation; eosio_assert(already_allocated.amount < total_allocation.amount, "all available VTX already allocated"); asset allocation = calculate_allocation(sse, total_allocation); asset to_send = allocation - already_allocated; eosio_assert(to_send.amount > 0, "liquid allocation is 0, try later"); vector<permission_level> p; p.push_back(permission_level{ get_self(), "active"_n }); p.push_back(permission_level{ txfds_treasury, "active"_n }); action( p, vtxsys_contract, "transfer"_n, std::make_tuple( get_self(), account, to_send, std::string("") ) ).send(); facilitators.modify(iterator, txfds_treasury, [&]( auto& row ) { row.already_allocated += to_send; }); } // WARNING: txfdsmocked NEEDS ONLY FOR TESTING // DO NOT FORGET TO DELETE IT BEFORE PRODUCTION DEPLOY void volentixfutr::txfdsmocked(name account, uint32_t sse_mocked) { require_auth( txfds_treasury ); require_auth( account ); facilitators_index facilitators(_self, _self.value); auto iterator = facilitators.find(account.value); eosio_assert(iterator != facilitators.end(), "facilitator doesn't exist"); // CURRENT TIME MOCK IS HERE //time_point_sec tps = time_point_sec(); //uint32_t sse = tps.sec_since_epoch(); uint32_t sse = sse_mocked; asset already_allocated = iterator->already_allocated; asset total_allocation = iterator->allocation; eosio_assert(already_allocated.amount < total_allocation.amount, "all available VTX already allocated"); asset allocation = calculate_allocation(sse, total_allocation); asset to_send = allocation - already_allocated; eosio_assert(to_send.amount > 0, "liquid allocation is 0, try later"); vector<permission_level> p; p.push_back(permission_level{ get_self(), "active"_n }); p.push_back(permission_level{ txfds_treasury, "active"_n }); action( p, vtxsys_contract, "transfer"_n, std::make_tuple( get_self(), account, to_send, std::string("") ) ).send(); facilitators.modify(iterator, txfds_treasury, [&]( auto& row ) { row.already_allocated += to_send; }); } void volentixfutr::afacilitator(name account, asset allocation) { require_auth(facilitators_modify_treasury); eosio_assert(allocation.symbol == vtx_symbol, "only VTX symbol allowed"); eosio_assert(allocation.amount > 0, "allocation should be greater than 0"); facilitators_index facilitators(_self, _self.value); auto iterator = facilitators.find( account.value ); if ( iterator == facilitators.end() ) { facilitators.emplace(facilitators_modify_treasury, [&] ( auto& row ) { row.key = account; row.allocation = allocation; row.already_allocated.symbol = vtx_symbol; row.already_allocated.amount = 0; }); } else { facilitators.modify(iterator, facilitators_modify_treasury, [&]( auto& row ) { row.allocation = allocation; }); } } void volentixfutr::erase(name account) { require_auth(facilitators_modify_treasury); facilitators_index facilitators(_self, _self.value); auto iterator = facilitators.find( account.value ); eosio_assert(iterator != facilitators.end(), "facilitator does not exist"); facilitators.erase(iterator); } EOSIO_DISPATCH(volentixfutr, (afacilitator)(txfds)(erase)(txfdsmocked)) // 130000000 / 126227704 // Facilitators // Permissions: Facilitators, treasury // Time lock 4 years. // At the discretion of the development partners management committee. // testnet:volentixfutr
37.123894
108
0.694398
[ "vector" ]
658bc0904bca98313f08a5d7fdd8fb9430c88034
851
cpp
C++
27. LeetCode Problems/Next Permutation.cpp
Ujjawalgupta42/Hacktoberfest2021-DSA
eccd9352055085973e3d6a1feb10dd193905584b
[ "MIT" ]
225
2021-10-01T03:09:01.000Z
2022-03-11T11:32:49.000Z
27. LeetCode Problems/Next Permutation.cpp
Ujjawalgupta42/Hacktoberfest2021-DSA
eccd9352055085973e3d6a1feb10dd193905584b
[ "MIT" ]
252
2021-10-01T03:45:20.000Z
2021-12-07T18:32:46.000Z
27. LeetCode Problems/Next Permutation.cpp
Ujjawalgupta42/Hacktoberfest2021-DSA
eccd9352055085973e3d6a1feb10dd193905584b
[ "MIT" ]
911
2021-10-01T02:55:19.000Z
2022-02-06T09:08:37.000Z
//KHUSHBOO DEV //Implement next permutation, which rearranges numbers into the lexicographically next greater permutation of numbers. #include <bits/stdc++.h> using namespace std; // function to find the next permutation. void nextPermutation(vector<int>& nums) { int n=nums.size(); int i=n-2; int j=0; while(i>=0 && nums[i]>=nums[i+1]) { i--; } if(i>=0){ j=n-1; while(j>=0 && nums[j]<=nums[i]) j--; swap(nums[i],nums[j]); } reverse(nums.begin()+i+1,nums.end()); } int main() { vector<int>nums={3,2,1}; //given vector of integers nextPermutation(nums);//function to find the next permutation. for(int i=0;i<nums.size();i++) cout<<nums[i]<<" "; }
23
119
0.513514
[ "vector" ]
658f5ef3415cf21f1e9b910d3a36045bb7f45eb0
6,476
cc
C++
chrome/browser/android/feed/feed_offline_bridge.cc
sarang-apps/darshan_browser
173649bb8a7c656dc60784d19e7bb73e07c20daa
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
chrome/browser/android/feed/feed_offline_bridge.cc
sarang-apps/darshan_browser
173649bb8a7c656dc60784d19e7bb73e07c20daa
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
chrome/browser/android/feed/feed_offline_bridge.cc
sarang-apps/darshan_browser
173649bb8a7c656dc60784d19e7bb73e07c20daa
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
2
2021-01-05T23:43:46.000Z
2021-01-07T23:36:34.000Z
// Copyright 2018 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/android/feed/feed_offline_bridge.h" #include <memory> #include <utility> #include "base/android/callback_android.h" #include "base/android/jni_android.h" #include "base/android/jni_array.h" #include "base/android/jni_string.h" #include "base/bind.h" #include "base/optional.h" #include "base/time/time.h" #include "chrome/android/chrome_jni_headers/FeedOfflineBridge_jni.h" #include "chrome/browser/android/feed/feed_host_service_factory.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/profiles/profile_android.h" #include "components/feed/content/feed_host_service.h" #include "components/feed/core/content_metadata.h" using base::android::JavaRef; using base::android::JavaParamRef; using base::android::ScopedJavaGlobalRef; using base::android::ScopedJavaLocalRef; namespace feed { static jlong JNI_FeedOfflineBridge_Init( JNIEnv* env, const JavaParamRef<jobject>& j_this, const JavaParamRef<jobject>& j_profile) { Profile* profile = ProfileAndroid::FromProfileAndroid(j_profile); FeedHostService* host_service = FeedHostServiceFactory::GetForBrowserContext(profile); return reinterpret_cast<intptr_t>( new FeedOfflineBridge(j_this, host_service->GetOfflineHost())); } FeedOfflineBridge::FeedOfflineBridge(const JavaRef<jobject>& j_this, FeedOfflineHost* offline_host) : j_this_(ScopedJavaGlobalRef<jobject>(j_this)), offline_host_(offline_host) { DCHECK(offline_host_); // The host guarantees to not invoke these callbacks until Initialize() exits. // This is important because until the Java bridge's constructor finishes, any // attempt to cross JNI from native to Java will fail. offline_host_->Initialize( base::BindRepeating(&FeedOfflineBridge::TriggerGetKnownContent, weak_factory_.GetWeakPtr()), base::BindRepeating(&FeedOfflineBridge::NotifyStatusChange, weak_factory_.GetWeakPtr())); } FeedOfflineBridge::~FeedOfflineBridge() = default; void FeedOfflineBridge::Destroy(JNIEnv* env, const JavaRef<jobject>& j_this) { delete this; } ScopedJavaLocalRef<jobject> FeedOfflineBridge::GetOfflineId( JNIEnv* env, const JavaRef<jobject>& j_this, const JavaRef<jstring>& j_url) { std::string url = ConvertJavaStringToUTF8(env, j_url); base::Optional<int64_t> id = offline_host_->GetOfflineId(url); return id ? Java_FeedOfflineBridge_createLong(env, *id) : nullptr; } void FeedOfflineBridge::GetOfflineStatus(JNIEnv* env, const JavaRef<jobject>& j_this, const JavaRef<jobjectArray>& j_urls, const JavaRef<jobject>& j_callback) { std::vector<std::string> urls; base::android::AppendJavaStringArrayToStringVector(env, j_urls, &urls); ScopedJavaGlobalRef<jobject> callback(j_callback); offline_host_->GetOfflineStatus( std::move(urls), base::BindOnce(&FeedOfflineBridge::OnGetOfflineStatus, weak_factory_.GetWeakPtr(), callback)); } void FeedOfflineBridge::OnContentRemoved( JNIEnv* env, const base::android::JavaRef<jobject>& j_this, const base::android::JavaRef<jobjectArray>& j_urls) { std::vector<std::string> urls; base::android::AppendJavaStringArrayToStringVector(env, j_urls, &urls); offline_host_->OnContentRemoved(urls); } void FeedOfflineBridge::OnNewContentReceived( JNIEnv* env, const base::android::JavaRef<jobject>& j_this) { offline_host_->OnNewContentReceived(); } void FeedOfflineBridge::OnNoListeners( JNIEnv* env, const base::android::JavaRef<jobject>& j_this) { offline_host_->OnNoListeners(); } void FeedOfflineBridge::AppendContentMetadata( JNIEnv* env, const base::android::JavaRef<jobject>& j_this, const base::android::JavaRef<jstring>& j_url, const base::android::JavaRef<jstring>& j_title, const jlong j_time_published_ms, const base::android::JavaRef<jstring>& j_image_url, const base::android::JavaRef<jstring>& j_publisher, const base::android::JavaRef<jstring>& j_favicon_url, const base::android::JavaRef<jstring>& j_snippet) { ContentMetadata metadata; DCHECK(!j_url.is_null()); metadata.url = base::android::ConvertJavaStringToUTF8(env, j_url); DCHECK(!j_title.is_null()); metadata.title = base::android::ConvertJavaStringToUTF8(env, j_title); metadata.time_published = base::Time::FromJavaTime(j_time_published_ms); if (!j_image_url.is_null()) { metadata.image_url = base::android::ConvertJavaStringToUTF8(env, j_image_url); } if (!j_publisher.is_null()) { metadata.publisher = base::android::ConvertJavaStringToUTF8(env, j_publisher); } if (!j_favicon_url.is_null()) { metadata.favicon_url = base::android::ConvertJavaStringToUTF8(env, j_favicon_url); } if (!j_snippet.is_null()) { metadata.snippet = base::android::ConvertJavaStringToUTF8(env, j_snippet); } known_content_metadata_buffer_.emplace_back(std::move(metadata)); } void FeedOfflineBridge::OnGetKnownContentDone( JNIEnv* env, const base::android::JavaRef<jobject>& j_this) { offline_host_->OnGetKnownContentDone( std::move(known_content_metadata_buffer_)); } void FeedOfflineBridge::TriggerGetKnownContent() { DCHECK(known_content_metadata_buffer_.empty()); JNIEnv* env = base::android::AttachCurrentThread(); Java_FeedOfflineBridge_getKnownContent(env, j_this_); } void FeedOfflineBridge::NotifyStatusChange(const std::string& url, bool available_offline) { JNIEnv* env = base::android::AttachCurrentThread(); ScopedJavaLocalRef<jstring> j_string = base::android::ConvertUTF8ToJavaString(env, url); Java_FeedOfflineBridge_notifyStatusChange(env, j_this_, j_string, available_offline); } void FeedOfflineBridge::OnGetOfflineStatus( ScopedJavaGlobalRef<jobject> callback, std::vector<std::string> urls) { JNIEnv* env = base::android::AttachCurrentThread(); ScopedJavaLocalRef<jobjectArray> j_urls = base::android::ToJavaArrayOfStrings(env, urls); RunObjectCallbackAndroid(callback, j_urls); } } // namespace feed
37.871345
80
0.721279
[ "vector" ]
6594391d5b15f5a8a14a329873145e6b50a49ec4
1,386
cpp
C++
ch1/UVa11616.cpp
lyskevin/cpbook-code
027f77933428d7688f935800ffa9109794e429b1
[ "UPL-1.0" ]
1,441
2018-12-03T23:46:17.000Z
2022-03-29T06:36:43.000Z
ch1/UVa11616.cpp
lyskevin/cpbook-code
027f77933428d7688f935800ffa9109794e429b1
[ "UPL-1.0" ]
53
2018-12-11T13:50:35.000Z
2022-03-20T04:30:39.000Z
ch1/UVa11616.cpp
lyskevin/cpbook-code
027f77933428d7688f935800ffa9109794e429b1
[ "UPL-1.0" ]
420
2018-12-04T11:22:08.000Z
2022-03-27T15:25:33.000Z
// Roman Numerals #include <bits/stdc++.h> using namespace std; typedef pair<int, string> is; void AtoR(int A) { // Arabic to Roman vector<is> convert({ {1000,"M"}, {900,"CM"}, {500,"D"}, {400,"CD"}, {100,"C"}, {90,"XC"}, {50,"L"}, {40,"XL"}, {10,"X"}, {9,"IX"}, {5,"V"}, {4,"IV"}, {1,"I"} }); for (auto &[value, roman] : convert) // from large to small while (A >= value) { cout << roman; A -= value; } cout << "\n"; } int value(char letter) { switch (letter) { case 'I': return 1; case 'V': return 5; case 'X': return 10; case 'L': return 50; case 'C': return 100; case 'D': return 500; case 'M': return 1000; } return 0; } void RtoA(string R) { // Roman to Arabic int ans = 0; for (int i = 0; R[i]; ++i) if (R[i+1] && (value(R[i]) < value(R[i+1]))) { // check next char first ans += value(R[i+1])-value(R[i]); // by definition ++i; // skip this char } else ans += value(R[i]); cout << ans << "\n"; } int main() { string S; while (getline(cin, S)) { if (isdigit(S[0])) AtoR(stoi(S)); // Arabic to Roman Numerals else RtoA(S); // Roman to Arabic Numerals } return 0; }
24.75
76
0.44228
[ "vector" ]
6597cd05333727b1ef4904a3ef80908012e80605
4,512
hpp
C++
include/arxmlStorage.hpp
JonasRock/ARXML_LanguageServer
f31cc0b2ca9233ac544cf10aee6d799ea9e55320
[ "Apache-2.0" ]
1
2021-09-11T06:28:35.000Z
2021-09-11T06:28:35.000Z
include/arxmlStorage.hpp
JonasRock/ARXML_LanguageServer
f31cc0b2ca9233ac544cf10aee6d799ea9e55320
[ "Apache-2.0" ]
1
2022-01-27T08:47:22.000Z
2022-01-27T12:23:57.000Z
include/arxmlStorage.hpp
JonasRock/ARXML_LanguageServer
f31cc0b2ca9233ac544cf10aee6d799ea9e55320
[ "Apache-2.0" ]
null
null
null
#ifndef SHORTNAMESTORAGE_H #define SHORTNAMESTORAGE_H #include <string> #include <vector> #include <deque> #include <functional> #include "boost/multi_index_container.hpp" #include "boost/multi_index/ordered_index.hpp" #include "boost/multi_index/mem_fun.hpp" #include "boost/multi_index/member.hpp" #include "boost/multi_index/composite_key.hpp" #include "types.hpp" namespace lsp { struct ReferenceElement; // struct ShortnameElement; struct ShortnameElement { std::string name; std::string path; uint32_t charOffset; uint32_t fileIndex; mutable std::vector<const ShortnameElement*> children; mutable std::vector<const ReferenceElement*> references; const ShortnameElement* parent; std::string getFullPath() const; }; struct ReferenceElement { std::string name; uint32_t charOffset; std::string targetPath; const ShortnameElement* owner; uint32_t fileIndex; }; // Typedef for the multi index map for the shortnames struct tag_fullPathIndex {}; struct tag_offsetIndex {}; typedef boost::multi_index_container< ShortnameElement, boost::multi_index::indexed_by< boost::multi_index::ordered_unique< boost::multi_index::tag<tag_fullPathIndex>, boost::multi_index::composite_key< ShortnameElement, //This is ordered with fileIndex as the second key, so we can search for elements by full path without specifying an fileIndex //This is especially important for references where we don't necessarily know where the element is boost::multi_index::const_mem_fun<ShortnameElement, std::string, &ShortnameElement::getFullPath>, boost::multi_index::member<ShortnameElement, uint32_t, &ShortnameElement::fileIndex> > >, boost::multi_index::ordered_unique< boost::multi_index::tag<tag_offsetIndex>, boost::multi_index::composite_key< ShortnameElement, //This is ordered with fileIndex as first key as it doesnt make much sense to search of an offset without saying what file //This also allows us to use emplace hint effectively, as we can always append at the end, improving performance boost::multi_index::member<ShortnameElement, uint32_t, &ShortnameElement::fileIndex>, boost::multi_index::member<ShortnameElement, uint32_t, &ShortnameElement::charOffset> > > > > shortnameContainer_t; class ArxmlStorage { public: const ShortnameElement &getShortnameByOffset(const uint32_t &offset, const uint32_t fileIndex) const; const ReferenceElement &getReferenceByOffset(const uint32_t &offset, const uint32_t fileIndex) const; const ShortnameElement &getLastShortnameByOffset(const uint32_t &offset, const uint32_t fileIndex) const; const ShortnameElement &getShortnameByFullPath(const std::string &fullPath, const uint32_t fileIndex) const; std::vector<const lsp::ShortnameElement*> getShortnamesByFullPath(const std::string &fullPath) const; std::vector<const ReferenceElement*> getReferencesByShortname(const ShortnameElement &elem) const; std::vector<const lsp::ShortnameElement*> getShortnamesByPathOnly(const std::string &path) const; const lsp::ShortnameElement* addShortname(const ShortnameElement &elem); const lsp::ReferenceElement* addReference(const ReferenceElement &elem); void addFileIndex(std::string uri); uint32_t getFileIndex(std::string uri); std::string getUriFromFileIndex(uint32_t fileIndex); bool containsFile(std::string uri);; void addNewlineOffset(const uint32_t newlineOffset, const uint32_t fileIndex); void reserveNewlineOffsets(const uint32_t numNewlineOffsets, const uint32_t fileIndex); uint32_t getOffsetFromPosition(const lsp::types::Position &position, const uint32_t fileIndex) const; const lsp::types::Position getPositionFromOffset(const uint32_t offset, const uint32_t fileIndex) const; ArxmlStorage(); private: shortnameContainer_t shortnames_; shortnameContainer_t::index<tag_fullPathIndex>::type &shortnamesFullPathIndex_; shortnameContainer_t::index<tag_offsetIndex>::type &shortnamesOffsetIndex_; std::deque<ReferenceElement> references_; std::vector<std::vector<uint32_t>> newlineOffsets_; //sanitizedFilePath_[fileIndex] = corresponding file path std::vector<std::string> URIs_; }; } /* namespace lsp */ #endif /* SHORTNAMESTORAGE_H */
39.578947
142
0.73781
[ "vector" ]
659a3c4c9738c72c94d29b64f99d425767f96aa1
666
cpp
C++
algorithms/numbers/factorial-sequence/implem_with_generic_sequence.cpp
dubzzz/various-algorithms
16af4c05acfcb23d199df0851402b0da3ebba91c
[ "MIT" ]
1
2017-04-17T18:32:46.000Z
2017-04-17T18:32:46.000Z
algorithms/numbers/factorial-sequence/implem_with_generic_sequence.cpp
dubzzz/various-algorithms
16af4c05acfcb23d199df0851402b0da3ebba91c
[ "MIT" ]
10
2016-12-25T04:42:56.000Z
2017-03-30T20:42:25.000Z
algorithms/numbers/factorial-sequence/implem_with_generic_sequence.cpp
dubzzz/various-algorithms
16af4c05acfcb23d199df0851402b0da3ebba91c
[ "MIT" ]
1
2022-03-25T17:39:05.000Z
2022-03-25T17:39:05.000Z
#include <algorithm> #include <functional> #include <numeric> #include <vector> #include "aim.hpp" // Algorithm to be tested template <class Fun> auto build_sequence(Fun&& fun, std::size_t num, std::size_t init, unsigned long long uInit) { std::vector<unsigned long long> vs(num); std::iota(vs.begin(), vs.end(), init); vs[0] = uInit; std::transform(vs.begin(), vs.end()-1, vs.begin()+1, vs.begin()+1, std::forward<Fun>(fun)); return vs; } std::vector<unsigned long long> build_factorials(unsigned num) { return num == 0 ? std::vector<unsigned long long>{} : build_sequence([](auto&& n, auto&& prev) { return n * prev; }, num, 0, 1); }
24.666667
112
0.651652
[ "vector", "transform" ]
4f2225df40cee5182dcd36851c93ae83005439c9
2,709
hpp
C++
src/get_initial_calib.hpp
abhi1625/camera-calibration
d34a96245d86ed36432db3037919348d7d3a7846
[ "MIT" ]
3
2019-09-15T01:57:30.000Z
2020-12-04T08:03:33.000Z
src/get_initial_calib.hpp
abhi1625/camera-calibration
d34a96245d86ed36432db3037919348d7d3a7846
[ "MIT" ]
4
2019-09-17T21:08:49.000Z
2019-10-24T18:46:55.000Z
src/get_initial_calib.hpp
abhi1625/camera-calibration
d34a96245d86ed36432db3037919348d7d3a7846
[ "MIT" ]
1
2021-07-16T03:22:22.000Z
2021-07-16T03:22:22.000Z
/**@file get_initial_calib.hpp * @brief Header file containing required headers and methods * for computing initial intrinsic calibration matrix. * * Detailed description follows here. * @author : Abhinav Modi, Kartik Madhira * * Copyright 2019 MIT License */ #pragma once #include <iostream> #include <vector> #include "Eigen/Dense" #include "Eigen/Core" #include <opencv2/core/core.hpp> #include <opencv2/highgui/highgui.hpp> #include <boost/filesystem.hpp> #include <opencv2/core/eigen.hpp> #include <opencv2/calib3d/calib3d.hpp> #include <opencv2/imgproc/imgproc.hpp> using namespace Eigen; //NOLINT using std::vector; using std::cout; /** * @brief get_corners outputs corners of the input checkerboard image. * @param board_image - input checkerboard image. * @param pattern_size - tuple(num_rows, num_columns) in the checkerboard. * @param show_corners - flag to enable display of input image with corners. * @return vector of corners points in the input checkerboard image. */ vector<cv::Point2f> get_corners(cv::Mat board_image, cv::Size pattern_size, bool show_corners); /** * @brief get_V_matrix outputs V matrix. * @param corner_vector - vector of corner points of the checkerboard image. * @param square_size - size of the square pattern in the checkerboard. * @param pattern_size - tuple(num_rows, num_columns) in the checkerboard. * @return 2D matrix of shape(12,2) containing V values */ MatrixXf get_V_matrix(vector<cv::Point2f> corner_vector, float square_size, cv::Size pattern_size); /** * @brief get_homography computes homography matrix using image and world coords * @param world_corners - (N, 2) matrix of world coordinates * @param square_size - (N, 2) matrix of image coordinates * @return (3, 3) homography matrix */ cv::Mat get_homography(cv::Mat world_corners, cv::Mat image_corners); /** * @brief create_V_matrix computes V matrix using homography * @param world_corners - (N, 2) matrix of world coordinates * @param square_size - (N, 2) matrix of image coordinates * @return (3, 3) homography matrix */ MatrixXf create_V_matrix(const cv::Mat& H); /** * @brief get_vij_matrix is a helper function to compute vij matrix * @param vij - reference to the vij matrix for computing V matrix * @param H - const reference to the Homography matrix * @param i - index i for vij * @param j - index j for vij */ void get_vij_matrix(MatrixXf& vij, const cv::Mat& H, int i, int j); //NOLINT MatrixXf get_initial_K(const MatrixXf& V); MatrixXf get_B_matrix(const MatrixXf& rt_eigen_matrix); Matrix3f compute_K(const MatrixXf& B);
33.8625
80
0.715024
[ "shape", "vector" ]
4f22fe4f750a7ae0ead45d43d19fa0d6be999b1b
3,812
hpp
C++
src/ReadLoader.hpp
AustinHartman/shasta
105b8e85e272247f72ced59005c88879631931c0
[ "BSD-3-Clause" ]
null
null
null
src/ReadLoader.hpp
AustinHartman/shasta
105b8e85e272247f72ced59005c88879631931c0
[ "BSD-3-Clause" ]
null
null
null
src/ReadLoader.hpp
AustinHartman/shasta
105b8e85e272247f72ced59005c88879631931c0
[ "BSD-3-Clause" ]
null
null
null
#ifndef SHASTA_READ_LOADER_HPP #define SHASTA_READ_LOADER_HPP // shasta #include "LongBaseSequence.hpp" #include "MemoryMappedObject.hpp" #include "MultithreadedObject.hpp" #include "Reads.hpp" // Standard library. #include "memory.hpp" #include "string.hpp" namespace shasta { class ReadLoader; } // Class used to load reads from a fasta file. class shasta::ReadLoader : public MultithreadedObject<ReadLoader>{ public: // The constructor does all the work. ReadLoader( const string& fileName, uint64_t minReadLength, bool noCache, size_t threadCount, const string& dataNamePrefix, size_t pageSize, Reads& reads); ~ReadLoader(); // The number of reads and raw bases discarded because the read // contained invalid bases. uint64_t discardedInvalidBaseReadCount = 0; uint64_t discardedInvalidBaseBaseCount = 0; // Only counts the valid bases in those reads. // The number of reads and raw bases discarded because the read length // was less than minReadLength. uint64_t discardedShortReadReadCount = 0; uint64_t discardedShortReadBaseCount = 0; // The number of reads and raw bases discarded because the read // contained repeat counts greater than 255. uint64_t discardedBadRepeatCountReadCount = 0; uint64_t discardedBadRepeatCountBaseCount = 0; private: // The name of the file we are processing. const string& fileName; // The minimum read length. Shorter reads are not stored. const uint64_t minReadLength; // If set, use the O_DIRECT flag when opening input files (Linux only). bool noCache; // The number of threads to be used for processing. // Reading is done single-threaded as there is usually no benefit // frm multithreaded reading. size_t threadCount; void adjustThreadCount(); // Information that we can use to create temporary // memory mapped binary data structures. const string& dataNamePrefix; const size_t pageSize; // The data structure that the reads will be added to. Reads& reads; // Create the name to be used for a MemoryMapped object. string dataName( const string& dataName) const; string threadDataName( size_t threadId, const string& dataName) const; // Read an entire file into a buffer, // using threadCountForReading threads. MemoryMapped::Vector<char> buffer; void readFile(); // Vectors where each thread stores the reads it found. // Indexed by threadId. vector< unique_ptr<MemoryMapped::VectorOfVectors<char, uint64_t> > > threadReadNames; vector< unique_ptr<MemoryMapped::VectorOfVectors<char, uint64_t> > > threadReadMetaData; vector< unique_ptr<LongBaseSequences> > threadReads; vector< unique_ptr<MemoryMapped::VectorOfVectors<uint8_t, uint64_t> > > threadReadRepeatCounts; void allocatePerThreadDataStructures(); void allocatePerThreadDataStructures(size_t threadId); // Store the reads computed by each thread and free // the per-thread data structures. void storeReads(); // Functions used for fasta files. void processFastaFile(); void processFastaFileThreadFunction(size_t threadId); // Function that returns true if a read begins // at this position in Fasta format. bool fastaReadBeginsHere(uint64_t offset) const; // Functions used for fastq files. void processFastqFile(); void processFastqFileThreadFunction(size_t threadId); // Find all line ends in the file. void findLineEnds(); void findLineEndsThreadFunction(size_t threadId); vector< vector<uint64_t> > threadLineEnds; vector<uint64_t> lineEnds; #ifdef __linux__ int tryDirectIO(const string& fileName); #endif }; #endif
30.015748
99
0.715897
[ "object", "vector" ]
4f27d86798396fce033f2aa2bfc633d7b51ee965
23,703
cc
C++
chrome/browser/ui/libgtk2ui/select_file_dialog_impl_gtk2.cc
shaochangbin/chromium-crosswalk
634d34e4cf82b4f7400357c53ec12efaffe94add
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
2
2019-01-16T03:57:28.000Z
2021-01-23T15:29:45.000Z
chrome/browser/ui/libgtk2ui/select_file_dialog_impl_gtk2.cc
shaochangbin/chromium-crosswalk
634d34e4cf82b4f7400357c53ec12efaffe94add
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
chrome/browser/ui/libgtk2ui/select_file_dialog_impl_gtk2.cc
shaochangbin/chromium-crosswalk
634d34e4cf82b4f7400357c53ec12efaffe94add
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
1
2017-03-15T13:21:38.000Z
2017-03-15T13:21:38.000Z
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include <gdk/gdk.h> #include <gdk/gdkx.h> #include <gtk/gtk.h> #include <map> #include <set> #include <vector> // Xlib defines RootWindow #undef RootWindow #include "base/logging.h" #include "base/memory/scoped_ptr.h" #include "base/message_loop/message_loop.h" #include "base/strings/string_util.h" #include "base/strings/sys_string_conversions.h" #include "base/strings/utf_string_conversions.h" #include "base/threading/thread.h" #include "base/threading/thread_restrictions.h" #include "chrome/browser/ui/libgtk2ui/gtk2_signal.h" #include "chrome/browser/ui/libgtk2ui/select_file_dialog_impl.h" #include "grit/ui_strings.h" #include "ui/aura/window_observer.h" #include "ui/aura/window_tree_host.h" #include "ui/base/l10n/l10n_util.h" #include "ui/shell_dialogs/select_file_dialog.h" namespace { const char kAuraTransientParent[] = "aura-transient-parent"; // Set |dialog| as transient for |parent|, which will keep it on top and center // it above |parent|. void SetGtkTransientForAura(GtkWidget* dialog, aura::Window* parent) { gtk_widget_realize(dialog); GdkWindow* gdk_window = gtk_widget_get_window(dialog); // TODO(erg): Check to make sure we're using X11 if wayland or some other // display server ever happens. Otherwise, this will crash. XSetTransientForHint(GDK_WINDOW_XDISPLAY(gdk_window), GDK_WINDOW_XID(gdk_window), parent->GetHost()->GetAcceleratedWidget()); // We also set the |parent| as a property of |dialog|, so that we can unlink // the two later. g_object_set_data(G_OBJECT(dialog), kAuraTransientParent, parent); } // Makes sure that .jpg also shows .JPG. gboolean FileFilterCaseInsensitive(const GtkFileFilterInfo* file_info, std::string* file_extension) { return EndsWith(file_info->filename, *file_extension, false); } // Deletes |data| when gtk_file_filter_add_custom() is done with it. void OnFileFilterDataDestroyed(std::string* file_extension) { delete file_extension; } } // namespace namespace libgtk2ui { // Implementation of SelectFileDialog that shows a Gtk common dialog for // choosing a file or folder. This acts as a modal dialog. class SelectFileDialogImplGTK : public SelectFileDialogImpl, public aura::WindowObserver { public: explicit SelectFileDialogImplGTK(Listener* listener, ui::SelectFilePolicy* policy); protected: virtual ~SelectFileDialogImplGTK(); // SelectFileDialog implementation. // |params| is user data we pass back via the Listener interface. virtual void SelectFileImpl( Type type, const base::string16& title, const base::FilePath& default_path, const FileTypeInfo* file_types, int file_type_index, const base::FilePath::StringType& default_extension, gfx::NativeWindow owning_window, void* params) OVERRIDE; private: virtual bool HasMultipleFileTypeChoicesImpl() OVERRIDE; // Overridden from aura::WindowObserver: virtual void OnWindowDestroying(aura::Window* window) OVERRIDE; // Add the filters from |file_types_| to |chooser|. void AddFilters(GtkFileChooser* chooser); // Notifies the listener that a single file was chosen. void FileSelected(GtkWidget* dialog, const base::FilePath& path); // Notifies the listener that multiple files were chosen. void MultiFilesSelected(GtkWidget* dialog, const std::vector<base::FilePath>& files); // Notifies the listener that no file was chosen (the action was canceled). // Dialog is passed so we can find that |params| pointer that was passed to // us when we were told to show the dialog. void FileNotSelected(GtkWidget* dialog); GtkWidget* CreateSelectFolderDialog( Type type, const std::string& title, const base::FilePath& default_path, gfx::NativeWindow parent); GtkWidget* CreateFileOpenDialog(const std::string& title, const base::FilePath& default_path, gfx::NativeWindow parent); GtkWidget* CreateMultiFileOpenDialog(const std::string& title, const base::FilePath& default_path, gfx::NativeWindow parent); GtkWidget* CreateSaveAsDialog(const std::string& title, const base::FilePath& default_path, gfx::NativeWindow parent); // Removes and returns the |params| associated with |dialog| from // |params_map_|. void* PopParamsForDialog(GtkWidget* dialog); // Take care of internal data structures when a file dialog is destroyed. void FileDialogDestroyed(GtkWidget* dialog); // Check whether response_id corresponds to the user cancelling/closing the // dialog. Used as a helper for the below callbacks. bool IsCancelResponse(gint response_id); // Common function for OnSelectSingleFileDialogResponse and // OnSelectSingleFolderDialogResponse. void SelectSingleFileHelper(GtkWidget* dialog, gint response_id, bool allow_folder); // Common function for CreateFileOpenDialog and CreateMultiFileOpenDialog. GtkWidget* CreateFileOpenHelper(const std::string& title, const base::FilePath& default_path, gfx::NativeWindow parent); // Callback for when the user responds to a Save As or Open File dialog. CHROMEGTK_CALLBACK_1(SelectFileDialogImplGTK, void, OnSelectSingleFileDialogResponse, int); // Callback for when the user responds to a Select Folder dialog. CHROMEGTK_CALLBACK_1(SelectFileDialogImplGTK, void, OnSelectSingleFolderDialogResponse, int); // Callback for when the user responds to a Open Multiple Files dialog. CHROMEGTK_CALLBACK_1(SelectFileDialogImplGTK, void, OnSelectMultiFileDialogResponse, int); // Callback for when the file chooser gets destroyed. CHROMEGTK_CALLBACK_0(SelectFileDialogImplGTK, void, OnFileChooserDestroy); // Callback for when we update the preview for the selection. CHROMEGTK_CALLBACK_0(SelectFileDialogImplGTK, void, OnUpdatePreview); // A map from dialog windows to the |params| user data associated with them. std::map<GtkWidget*, void*> params_map_; // The GtkImage widget for showing previews of selected images. GtkWidget* preview_; // All our dialogs. std::set<GtkWidget*> dialogs_; DISALLOW_COPY_AND_ASSIGN(SelectFileDialogImplGTK); }; // The size of the preview we display for selected image files. We set height // larger than width because generally there is more free space vertically // than horiztonally (setting the preview image will alway expand the width of // the dialog, but usually not the height). The image's aspect ratio will always // be preserved. static const int kPreviewWidth = 256; static const int kPreviewHeight = 512; SelectFileDialogImpl* SelectFileDialogImpl::NewSelectFileDialogImplGTK( Listener* listener, ui::SelectFilePolicy* policy) { return new SelectFileDialogImplGTK(listener, policy); } SelectFileDialogImplGTK::SelectFileDialogImplGTK(Listener* listener, ui::SelectFilePolicy* policy) : SelectFileDialogImpl(listener, policy), preview_(NULL) { } SelectFileDialogImplGTK::~SelectFileDialogImplGTK() { while (dialogs_.begin() != dialogs_.end()) { gtk_widget_destroy(*(dialogs_.begin())); } } bool SelectFileDialogImplGTK::HasMultipleFileTypeChoicesImpl() { return file_types_.extensions.size() > 1; } void SelectFileDialogImplGTK::OnWindowDestroying(aura::Window* window) { // Remove the |parent| property associated with the |dialog|. for (std::set<GtkWidget*>::iterator it = dialogs_.begin(); it != dialogs_.end(); ++it) { aura::Window* parent = reinterpret_cast<aura::Window*>( g_object_get_data(G_OBJECT(*it), kAuraTransientParent)); if (parent == window) g_object_set_data(G_OBJECT(*it), kAuraTransientParent, NULL); } std::set<aura::Window*>::iterator iter = parents_.find(window); if (iter != parents_.end()) { (*iter)->RemoveObserver(this); parents_.erase(iter); } } // We ignore |default_extension|. void SelectFileDialogImplGTK::SelectFileImpl( Type type, const base::string16& title, const base::FilePath& default_path, const FileTypeInfo* file_types, int file_type_index, const base::FilePath::StringType& default_extension, gfx::NativeWindow owning_window, void* params) { type_ = type; // |owning_window| can be null when user right-clicks on a downloadable item // and chooses 'Open Link in New Tab' when 'Ask where to save each file // before downloading.' preference is turned on. (http://crbug.com/29213) if (owning_window) { owning_window->AddObserver(this); parents_.insert(owning_window); } std::string title_string = base::UTF16ToUTF8(title); file_type_index_ = file_type_index; if (file_types) file_types_ = *file_types; GtkWidget* dialog = NULL; switch (type) { case SELECT_FOLDER: case SELECT_UPLOAD_FOLDER: dialog = CreateSelectFolderDialog(type, title_string, default_path, owning_window); break; case SELECT_OPEN_FILE: dialog = CreateFileOpenDialog(title_string, default_path, owning_window); break; case SELECT_OPEN_MULTI_FILE: dialog = CreateMultiFileOpenDialog(title_string, default_path, owning_window); break; case SELECT_SAVEAS_FILE: dialog = CreateSaveAsDialog(title_string, default_path, owning_window); break; default: NOTREACHED(); return; } g_signal_connect(dialog, "delete-event", G_CALLBACK(gtk_widget_hide_on_delete), NULL); dialogs_.insert(dialog); preview_ = gtk_image_new(); g_signal_connect(dialog, "destroy", G_CALLBACK(OnFileChooserDestroyThunk), this); g_signal_connect(dialog, "update-preview", G_CALLBACK(OnUpdatePreviewThunk), this); gtk_file_chooser_set_preview_widget(GTK_FILE_CHOOSER(dialog), preview_); params_map_[dialog] = params; // TODO(erg): Figure out how to fake GTK window-to-parent modality without // having the parent be a real GtkWindow. gtk_window_set_modal(GTK_WINDOW(dialog), TRUE); gtk_widget_show_all(dialog); } void SelectFileDialogImplGTK::AddFilters(GtkFileChooser* chooser) { for (size_t i = 0; i < file_types_.extensions.size(); ++i) { GtkFileFilter* filter = NULL; std::set<std::string> fallback_labels; for (size_t j = 0; j < file_types_.extensions[i].size(); ++j) { const std::string& current_extension = file_types_.extensions[i][j]; if (!current_extension.empty()) { if (!filter) filter = gtk_file_filter_new(); scoped_ptr<std::string> file_extension( new std::string("." + current_extension)); fallback_labels.insert(std::string("*").append(*file_extension)); gtk_file_filter_add_custom( filter, GTK_FILE_FILTER_FILENAME, reinterpret_cast<GtkFileFilterFunc>(FileFilterCaseInsensitive), file_extension.release(), reinterpret_cast<GDestroyNotify>(OnFileFilterDataDestroyed)); } } // We didn't find any non-empty extensions to filter on. if (!filter) continue; // The description vector may be blank, in which case we are supposed to // use some sort of default description based on the filter. if (i < file_types_.extension_description_overrides.size()) { gtk_file_filter_set_name(filter, base::UTF16ToUTF8( file_types_.extension_description_overrides[i]).c_str()); } else { // There is no system default filter description so we use // the extensions themselves if the description is blank. std::vector<std::string> fallback_labels_vector(fallback_labels.begin(), fallback_labels.end()); std::string fallback_label = JoinString(fallback_labels_vector, ','); gtk_file_filter_set_name(filter, fallback_label.c_str()); } gtk_file_chooser_add_filter(chooser, filter); if (i == file_type_index_ - 1) gtk_file_chooser_set_filter(chooser, filter); } // Add the *.* filter, but only if we have added other filters (otherwise it // is implied). if (file_types_.include_all_files && !file_types_.extensions.empty()) { GtkFileFilter* filter = gtk_file_filter_new(); gtk_file_filter_add_pattern(filter, "*"); gtk_file_filter_set_name(filter, l10n_util::GetStringUTF8(IDS_SAVEAS_ALL_FILES).c_str()); gtk_file_chooser_add_filter(chooser, filter); } } void SelectFileDialogImplGTK::FileSelected(GtkWidget* dialog, const base::FilePath& path) { if (type_ == SELECT_SAVEAS_FILE) { *last_saved_path_ = path.DirName(); } else if (type_ == SELECT_OPEN_FILE || type_ == SELECT_FOLDER || type_ == SELECT_UPLOAD_FOLDER) { *last_opened_path_ = path.DirName(); } else { NOTREACHED(); } if (listener_) { GtkFileFilter* selected_filter = gtk_file_chooser_get_filter(GTK_FILE_CHOOSER(dialog)); GSList* filters = gtk_file_chooser_list_filters(GTK_FILE_CHOOSER(dialog)); int idx = g_slist_index(filters, selected_filter); g_slist_free(filters); listener_->FileSelected(path, idx + 1, PopParamsForDialog(dialog)); } gtk_widget_destroy(dialog); } void SelectFileDialogImplGTK::MultiFilesSelected(GtkWidget* dialog, const std::vector<base::FilePath>& files) { *last_opened_path_ = files[0].DirName(); if (listener_) listener_->MultiFilesSelected(files, PopParamsForDialog(dialog)); gtk_widget_destroy(dialog); } void SelectFileDialogImplGTK::FileNotSelected(GtkWidget* dialog) { void* params = PopParamsForDialog(dialog); if (listener_) listener_->FileSelectionCanceled(params); gtk_widget_destroy(dialog); } GtkWidget* SelectFileDialogImplGTK::CreateFileOpenHelper( const std::string& title, const base::FilePath& default_path, gfx::NativeWindow parent) { GtkWidget* dialog = gtk_file_chooser_dialog_new(title.c_str(), NULL, GTK_FILE_CHOOSER_ACTION_OPEN, GTK_STOCK_CANCEL, GTK_RESPONSE_CANCEL, GTK_STOCK_OPEN, GTK_RESPONSE_ACCEPT, NULL); SetGtkTransientForAura(dialog, parent); AddFilters(GTK_FILE_CHOOSER(dialog)); if (!default_path.empty()) { if (CallDirectoryExistsOnUIThread(default_path)) { gtk_file_chooser_set_current_folder(GTK_FILE_CHOOSER(dialog), default_path.value().c_str()); } else { // If the file doesn't exist, this will just switch to the correct // directory. That's good enough. gtk_file_chooser_set_filename(GTK_FILE_CHOOSER(dialog), default_path.value().c_str()); } } else if (!last_opened_path_->empty()) { gtk_file_chooser_set_current_folder(GTK_FILE_CHOOSER(dialog), last_opened_path_->value().c_str()); } return dialog; } GtkWidget* SelectFileDialogImplGTK::CreateSelectFolderDialog( Type type, const std::string& title, const base::FilePath& default_path, gfx::NativeWindow parent) { std::string title_string = title; if (title_string.empty()) { title_string = (type == SELECT_UPLOAD_FOLDER) ? l10n_util::GetStringUTF8(IDS_SELECT_UPLOAD_FOLDER_DIALOG_TITLE) : l10n_util::GetStringUTF8(IDS_SELECT_FOLDER_DIALOG_TITLE); } std::string accept_button_label = (type == SELECT_UPLOAD_FOLDER) ? l10n_util::GetStringUTF8(IDS_SELECT_UPLOAD_FOLDER_DIALOG_UPLOAD_BUTTON) : GTK_STOCK_OPEN; GtkWidget* dialog = gtk_file_chooser_dialog_new(title_string.c_str(), NULL, GTK_FILE_CHOOSER_ACTION_SELECT_FOLDER, GTK_STOCK_CANCEL, GTK_RESPONSE_CANCEL, accept_button_label.c_str(), GTK_RESPONSE_ACCEPT, NULL); SetGtkTransientForAura(dialog, parent); if (!default_path.empty()) { gtk_file_chooser_set_filename(GTK_FILE_CHOOSER(dialog), default_path.value().c_str()); } else if (!last_opened_path_->empty()) { gtk_file_chooser_set_current_folder(GTK_FILE_CHOOSER(dialog), last_opened_path_->value().c_str()); } gtk_file_chooser_set_select_multiple(GTK_FILE_CHOOSER(dialog), FALSE); g_signal_connect(dialog, "response", G_CALLBACK(OnSelectSingleFolderDialogResponseThunk), this); return dialog; } GtkWidget* SelectFileDialogImplGTK::CreateFileOpenDialog( const std::string& title, const base::FilePath& default_path, gfx::NativeWindow parent) { std::string title_string = !title.empty() ? title : l10n_util::GetStringUTF8(IDS_OPEN_FILE_DIALOG_TITLE); GtkWidget* dialog = CreateFileOpenHelper(title_string, default_path, parent); gtk_file_chooser_set_select_multiple(GTK_FILE_CHOOSER(dialog), FALSE); g_signal_connect(dialog, "response", G_CALLBACK(OnSelectSingleFileDialogResponseThunk), this); return dialog; } GtkWidget* SelectFileDialogImplGTK::CreateMultiFileOpenDialog( const std::string& title, const base::FilePath& default_path, gfx::NativeWindow parent) { std::string title_string = !title.empty() ? title : l10n_util::GetStringUTF8(IDS_OPEN_FILES_DIALOG_TITLE); GtkWidget* dialog = CreateFileOpenHelper(title_string, default_path, parent); gtk_file_chooser_set_select_multiple(GTK_FILE_CHOOSER(dialog), TRUE); g_signal_connect(dialog, "response", G_CALLBACK(OnSelectMultiFileDialogResponseThunk), this); return dialog; } GtkWidget* SelectFileDialogImplGTK::CreateSaveAsDialog(const std::string& title, const base::FilePath& default_path, gfx::NativeWindow parent) { std::string title_string = !title.empty() ? title : l10n_util::GetStringUTF8(IDS_SAVE_AS_DIALOG_TITLE); GtkWidget* dialog = gtk_file_chooser_dialog_new(title_string.c_str(), NULL, GTK_FILE_CHOOSER_ACTION_SAVE, GTK_STOCK_CANCEL, GTK_RESPONSE_CANCEL, GTK_STOCK_SAVE, GTK_RESPONSE_ACCEPT, NULL); SetGtkTransientForAura(dialog, parent); AddFilters(GTK_FILE_CHOOSER(dialog)); if (!default_path.empty()) { // Since the file may not already exist, we use // set_current_folder() followed by set_current_name(), as per the // recommendation of the GTK docs. gtk_file_chooser_set_current_folder(GTK_FILE_CHOOSER(dialog), default_path.DirName().value().c_str()); gtk_file_chooser_set_current_name(GTK_FILE_CHOOSER(dialog), default_path.BaseName().value().c_str()); } else if (!last_saved_path_->empty()) { gtk_file_chooser_set_current_folder(GTK_FILE_CHOOSER(dialog), last_saved_path_->value().c_str()); } gtk_file_chooser_set_select_multiple(GTK_FILE_CHOOSER(dialog), FALSE); gtk_file_chooser_set_do_overwrite_confirmation(GTK_FILE_CHOOSER(dialog), TRUE); g_signal_connect(dialog, "response", G_CALLBACK(OnSelectSingleFileDialogResponseThunk), this); return dialog; } void* SelectFileDialogImplGTK::PopParamsForDialog(GtkWidget* dialog) { std::map<GtkWidget*, void*>::iterator iter = params_map_.find(dialog); DCHECK(iter != params_map_.end()); void* params = iter->second; params_map_.erase(iter); return params; } void SelectFileDialogImplGTK::FileDialogDestroyed(GtkWidget* dialog) { dialogs_.erase(dialog); // Parent may be NULL in a few cases: 1) on shutdown when // AllBrowsersClosed() trigger this handler after all the browser // windows got destroyed, or 2) when the parent tab has been opened by // 'Open Link in New Tab' context menu on a downloadable item and // the tab has no content (see the comment in SelectFile as well). aura::Window* parent = reinterpret_cast<aura::Window*>( g_object_get_data(G_OBJECT(dialog), kAuraTransientParent)); if (!parent) return; std::set<aura::Window*>::iterator iter = parents_.find(parent); if (iter != parents_.end()) { (*iter)->RemoveObserver(this); parents_.erase(iter); } else { NOTREACHED(); } } bool SelectFileDialogImplGTK::IsCancelResponse(gint response_id) { bool is_cancel = response_id == GTK_RESPONSE_CANCEL || response_id == GTK_RESPONSE_DELETE_EVENT; if (is_cancel) return true; DCHECK(response_id == GTK_RESPONSE_ACCEPT); return false; } void SelectFileDialogImplGTK::SelectSingleFileHelper(GtkWidget* dialog, gint response_id, bool allow_folder) { if (IsCancelResponse(response_id)) { FileNotSelected(dialog); return; } gchar* filename = gtk_file_chooser_get_filename(GTK_FILE_CHOOSER(dialog)); if (!filename) { FileNotSelected(dialog); return; } base::FilePath path(filename); g_free(filename); if (allow_folder) { FileSelected(dialog, path); return; } if (CallDirectoryExistsOnUIThread(path)) FileNotSelected(dialog); else FileSelected(dialog, path); } void SelectFileDialogImplGTK::OnSelectSingleFileDialogResponse( GtkWidget* dialog, int response_id) { SelectSingleFileHelper(dialog, response_id, false); } void SelectFileDialogImplGTK::OnSelectSingleFolderDialogResponse( GtkWidget* dialog, int response_id) { SelectSingleFileHelper(dialog, response_id, true); } void SelectFileDialogImplGTK::OnSelectMultiFileDialogResponse(GtkWidget* dialog, int response_id) { if (IsCancelResponse(response_id)) { FileNotSelected(dialog); return; } GSList* filenames = gtk_file_chooser_get_filenames(GTK_FILE_CHOOSER(dialog)); if (!filenames) { FileNotSelected(dialog); return; } std::vector<base::FilePath> filenames_fp; for (GSList* iter = filenames; iter != NULL; iter = g_slist_next(iter)) { base::FilePath path(static_cast<char*>(iter->data)); g_free(iter->data); if (CallDirectoryExistsOnUIThread(path)) continue; filenames_fp.push_back(path); } g_slist_free(filenames); if (filenames_fp.empty()) { FileNotSelected(dialog); return; } MultiFilesSelected(dialog, filenames_fp); } void SelectFileDialogImplGTK::OnFileChooserDestroy(GtkWidget* dialog) { FileDialogDestroyed(dialog); } void SelectFileDialogImplGTK::OnUpdatePreview(GtkWidget* chooser) { gchar* filename = gtk_file_chooser_get_preview_filename( GTK_FILE_CHOOSER(chooser)); if (!filename) return; // This will preserve the image's aspect ratio. GdkPixbuf* pixbuf = gdk_pixbuf_new_from_file_at_size(filename, kPreviewWidth, kPreviewHeight, NULL); g_free(filename); if (pixbuf) { gtk_image_set_from_pixbuf(GTK_IMAGE(preview_), pixbuf); g_object_unref(pixbuf); } gtk_file_chooser_set_preview_widget_active(GTK_FILE_CHOOSER(chooser), pixbuf ? TRUE : FALSE); } } // namespace libgtk2ui
36.978159
80
0.694216
[ "vector" ]
4f2a86923c52bb39331480f9149c3ed21bab941b
7,884
cpp
C++
src/+cv/private/VideoCapture_.cpp
rokm/mexopencv
22d459cd28df8a5e77fd7f2c8572b16723f60a1d
[ "BSD-3-Clause" ]
1
2021-05-12T21:33:44.000Z
2021-05-12T21:33:44.000Z
src/+cv/private/VideoCapture_.cpp
rokm/mexopencv
22d459cd28df8a5e77fd7f2c8572b16723f60a1d
[ "BSD-3-Clause" ]
null
null
null
src/+cv/private/VideoCapture_.cpp
rokm/mexopencv
22d459cd28df8a5e77fd7f2c8572b16723f60a1d
[ "BSD-3-Clause" ]
1
2020-09-29T22:33:52.000Z
2020-09-29T22:33:52.000Z
/** * @file VideoCapture_.cpp * @brief mex interface for cv::VideoCapture * @ingroup videoio * @author Kota Yamaguchi * @date 2012 */ #include "mexopencv.hpp" using namespace std; using namespace cv; namespace { // Persistent objects /// Last object id to allocate int last_id = 0; /// Object container map<int,Ptr<VideoCapture> > obj_; /// Capture Property map for option processing const ConstMap<string,int> CapProp = ConstMap<string,int> ("PosMsec", cv::CAP_PROP_POS_MSEC) ("PosFrames", cv::CAP_PROP_POS_FRAMES) ("PosAviRatio", cv::CAP_PROP_POS_AVI_RATIO) ("FrameWidth", cv::CAP_PROP_FRAME_WIDTH) ("FrameHeight", cv::CAP_PROP_FRAME_HEIGHT) ("FPS", cv::CAP_PROP_FPS) ("FourCC", cv::CAP_PROP_FOURCC) ("FrameCount", cv::CAP_PROP_FRAME_COUNT) ("Format", cv::CAP_PROP_FORMAT) ("Mode", cv::CAP_PROP_MODE) ("Brightness", cv::CAP_PROP_BRIGHTNESS) ("Contrast", cv::CAP_PROP_CONTRAST) ("Saturation", cv::CAP_PROP_SATURATION) ("Hue", cv::CAP_PROP_HUE) ("Gain", cv::CAP_PROP_GAIN) ("Exposure", cv::CAP_PROP_EXPOSURE) ("ConvertRGB", cv::CAP_PROP_CONVERT_RGB) //("WhiteBalanceBlue", cv::CAP_PROP_WHITE_BALANCE_BLUE_U) ("Rectification", cv::CAP_PROP_RECTIFICATION) //TODO: other undocumented properties ("Monochrome", cv::CAP_PROP_MONOCHROME) ("Sharpness", cv::CAP_PROP_SHARPNESS) ("AutoExposure", cv::CAP_PROP_AUTO_EXPOSURE) ("Gamma", cv::CAP_PROP_GAMMA) ("Temperature", cv::CAP_PROP_TEMPERATURE) ("Trigger", cv::CAP_PROP_TRIGGER) ("TriggerDelay", cv::CAP_PROP_TRIGGER_DELAY) //("WhiteBalanceRed", cv::CAP_PROP_WHITE_BALANCE_RED_V) ("Zoom", cv::CAP_PROP_ZOOM) ("Focus", cv::CAP_PROP_FOCUS) ("GUID", cv::CAP_PROP_GUID) ("ISOSpeed", cv::CAP_PROP_ISO_SPEED) ("Backlight", cv::CAP_PROP_BACKLIGHT) ("Pan", cv::CAP_PROP_PAN) ("Tilt", cv::CAP_PROP_TILT) ("Roll", cv::CAP_PROP_ROLL) ("Iris", cv::CAP_PROP_IRIS) ("Settings", cv::CAP_PROP_SETTINGS) ("Buffersize", cv::CAP_PROP_BUFFERSIZE) ("Autofocus", cv::CAP_PROP_AUTOFOCUS); /// Camera API map for option processing const ConstMap<string,int> CameraApiMap = ConstMap<string,int> ("Any", cv::CAP_ANY) ("VfW", cv::CAP_VFW) ("V4L", cv::CAP_V4L) ("V4L2", cv::CAP_V4L2) ("FireWire", cv::CAP_FIREWIRE) ("FireWare", cv::CAP_FIREWARE) ("IEEE1394", cv::CAP_IEEE1394) ("DC1394", cv::CAP_DC1394) ("CMU1394", cv::CAP_CMU1394) ("QuickTime", cv::CAP_QT) ("Unicap", cv::CAP_UNICAP) ("DirectShow", cv::CAP_DSHOW) ("PvAPI", cv::CAP_PVAPI) ("OpenNI", cv::CAP_OPENNI) ("OpenNIAsus", cv::CAP_OPENNI_ASUS) ("Android", cv::CAP_ANDROID) ("XIMEA", cv::CAP_XIAPI) ("AVFoundation", cv::CAP_AVFOUNDATION) ("Giganetix", cv::CAP_GIGANETIX) ("MediaFoundation", cv::CAP_MSMF) ("WinRT", cv::CAP_WINRT) ("IntelPerC", cv::CAP_INTELPERC) ("OpenNI2", cv::CAP_OPENNI2) ("OpenNI2Asus", cv::CAP_OPENNI2_ASUS) ("gPhoto2", cv::CAP_GPHOTO2) ("GStreamer", cv::CAP_GSTREAMER) ("FFMPEG", cv::CAP_FFMPEG) ("Images", cv::CAP_IMAGES) ("Aravis", cv::CAP_ARAVIS) ("MotionJPEG", cv::CAP_OPENCV_MJPEG) ("MediaSDK", cv::CAP_INTEL_MFX); } /** * Main entry called from Matlab * @param nlhs number of left-hand-side arguments * @param plhs pointers to mxArrays in the left-hand-side * @param nrhs number of right-hand-side arguments * @param prhs pointers to mxArrays in the right-hand-side */ void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) { // Check the number of arguments nargchk(nrhs>=2 && nlhs<=1); // Argument vector vector<MxArray> rhs(prhs, prhs+nrhs); int id = rhs[0].toInt(); string method(rhs[1].toString()); // Constructor is called. Create a new object from arguments if (method == "new") { nargchk(nrhs==2 && nlhs<=1); obj_[++last_id] = makePtr<VideoCapture>(); plhs[0] = MxArray(last_id); mexLock(); return; } // Big operation switch Ptr<VideoCapture> obj = obj_[id]; if (obj.empty()) mexErrMsgIdAndTxt("mexopencv:error", "Object not found id=%d", id); if (method == "delete") { nargchk(nrhs==2 && nlhs==0); obj_.erase(id); mexUnlock(); } else if (method == "open") { nargchk(nrhs>=3 && (nrhs%2)==1 && nlhs<=1); int pref = cv::CAP_ANY; for (int i=3; i<nrhs; i+=2) { string key(rhs[i].toString()); if (key == "API") pref = CameraApiMap[rhs[i+1].toString()]; else mexErrMsgIdAndTxt("mexopencv:error", "Unrecognized option %s", key.c_str()); } // index should be within 0-99, and pref is multiples of 100 bool b = (rhs[2].isChar()) ? obj->open(rhs[2].toString(), pref) : obj->open(rhs[2].toInt() + pref); plhs[0] = MxArray(b); } else if (method == "isOpened") { nargchk(nrhs==2 && nlhs<=1); bool b = obj->isOpened(); plhs[0] = MxArray(b); } else if (method == "release") { nargchk(nrhs==2 && nlhs==0); obj->release(); } else if (method == "grab") { nargchk(nrhs==2 && nlhs<=1); bool b = obj->grab(); plhs[0] = MxArray(b); } else if (method == "retrieve") { nargchk(nrhs>=2 && (nrhs%2)==0 && nlhs<=1); int idx = 0; bool flip = true; for (int i=2; i<nrhs; i+=2) { string key(rhs[i].toString()); if (key == "FlipChannels") flip = rhs[i+1].toBool(); else if (key == "StreamIdx") idx = rhs[i+1].toInt(); else mexErrMsgIdAndTxt("mexopencv:error", "Unrecognized option %s", key.c_str()); } Mat image; bool b = obj->retrieve(image, idx); if (b && flip && image.channels()==3) cvtColor(image, image, cv::COLOR_BGR2RGB); plhs[0] = MxArray(b ? image : Mat()); } else if (method == "read") { nargchk(nrhs>=2 && (nrhs%2)==0 && nlhs<=1); bool flip = true; for (int i=2; i<nrhs; i+=2) { string key(rhs[i].toString()); if (key == "FlipChannels") flip = rhs[i+1].toBool(); else mexErrMsgIdAndTxt("mexopencv:error", "Unrecognized option %s", key.c_str()); } Mat image; bool b = obj->read(image); if (b && flip && image.channels()==3) cvtColor(image, image, cv::COLOR_BGR2RGB); plhs[0] = MxArray(b ? image : Mat()); } else if (method == "get") { nargchk(nrhs==3 && nlhs<=1); int propId = (rhs[2].isChar()) ? CapProp[rhs[2].toString()] : rhs[2].toInt(); double value = obj->get(propId); plhs[0] = MxArray(value); } else if (method == "set") { nargchk(nrhs==4 && nlhs==0); int propId = (rhs[2].isChar()) ? CapProp[rhs[2].toString()] : rhs[2].toInt(); double value = rhs[3].toDouble(); bool success = obj->set(propId, value); if (!success) mexWarnMsgIdAndTxt("mexopencv:error", "Error setting property %d", propId); } else mexErrMsgIdAndTxt("mexopencv:error", "Unrecognized operation %s", method.c_str()); }
35.674208
76
0.541603
[ "object", "vector" ]
4f2bf4fabdfce8d7d6a6497ea20d3f01e2cdc174
22,495
cpp
C++
audio/sysvad/EndpointsCommon/mintopo.cpp
hassnaaHamdi/Windows-driver-samples
325b87cf839b1b5c0ff46bb8c201612cfaedc561
[ "MS-PL" ]
2
2020-11-06T09:35:06.000Z
2021-12-10T05:14:17.000Z
audio/sysvad/EndpointsCommon/mintopo.cpp
hassnaaHamdi/Windows-driver-samples
325b87cf839b1b5c0ff46bb8c201612cfaedc561
[ "MS-PL" ]
null
null
null
audio/sysvad/EndpointsCommon/mintopo.cpp
hassnaaHamdi/Windows-driver-samples
325b87cf839b1b5c0ff46bb8c201612cfaedc561
[ "MS-PL" ]
1
2021-12-10T05:14:20.000Z
2021-12-10T05:14:20.000Z
/*++ Copyright (c) 1997-2011 Microsoft Corporation All Rights Reserved Module Name: mintopo.cpp Abstract: Implementation of topology miniport. --*/ #pragma warning (disable : 4127) #include <sysvad.h> #include "simple.h" #include "minwavert.h" #include "mintopo.h" //============================================================================= #pragma code_seg("PAGE") NTSTATUS CreateMiniportTopologySYSVAD ( _Out_ PUNKNOWN * Unknown, _In_ REFCLSID, _In_opt_ PUNKNOWN UnknownOuter, _When_((PoolType & NonPagedPoolMustSucceed) != 0, __drv_reportError("Must succeed pool allocations are forbidden. " "Allocation failures cause a system crash")) _In_ POOL_TYPE PoolType, _In_ PUNKNOWN UnknownAdapter, _In_opt_ PVOID DeviceContext, _In_ PENDPOINT_MINIPAIR MiniportPair ) /*++ Routine Description: Creates a new topology miniport. Arguments: Unknown - RefclsId - PoolType - UnknownOuter - DeviceContext - MiniportPair - Return Value: NT status code. --*/ { PAGED_CODE(); UNREFERENCED_PARAMETER(UnknownAdapter); ASSERT(Unknown); ASSERT(MiniportPair); CMiniportTopology *obj = new (PoolType, MINWAVERT_POOLTAG) CMiniportTopology( UnknownOuter, MiniportPair->TopoDescriptor, MiniportPair->DeviceMaxChannels, MiniportPair->DeviceType, DeviceContext ); if (NULL == obj) { return STATUS_INSUFFICIENT_RESOURCES; } obj->AddRef(); *Unknown = reinterpret_cast<IUnknown*>(obj); return STATUS_SUCCESS; } // CreateMiniportTopologySYSVAD //============================================================================= #pragma code_seg("PAGE") CMiniportTopology::~CMiniportTopology ( void ) /*++ Routine Description: Topology miniport destructor Arguments: Return Value: NT status code. --*/ { PAGED_CODE(); DPF_ENTER(("[CMiniportTopology::~CMiniportTopology]")); #if defined(SYSVAD_BTH_BYPASS) || defined(SYSVAD_USB_SIDEBAND) || defined (SYSVAD_A2DP_SIDEBAND) if (IsSidebandDevice()) { ASSERT(m_pSidebandDevice != NULL); // // Register with BthHfpDevice, A2dpHpDevice or UsbHsDevice to get notification events. // if(IsSidebandDevice()) { m_pSidebandDevice->SetVolumeHandler(m_DeviceType, NULL, NULL); m_pSidebandDevice->SetMuteHandler(m_DeviceType, NULL, NULL); m_pSidebandDevice->SetConnectionStatusHandler(m_DeviceType, NULL, NULL); } SAFE_RELEASE(m_pSidebandDevice); // ISidebandDeviceCommon } #endif // defined(SYSVAD_BTH_BYPASS) || defined(SYSVAD_USB_SIDEBAND) || defined(SYSVAD_A2DP_SIDEBAND) } // ~CMiniportTopology //============================================================================= #pragma code_seg("PAGE") NTSTATUS CMiniportTopology::DataRangeIntersection ( _In_ ULONG PinId, _In_ PKSDATARANGE ClientDataRange, _In_ PKSDATARANGE MyDataRange, _In_ ULONG OutputBufferLength, _Out_writes_bytes_to_opt_(OutputBufferLength, *ResultantFormatLength) PVOID ResultantFormat, _Out_ PULONG ResultantFormatLength ) /*++ Routine Description: The DataRangeIntersection function determines the highest quality intersection of two data ranges. Arguments: PinId - Pin for which data intersection is being determined. ClientDataRange - Pointer to KSDATARANGE structure which contains the data range submitted by client in the data range intersection property request. MyDataRange - Pin's data range to be compared with client's data range. OutputBufferLength - Size of the buffer pointed to by the resultant format parameter. ResultantFormat - Pointer to value where the resultant format should be returned. ResultantFormatLength - Actual length of the resultant format that is placed at ResultantFormat. This should be less than or equal to OutputBufferLength. Return Value: NT status code. --*/ { PAGED_CODE(); return CMiniportTopologySYSVAD::DataRangeIntersection ( PinId, ClientDataRange, MyDataRange, OutputBufferLength, ResultantFormat, ResultantFormatLength ); } // DataRangeIntersection //============================================================================= #pragma code_seg("PAGE") STDMETHODIMP CMiniportTopology::GetDescription ( _Out_ PPCFILTER_DESCRIPTOR * OutFilterDescriptor ) /*++ Routine Description: The GetDescription function gets a pointer to a filter description. It provides a location to deposit a pointer in miniport's description structure. This is the placeholder for the FromNode or ToNode fields in connections which describe connections to the filter's pins. Arguments: OutFilterDescriptor - Pointer to the filter description. Return Value: NT status code. --*/ { PAGED_CODE(); ASSERT(OutFilterDescriptor); return CMiniportTopologySYSVAD::GetDescription(OutFilterDescriptor); } // GetDescription //============================================================================= #pragma code_seg("PAGE") STDMETHODIMP CMiniportTopology::Init ( _In_ PUNKNOWN UnknownAdapter, _In_ PRESOURCELIST ResourceList, _In_ PPORTTOPOLOGY Port_ ) /*++ Routine Description: The Init function initializes the miniport. Callers of this function should run at IRQL PASSIVE_LEVEL Arguments: UnknownAdapter - A pointer to the Iuknown interface of the adapter object. ResourceList - Pointer to the resource list to be supplied to the miniport during initialization. The port driver is free to examine the contents of the ResourceList. The port driver will not be modify the ResourceList contents. Port - Pointer to the topology port object that is linked with this miniport. Return Value: NT status code. --*/ { UNREFERENCED_PARAMETER(ResourceList); PAGED_CODE(); ASSERT(UnknownAdapter); ASSERT(Port_); DPF_ENTER(("[CMiniportTopology::Init]")); NTSTATUS ntStatus; ntStatus = CMiniportTopologySYSVAD::Init ( UnknownAdapter, Port_ ); IF_FAILED_ACTION_JUMP( ntStatus, DPF(D_ERROR, ("Init: CMiniportTopologySYSVAD::Init failed, 0x%x", ntStatus)), Done); #if defined(SYSVAD_BTH_BYPASS) || defined(SYSVAD_USB_SIDEBAND) || defined(SYSVAD_A2DP_SIDEBAND) if (IsSidebandDevice()) { PSIDEBANDDEVICECOMMON sidebandDevice = NULL; sidebandDevice = GetSidebandDevice(); // weak ref. ASSERT(sidebandDevice != NULL); // // Register with BthHfpDevice to get notification events. // if (m_DeviceType == eBthHfpMicDevice || m_DeviceType == eUsbHsMicDevice) { sidebandDevice->SetVolumeHandler( m_DeviceType, EvtMicVolumeHandler, // handler PCMiniportTopology(this)); // context. sidebandDevice->SetConnectionStatusHandler( m_DeviceType, EvtMicConnectionStatusHandler, // handler PCMiniportTopology(this)); // context. } else { ASSERT(m_DeviceType == eBthHfpSpeakerDevice || m_DeviceType == eUsbHsSpeakerDevice || m_DeviceType == eA2dpHpSpeakerDevice); sidebandDevice->SetVolumeHandler( m_DeviceType, EvtSpeakerVolumeHandler, // handler PCMiniportTopology(this)); // context. sidebandDevice->SetConnectionStatusHandler( m_DeviceType, EvtSpeakerConnectionStatusHandler, // handler PCMiniportTopology(this)); // context. } } #endif // defined(SYSVAD_BTH_BYPASS) || defined(SYSVAD_USB_SIDEBAND) || defined(SYSVAD_A2DP_SIDEBAND) Done: return ntStatus; } // Init //============================================================================= #pragma code_seg("PAGE") STDMETHODIMP CMiniportTopology::NonDelegatingQueryInterface ( _In_ REFIID Interface, _COM_Outptr_ PVOID * Object ) /*++ Routine Description: QueryInterface for MiniportTopology Arguments: Interface - GUID of the interface Object - interface object to be returned. Return Value: NT status code. --*/ { PAGED_CODE(); ASSERT(Object); if (IsEqualGUIDAligned(Interface, IID_IUnknown)) { *Object = PVOID(PUNKNOWN(this)); } else if (IsEqualGUIDAligned(Interface, IID_IMiniport)) { *Object = PVOID(PMINIPORT(this)); } else if (IsEqualGUIDAligned(Interface, IID_IMiniportTopology)) { *Object = PVOID(PMINIPORTTOPOLOGY(this)); } else { *Object = NULL; } if (*Object) { // We reference the interface for the caller. PUNKNOWN(*Object)->AddRef(); return(STATUS_SUCCESS); } return(STATUS_INVALID_PARAMETER); } // NonDelegatingQueryInterface //============================================================================= #pragma code_seg("PAGE") NTSTATUS CMiniportTopology::PropertyHandlerJackDescription ( _In_ PPCPROPERTY_REQUEST PropertyRequest, _In_ ULONG cJackDescriptions, _In_reads_(cJackDescriptions) PKSJACK_DESCRIPTION * JackDescriptions ) /*++ Routine Description: Handles ( KSPROPSETID_Jack, KSPROPERTY_JACK_DESCRIPTION ) Arguments: PropertyRequest - cJackDescriptions - # of elements in the jack descriptions array. JackDescriptions - Array of jack descriptions pointers. Return Value: NT status code. --*/ { PAGED_CODE(); ASSERT(PropertyRequest); DPF_ENTER(("[PropertyHandlerJackDescription]")); NTSTATUS ntStatus = STATUS_INVALID_DEVICE_REQUEST; ULONG nPinId = (ULONG)-1; if (PropertyRequest->InstanceSize >= sizeof(ULONG)) { nPinId = *(PULONG(PropertyRequest->Instance)); if ((nPinId < cJackDescriptions) && (JackDescriptions[nPinId] != NULL)) { if (PropertyRequest->Verb & KSPROPERTY_TYPE_BASICSUPPORT) { ntStatus = PropertyHandler_BasicSupport ( PropertyRequest, KSPROPERTY_TYPE_BASICSUPPORT | KSPROPERTY_TYPE_GET, VT_ILLEGAL ); } else { ULONG cbNeeded = sizeof(KSMULTIPLE_ITEM) + sizeof(KSJACK_DESCRIPTION); if (PropertyRequest->ValueSize == 0) { PropertyRequest->ValueSize = cbNeeded; ntStatus = STATUS_BUFFER_OVERFLOW; } else if (PropertyRequest->ValueSize < cbNeeded) { ntStatus = STATUS_BUFFER_TOO_SMALL; } else { if (PropertyRequest->Verb & KSPROPERTY_TYPE_GET) { PKSMULTIPLE_ITEM pMI = (PKSMULTIPLE_ITEM)PropertyRequest->Value; PKSJACK_DESCRIPTION pDesc = (PKSJACK_DESCRIPTION)(pMI+1); pMI->Size = cbNeeded; pMI->Count = 1; RtlCopyMemory(pDesc, JackDescriptions[nPinId], sizeof(KSJACK_DESCRIPTION)); ntStatus = STATUS_SUCCESS; } } } } } return ntStatus; } //============================================================================= #pragma code_seg("PAGE") NTSTATUS CMiniportTopology::PropertyHandlerJackDescription2 ( _In_ PPCPROPERTY_REQUEST PropertyRequest, _In_ ULONG cJackDescriptions, _In_reads_(cJackDescriptions) PKSJACK_DESCRIPTION * JackDescriptions, _In_ DWORD JackCapabilities ) /*++ Routine Description: Handles ( KSPROPSETID_Jack, KSPROPERTY_JACK_DESCRIPTION2 ) Arguments: PropertyRequest - cJackDescriptions - # of elements in the jack descriptions array. JackDescriptions - Array of jack descriptions pointers. JackCapabilities - Jack capabilities flags. Return Value: NT status code. --*/ { PAGED_CODE(); ASSERT(PropertyRequest); DPF_ENTER(("[PropertyHandlerJackDescription2]")); NTSTATUS ntStatus = STATUS_INVALID_DEVICE_REQUEST; ULONG nPinId = (ULONG)-1; if (PropertyRequest->InstanceSize >= sizeof(ULONG)) { nPinId = *(PULONG(PropertyRequest->Instance)); if ((nPinId < cJackDescriptions) && (JackDescriptions[nPinId] != NULL)) { if (PropertyRequest->Verb & KSPROPERTY_TYPE_BASICSUPPORT) { ntStatus = PropertyHandler_BasicSupport ( PropertyRequest, KSPROPERTY_TYPE_BASICSUPPORT | KSPROPERTY_TYPE_GET, VT_ILLEGAL ); } else { ULONG cbNeeded = sizeof(KSMULTIPLE_ITEM) + sizeof(KSJACK_DESCRIPTION2); if (PropertyRequest->ValueSize == 0) { PropertyRequest->ValueSize = cbNeeded; ntStatus = STATUS_BUFFER_OVERFLOW; } else if (PropertyRequest->ValueSize < cbNeeded) { ntStatus = STATUS_BUFFER_TOO_SMALL; } else { if (PropertyRequest->Verb & KSPROPERTY_TYPE_GET) { PKSMULTIPLE_ITEM pMI = (PKSMULTIPLE_ITEM)PropertyRequest->Value; PKSJACK_DESCRIPTION2 pDesc = (PKSJACK_DESCRIPTION2)(pMI+1); pMI->Size = cbNeeded; pMI->Count = 1; RtlZeroMemory(pDesc, sizeof(KSJACK_DESCRIPTION2)); // // Specifies the lower 16 bits of the DWORD parameter. This parameter indicates whether // the jack is currently active, streaming, idle, or hardware not ready. // pDesc->DeviceStateInfo = 0; // // From MSDN: // "If an audio device lacks jack presence detection, the IsConnected member of // the KSJACK_DESCRIPTION structure must always be set to TRUE. To remove the // ambiguity that results from this dual meaning of the TRUE value for IsConnected, // a client application can call IKsJackDescription2::GetJackDescription2 to read // the JackCapabilities flag of the KSJACK_DESCRIPTION2 structure. If this flag has // the JACKDESC2_PRESENCE_DETECT_CAPABILITY bit set, it indicates that the endpoint // does in fact support jack presence detection. In that case, the return value of // the IsConnected member can be interpreted to accurately reflect the insertion status // of the jack." // // Bit definitions: // 0x00000001 - JACKDESC2_PRESENCE_DETECT_CAPABILITY // 0x00000002 - JACKDESC2_DYNAMIC_FORMAT_CHANGE_CAPABILITY // pDesc->JackCapabilities = JackCapabilities; ntStatus = STATUS_SUCCESS; } } } } } return ntStatus; } #if defined(SYSVAD_BTH_BYPASS) || defined(SYSVAD_USB_SIDEBAND) //============================================================================= #pragma code_seg() VOID CMiniportTopology::EvtSpeakerVolumeHandler ( _In_opt_ PVOID Context ) { DPF_ENTER(("[CMiniportTopologySYSVAD::EvtSpeakerVolumeHandler]")); PCMiniportTopology This = PCMiniportTopology(Context); if (This == NULL) { DPF(D_ERROR, ("EvtSpeakerVolumeHandler: context is null")); return; } This->GenerateEventList( (GUID*)&KSEVENTSETID_AudioControlChange, // event set. NULL is a wild card for all events. KSEVENT_CONTROL_CHANGE, // event ID. FALSE, // do not use pid ID. ULONG(-1), // pin ID, not used. TRUE, // use node ID KSNODE_TOPO_VOLUME); // node ID. } //============================================================================= #pragma code_seg() VOID CMiniportTopology::EvtSpeakerConnectionStatusHandler ( _In_opt_ PVOID Context ) { DPF_ENTER(("[CMiniportTopologySYSVAD::EvtSpeakerConnectionStatusHandler]")); PCMiniportTopology This = PCMiniportTopology(Context); if (This == NULL) { DPF(D_ERROR, ("EvtSpeakerConnectionStatusHandler: context is null")); return; } This->GenerateEventList( (GUID*)&KSEVENTSETID_PinCapsChange, // event set. NULL is a wild card for all events. KSEVENT_PINCAPS_JACKINFOCHANGE, // event ID. TRUE, // use pid ID. KSPIN_TOPO_LINEOUT_DEST, // pin ID. FALSE, // do not use node ID. ULONG(-1)); // node ID, not used. } //============================================================================= #pragma code_seg() VOID CMiniportTopology::EvtMicVolumeHandler ( _In_opt_ PVOID Context ) { DPF_ENTER(("[CMiniportTopologySYSVAD::EvtMicVolumeHandler]")); PCMiniportTopology This = PCMiniportTopology(Context); if (This == NULL) { DPF(D_ERROR, ("EvtMicVolumeHandler: context is null")); return; } This->GenerateEventList( (GUID*)&KSEVENTSETID_AudioControlChange, // event set. NULL is a wild card for all events. KSEVENT_CONTROL_CHANGE, // event ID. FALSE, // do not use pid ID. ULONG(-1), // pin ID, not used. TRUE, // use node ID. KSNODE_TOPO_VOLUME); // node ID. } //============================================================================= #pragma code_seg() VOID CMiniportTopology::EvtMicConnectionStatusHandler ( _In_opt_ PVOID Context ) { DPF_ENTER(("[CMiniportTopologySYSVAD::EvtMicConnectionStatusHandler]")); PCMiniportTopology This = PCMiniportTopology(Context); if (This == NULL) { DPF(D_ERROR, ("EvtMicConnectionStatusHandler: context is null")); return; } This->GenerateEventList( (GUID*)&KSEVENTSETID_PinCapsChange, // event set. NULL is a wild card for all events. KSEVENT_PINCAPS_JACKINFOCHANGE, // event ID. TRUE, // use pid ID. KSPIN_TOPO_MIC_ELEMENTS, // pin ID. FALSE, // do not use node ID. ULONG(-1)); // node ID, not used. } #endif // defined(SYSVAD_BTH_BYPASS) || defined(SYSVAD_USB_SIDEBAND) //============================================================================= #pragma code_seg("PAGE") NTSTATUS PropertyHandler_Topology ( _In_ PPCPROPERTY_REQUEST PropertyRequest ) /*++ Routine Description: Redirects property request to miniport object Arguments: PropertyRequest - Return Value: NT status code. --*/ { PAGED_CODE(); ASSERT(PropertyRequest); DPF_ENTER(("[PropertyHandler_Topology]")); // PropertryRequest structure is filled by portcls. // MajorTarget is a pointer to miniport object for miniports. // return ((PCMiniportTopology) (PropertyRequest->MajorTarget))->PropertyHandlerGeneric ( PropertyRequest ); } // PropertyHandler_Topology #pragma code_seg() //============================================================================= NTSTATUS CMiniportTopology_EventHandler_JackState ( _In_ PPCEVENT_REQUEST EventRequest ) { CMiniportTopology* miniport = reinterpret_cast<CMiniportTopology*>(EventRequest->MajorTarget); if (EventRequest->Verb == PCEVENT_VERB_ADD) { miniport->AddEventToEventList(EventRequest->EventEntry); } return STATUS_SUCCESS; }
30.113788
137
0.534074
[ "object" ]
4f2c3e24e62c5978fed9dbd329699166712909e9
38,872
cpp
C++
samples/sample_fei/src/fei_encode.cpp
me176c-dev/MediaSDK
0c7f315958b78c98c5c06bd60565eb8c1ad15d41
[ "MIT" ]
null
null
null
samples/sample_fei/src/fei_encode.cpp
me176c-dev/MediaSDK
0c7f315958b78c98c5c06bd60565eb8c1ad15d41
[ "MIT" ]
null
null
null
samples/sample_fei/src/fei_encode.cpp
me176c-dev/MediaSDK
0c7f315958b78c98c5c06bd60565eb8c1ad15d41
[ "MIT" ]
null
null
null
/******************************************************************************\ Copyright (c) 2005-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, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER 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. This sample was distributed or derived from the Intel's Media Samples package. The original version of this sample may be obtained from https://software.intel.com/en-us/intel-media-server-studio or https://software.intel.com/en-us/media-client-solutions-support. \**********************************************************************************/ #include "fei_encode.h" #ifndef MFX_VERSION #error MFX_VERSION not defined #endif FEI_EncodeInterface::FEI_EncodeInterface(MFXVideoSession* session, mfxU32 allocId, bufList* ext_bufs, AppConfig* config) : m_pmfxSession(session) , m_pmfxENCODE(new MFXVideoENCODE(*session)) , m_allocId(allocId) , m_pExtBuffers(ext_bufs) , m_pAppConfig(config) , m_SyncPoint(0) , m_bSingleFieldMode(config->bFieldProcessingMode) , m_pMvPred_in(NULL) , m_pENC_MBCtrl_in(NULL) , m_pMbQP_in(NULL) , m_pRepackCtrl_in(NULL) , m_pWeights_in(NULL) , m_pMBstat_out(NULL) , m_pMV_out(NULL) , m_pMBcode_out(NULL) #if (MFX_VERSION >= 1025) , m_pRepackStat_out(NULL) #endif { MSDK_ZERO_MEMORY(m_videoParams); MSDK_ZERO_MEMORY(m_encodeControl); m_encodeControl.FrameType = MFX_FRAMETYPE_UNKNOWN; m_encodeControl.QP = m_pAppConfig->QP; m_InitExtParams.reserve(5); /* Default values for I-frames */ memset(&m_tmpMBencMV, 0x8000, sizeof(mfxExtFeiEncMV::mfxExtFeiEncMVMB)); } FEI_EncodeInterface::~FEI_EncodeInterface() { MSDK_SAFE_DELETE(m_pmfxENCODE); mfxExtFeiSliceHeader* pSlices = NULL; for (mfxU32 i = 0; i < m_InitExtParams.size(); ++i) { switch (m_InitExtParams[i]->BufferId) { case MFX_EXTBUFF_FEI_PARAM: { mfxExtFeiParam* ptr = reinterpret_cast<mfxExtFeiParam*>(m_InitExtParams[i]); MSDK_SAFE_DELETE(ptr); } break; case MFX_EXTBUFF_CODING_OPTION2: { mfxExtCodingOption2* ptr = reinterpret_cast<mfxExtCodingOption2*>(m_InitExtParams[i]); MSDK_SAFE_DELETE(ptr); } break; case MFX_EXTBUFF_CODING_OPTION3: { mfxExtCodingOption3* ptr = reinterpret_cast<mfxExtCodingOption3*>(m_InitExtParams[i]); MSDK_SAFE_DELETE(ptr); } break; case MFX_EXTBUFF_FEI_SLICE: { mfxExtFeiSliceHeader* ptr = reinterpret_cast<mfxExtFeiSliceHeader*>(m_InitExtParams[i]); MSDK_SAFE_DELETE_ARRAY(ptr->Slice); if (!pSlices) { pSlices = ptr; } } break; #if (MFX_VERSION >= 1025) case MFX_EXTBUFF_MULTI_FRAME_PARAM: { mfxExtMultiFrameParam* ptr = reinterpret_cast<mfxExtMultiFrameParam*>(m_InitExtParams[i]); MSDK_SAFE_DELETE(ptr); } break; case MFX_EXTBUFF_MULTI_FRAME_CONTROL: { mfxExtMultiFrameControl* ptr = reinterpret_cast<mfxExtMultiFrameControl*>(m_InitExtParams[i]); MSDK_SAFE_DELETE(ptr); } break; #endif } } MSDK_SAFE_DELETE_ARRAY(pSlices); m_InitExtParams.clear(); SAFE_FCLOSE(m_pMvPred_in); SAFE_FCLOSE(m_pENC_MBCtrl_in); SAFE_FCLOSE(m_pMbQP_in); SAFE_FCLOSE(m_pRepackCtrl_in); SAFE_FCLOSE(m_pWeights_in); SAFE_FCLOSE(m_pMBstat_out); SAFE_FCLOSE(m_pMV_out); SAFE_FCLOSE(m_pMBcode_out); #if (MFX_VERSION >= 1025) SAFE_FCLOSE(m_pRepackStat_out); #endif m_pAppConfig->PipelineCfg.pEncodeVideoParam = NULL; } void FEI_EncodeInterface::GetRefInfo( mfxU16 & picStruct, mfxU16 & refDist, mfxU16 & numRefFrame, mfxU16 & gopSize, mfxU16 & gopOptFlag, mfxU16 & idrInterval, mfxU16 & numRefActiveP, mfxU16 & numRefActiveBL0, mfxU16 & numRefActiveBL1, mfxU16 & bRefType, bool & bSigleFieldProcessing) { for (mfxU32 i = 0; i < m_InitExtParams.size(); ++i) { switch (m_InitExtParams[i]->BufferId) { case MFX_EXTBUFF_CODING_OPTION2: { mfxExtCodingOption2* ptr = reinterpret_cast<mfxExtCodingOption2*>(m_InitExtParams[i]); bRefType = ptr->BRefType; } break; case MFX_EXTBUFF_CODING_OPTION3: { mfxExtCodingOption3* ptr = reinterpret_cast<mfxExtCodingOption3*>(m_InitExtParams[i]); numRefActiveP = ptr->NumRefActiveP[0]; numRefActiveBL0 = ptr->NumRefActiveBL0[0]; numRefActiveBL1 = ptr->NumRefActiveBL1[0]; } break; case MFX_EXTBUFF_FEI_PARAM: { mfxExtFeiParam* ptr = reinterpret_cast<mfxExtFeiParam*>(m_InitExtParams[i]); m_bSingleFieldMode = bSigleFieldProcessing = ptr->SingleFieldProcessing == MFX_CODINGOPTION_ON; } break; default: break; } } picStruct = m_videoParams.mfx.FrameInfo.PicStruct; refDist = m_videoParams.mfx.GopRefDist; numRefFrame = m_videoParams.mfx.NumRefFrame; gopSize = m_videoParams.mfx.GopPicSize; gopOptFlag = m_videoParams.mfx.GopOptFlag; idrInterval = m_videoParams.mfx.IdrInterval; } mfxStatus FEI_EncodeInterface::FillParameters() { mfxStatus sts = MFX_ERR_NONE; /* Share ENCODE video parameters with other interfaces */ m_pAppConfig->PipelineCfg.pEncodeVideoParam = &m_videoParams; m_videoParams.AllocId = m_allocId; m_videoParams.mfx.CodecId = m_pAppConfig->CodecId; m_videoParams.mfx.TargetUsage = 0; // FEI doesn't have support of m_videoParams.mfx.TargetKbps = 0; // these features m_videoParams.mfx.RateControlMethod = MFX_RATECONTROL_CQP; // For now FEI work with RATECONTROL_CQP only sts = ConvertFrameRate(m_pAppConfig->dFrameRate, &m_videoParams.mfx.FrameInfo.FrameRateExtN, &m_videoParams.mfx.FrameInfo.FrameRateExtD); MSDK_CHECK_STATUS(sts, "ConvertFrameRate failed"); /* Binary flag, 0 signals encoder to take frames in display order. PREENC, ENCPAK, ENC, PAK interfaces works only in encoded order */ m_videoParams.mfx.EncodedOrder = mfxU16(m_pAppConfig->EncodedOrder || (m_pAppConfig->bPREENC || m_pAppConfig->bENCPAK || m_pAppConfig->bOnlyENC || m_pAppConfig->bOnlyPAK)); m_videoParams.mfx.QPI = m_videoParams.mfx.QPP = m_videoParams.mfx.QPB = m_pAppConfig->QP; /* Specify memory type */ m_videoParams.IOPattern = mfxU16(m_pAppConfig->bUseHWmemory ? MFX_IOPATTERN_IN_VIDEO_MEMORY : MFX_IOPATTERN_IN_SYSTEM_MEMORY); if (m_pAppConfig->bDECODE && !m_pAppConfig->bVPP) { MSDK_CHECK_POINTER(m_pAppConfig->PipelineCfg.pDecodeVideoParam, MFX_ERR_NULL_PTR); /* in case of decoder without VPP copy FrameInfo from decoder */ MSDK_MEMCPY_VAR(m_videoParams.mfx.FrameInfo, &m_pAppConfig->PipelineCfg.pDecodeVideoParam->mfx.FrameInfo, sizeof(mfxFrameInfo)); m_videoParams.mfx.FrameInfo.PicStruct = m_pAppConfig->nPicStruct; m_pAppConfig->nWidth = m_pAppConfig->nDstWidth = m_videoParams.mfx.FrameInfo.CropW; m_pAppConfig->nHeight = m_pAppConfig->nDstHeight = m_videoParams.mfx.FrameInfo.CropH; } else if (m_pAppConfig->bVPP) { MSDK_CHECK_POINTER(m_pAppConfig->PipelineCfg.pVppVideoParam, MFX_ERR_NULL_PTR); /* in case of VPP copy FrameInfo from VPP output */ MSDK_MEMCPY_VAR(m_videoParams.mfx.FrameInfo, &m_pAppConfig->PipelineCfg.pVppVideoParam->vpp.Out, sizeof(mfxFrameInfo)); } else { // frame info parameters m_videoParams.mfx.FrameInfo.FourCC = MFX_FOURCC_NV12; m_videoParams.mfx.FrameInfo.ChromaFormat = MFX_CHROMAFORMAT_YUV420; m_videoParams.mfx.FrameInfo.PicStruct = m_pAppConfig->nPicStruct; // Set frame size and crops // Width must be a multiple of 16 // Height must be a multiple of 16 in case of frame picture and a multiple of 32 in case of field picture m_videoParams.mfx.FrameInfo.Width = MSDK_ALIGN16(m_pAppConfig->nDstWidth); m_videoParams.mfx.FrameInfo.Height = (MFX_PICSTRUCT_PROGRESSIVE & m_videoParams.mfx.FrameInfo.PicStruct) ? MSDK_ALIGN16(m_pAppConfig->nDstHeight) : MSDK_ALIGN32(m_pAppConfig->nDstHeight); m_videoParams.mfx.FrameInfo.CropX = 0; m_videoParams.mfx.FrameInfo.CropY = 0; m_videoParams.mfx.FrameInfo.CropW = m_pAppConfig->nDstWidth; m_videoParams.mfx.FrameInfo.CropH = m_pAppConfig->nDstHeight; } m_videoParams.AsyncDepth = 1; //current limitation m_videoParams.mfx.GopRefDist = (std::max)(m_pAppConfig->refDist, mfxU16(1)); m_videoParams.mfx.GopPicSize = (std::max)(m_pAppConfig->gopSize, mfxU16(1)); m_videoParams.mfx.IdrInterval = m_pAppConfig->nIdrInterval; m_videoParams.mfx.GopOptFlag = m_pAppConfig->GopOptFlag; m_videoParams.mfx.CodecProfile = m_pAppConfig->CodecProfile; m_videoParams.mfx.CodecLevel = m_pAppConfig->CodecLevel; /* Multi references and multi slices*/ m_videoParams.mfx.NumRefFrame = (std::max)(m_pAppConfig->numRef, mfxU16(1)); m_videoParams.mfx.NumSlice = (std::max)(m_pAppConfig->numSlices, mfxU16(1)); // configure trellis, B-pyramid, RAW-reference settings mfxExtCodingOption2* pCodingOption2 = new mfxExtCodingOption2; MSDK_ZERO_MEMORY(*pCodingOption2); pCodingOption2->Header.BufferId = MFX_EXTBUFF_CODING_OPTION2; pCodingOption2->Header.BufferSz = sizeof(mfxExtCodingOption2); pCodingOption2->UseRawRef = mfxU16(m_pAppConfig->bRawRef ? MFX_CODINGOPTION_ON : MFX_CODINGOPTION_OFF); pCodingOption2->BRefType = m_pAppConfig->bRefType; pCodingOption2->Trellis = m_pAppConfig->Trellis; m_InitExtParams.push_back(reinterpret_cast<mfxExtBuffer *>(pCodingOption2)); // configure P/B reference number, explicit weighted prediction mfxExtCodingOption3* pCodingOption3 = new mfxExtCodingOption3; MSDK_ZERO_MEMORY(*pCodingOption3); pCodingOption3->Header.BufferId = MFX_EXTBUFF_CODING_OPTION3; pCodingOption3->Header.BufferSz = sizeof(mfxExtCodingOption3); pCodingOption3->NumRefActiveP[0] = m_pAppConfig->NumRefActiveP; pCodingOption3->NumRefActiveBL0[0] = m_pAppConfig->NumRefActiveBL0; pCodingOption3->NumRefActiveBL1[0] = m_pAppConfig->NumRefActiveBL1; // weight table file is provided, so explicit weight prediction is enabled. pCodingOption3->WeightedPred = m_pAppConfig->weightsFile ? MFX_WEIGHTED_PRED_EXPLICIT : MFX_WEIGHTED_PRED_UNKNOWN; pCodingOption3->WeightedBiPred = m_pAppConfig->weightsFile ? MFX_WEIGHTED_PRED_EXPLICIT : MFX_WEIGHTED_PRED_UNKNOWN; pCodingOption3->WeightedBiPred = m_pAppConfig->bImplicitWPB ? MFX_WEIGHTED_PRED_IMPLICIT : pCodingOption3->WeightedBiPred; /* values stored in m_CodingOption3 required to fill encoding task for PREENC/ENC/PAK*/ m_InitExtParams.push_back(reinterpret_cast<mfxExtBuffer *>(pCodingOption3)); /* Create extension buffer to Init FEI ENCODE */ mfxExtFeiParam* pExtBufInit = new mfxExtFeiParam; MSDK_ZERO_MEMORY(*pExtBufInit); pExtBufInit->Header.BufferId = MFX_EXTBUFF_FEI_PARAM; pExtBufInit->Header.BufferSz = sizeof(mfxExtFeiParam); pExtBufInit->Func = MFX_FEI_FUNCTION_ENCODE; pExtBufInit->SingleFieldProcessing = mfxU16(m_bSingleFieldMode ? MFX_CODINGOPTION_ON : MFX_CODINGOPTION_OFF); m_InitExtParams.push_back(reinterpret_cast<mfxExtBuffer *>(pExtBufInit)); /* Create extension buffer to init deblocking parameters */ if (m_pAppConfig->DisableDeblockingIdc || m_pAppConfig->SliceAlphaC0OffsetDiv2 || m_pAppConfig->SliceBetaOffsetDiv2) { mfxU16 numFields = (m_videoParams.mfx.FrameInfo.PicStruct & MFX_PICSTRUCT_PROGRESSIVE) ? 1 : 2; mfxExtFeiSliceHeader* pSliceHeader = new mfxExtFeiSliceHeader[numFields]; MSDK_ZERO_ARRAY(pSliceHeader, numFields); for (mfxU16 fieldId = 0; fieldId < numFields; ++fieldId) { pSliceHeader[fieldId].Header.BufferId = MFX_EXTBUFF_FEI_SLICE; pSliceHeader[fieldId].Header.BufferSz = sizeof(mfxExtFeiSliceHeader); pSliceHeader[fieldId].NumSlice = m_videoParams.mfx.NumSlice; pSliceHeader[fieldId].Slice = new mfxExtFeiSliceHeader::mfxSlice[pSliceHeader[fieldId].NumSlice]; MSDK_ZERO_ARRAY(pSliceHeader[fieldId].Slice, pSliceHeader[fieldId].NumSlice); for (mfxU16 sliceNum = 0; sliceNum < pSliceHeader[fieldId].NumSlice; ++sliceNum) { pSliceHeader[fieldId].Slice[sliceNum].DisableDeblockingFilterIdc = m_pAppConfig->DisableDeblockingIdc; pSliceHeader[fieldId].Slice[sliceNum].SliceAlphaC0OffsetDiv2 = m_pAppConfig->SliceAlphaC0OffsetDiv2; pSliceHeader[fieldId].Slice[sliceNum].SliceBetaOffsetDiv2 = m_pAppConfig->SliceBetaOffsetDiv2; } m_InitExtParams.push_back(reinterpret_cast<mfxExtBuffer *>(&pSliceHeader[fieldId])); } } #if (MFX_VERSION >= 1025) if (m_pAppConfig->mfeMode != 0 || m_pAppConfig->numMfeFrames != 0) { // configure multiframe mode and number of frames // either of mfeMode and numMfeFrames must be set // if one of them not set - zero is passed to Media SDK and used internal default value mfxExtMultiFrameParam* pMfeParam = new mfxExtMultiFrameParam; MSDK_ZERO_MEMORY(*pMfeParam); pMfeParam->Header.BufferId = MFX_EXTBUFF_MULTI_FRAME_PARAM; pMfeParam->Header.BufferSz = sizeof(mfxExtMultiFrameParam); pMfeParam->MFMode = m_pAppConfig->mfeMode; pMfeParam->MaxNumFrames = m_pAppConfig->numMfeFrames; m_InitExtParams.push_back(reinterpret_cast<mfxExtBuffer *>(pMfeParam)); if(m_pAppConfig->mfeTimeout != 0) { //set default timeout per session if passed from commandline mfxExtMultiFrameControl* pMfeControl = new mfxExtMultiFrameControl; MSDK_ZERO_MEMORY(*pMfeControl); pMfeControl->Header.BufferId = MFX_EXTBUFF_MULTI_FRAME_CONTROL; pMfeControl->Header.BufferSz = sizeof(mfxExtMultiFrameControl); pMfeControl->Timeout = m_pAppConfig->mfeTimeout; m_InitExtParams.push_back(reinterpret_cast<mfxExtBuffer *>(pMfeControl)); } } else if (m_pAppConfig->mfeTimeout != 0 && m_pAppConfig->mfeMode == 0 && m_pAppConfig->numMfeFrames == 0) { printf("WARNING: MFE not enabled, to enable MFE specify mfe_mode and/or mfe_frames\n"); } #endif if (!m_InitExtParams.empty()) { m_videoParams.ExtParam = m_InitExtParams.data(); m_videoParams.NumExtParam = (mfxU16)m_InitExtParams.size(); } /* Init file pointers if some input buffers are specified */ if (!m_pAppConfig->bPREENC && m_pMvPred_in == NULL && m_pAppConfig->mvinFile != NULL) //not load if we couple with PREENC { printf("Using MV input file: %s\n", m_pAppConfig->mvinFile); MSDK_FOPEN(m_pMvPred_in, m_pAppConfig->mvinFile, MSDK_CHAR("rb")); if (m_pMvPred_in == NULL) { mdprintf(stderr, "Can't open file %s\n", m_pAppConfig->mvinFile); exit(-1); } /* Alloc temporal buffers */ if (m_pAppConfig->bRepackPreencMV) { m_tmpForMedian.resize(16); mfxU32 n_MB = m_pAppConfig->bDynamicRC ? m_pAppConfig->PipelineCfg.numMB_drc_max : m_pAppConfig->PipelineCfg.numMB_frame; m_tmpForReading.resize(n_MB); } } m_mfxBS.Extend(m_videoParams.mfx.FrameInfo.Width * m_videoParams.mfx.FrameInfo.Height * 4); if (m_pRepackCtrl_in == NULL && m_pAppConfig->repackctrlFile != NULL) { printf("Using Frame Size control input file: %s\n", m_pAppConfig->repackctrlFile); MSDK_FOPEN(m_pRepackCtrl_in, m_pAppConfig->repackctrlFile, MSDK_CHAR("rb")); if (m_pRepackCtrl_in == NULL) { mdprintf(stderr, "Can't open file %s\n", m_pAppConfig->repackctrlFile); exit(-1); } } #if (MFX_VERSION >= 1025) if (m_pRepackStat_out == NULL && m_pAppConfig->repackstatFile != NULL) { printf("Using Repack status output file: %s\n", m_pAppConfig->repackstatFile); MSDK_FOPEN(m_pRepackStat_out, m_pAppConfig->repackstatFile, MSDK_CHAR("w")); if (m_pRepackStat_out == NULL) { mdprintf(stderr, "Can't open file %s\n", m_pAppConfig->repackstatFile); exit(-1); } } #endif if (m_pENC_MBCtrl_in == NULL && m_pAppConfig->mbctrinFile != NULL) { printf("Using MB control input file: %s\n", m_pAppConfig->mbctrinFile); MSDK_FOPEN(m_pENC_MBCtrl_in, m_pAppConfig->mbctrinFile, MSDK_CHAR("rb")); if (m_pENC_MBCtrl_in == NULL) { mdprintf(stderr, "Can't open file %s\n", m_pAppConfig->mbctrinFile); exit(-1); } } if (m_pMbQP_in == NULL && m_pAppConfig->mbQpFile != NULL) { printf("Use MB QP input file: %s\n", m_pAppConfig->mbQpFile); MSDK_FOPEN(m_pMbQP_in, m_pAppConfig->mbQpFile, MSDK_CHAR("rb")); if (m_pMbQP_in == NULL) { mdprintf(stderr, "Can't open file %s\n", m_pAppConfig->mbQpFile); exit(-1); } } if (m_pMBstat_out == NULL && m_pAppConfig->mbstatoutFile != NULL) { printf("Use MB distortion output file: %s\n", m_pAppConfig->mbstatoutFile); MSDK_FOPEN(m_pMBstat_out, m_pAppConfig->mbstatoutFile, MSDK_CHAR("wb")); if (m_pMBstat_out == NULL) { mdprintf(stderr, "Can't open file %s\n", m_pAppConfig->mbstatoutFile); exit(-1); } } if (m_pMV_out == NULL && m_pAppConfig->mvoutFile != NULL) { printf("Use MV output file: %s\n", m_pAppConfig->mvoutFile); MSDK_FOPEN(m_pMV_out, m_pAppConfig->mvoutFile, MSDK_CHAR("wb")); if (m_pMV_out == NULL) { mdprintf(stderr, "Can't open file %s\n", m_pAppConfig->mvoutFile); exit(-1); } } if (m_pMBcode_out == NULL && m_pAppConfig->mbcodeoutFile != NULL) { printf("Use MB code output file: %s\n", m_pAppConfig->mbcodeoutFile); MSDK_FOPEN(m_pMBcode_out, m_pAppConfig->mbcodeoutFile, MSDK_CHAR("wb")); if (m_pMBcode_out == NULL) { mdprintf(stderr, "Can't open file %s\n", m_pAppConfig->mbcodeoutFile); exit(-1); } } if (m_pWeights_in == NULL && m_pAppConfig->weightsFile != NULL) { printf("Using Prediction Weights Table input file: %s\n", m_pAppConfig->weightsFile); MSDK_FOPEN(m_pWeights_in, m_pAppConfig->weightsFile, MSDK_CHAR("rb")); if (m_pWeights_in == NULL) { mdprintf(stderr, "Can't open file %s\n", m_pAppConfig->weightsFile); exit(-1); } } sts = m_FileWriter.Init(m_pAppConfig->dstFileBuff[0]); MSDK_CHECK_STATUS(sts, "FEI ENCODE: FileWriter.Init failed"); return sts; } mfxStatus FEI_EncodeInterface::InitFrameParams(iTask* eTask) { MSDK_CHECK_POINTER(eTask, MFX_ERR_NULL_PTR); mfxStatus sts = MFX_ERR_NONE; mfxFrameSurface1* encodeSurface = eTask->ENC_in.InSurface; /* Alloc temporal buffers */ if (m_pAppConfig->bRepackPreencMV && !m_tmpForReading.size()) { mfxU32 n_MB = m_pAppConfig->bDynamicRC ? m_pAppConfig->PipelineCfg.numMB_drc_max : m_pAppConfig->PipelineCfg.numMB_frame; m_tmpForReading.resize(n_MB); } // Store current set of Ext Buffers eTask->bufs = m_pExtBuffers->GetFreeSet(); MSDK_CHECK_POINTER(eTask->bufs, MFX_ERR_NULL_PTR); /* Adjust number of MBs in extension buffers */ if (m_pAppConfig->PipelineCfg.DRCresetPoint || m_pAppConfig->PipelineCfg.mixedPicstructs) { mfxU32 n_MB = m_pAppConfig->PipelineCfg.DRCresetPoint ? m_pAppConfig->PipelineCfg.numMB_drc_curr : // DRC (!eTask->m_fieldPicFlag ? m_pAppConfig->PipelineCfg.numMB_frame : // Mixed Picstructs : progressive m_pAppConfig->PipelineCfg.numMB_refPic); // Mixed Picstructs : interlaced eTask->bufs->ResetMBnum(n_MB, m_pAppConfig->PipelineCfg.DRCresetPoint); } mfxU8 ffid = eTask->m_fieldPicFlag && (encodeSurface->Info.PicStruct & MFX_PICSTRUCT_FIELD_BFF); if (m_videoParams.mfx.EncodedOrder) { // We have to force frame type through control in case of ENCODE in EncodedOrder mode m_encodeControl.FrameType = eTask->m_fieldPicFlag ? createType(*eTask) : ExtractFrameType(*eTask); } else if (eTask->m_type[ffid] & MFX_FRAMETYPE_IDR) { // As well as IDR frame in case of loop mode m_encodeControl.FrameType = !eTask->m_fieldPicFlag ? eTask->m_type[ffid] : (((mfxU16(eTask->m_type[1 - ffid])) << 8) | eTask->m_type[ffid]); } else { // No forced frametype otherwise m_encodeControl.FrameType = 0; } /* Load input Buffer for FEI ENCODE */ mfxU32 feiEncCtrlId = ffid, pMvPredId = ffid, pWeightsId = ffid, encMBID = 0, mbQPID = 0, fieldId = 0; for (std::vector<mfxExtBuffer*>::iterator it = eTask->bufs->PB_bufs.in.buffers.begin(); it != eTask->bufs->PB_bufs.in.buffers.end(); ++it) { switch ((*it)->BufferId) { case MFX_EXTBUFF_FEI_ENC_MV_PRED: if (!m_pAppConfig->bPREENC && m_pMvPred_in) { if (m_pAppConfig->PipelineCfg.mixedPicstructs && (encodeSurface->Info.PicStruct & MFX_PICSTRUCT_PROGRESSIVE) && pMvPredId != ffid) { continue; } mfxExtFeiEncMVPredictors* pMvPredBuf = reinterpret_cast<mfxExtFeiEncMVPredictors*>(*it); if (!(eTask->m_type[pMvPredId] & MFX_FRAMETYPE_I)) { if (m_pAppConfig->bRepackPreencMV) { SAFE_FREAD(&m_tmpForReading[0], sizeof(m_tmpForReading[0])*pMvPredBuf->NumMBAlloc, 1, m_pMvPred_in, MFX_ERR_MORE_DATA); repackPreenc2Enc(&m_tmpForReading[0], pMvPredBuf->MB, pMvPredBuf->NumMBAlloc, &m_tmpForMedian[0]); } else { SAFE_FREAD(pMvPredBuf->MB, sizeof(pMvPredBuf->MB[0])*pMvPredBuf->NumMBAlloc, 1, m_pMvPred_in, MFX_ERR_MORE_DATA); } } else{ int shft = m_pAppConfig->bRepackPreencMV ? sizeof(mfxExtFeiPreEncMV::mfxExtFeiPreEncMVMB) : sizeof(mfxExtFeiEncMVPredictors::mfxExtFeiEncMVPredictorsMB); SAFE_FSEEK(m_pMvPred_in, shft*pMvPredBuf->NumMBAlloc, SEEK_CUR, MFX_ERR_MORE_DATA); } } pMvPredId = 1 - pMvPredId; // set to sfid break; case MFX_EXTBUFF_FEI_ENC_MB: if (m_pENC_MBCtrl_in){ if (m_pAppConfig->PipelineCfg.mixedPicstructs && (encodeSurface->Info.PicStruct & MFX_PICSTRUCT_PROGRESSIVE) && !!encMBID) continue; mfxExtFeiEncMBCtrl* pMbEncCtrl = reinterpret_cast<mfxExtFeiEncMBCtrl*>(*it); SAFE_FREAD(pMbEncCtrl->MB, sizeof(pMbEncCtrl->MB[0])*pMbEncCtrl->NumMBAlloc, 1, m_pENC_MBCtrl_in, MFX_ERR_MORE_DATA); encMBID++; } break; case MFX_EXTBUFF_FEI_ENC_QP: if (m_pMbQP_in){ if (m_pAppConfig->PipelineCfg.mixedPicstructs && (encodeSurface->Info.PicStruct & MFX_PICSTRUCT_PROGRESSIVE) && !!mbQPID) continue; mfxExtFeiEncQP* pMbQP = reinterpret_cast<mfxExtFeiEncQP*>(*it); #if MFX_VERSION >= 1023 SAFE_FREAD(pMbQP->MB, sizeof(pMbQP->MB[0])*pMbQP->NumMBAlloc, 1, m_pMbQP_in, MFX_ERR_MORE_DATA); #else SAFE_FREAD(pMbQP->QP, sizeof(pMbQP->QP[0])*pMbQP->NumQPAlloc, 1, m_pMbQP_in, MFX_ERR_MORE_DATA); #endif mbQPID++; } break; case MFX_EXTBUFF_FEI_ENC_CTRL: { mfxExtFeiEncFrameCtrl* feiEncCtrl = reinterpret_cast<mfxExtFeiEncFrameCtrl*>(*it); if (m_pAppConfig->PipelineCfg.mixedPicstructs && (encodeSurface->Info.PicStruct & MFX_PICSTRUCT_PROGRESSIVE) && feiEncCtrlId != ffid) continue; // adjust ref window size if search window is 0 if (feiEncCtrl->SearchWindow == 0) { bool adjust_window = (eTask->m_type[feiEncCtrlId] & MFX_FRAMETYPE_B) && m_pAppConfig->RefHeight * m_pAppConfig->RefWidth > 1024; feiEncCtrl->RefHeight = adjust_window ? 32 : m_pAppConfig->RefHeight; feiEncCtrl->RefWidth = adjust_window ? 32 : m_pAppConfig->RefWidth; } feiEncCtrl->MVPredictor = (eTask->m_type[feiEncCtrlId] & MFX_FRAMETYPE_I) ? 0 : (m_pAppConfig->mvinFile != NULL || m_pAppConfig->bPREENC); /* Set number to actual ref number for each field. Driver requires these fields to be zero in case of feiEncCtrl->MVPredictor == false but MSDK lib will adjust them to zero if application doesn't */ feiEncCtrl->NumMVPredictors[0] = feiEncCtrl->NumMVPredictors[1] = 0; if (feiEncCtrl->MVPredictor) { // feiEncCtrlId tracks id in term of field parity, GetNumMVP accepts fieldId feiEncCtrl->NumMVPredictors[0] = GetNumL0MVPs(*eTask, feiEncCtrlId != ffid); feiEncCtrl->NumMVPredictors[1] = GetNumL1MVPs(*eTask, feiEncCtrlId != ffid); } fieldId++; feiEncCtrlId = 1 - feiEncCtrlId; // set to sfid } break; case MFX_EXTBUFF_FEI_REPACK_CTRL: if (m_pRepackCtrl_in) { mfxExtFeiRepackCtrl* feiRepackCtrl = reinterpret_cast<mfxExtFeiRepackCtrl*>(*it); SAFE_FREAD(&(feiRepackCtrl->MaxFrameSize), sizeof(mfxU32), 1, m_pRepackCtrl_in, MFX_ERR_MORE_DATA); SAFE_FREAD(&(feiRepackCtrl->NumPasses), sizeof(mfxU32), 1, m_pRepackCtrl_in, MFX_ERR_MORE_DATA); SAFE_FREAD(feiRepackCtrl->DeltaQP, sizeof(mfxU8) * 8, 1, m_pRepackCtrl_in, MFX_ERR_MORE_DATA); if (feiRepackCtrl->NumPasses > 4) { msdk_printf(MSDK_STRING("WARNING: NumPasses should be less than or equal to 4\n")); } } break; case MFX_EXTBUFF_PRED_WEIGHT_TABLE: if (m_pWeights_in) { if (m_pAppConfig->PipelineCfg.mixedPicstructs && (encodeSurface->Info.PicStruct & MFX_PICSTRUCT_PROGRESSIVE) && pWeightsId != ffid) continue; mfxExtPredWeightTable* feiWeightTable = reinterpret_cast<mfxExtPredWeightTable*>(*it); if ((eTask->m_type[pWeightsId] & MFX_FRAMETYPE_P) || ((eTask->m_type[pWeightsId] & MFX_FRAMETYPE_B) && !m_pAppConfig->bImplicitWPB)) { SAFE_FREAD(&(feiWeightTable->LumaLog2WeightDenom), sizeof(mfxU16), 1, m_pWeights_in, MFX_ERR_MORE_DATA); SAFE_FREAD(&(feiWeightTable->ChromaLog2WeightDenom), sizeof(mfxU16), 1, m_pWeights_in, MFX_ERR_MORE_DATA); SAFE_FREAD(feiWeightTable->LumaWeightFlag, sizeof(mfxU16) * 2 * 32, //[list][list entry] 1, m_pWeights_in, MFX_ERR_MORE_DATA); SAFE_FREAD(feiWeightTable->ChromaWeightFlag, sizeof(mfxU16) * 2 * 32, //[list][list entry] 1, m_pWeights_in, MFX_ERR_MORE_DATA); SAFE_FREAD(feiWeightTable->Weights, sizeof(mfxI16) * 2 * 32 * 3 * 2, //[list][list entry][Y, Cb, Cr][weight, offset] 1, m_pWeights_in, MFX_ERR_MORE_DATA); } else{ unsigned int seek_size = sizeof(mfxU16) + sizeof(mfxU16) + sizeof(mfxU16) * 2 * 32 + sizeof(mfxU16) * 2 * 32 + sizeof(mfxI16) * 2 * 32 * 3 * 2; SAFE_FSEEK(m_pWeights_in, seek_size, SEEK_CUR, MFX_ERR_MORE_DATA); } } pWeightsId = 1 - pWeightsId; // set to sfid break; } // switch (eTask->bufs->PB_bufs.in.ExtParam[i]->BufferId) } // for (int i = 0; i<eTask->bufs->PB_bufs.in.NumExtParam; i++) // Add input buffers bool is_I_frame = !eTask->m_fieldPicFlag && (eTask->m_type[ffid] & MFX_FRAMETYPE_I); // Initialize controller for Extension buffers sts = eTask->ExtBuffersController.InitializeController(eTask->bufs, bufSetController::ENCODE, is_I_frame, !eTask->m_fieldPicFlag); MSDK_CHECK_STATUS(sts, "eTask->ExtBuffersController.InitializeController failed"); return sts; } mfxStatus FEI_EncodeInterface::AllocateSufficientBuffer() { mfxVideoParam par; MSDK_ZERO_MEMORY(par); // find out the required buffer size mfxStatus sts = m_pmfxENCODE->GetVideoParam(&par); MSDK_CHECK_STATUS(sts, "m_pmfxENCODE->GetVideoParam failed"); m_mfxBS.Extend(par.mfx.BufferSizeInKB * 1000); return sts; } mfxStatus FEI_EncodeInterface::EncodeOneFrame(iTask* eTask) { MFX_ITT_TASK("EncodeOneFrame"); mfxStatus sts = MFX_ERR_NONE; // ENC_in.InSurface always holds full-res surface. // eTask=NULL is valid for the case of draining encoder frames when input is in display order. mfxFrameSurface1* encodeSurface = eTask ? eTask->ENC_in.InSurface : nullptr; if (encodeSurface) // no need to do this for buffered frames { sts = InitFrameParams(eTask); MSDK_CHECK_STATUS(sts, "FEI ENCODE: InitFrameParams failed"); } int numberOfCalls = (m_bSingleFieldMode && (!eTask || eTask->m_fieldPicFlag)) ? 2 : 1; for (int i = 0; i < numberOfCalls; ++i) { for (;;) { // at this point surface for encoder contains either a frame from file or a frame processed by vpp if (encodeSurface) { // Attach extension buffers for current field // (in double-field mode both calls will return equal sets, holding buffers for both fields) std::vector<mfxExtBuffer *> * in_buffers = eTask->ExtBuffersController.GetBuffers(bufSetController::ENCODE, i, true); MSDK_CHECK_POINTER(in_buffers, MFX_ERR_NULL_PTR); std::vector<mfxExtBuffer *> * out_buffers = eTask->ExtBuffersController.GetBuffers(bufSetController::ENCODE, i, false); MSDK_CHECK_POINTER(out_buffers, MFX_ERR_NULL_PTR); // Input buffers m_encodeControl.NumExtParam = mfxU16(in_buffers->size()); m_encodeControl.ExtParam = !in_buffers->empty() ? in_buffers->data() : NULL; // Output buffers m_mfxBS.NumExtParam = mfxU16(out_buffers->size()); m_mfxBS.ExtParam = !out_buffers->empty() ? out_buffers->data() : NULL; } // Encoding goes below sts = m_pmfxENCODE->EncodeFrameAsync(&m_encodeControl, encodeSurface, &m_mfxBS, &m_SyncPoint); MSDK_CHECK_WRN(sts, "WRN during EncodeFrameAsync"); if (MFX_ERR_NONE < sts && !m_SyncPoint) // repeat the call if warning and no output { if (MFX_WRN_DEVICE_BUSY == sts) { WaitForDeviceToBecomeFree(*m_pmfxSession, m_SyncPoint, sts); } } else if (MFX_ERR_NONE < sts && m_SyncPoint) { sts = m_pmfxSession->SyncOperation(m_SyncPoint, MSDK_WAIT_INTERVAL); MSDK_CHECK_ERR_NONE_STATUS(sts, MFX_ERR_ABORTED, "FEI ENCODE: SyncOperation failed"); break; } else if (MFX_ERR_NOT_ENOUGH_BUFFER == sts) { sts = AllocateSufficientBuffer(); MSDK_CHECK_STATUS(sts, "FEI ENCODE: AllocateSufficientBuffer failed"); } else { if (m_SyncPoint) { sts = m_pmfxSession->SyncOperation(m_SyncPoint, MSDK_WAIT_INTERVAL); MSDK_CHECK_ERR_NONE_STATUS(sts, MFX_ERR_ABORTED, "FEI ENCODE: SyncOperation failed"); } break; } } // for(;;) MSDK_BREAK_ON_ERROR(sts); } // for (int i = 0; i < numberOfCalls; ++i) if (sts == MFX_ERR_MORE_DATA) { // MFX_ERR_MORE_DATA is correct status to finish encoding of buffered frames (for which encodeSurface == NULL). // Otherwise, ignore it return encodeSurface ? MFX_ERR_NONE : MFX_ERR_MORE_DATA; } MSDK_CHECK_STATUS(sts, "FEI ENCODE: EncodeFrameAsync failed"); sts = m_FileWriter.WriteNextFrame(&m_mfxBS); MSDK_CHECK_STATUS(sts, "FEI ENCODE: WriteNextFrame failed"); sts = FlushOutput(eTask); MSDK_CHECK_STATUS(sts, "FEI ENCODE: FlushOutput failed"); return sts; } mfxStatus FEI_EncodeInterface::FlushOutput(iTask* eTask) { mfxExtBuffer** output_buffers = NULL; mfxU32 n_output_buffers = 0; if (eTask) { MSDK_CHECK_POINTER(eTask->bufs, MFX_ERR_NULL_PTR); output_buffers = eTask->bufs->PB_bufs.out.buffers.data(); n_output_buffers = eTask->bufs->PB_bufs.out.buffers.size(); } else { // In case of draining frames from encoder in display-order mode output_buffers = m_mfxBS.ExtParam; n_output_buffers = m_mfxBS.NumExtParam; } mfxU32 mvBufCounter = 0; for (mfxU32 i = 0; i < n_output_buffers; ++i) { MSDK_CHECK_POINTER(output_buffers[i], MFX_ERR_NULL_PTR); switch (output_buffers[i]->BufferId) { case MFX_EXTBUFF_FEI_ENC_MV: if (m_pMV_out) { mfxExtFeiEncMV* mvBuf = reinterpret_cast<mfxExtFeiEncMV*>(output_buffers[i]); if (!(extractType(m_mfxBS.FrameType, mvBufCounter) & MFX_FRAMETYPE_I)){ SAFE_FWRITE(mvBuf->MB, sizeof(mvBuf->MB[0])*mvBuf->NumMBAlloc, 1, m_pMV_out, MFX_ERR_MORE_DATA); } else { for (mfxU32 k = 0; k < mvBuf->NumMBAlloc; k++){ SAFE_FWRITE(&m_tmpMBencMV, sizeof(mfxExtFeiEncMV::mfxExtFeiEncMVMB), 1, m_pMV_out, MFX_ERR_MORE_DATA); } } ++mvBufCounter; } break; case MFX_EXTBUFF_FEI_ENC_MB_STAT: if (m_pMBstat_out) { mfxExtFeiEncMBStat* mbstatBuf = reinterpret_cast<mfxExtFeiEncMBStat*>(output_buffers[i]); SAFE_FWRITE(mbstatBuf->MB, sizeof(mbstatBuf->MB[0])*mbstatBuf->NumMBAlloc, 1, m_pMBstat_out, MFX_ERR_MORE_DATA); } break; case MFX_EXTBUFF_FEI_PAK_CTRL: if (m_pMBcode_out) { mfxExtFeiPakMBCtrl* mbcodeBuf = reinterpret_cast<mfxExtFeiPakMBCtrl*>(output_buffers[i]); SAFE_FWRITE(mbcodeBuf->MB, sizeof(mbcodeBuf->MB[0])*mbcodeBuf->NumMBAlloc, 1, m_pMBcode_out, MFX_ERR_MORE_DATA); } break; #if (MFX_VERSION >= 1025) case MFX_EXTBUFF_FEI_REPACK_STAT: if (m_pRepackStat_out) { mfxExtFeiRepackStat* repackStat = reinterpret_cast<mfxExtFeiRepackStat*> (output_buffers[i]); mfxI8 repackStatChar[64]; snprintf(repackStatChar, sizeof(repackStatChar), "FrameOrder %d: %d NumPasses\n", eTask?eTask->m_frameOrder:0, repackStat->NumPasses); SAFE_FWRITE(repackStatChar, strlen(repackStatChar), 1, m_pRepackStat_out, MFX_ERR_MORE_DATA); repackStat->NumPasses = 0; } break; #endif } // switch (output_buffers[i]->BufferId) } // for (mfxU32 i = 0; i < n_output_buffers; ++i) return MFX_ERR_NONE; } mfxStatus FEI_EncodeInterface::ResetState() { mfxStatus sts = MFX_ERR_NONE; //while (MFX_ERR_NONE == sts) { // sts = EncodeOneFrame(NULL, NULL, PairU8(NULL,NULL)); //} // mark sync point as free m_SyncPoint = NULL; // prepare bit stream m_mfxBS.DataOffset = 0; m_mfxBS.DataLength = 0; // reset FileWriter sts = m_FileWriter.Init(m_pAppConfig->dstFileBuff[0]); MSDK_CHECK_STATUS(sts, "FEI ENCODE: FileWriter.Init failed"); SAFE_FSEEK(m_pMvPred_in, 0, SEEK_SET, MFX_ERR_MORE_DATA); SAFE_FSEEK(m_pENC_MBCtrl_in, 0, SEEK_SET, MFX_ERR_MORE_DATA); SAFE_FSEEK(m_pMbQP_in, 0, SEEK_SET, MFX_ERR_MORE_DATA); SAFE_FSEEK(m_pRepackCtrl_in, 0, SEEK_SET, MFX_ERR_MORE_DATA); SAFE_FSEEK(m_pWeights_in, 0, SEEK_SET, MFX_ERR_MORE_DATA); SAFE_FSEEK(m_pMBstat_out, 0, SEEK_SET, MFX_ERR_MORE_DATA); SAFE_FSEEK(m_pMV_out, 0, SEEK_SET, MFX_ERR_MORE_DATA); SAFE_FSEEK(m_pMBcode_out, 0, SEEK_SET, MFX_ERR_MORE_DATA); #if (MFX_VERSION >= 1025) SAFE_FSEEK(m_pRepackStat_out,0, SEEK_SET, MFX_ERR_MORE_DATA); #endif return sts; }
43.529675
755
0.64504
[ "vector" ]
4f2e995ac46ed6db25e8ca854bee2b489098438e
149,471
cpp
C++
Code/Editor/CryEdit.cpp
LB-KacperKapusta/o3de
207ec6e60d02483e43f4f07bcedbd82aff8168f5
[ "Apache-2.0", "MIT" ]
null
null
null
Code/Editor/CryEdit.cpp
LB-KacperKapusta/o3de
207ec6e60d02483e43f4f07bcedbd82aff8168f5
[ "Apache-2.0", "MIT" ]
null
null
null
Code/Editor/CryEdit.cpp
LB-KacperKapusta/o3de
207ec6e60d02483e43f4f07bcedbd82aff8168f5
[ "Apache-2.0", "MIT" ]
null
null
null
/* * Copyright (c) Contributors to the Open 3D Engine Project. * For complete copyright and license terms please see the LICENSE at the root of this distribution. * * SPDX-License-Identifier: Apache-2.0 OR MIT * */ #include "EditorDefs.h" #ifdef WIN32 AZ_PUSH_DISABLE_WARNING(4458, "-Wunknown-warning-option") #include <gdiplus.h> AZ_POP_DISABLE_WARNING #pragma comment (lib, "Gdiplus.lib") #include <WinUser.h> // needed for MessageBoxW in the assert handler #endif #include <array> #include <string> #include "CryEdit.h" // Qt #include <QCommandLineParser> #include <QSharedMemory> #include <QSystemSemaphore> #include <QDesktopServices> #include <QElapsedTimer> #include <QProcess> #include <QScopedValueRollback> #include <QClipboard> #include <QMenuBar> #include <QDialogButtonBox> // Aws Native SDK #include <aws/sts/STSClient.h> #include <aws/core/auth/AWSCredentialsProvider.h> #include <aws/sts/model/GetFederationTokenRequest.h> #include <aws/core/http/HttpClient.h> #include <aws/core/http/HttpResponse.h> #include <aws/core/utils/json/JsonSerializer.h> // AzCore #include <AzCore/Casting/numeric_cast.h> #include <AzCore/Module/Environment.h> #include <AzCore/RTTI/BehaviorContext.h> #include <AzCore/std/smart_ptr/make_shared.h> #include <AzCore/Settings/SettingsRegistryMergeUtils.h> #include <AzCore/Utils/Utils.h> #include <AzCore/Console/IConsole.h> // AzFramework #include <AzFramework/Components/CameraBus.h> #include <AzFramework/StringFunc/StringFunc.h> #include <AzFramework/Terrain/TerrainDataRequestBus.h> #include <AzFramework/ProjectManager/ProjectManager.h> #include <AzFramework/Spawnable/RootSpawnableInterface.h> // AzToolsFramework #include <AzToolsFramework/Component/EditorComponentAPIBus.h> #include <AzToolsFramework/Component/EditorLevelComponentAPIBus.h> #include <AzToolsFramework/UI/UICore/ProgressShield.hxx> #include <AzToolsFramework/UI/UICore/WidgetHelpers.h> #include <AzToolsFramework/Slice/SliceUtilities.h> #include <AzToolsFramework/ViewportSelection/EditorTransformComponentSelectionRequestBus.h> #include <AzToolsFramework/API/EditorPythonConsoleBus.h> #include <AzToolsFramework/API/EditorPythonRunnerRequestsBus.h> #include <AzToolsFramework/API/ToolsApplicationAPI.h> #include <AzToolsFramework/Entity/PrefabEditorEntityOwnershipInterface.h> #include <AzToolsFramework/PythonTerminal/ScriptHelpDialog.h> // AzQtComponents #include <AzQtComponents/Components/StyleManager.h> #include <AzQtComponents/Utilities/HandleDpiAwareness.h> #include <AzQtComponents/Components/WindowDecorationWrapper.h> #include <AzQtComponents/Utilities/QtPluginPaths.h> // CryCommon #include <CryCommon/ITimer.h> #include <CryCommon/ILevelSystem.h> // Editor #include "Settings.h" #include "GameExporter.h" #include "GameResourcesExporter.h" #include "ActionManager.h" #include "MainWindow.h" #include "Core/QtEditorApplication.h" #include "StringDlg.h" #include "NewLevelDialog.h" #include "LayoutConfigDialog.h" #include "ViewManager.h" #include "FileTypeUtils.h" #include "PluginManager.h" #include "IEditorImpl.h" #include "StartupLogoDialog.h" #include "DisplaySettings.h" #include "GameEngine.h" #include "StartupTraceHandler.h" #include "ToolsConfigPage.h" #include "Objects/SelectionGroup.h" #include "Include/IObjectManager.h" #include "WaitProgress.h" #include "ToolBox.h" #include "LevelInfo.h" #include "EditorPreferencesDialog.h" #include "AnimationContext.h" #include "GotoPositionDlg.h" #include "ConsoleDialog.h" #include "Controls/ConsoleSCB.h" #include "ScopedVariableSetter.h" #include "Util/3DConnexionDriver.h" #include "DimensionsDialog.h" #include "Util/AutoDirectoryRestoreFileDialog.h" #include "Util/EditorAutoLevelLoadTest.h" #include "AboutDialog.h" #include <AzToolsFramework/PythonTerminal/ScriptHelpDialog.h> #include "QuickAccessBar.h" #include "Export/ExportManager.h" #include "LevelFileDialog.h" #include "LevelIndependentFileMan.h" #include "WelcomeScreen/WelcomeScreenDialog.h" #include "Controls/ReflectedPropertyControl/PropertyCtrl.h" #include "Controls/ReflectedPropertyControl/ReflectedVar.h" #include "EditorToolsApplication.h" #include "Plugins/ComponentEntityEditorPlugin/Objects/ComponentEntityObject.h" // AWSNativeSDK #include <AzToolsFramework/Undo/UndoSystem.h> #include <AWSNativeSDKInit/AWSNativeSDKInit.h> #if defined(AZ_PLATFORM_WINDOWS) #include <AzFramework/API/ApplicationAPI_Platform.h> #endif #if AZ_TRAIT_OS_PLATFORM_APPLE #include "WindowObserver_mac.h" #endif #include <AzCore/RTTI/BehaviorContext.h> #include <AzFramework/Render/Intersector.h> #include <AzCore/std/smart_ptr/make_shared.h> static const char O3DEEditorClassName[] = "O3DEEditorClass"; static const char O3DEApplicationName[] = "O3DEApplication"; static AZ::EnvironmentVariable<bool> inEditorBatchMode = nullptr; RecentFileList::RecentFileList() { m_settings.beginGroup(QStringLiteral("Application")); m_settings.beginGroup(QStringLiteral("Recent File List")); ReadList(); } void RecentFileList::Remove(int index) { m_arrNames.removeAt(index); } void RecentFileList::Add(const QString& f) { QString filename = QDir::toNativeSeparators(f); m_arrNames.removeAll(filename); m_arrNames.push_front(filename); while (m_arrNames.count() > Max) { m_arrNames.removeAt(Max); } } int RecentFileList::GetSize() { return m_arrNames.count(); } void RecentFileList::GetDisplayName(QString& name, int index, const QString& curDir) { name = m_arrNames[index]; const QDir cur(curDir); QDir fileDir(name); // actually pointing at file, first cdUp() gets us the parent dir while (fileDir.cdUp()) { if (fileDir == cur) { name = cur.relativeFilePath(name); break; } } name = QDir::toNativeSeparators(name); } QString& RecentFileList::operator[](int index) { return m_arrNames[index]; } void RecentFileList::ReadList() { m_arrNames.clear(); for (int i = 1; i <= Max; ++i) { QString f = m_settings.value(QStringLiteral("File%1").arg(i)).toString(); if (!f.isEmpty()) { m_arrNames.push_back(f); } } } void RecentFileList::WriteList() { m_settings.remove(QString()); int i = 1; for (auto f : m_arrNames) { m_settings.setValue(QStringLiteral("File%1").arg(i++), f); } } #define ERROR_LEN 256 CCryDocManager::CCryDocManager() { } CCrySingleDocTemplate* CCryDocManager::SetDefaultTemplate(CCrySingleDocTemplate* pNew) { CCrySingleDocTemplate* pOld = m_pDefTemplate; m_pDefTemplate = pNew; m_templateList.clear(); m_templateList.push_back(m_pDefTemplate); return pOld; } // Copied from MFC to get rid of the silly ugly unoverridable doc-type pick dialog void CCryDocManager::OnFileNew() { assert(m_pDefTemplate != nullptr); m_pDefTemplate->OpenDocumentFile(nullptr); // if returns NULL, the user has already been alerted } bool CCryDocManager::DoPromptFileName(QString& fileName, [[maybe_unused]] UINT nIDSTitle, [[maybe_unused]] DWORD lFlags, bool bOpenFileDialog, [[maybe_unused]] CDocTemplate* pTemplate) { CLevelFileDialog levelFileDialog(bOpenFileDialog); levelFileDialog.show(); levelFileDialog.adjustSize(); if (levelFileDialog.exec() == QDialog::Accepted) { fileName = levelFileDialog.GetFileName(); return true; } return false; } CCryEditDoc* CCryDocManager::OpenDocumentFile(const char* lpszFileName, bool bAddToMRU) { assert(lpszFileName != nullptr); // find the highest confidence auto pos = m_templateList.begin(); CCrySingleDocTemplate::Confidence bestMatch = CCrySingleDocTemplate::noAttempt; CCrySingleDocTemplate* pBestTemplate = nullptr; CCryEditDoc* pOpenDocument = nullptr; if (lpszFileName[0] == '\"') { ++lpszFileName; } QString szPath = QString::fromUtf8(lpszFileName); if (szPath.endsWith('"')) { szPath.remove(szPath.length() - 1, 1); } while (pos != m_templateList.end()) { auto pTemplate = *(pos++); CCrySingleDocTemplate::Confidence match; assert(pOpenDocument == nullptr); match = pTemplate->MatchDocType(szPath.toUtf8().data(), pOpenDocument); if (match > bestMatch) { bestMatch = match; pBestTemplate = pTemplate; } if (match == CCrySingleDocTemplate::yesAlreadyOpen) { break; // stop here } } if (pOpenDocument != nullptr) { return pOpenDocument; } if (pBestTemplate == nullptr) { QMessageBox::critical(AzToolsFramework::GetActiveWindow(), QString(), QObject::tr("Failed to open document.")); return nullptr; } return pBestTemplate->OpenDocumentFile(szPath.toUtf8().data(), bAddToMRU, false); } ////////////////////////////////////////////////////////////////////////////// // CCryEditApp #undef ON_COMMAND #define ON_COMMAND(id, method) \ MainWindow::instance()->GetActionManager()->RegisterActionHandler(id, this, &CCryEditApp::method); #undef ON_COMMAND_RANGE #define ON_COMMAND_RANGE(idStart, idEnd, method) \ for (int i = idStart; i <= idEnd; ++i) \ ON_COMMAND(i, method); AZ_CVAR_EXTERNED(bool, ed_previewGameInFullscreen_once); void CCryEditApp::RegisterActionHandlers() { ON_COMMAND(ID_APP_ABOUT, OnAppAbout) ON_COMMAND(ID_APP_SHOW_WELCOME, OnAppShowWelcomeScreen) ON_COMMAND(ID_DOCUMENTATION_TUTORIALS, OnDocumentationTutorials) ON_COMMAND(ID_DOCUMENTATION_O3DE, OnDocumentationO3DE) ON_COMMAND(ID_DOCUMENTATION_GAMELIFT, OnDocumentationGamelift) ON_COMMAND(ID_DOCUMENTATION_RELEASENOTES, OnDocumentationReleaseNotes) ON_COMMAND(ID_DOCUMENTATION_GAMEDEVBLOG, OnDocumentationGameDevBlog) ON_COMMAND(ID_DOCUMENTATION_FORUMS, OnDocumentationForums) ON_COMMAND(ID_DOCUMENTATION_AWSSUPPORT, OnDocumentationAWSSupport) ON_COMMAND(ID_FILE_EXPORT_SELECTEDOBJECTS, OnExportSelectedObjects) ON_COMMAND(ID_EDIT_HOLD, OnEditHold) ON_COMMAND(ID_EDIT_FETCH, OnEditFetch) ON_COMMAND(ID_FILE_EXPORTTOGAMENOSURFACETEXTURE, OnFileExportToGameNoSurfaceTexture) ON_COMMAND(ID_VIEW_SWITCHTOGAME, OnViewSwitchToGame) MainWindow::instance()->GetActionManager()->RegisterActionHandler(ID_VIEW_SWITCHTOGAME_FULLSCREEN, [this]() { ed_previewGameInFullscreen_once = true; OnViewSwitchToGame(); }); ON_COMMAND(ID_MOVE_OBJECT, OnMoveObject) ON_COMMAND(ID_RENAME_OBJ, OnRenameObj) ON_COMMAND(ID_UNDO, OnUndo) ON_COMMAND(ID_TOOLBAR_WIDGET_REDO, OnUndo) // Can't use the same ID, because for the menu we can't have a QWidgetAction, while for the toolbar we want one ON_COMMAND(ID_IMPORT_ASSET, OnOpenAssetImporter) ON_COMMAND(ID_EDIT_LEVELDATA, OnEditLevelData) ON_COMMAND(ID_FILE_EDITLOGFILE, OnFileEditLogFile) ON_COMMAND(ID_FILE_RESAVESLICES, OnFileResaveSlices) ON_COMMAND(ID_FILE_EDITEDITORINI, OnFileEditEditorini) ON_COMMAND(ID_PREFERENCES, OnPreferences) ON_COMMAND(ID_REDO, OnRedo) ON_COMMAND(ID_TOOLBAR_WIDGET_REDO, OnRedo) ON_COMMAND(ID_FILE_OPEN_LEVEL, OnOpenLevel) #ifdef ENABLE_SLICE_EDITOR ON_COMMAND(ID_FILE_NEW_SLICE, OnCreateSlice) ON_COMMAND(ID_FILE_OPEN_SLICE, OnOpenSlice) #endif ON_COMMAND(ID_SWITCH_PHYSICS, OnSwitchPhysics) ON_COMMAND(ID_GAME_SYNCPLAYER, OnSyncPlayer) ON_COMMAND(ID_RESOURCES_REDUCEWORKINGSET, OnResourcesReduceworkingset) ON_COMMAND(ID_VIEW_CONFIGURELAYOUT, OnViewConfigureLayout) ON_COMMAND(IDC_SELECTION, OnDummyCommand) ////////////////////////////////////////////////////////////////////////// ON_COMMAND(ID_TAG_LOC1, OnTagLocation1) ON_COMMAND(ID_TAG_LOC2, OnTagLocation2) ON_COMMAND(ID_TAG_LOC3, OnTagLocation3) ON_COMMAND(ID_TAG_LOC4, OnTagLocation4) ON_COMMAND(ID_TAG_LOC5, OnTagLocation5) ON_COMMAND(ID_TAG_LOC6, OnTagLocation6) ON_COMMAND(ID_TAG_LOC7, OnTagLocation7) ON_COMMAND(ID_TAG_LOC8, OnTagLocation8) ON_COMMAND(ID_TAG_LOC9, OnTagLocation9) ON_COMMAND(ID_TAG_LOC10, OnTagLocation10) ON_COMMAND(ID_TAG_LOC11, OnTagLocation11) ON_COMMAND(ID_TAG_LOC12, OnTagLocation12) ////////////////////////////////////////////////////////////////////////// ON_COMMAND(ID_GOTO_LOC1, OnGotoLocation1) ON_COMMAND(ID_GOTO_LOC2, OnGotoLocation2) ON_COMMAND(ID_GOTO_LOC3, OnGotoLocation3) ON_COMMAND(ID_GOTO_LOC4, OnGotoLocation4) ON_COMMAND(ID_GOTO_LOC5, OnGotoLocation5) ON_COMMAND(ID_GOTO_LOC6, OnGotoLocation6) ON_COMMAND(ID_GOTO_LOC7, OnGotoLocation7) ON_COMMAND(ID_GOTO_LOC8, OnGotoLocation8) ON_COMMAND(ID_GOTO_LOC9, OnGotoLocation9) ON_COMMAND(ID_GOTO_LOC10, OnGotoLocation10) ON_COMMAND(ID_GOTO_LOC11, OnGotoLocation11) ON_COMMAND(ID_GOTO_LOC12, OnGotoLocation12) ////////////////////////////////////////////////////////////////////////// ON_COMMAND(ID_TOOLS_LOGMEMORYUSAGE, OnToolsLogMemoryUsage) ON_COMMAND(ID_TOOLS_CUSTOMIZEKEYBOARD, OnCustomizeKeyboard) ON_COMMAND(ID_TOOLS_CONFIGURETOOLS, OnToolsConfiguretools) ON_COMMAND(ID_TOOLS_SCRIPTHELP, OnToolsScriptHelp) #ifdef FEATURE_ORTHOGRAPHIC_VIEW ON_COMMAND(ID_VIEW_CYCLE2DVIEWPORT, OnViewCycle2dviewport) #endif ON_COMMAND(ID_DISPLAY_GOTOPOSITION, OnDisplayGotoPosition) ON_COMMAND(ID_FILE_SAVELEVELRESOURCES, OnFileSavelevelresources) ON_COMMAND(ID_CLEAR_REGISTRY, OnClearRegistryData) ON_COMMAND(ID_VALIDATELEVEL, OnValidatelevel) ON_COMMAND(ID_TOOLS_PREFERENCES, OnToolsPreferences) ON_COMMAND(ID_SWITCHCAMERA_DEFAULTCAMERA, OnSwitchToDefaultCamera) ON_COMMAND(ID_SWITCHCAMERA_SEQUENCECAMERA, OnSwitchToSequenceCamera) ON_COMMAND(ID_SWITCHCAMERA_SELECTEDCAMERA, OnSwitchToSelectedcamera) ON_COMMAND(ID_SWITCHCAMERA_NEXT, OnSwitchcameraNext) ON_COMMAND(ID_OPEN_SUBSTANCE_EDITOR, OnOpenProceduralMaterialEditor) ON_COMMAND(ID_OPEN_ASSET_BROWSER, OnOpenAssetBrowserView) ON_COMMAND(ID_OPEN_AUDIO_CONTROLS_BROWSER, OnOpenAudioControlsEditor) ON_COMMAND(ID_DISPLAY_SHOWHELPERS, OnShowHelpers) ON_COMMAND(ID_OPEN_TRACKVIEW, OnOpenTrackView) ON_COMMAND(ID_OPEN_UICANVASEDITOR, OnOpenUICanvasEditor) ON_COMMAND(ID_OPEN_QUICK_ACCESS_BAR, OnOpenQuickAccessBar) ON_COMMAND(ID_FILE_SAVE_LEVEL, OnFileSave) ON_COMMAND(ID_FILE_EXPORTOCCLUSIONMESH, OnFileExportOcclusionMesh) // Project Manager ON_COMMAND(ID_FILE_PROJECT_MANAGER_SETTINGS, OnOpenProjectManagerSettings) ON_COMMAND(ID_FILE_PROJECT_MANAGER_NEW, OnOpenProjectManagerNew) ON_COMMAND(ID_FILE_PROJECT_MANAGER_OPEN, OnOpenProjectManager) } CCryEditApp* CCryEditApp::s_currentInstance = nullptr; ///////////////////////////////////////////////////////////////////////////// // CCryEditApp construction CCryEditApp::CCryEditApp() { s_currentInstance = this; m_sPreviewFile[0] = 0; // Place all significant initialization in InitInstance ZeroStruct(m_tagLocations); ZeroStruct(m_tagAngles); AzFramework::AssetSystemInfoBus::Handler::BusConnect(); m_disableIdleProcessingCounter = 0; EditorIdleProcessingBus::Handler::BusConnect(); } ////////////////////////////////////////////////////////////////////////// CCryEditApp::~CCryEditApp() { EditorIdleProcessingBus::Handler::BusDisconnect(); AzFramework::AssetSystemInfoBus::Handler::BusDisconnect(); s_currentInstance = nullptr; } CCryEditApp* CCryEditApp::instance() { return s_currentInstance; } class CEditCommandLineInfo { public: bool m_bTest = false; bool m_bAutoLoadLevel = false; bool m_bExport = false; bool m_bExportTexture = false; bool m_bMatEditMode = false; bool m_bConsoleMode = false; bool m_bNullRenderer = false; bool m_bDeveloperMode = false; bool m_bRunPythonScript = false; bool m_bRunPythonTestScript = false; bool m_bShowVersionInfo = false; QString m_exportFile; QString m_strFileName; QString m_appRoot; QString m_logFile; QString m_pythonArgs; QString m_pythontTestCase; QString m_execFile; QString m_execLineCmd; bool m_bSkipWelcomeScreenDialog = false; bool m_bAutotestMode = false; struct CommandLineStringOption { QString name; QString description; QString valueName; }; CEditCommandLineInfo() { bool dummy; QCommandLineParser parser; parser.addHelpOption(); parser.setSingleDashWordOptionMode(QCommandLineParser::ParseAsLongOptions); parser.setApplicationDescription(QObject::tr("O3DE Editor")); // nsDocumentRevisionDebugMode is an argument that the macOS system passed into an App bundle that is being debugged. // Need to include it here so that Qt argument parser does not error out. bool nsDocumentRevisionsDebugMode = false; const std::vector<std::pair<QString, bool&> > options = { { "export", m_bExport }, { "exportTexture", m_bExportTexture }, { "test", m_bTest }, { "auto_level_load", m_bAutoLoadLevel }, { "MatEdit", m_bMatEditMode }, { "BatchMode", m_bConsoleMode }, { "NullRenderer", m_bNullRenderer }, { "devmode", m_bDeveloperMode }, { "VTUNE", dummy }, { "runpython", m_bRunPythonScript }, { "runpythontest", m_bRunPythonTestScript }, { "version", m_bShowVersionInfo }, { "NSDocumentRevisionsDebugMode", nsDocumentRevisionsDebugMode}, { "skipWelcomeScreenDialog", m_bSkipWelcomeScreenDialog}, { "autotest_mode", m_bAutotestMode}, { "regdumpall", dummy }, { "attach-debugger", dummy }, // Attaches a debugger for the current application { "wait-for-debugger", dummy }, // Waits until a debugger is attached to the current application }; QString dummyString; const std::vector<std::pair<CommandLineStringOption, QString&> > stringOptions = { {{"logfile", "File name of the log file to write out to.", "logfile"}, m_logFile}, {{"runpythonargs", "Command-line argument string to pass to the python script if --runpython or --runpythontest was used.", "runpythonargs"}, m_pythonArgs}, {{"pythontestcase", "Test case name of python test script if --runpythontest was used.", "pythontestcase"}, m_pythontTestCase}, {{"exec", "cfg file to run on startup, used for systems like automation", "exec"}, m_execFile}, {{"rhi", "Command-line argument to force which rhi to use", "dummyString"}, dummyString }, {{"rhi-device-validation", "Command-line argument to configure rhi validation", "dummyString"}, dummyString }, {{"exec_line", "command to run on startup, used for systems like automation", "exec_line"}, m_execLineCmd}, {{"regset", "Command-line argument to override settings registry values", "regset"}, dummyString}, {{"regremove", "Deletes a value within the global settings registry at the JSON pointer path @key", "regremove"}, dummyString}, {{"regdump", "Sets a value within the global settings registry at the JSON pointer path @key with value of @value", "regdump"}, dummyString}, {{"project-path", "Supplies the path to the project that the Editor should use", "project-path"}, dummyString}, {{"engine-path", "Supplies the path to the engine", "engine-path"}, dummyString}, {{"project-cache-path", "Path to the project cache", "project-cache-path"}, dummyString}, {{"project-user-path", "Path to the project user path", "project-user-path"}, dummyString}, {{"project-log-path", "Path to the project log path", "project-log-path"}, dummyString} // add dummy entries here to prevent QCommandLineParser error-ing out on cmd line args that will be parsed later }; parser.addPositionalArgument("file", QCoreApplication::translate("main", "file to open")); for (const auto& option : options) { parser.addOption(QCommandLineOption(option.first)); } for (const auto& option : stringOptions) { parser.addOption(QCommandLineOption(option.first.name, option.first.description, option.first.valueName)); } QStringList args = qApp->arguments(); #ifdef Q_OS_WIN32 for (QString& arg : args) { if (!arg.isEmpty() && arg[0] == '/') { arg[0] = '-'; // QCommandLineParser only supports - and -- prefixes } } #endif if (!parser.parse(args)) { AZ_TracePrintf("QT CommandLine Parser", "QT command line parsing warned with message %s." " Has the QCommandLineParser had these options added to it", parser.errorText().toUtf8().constData()); } // Get boolean options const int numOptions = static_cast<int>(options.size()); for (int i = 0; i < numOptions; ++i) { options[i].second = parser.isSet(options[i].first); } // Get string options for (auto& option : stringOptions) { option.second = parser.value(option.first.valueName); } m_bExport = m_bExport || m_bExportTexture; const QStringList positionalArgs = parser.positionalArguments(); if (!positionalArgs.isEmpty()) { m_strFileName = positionalArgs.first(); if (positionalArgs.first().at(0) != '[') { m_exportFile = positionalArgs.first(); } } } }; struct SharedData { bool raise = false; char text[_MAX_PATH]; }; ///////////////////////////////////////////////////////////////////////////// // CTheApp::FirstInstance // FirstInstance checks for an existing instance of the application. // If one is found, it is activated. // // This function uses a technique similar to that described in KB // article Q141752 to locate the previous instance of the application. . bool CCryEditApp::FirstInstance(bool bForceNewInstance) { QSystemSemaphore sem(QString(O3DEApplicationName) + "_sem", 1); sem.acquire(); { FixDanglingSharedMemory(O3DEEditorClassName); } sem.release(); m_mutexApplication = new QSharedMemory(O3DEEditorClassName); if (!m_mutexApplication->create(sizeof(SharedData)) && !bForceNewInstance) { m_mutexApplication->attach(); // another instance is already running - activate it sem.acquire(); SharedData* data = reinterpret_cast<SharedData*>(m_mutexApplication->data()); data->raise = true; if (m_bPreviewMode) { // IF in preview mode send this window copy data message to load new preview file. azstrcpy(data->text, MAX_PATH, m_sPreviewFile); } return false; } else { m_mutexApplication->attach(); // this is the first instance sem.acquire(); ::memset(m_mutexApplication->data(), 0, m_mutexApplication->size()); sem.release(); QTimer* t = new QTimer(this); connect(t, &QTimer::timeout, this, [this]() { QSystemSemaphore sem(QString(O3DEApplicationName) + "_sem", 1); sem.acquire(); SharedData* data = reinterpret_cast<SharedData*>(m_mutexApplication->data()); QString preview = QString::fromLatin1(data->text); if (data->raise) { QWidget* w = MainWindow::instance(); w->setWindowState((w->windowState() & ~Qt::WindowMinimized) | Qt::WindowActive); w->raise(); w->activateWindow(); data->raise = false; } if (!preview.isEmpty()) { // Load this file LoadFile(preview); data->text[0] = 0; } sem.release(); }); t->start(1000); return true; } return true; } ////////////////////////////////////////////////////////////////////////// void CCryEditApp::OnFileSave() { if (m_savingLevel) { return; } const QScopedValueRollback<bool> rollback(m_savingLevel, true); bool usePrefabSystemForLevels = false; AzFramework::ApplicationRequests::Bus::BroadcastResult( usePrefabSystemForLevels, &AzFramework::ApplicationRequests::IsPrefabSystemForLevelsEnabled); if (!usePrefabSystemForLevels) { GetIEditor()->GetDocument()->DoFileSave(); } else { auto* prefabEditorEntityOwnershipInterface = AZ::Interface<AzToolsFramework::PrefabEditorEntityOwnershipInterface>::Get(); auto* prefabIntegrationInterface = AZ::Interface<AzToolsFramework::Prefab::PrefabIntegrationInterface>::Get(); AZ_Assert(prefabEditorEntityOwnershipInterface != nullptr, "PrefabEditorEntityOwnershipInterface is not found."); AZ_Assert(prefabIntegrationInterface != nullptr, "PrefabIntegrationInterface is not found."); AzToolsFramework::Prefab::TemplateId rootPrefabTemplateId = prefabEditorEntityOwnershipInterface->GetRootPrefabTemplateId(); prefabIntegrationInterface->ExecuteSavePrefabDialog(rootPrefabTemplateId, true); } } ////////////////////////////////////////////////////////////////////////// void CCryEditApp::OnUpdateDocumentReady(QAction* action) { action->setEnabled(GetIEditor() && GetIEditor()->GetDocument() && GetIEditor()->GetDocument()->IsDocumentReady() && !m_bIsExportingLegacyData && !m_creatingNewLevel && !m_openingLevel && !m_savingLevel); } ////////////////////////////////////////////////////////////////////////// void CCryEditApp::OnUpdateFileOpen(QAction* action) { action->setEnabled(!m_bIsExportingLegacyData && !m_creatingNewLevel && !m_openingLevel && !m_savingLevel); } bool CCryEditApp::ShowEnableDisableGemDialog(const QString& title, const QString& message) { const QString informativeMessage = QObject::tr("Please follow the instructions <a href=\"http://docs.aws.amazon.com/lumberyard/latest/userguide/gems-system-gems.html\">here</a>, after which the Editor will be re-launched automatically."); QMessageBox box(AzToolsFramework::GetActiveWindow()); box.addButton(QObject::tr("Continue"), QMessageBox::AcceptRole); box.addButton(QObject::tr("Back"), QMessageBox::RejectRole); box.setWindowTitle(title); box.setText(message); box.setInformativeText(informativeMessage); box.setWindowFlags(box.windowFlags() & ~Qt::WindowContextHelpButtonHint); if (box.exec() == QMessageBox::AcceptRole) { // Called from a modal dialog with the main window as its parent. Best not to close the main window while the dialog is still active. QTimer::singleShot(0, MainWindow::instance(), &MainWindow::close); return true; } return false; } QString CCryEditApp::ShowWelcomeDialog() { WelcomeScreenDialog wsDlg(MainWindow::instance()); wsDlg.SetRecentFileList(GetRecentFileList()); wsDlg.exec(); QString levelName = wsDlg.GetLevelPath(); return levelName; } ////////////////////////////////////////////////////////////////////////// void CCryEditApp::InitDirectory() { ////////////////////////////////////////////////////////////////////////// // Initializes Root folder of the game. ////////////////////////////////////////////////////////////////////////// QString szExeFileName = qApp->applicationDirPath(); const static char* s_engineMarkerFile = "engine.json"; while (!QFile::exists(QString("%1/%2").arg(szExeFileName, s_engineMarkerFile))) { QDir currentdir(szExeFileName); if (!currentdir.cdUp()) { break; } szExeFileName = currentdir.absolutePath(); } QDir::setCurrent(szExeFileName); } ////////////////////////////////////////////////////////////////////////// // Needed to work with custom memory manager. ////////////////////////////////////////////////////////////////////////// CCryEditDoc* CCrySingleDocTemplate::OpenDocumentFile(const char* lpszPathName, bool bMakeVisible /*= true*/) { return OpenDocumentFile(lpszPathName, true, bMakeVisible); } CCryEditDoc* CCrySingleDocTemplate::OpenDocumentFile(const char* lpszPathName, bool bAddToMRU, [[maybe_unused]] bool bMakeVisible) { CCryEditDoc* pCurDoc = GetIEditor()->GetDocument(); if (pCurDoc) { if (!pCurDoc->SaveModified()) { return nullptr; } } if (!pCurDoc) { pCurDoc = qobject_cast<CCryEditDoc*>(m_documentClass->newInstance()); if (pCurDoc == nullptr) return nullptr; pCurDoc->setParent(this); } pCurDoc->SetModifiedFlag(false); if (lpszPathName == nullptr) { pCurDoc->SetTitle(tr("Untitled")); pCurDoc->OnNewDocument(); } else { pCurDoc->OnOpenDocument(lpszPathName); pCurDoc->SetPathName(lpszPathName); if (bAddToMRU) { CCryEditApp::instance()->AddToRecentFileList(lpszPathName); } } return pCurDoc; } CCrySingleDocTemplate::Confidence CCrySingleDocTemplate::MatchDocType(const char* lpszPathName, CCryEditDoc*& rpDocMatch) { assert(lpszPathName != nullptr); rpDocMatch = nullptr; // go through all documents CCryEditDoc* pDoc = GetIEditor()->GetDocument(); if (pDoc) { QString prevPathName = pDoc->GetLevelPathName(); // all we need to know here is whether it is the same file as before. if (!prevPathName.isEmpty()) { // QFileInfo is guaranteed to return true iff the two paths refer to the same path. if (QFileInfo(prevPathName) == QFileInfo(QString::fromUtf8(lpszPathName))) { // already open rpDocMatch = pDoc; return yesAlreadyOpen; } } } // see if it matches our default suffix const QString strFilterExt = EditorUtils::LevelFile::GetDefaultFileExtension(); const QString strOldFilterExt = EditorUtils::LevelFile::GetOldCryFileExtension(); const QString strSliceFilterExt = AzToolsFramework::SliceUtilities::GetSliceFileExtension().c_str(); // see if extension matches assert(strFilterExt[0] == '.'); QString strDot = "." + Path::GetExt(lpszPathName); if (!strDot.isEmpty()) { if(strDot == strFilterExt || strDot == strOldFilterExt || strDot == strSliceFilterExt) { return yesAttemptNative; // extension matches, looks like ours } } // otherwise we will guess it may work return yesAttemptForeign; } ///////////////////////////////////////////////////////////////////////////// namespace { AZStd::mutex g_splashScreenStateLock; enum ESplashScreenState { eSplashScreenState_Init, eSplashScreenState_Started, eSplashScreenState_Destroy }; ESplashScreenState g_splashScreenState = eSplashScreenState_Init; IInitializeUIInfo* g_pInitializeUIInfo = nullptr; QWidget* g_splashScreen = nullptr; } QString FormatVersion(const SFileVersion& v) { #if defined(LY_BUILD) return QObject::tr("Version %1.%2.%3.%4 - Build %5").arg(v[3]).arg(v[2]).arg(v[1]).arg(v[0]).arg(LY_BUILD); #else return QObject::tr("Version %1.%2.%3.%4").arg(v[3]).arg(v[2]).arg(v[1]).arg(v[0]); #endif } QString FormatRichTextCopyrightNotice() { // copyright symbol is HTML Entity = &#xA9; QString copyrightHtmlSymbol = "&#xA9;"; QString copyrightString = QObject::tr("Copyright %1 Contributors to the Open 3D Engine Project"); return copyrightString.arg(copyrightHtmlSymbol); } ///////////////////////////////////////////////////////////////////////////// void CCryEditApp::ShowSplashScreen(CCryEditApp* app) { g_splashScreenStateLock.lock(); CStartupLogoDialog* splashScreen = new CStartupLogoDialog(FormatVersion(app->m_pEditor->GetFileVersion()), FormatRichTextCopyrightNotice()); g_pInitializeUIInfo = splashScreen; g_splashScreen = splashScreen; g_splashScreenState = eSplashScreenState_Started; g_splashScreenStateLock.unlock(); splashScreen->show(); // Make sure the initial paint of the splash screen occurs so we dont get stuck with a blank window QCoreApplication::processEvents(QEventLoop::ExcludeUserInputEvents); QObject::connect(splashScreen, &QObject::destroyed, splashScreen, [=] { AZStd::scoped_lock lock(g_splashScreenStateLock); g_pInitializeUIInfo = nullptr; g_splashScreen = nullptr; }); } ///////////////////////////////////////////////////////////////////////////// void CCryEditApp::CreateSplashScreen() { if (!m_bConsoleMode && !IsInAutotestMode()) { // Create startup output splash ShowSplashScreen(this); GetIEditor()->Notify(eNotify_OnSplashScreenCreated); } else { // Create console m_pConsoleDialog = new CConsoleDialog(); m_pConsoleDialog->show(); g_pInitializeUIInfo = m_pConsoleDialog; } } ///////////////////////////////////////////////////////////////////////////// void CCryEditApp::CloseSplashScreen() { if (CStartupLogoDialog::instance()) { delete CStartupLogoDialog::instance(); g_splashScreenStateLock.lock(); g_splashScreenState = eSplashScreenState_Destroy; g_splashScreenStateLock.unlock(); } GetIEditor()->Notify(eNotify_OnSplashScreenDestroyed); } ///////////////////////////////////////////////////////////////////////////// void CCryEditApp::OutputStartupMessage(QString str) { g_splashScreenStateLock.lock(); if (g_pInitializeUIInfo) { g_pInitializeUIInfo->SetInfoText(str.toUtf8().data()); } g_splashScreenStateLock.unlock(); } ////////////////////////////////////////////////////////////////////////// void CCryEditApp::InitFromCommandLine(CEditCommandLineInfo& cmdInfo) { m_bConsoleMode |= cmdInfo.m_bConsoleMode; inEditorBatchMode = AZ::Environment::CreateVariable<bool>("InEditorBatchMode", m_bConsoleMode); m_bTestMode |= cmdInfo.m_bTest; m_bSkipWelcomeScreenDialog = cmdInfo.m_bSkipWelcomeScreenDialog || !cmdInfo.m_execFile.isEmpty() || !cmdInfo.m_execLineCmd.isEmpty() || cmdInfo.m_bAutotestMode; m_bExportMode = cmdInfo.m_bExport; m_bRunPythonTestScript = cmdInfo.m_bRunPythonTestScript; m_bRunPythonScript = cmdInfo.m_bRunPythonScript || cmdInfo.m_bRunPythonTestScript; m_execFile = cmdInfo.m_execFile; m_execLineCmd = cmdInfo.m_execLineCmd; m_bAutotestMode = cmdInfo.m_bAutotestMode || cmdInfo.m_bConsoleMode; m_pEditor->SetMatEditMode(cmdInfo.m_bMatEditMode); if (m_bExportMode) { m_exportFile = cmdInfo.m_exportFile; } // Do we have a passed filename ? if (!cmdInfo.m_strFileName.isEmpty()) { if (!m_bRunPythonScript && IsPreviewableFileType(cmdInfo.m_strFileName.toUtf8().constData())) { m_bPreviewMode = true; azstrncpy(m_sPreviewFile, _MAX_PATH, cmdInfo.m_strFileName.toUtf8().constData(), _MAX_PATH); } } if (cmdInfo.m_bAutoLoadLevel) { m_bLevelLoadTestMode = true; gEnv->bNoAssertDialog = true; CEditorAutoLevelLoadTest::Instance(); } } ///////////////////////////////////////////////////////////////////////////// AZ::Outcome<void, AZStd::string> CCryEditApp::InitGameSystem(HWND hwndForInputSystem) { CGameEngine* pGameEngine = new CGameEngine; AZ::Outcome<void, AZStd::string> initOutcome = pGameEngine->Init(m_bPreviewMode, m_bTestMode, qApp->arguments().join(" ").toUtf8().data(), g_pInitializeUIInfo, hwndForInputSystem); if (!initOutcome.IsSuccess()) { return initOutcome; } AZ_Assert(pGameEngine, "Game engine initialization failed, but initOutcome returned success."); m_pEditor->SetGameEngine(pGameEngine); // needs to be called after CrySystem has been loaded. gSettings.LoadDefaultGamePaths(); return AZ::Success(); } ///////////////////////////////////////////////////////////////////////////// bool CCryEditApp::CheckIfAlreadyRunning() { bool bForceNewInstance = false; if (!m_bPreviewMode) { FixDanglingSharedMemory(O3DEApplicationName); m_mutexApplication = new QSharedMemory(O3DEApplicationName); if (!m_mutexApplication->create(16)) { // Don't prompt the user in non-interactive export mode. Instead, default to allowing multiple instances to // run simultaneously, so that multiple level exports can be run in parallel on the same machine. // NOTE: If you choose to do this, be sure to export *different* levels, since nothing prevents multiple runs // from trying to write to the same level at the same time. // If we're running interactively, let's ask and make sure the user actually intended to do this. if (!m_bExportMode && QMessageBox::question(AzToolsFramework::GetActiveWindow(), QObject::tr("Too many apps"), QObject::tr("There is already an Open 3D Engine application running\nDo you want to start another one?")) != QMessageBox::Yes) { return false; } bForceNewInstance = true; } } if (!FirstInstance(bForceNewInstance)) { return false; } return true; } ///////////////////////////////////////////////////////////////////////////// bool CCryEditApp::InitGame() { if (!m_bPreviewMode && !GetIEditor()->IsInMatEditMode()) { AZ::IO::FixedMaxPathString projectPath = AZ::Utils::GetProjectPath(); Log((QString("project_path = %1").arg(!projectPath.empty() ? projectPath.c_str() : "<not set>")).toUtf8().data()); ICVar* pVar = gEnv->pConsole->GetCVar("sys_localization_folder"); const char* sLocalizationFolder = pVar ? pVar->GetString() : nullptr; Log((QString("sys_localization_folder = ") + (sLocalizationFolder && sLocalizationFolder[0] ? sLocalizationFolder : "<not set>")).toUtf8().data()); OutputStartupMessage("Starting Game..."); if (!GetIEditor()->GetGameEngine()->InitGame(nullptr)) { return false; } } ////////////////////////////////////////////////////////////////////////// // Apply settings post engine initialization. GetIEditor()->GetDisplaySettings()->PostInitApply(); gSettings.PostInitApply(); return true; } ///////////////////////////////////////////////////////////////////////////// void CCryEditApp::InitPlugins() { OutputStartupMessage("Loading Plugins..."); // Load the plugins { GetIEditor()->LoadPlugins(); #if defined(AZ_PLATFORM_WINDOWS) C3DConnexionDriver* p3DConnexionDriver = new C3DConnexionDriver; GetIEditor()->GetPluginManager()->RegisterPlugin(0, p3DConnexionDriver); #endif } } //////////////////////////////////////////////////////////////////////////// // Be careful when calling this function: it should be called after // everything else has finished initializing, otherwise, certain things // aren't set up yet. If in doubt, wrap it in a QTimer::singleShot(0ms); void CCryEditApp::InitLevel(const CEditCommandLineInfo& cmdInfo) { const char* defaultExtension = EditorUtils::LevelFile::GetDefaultFileExtension(); const char* oldExtension = EditorUtils::LevelFile::GetOldCryFileExtension(); if (m_bPreviewMode) { GetIEditor()->EnableAcceleratos(false); // Load geometry object. if (!cmdInfo.m_strFileName.isEmpty()) { LoadFile(cmdInfo.m_strFileName); } } else if (m_bExportMode && !m_exportFile.isEmpty()) { GetIEditor()->SetModifiedFlag(false); GetIEditor()->SetModifiedModule(eModifiedNothing); auto pDocument = OpenDocumentFile(m_exportFile.toUtf8().constData()); if (pDocument) { GetIEditor()->SetModifiedFlag(false); GetIEditor()->SetModifiedModule(eModifiedNothing); ExportLevel(cmdInfo.m_bExport, cmdInfo.m_bExportTexture, true); // Terminate process. CLogFile::WriteLine("Editor: Terminate Process after export"); } // the call to quit() must be posted to the event queue because the app is currently not yet running. // if we were to call quit() right now directly, the app would ignore it. QTimer::singleShot(0, QCoreApplication::instance(), &QCoreApplication::quit); return; } else if ((cmdInfo.m_strFileName.endsWith(defaultExtension, Qt::CaseInsensitive)) || (cmdInfo.m_strFileName.endsWith(oldExtension, Qt::CaseInsensitive))) { auto pDocument = OpenDocumentFile(cmdInfo.m_strFileName.toUtf8().constData()); if (pDocument) { GetIEditor()->SetModifiedFlag(false); GetIEditor()->SetModifiedModule(eModifiedNothing); } } else { ////////////////////////////////////////////////////////////////////////// //It can happen that if you are switching between projects and you have auto load set that //you could inadvertently load the wrong project and not know it, you would think you are editing //one level when in fact you are editing the old one. This can happen if both projects have the same //relative path... which is often the case when branching. // Ex. D:\cryengine\dev\ gets branched to D:\cryengine\branch\dev // Now you have gamesdk in both roots and therefore GameSDK\Levels\Singleplayer\Forest in both // If you execute the branch the m_pRecentFileList will be an absolute path to the old gamesdk, // then if auto load is set simply takes the old level and loads it in the new branch... //I would question ever trying to load a level not in our gamesdk, what happens when there are things that //an not exist in the level when built in a different gamesdk.. does it erase them, most likely, then you //just screwed up the level for everyone in the other gamesdk... //So if we are auto loading a level outside our current gamesdk we should act as though the flag //was unset and pop the dialog which should be in the correct location. This is not fool proof, but at //least this its a compromise that doesn't automatically do something you probably shouldn't. bool autoloadLastLevel = gSettings.bAutoloadLastLevelAtStartup; if (autoloadLastLevel && GetRecentFileList() && GetRecentFileList()->GetSize()) { QString gamePath = Path::GetEditingGameDataFolder().c_str(); Path::ConvertSlashToBackSlash(gamePath); gamePath = Path::ToUnixPath(gamePath.toLower()); gamePath = Path::AddSlash(gamePath); QString fullPath = GetRecentFileList()->m_arrNames[0]; Path::ConvertSlashToBackSlash(fullPath); fullPath = Path::ToUnixPath(fullPath.toLower()); fullPath = Path::AddSlash(fullPath); if (fullPath.indexOf(gamePath, 0) != 0) { autoloadLastLevel = false; } } ////////////////////////////////////////////////////////////////////////// QString levelName; bool isLevelNameValid = false; bool doLevelNeedLoading = true; const bool runningPythonScript = cmdInfo.m_bRunPythonScript || cmdInfo.m_bRunPythonTestScript; AZ::EBusLogicalResult<bool, AZStd::logical_or<bool> > skipStartupUIProcess(false); EBUS_EVENT_RESULT(skipStartupUIProcess, AzToolsFramework::EditorEvents::Bus, SkipEditorStartupUI); if (!skipStartupUIProcess.value) { do { isLevelNameValid = false; doLevelNeedLoading = true; if (gSettings.bShowDashboardAtStartup && !runningPythonScript && !GetIEditor()->IsInMatEditMode() && !m_bConsoleMode && !m_bSkipWelcomeScreenDialog && !m_bPreviewMode && !autoloadLastLevel) { levelName = ShowWelcomeDialog(); } else if (autoloadLastLevel && GetRecentFileList() && GetRecentFileList()->GetSize()) { levelName = GetRecentFileList()->m_arrNames[0]; } if (levelName.isEmpty()) { break; } if (levelName == "new") { //implies that the user has clicked the create new level option bool wasCreateLevelOperationCancelled = false; bool isNewLevelCreationSuccess = false; // This will show the new level dialog until a valid input has been entered by the user or until the user click cancel while (!isNewLevelCreationSuccess && !wasCreateLevelOperationCancelled) { isNewLevelCreationSuccess = CreateLevel(wasCreateLevelOperationCancelled); if (isNewLevelCreationSuccess == true) { doLevelNeedLoading = false; isLevelNameValid = true; } } ; } else if (levelName == "new slice") { QMessageBox::warning(AzToolsFramework::GetActiveWindow(), "Not implemented", "New Slice is not yet implemented."); } else { //implies that the user wants to open an existing level doLevelNeedLoading = true; isLevelNameValid = true; } } while (!isLevelNameValid);// if we reach here and levelName is not valid ,it implies that the user has clicked cancel on the create new level dialog // load level if (doLevelNeedLoading && !levelName.isEmpty()) { if (!CFileUtil::Exists(levelName, false)) { QMessageBox::critical(AzToolsFramework::GetActiveWindow(), QObject::tr("Missing level"), QObject::tr("Failed to auto-load last opened level. Level file does not exist:\n\n%1").arg(levelName)); return; } QString str; str = tr("Loading level %1 ...").arg(levelName); OutputStartupMessage(str); OpenDocumentFile(levelName.toUtf8().data()); } } } } ///////////////////////////////////////////////////////////////////////////// bool CCryEditApp::InitConsole() { // Execute command from cmdline -exec_line if applicable if (!m_execLineCmd.isEmpty()) { gEnv->pConsole->ExecuteString(QString("%1").arg(m_execLineCmd).toLocal8Bit()); } // Execute cfg from cmdline -exec if applicable if (!m_execFile.isEmpty()) { gEnv->pConsole->ExecuteString(QString("exec %1").arg(m_execFile).toLocal8Bit()); } // Execute special configs. gEnv->pConsole->ExecuteString("exec editor_autoexec.cfg"); gEnv->pConsole->ExecuteString("exec editor.cfg"); gEnv->pConsole->ExecuteString("exec user.cfg"); GetISystem()->ExecuteCommandLine(); return true; } ///////////////////////////////////////////////////////////////////////////// void CCryEditApp::CompileCriticalAssets() const { // regardless of what is set in the bootstrap wait for AP to be ready // wait a maximum of 100 milliseconds and pump the system event loop until empty struct AssetsInQueueNotification : public AzFramework::AssetSystemInfoBus::Handler { void CountOfAssetsInQueue(const int& count) override { CCryEditApp::OutputStartupMessage(QString("Asset Processor working... %1 jobs remaining.").arg(count)); } }; AssetsInQueueNotification assetsInQueueNotifcation; assetsInQueueNotifcation.BusConnect(); bool ready{}; while (!ready) { AzFramework::AssetSystemRequestBus::BroadcastResult(ready, &AzFramework::AssetSystemRequestBus::Events::WaitUntilAssetProcessorReady, AZStd::chrono::milliseconds(100)); if (!ready) { AzFramework::ApplicationRequests::Bus::Broadcast(&AzFramework::ApplicationRequests::PumpSystemEventLoopUntilEmpty); } } assetsInQueueNotifcation.BusDisconnect(); CCryEditApp::OutputStartupMessage(QString("Asset Processor is now ready.")); // VERY early on, as soon as we can, request that the asset system make sure the following assets take priority over others, // so that by the time we ask for them there is a greater likelihood that they're already good to go. // these can be loaded later but are still important: AzFramework::AssetSystemRequestBus::Broadcast(&AzFramework::AssetSystem::AssetSystemRequests::EscalateAssetBySearchTerm, "/texturemsg/"); AzFramework::AssetSystemRequestBus::Broadcast(&AzFramework::AssetSystem::AssetSystemRequests::EscalateAssetBySearchTerm, "engineassets/materials"); AzFramework::AssetSystemRequestBus::Broadcast(&AzFramework::AssetSystem::AssetSystemRequests::EscalateAssetBySearchTerm, "engineassets/geomcaches"); AzFramework::AssetSystemRequestBus::Broadcast(&AzFramework::AssetSystem::AssetSystemRequests::EscalateAssetBySearchTerm, "engineassets/objects"); // some are specifically extra important and will cause issues if missing completely: AzFramework::AssetSystemRequestBus::Broadcast(&AzFramework::AssetSystem::AssetSystemRequests::CompileAssetSync, "engineassets/objects/default.cgf"); } bool CCryEditApp::ConnectToAssetProcessor() const { bool connectedToAssetProcessor = false; // When the AssetProcessor is already launched it should take less than a second to perform a connection // but when the AssetProcessor needs to be launch it could take up to 15 seconds to have the AssetProcessor initialize // and able to negotiate a connection when running a debug build // and to negotiate a connection // Setting the connectTimeout to 3 seconds if not set within the settings registry AZStd::chrono::seconds connectTimeout(3); // Initialize the launchAssetProcessorTimeout to 15 seconds by default and check the settings registry for an override AZStd::chrono::seconds launchAssetProcessorTimeout(15); AZ::SettingsRegistryInterface* settingsRegistry = AZ::SettingsRegistry::Get(); if (settingsRegistry) { AZ::s64 timeoutValue{}; if (AZ::SettingsRegistryMergeUtils::PlatformGet(*settingsRegistry, timeoutValue, AZ::SettingsRegistryMergeUtils::BootstrapSettingsRootKey, "connect_ap_timeout")) { connectTimeout = AZStd::chrono::seconds(timeoutValue); } // Reset timeout integer timeoutValue = {}; if (AZ::SettingsRegistryMergeUtils::PlatformGet(*settingsRegistry, timeoutValue, AZ::SettingsRegistryMergeUtils::BootstrapSettingsRootKey, "launch_ap_timeout")) { launchAssetProcessorTimeout = AZStd::chrono::seconds(timeoutValue); } } CCryEditApp::OutputStartupMessage(QString("Connecting to Asset Processor... ")); AzFramework::AssetSystem::ConnectionSettings connectionSettings; AzFramework::AssetSystem::ReadConnectionSettingsFromSettingsRegistry(connectionSettings); connectionSettings.m_launchAssetProcessorOnFailedConnection = true; connectionSettings.m_connectionDirection = AzFramework::AssetSystem::ConnectionSettings::ConnectionDirection::ConnectToAssetProcessor; connectionSettings.m_connectionIdentifier = AzFramework::AssetSystem::ConnectionIdentifiers::Editor; connectionSettings.m_loggingCallback = [](AZStd::string_view logData) { CCryEditApp::OutputStartupMessage(QString::fromUtf8(logData.data(), aznumeric_cast<int>(logData.size()))); }; AzFramework::AssetSystemRequestBus::BroadcastResult(connectedToAssetProcessor, &AzFramework::AssetSystemRequestBus::Events::EstablishAssetProcessorConnection, connectionSettings); if (connectedToAssetProcessor) { CCryEditApp::OutputStartupMessage(QString("Connected to Asset Processor")); CompileCriticalAssets(); return true; } CCryEditApp::OutputStartupMessage(QString("Failed to connect to Asset Processor")); return false; } //! This handles the normal logging of Python output in the Editor by outputting //! the data to both the Editor Console and the Editor.log file struct CCryEditApp::PythonOutputHandler : public AzToolsFramework::EditorPythonConsoleNotificationBus::Handler { PythonOutputHandler() { AzToolsFramework::EditorPythonConsoleNotificationBus::Handler::BusConnect(); } ~PythonOutputHandler() override { AzToolsFramework::EditorPythonConsoleNotificationBus::Handler::BusDisconnect(); } int GetOrder() override { return 0; } void OnTraceMessage([[maybe_unused]] AZStd::string_view message) override { AZ_TracePrintf("python_test", "%.*s", static_cast<int>(message.size()), message.data()); } void OnErrorMessage([[maybe_unused]] AZStd::string_view message) override { AZ_Error("python_test", false, "%.*s", static_cast<int>(message.size()), message.data()); } void OnExceptionMessage([[maybe_unused]] AZStd::string_view message) override { AZ_Error("python_test", false, "EXCEPTION: %.*s", static_cast<int>(message.size()), message.data()); } }; //! Outputs Python test script print() to stdout //! If an exception happens in a Python test script, the process terminates struct PythonTestOutputHandler final : public CCryEditApp::PythonOutputHandler { PythonTestOutputHandler() = default; ~PythonTestOutputHandler() override = default; void OnTraceMessage(AZStd::string_view message) override { PythonOutputHandler::OnTraceMessage(message); printf("%.*s\n", static_cast<int>(message.size()), message.data()); } void OnErrorMessage(AZStd::string_view message) override { PythonOutputHandler::OnErrorMessage(message); printf("ERROR: %.*s\n", static_cast<int>(message.size()), message.data()); } void OnExceptionMessage(AZStd::string_view message) override { PythonOutputHandler::OnExceptionMessage(message); printf("EXCEPTION: %.*s\n", static_cast<int>(message.size()), message.data()); } }; void CCryEditApp::RunInitPythonScript(CEditCommandLineInfo& cmdInfo) { if (cmdInfo.m_bRunPythonTestScript) { m_pythonOutputHandler = AZStd::make_shared<PythonTestOutputHandler>(); } else { m_pythonOutputHandler = AZStd::make_shared<PythonOutputHandler>(); } using namespace AzToolsFramework; if (cmdInfo.m_bRunPythonScript || cmdInfo.m_bRunPythonTestScript) { // cmdInfo data is only available on startup, copy it QByteArray fileStr = cmdInfo.m_strFileName.toUtf8(); // We support specifying multiple files in the cmdline by separating them with ';' AZStd::vector<AZStd::string_view> fileList; AzFramework::StringFunc::TokenizeVisitor( fileStr.constData(), [&fileList](AZStd::string_view elem) { fileList.push_back(elem); }, ';', false /* keepEmptyStrings */ ); if (cmdInfo.m_pythonArgs.length() > 0 || cmdInfo.m_bRunPythonTestScript) { QByteArray pythonArgsStr = cmdInfo.m_pythonArgs.toUtf8(); AZStd::vector<AZStd::string_view> pythonArgs; AzFramework::StringFunc::TokenizeVisitor(pythonArgsStr.constData(), [&pythonArgs](AZStd::string_view elem) { pythonArgs.push_back(elem); }, ' ' ); if (cmdInfo.m_bRunPythonTestScript) { // Multiple testcases can be specified them with ';', these should match the files to run AZStd::vector<AZStd::string_view> testcaseList; testcaseList.resize(fileList.size()); { int i = 0; AzFramework::StringFunc::TokenizeVisitor( fileStr.constData(), [&i, &testcaseList](AZStd::string_view elem) { testcaseList[i++] = (elem); }, ';', false /* keepEmptyStrings */ ); } bool success = true; auto ExecuteByFilenamesTests = [&pythonArgs, &fileList, &testcaseList, &success](EditorPythonRunnerRequests* pythonRunnerRequests) { for (int i = 0; i < fileList.size(); ++i) { bool cur_success = pythonRunnerRequests->ExecuteByFilenameAsTest(fileList[i], testcaseList[i], pythonArgs); success = success && cur_success; } }; EditorPythonRunnerRequestBus::Broadcast(ExecuteByFilenamesTests); if (success) { // Close the editor gracefully as the test has completed GetIEditor()->GetDocument()->SetModifiedFlag(false); QTimer::singleShot(0, qApp, &QApplication::closeAllWindows); } else { // Close down the application with 0xF exit code indicating failure of the test AZ::Debug::Trace::Terminate(0xF); } } else { auto ExecuteByFilenamesWithArgs = [&pythonArgs, &fileList](EditorPythonRunnerRequests* pythonRunnerRequests) { for (AZStd::string_view filename : fileList) { pythonRunnerRequests->ExecuteByFilenameWithArgs(filename, pythonArgs); } }; EditorPythonRunnerRequestBus::Broadcast(ExecuteByFilenamesWithArgs); } } else { auto ExecuteByFilenames = [&fileList](EditorPythonRunnerRequests* pythonRunnerRequests) { for (AZStd::string_view filename : fileList) { pythonRunnerRequests->ExecuteByFilename(filename); } }; EditorPythonRunnerRequestBus::Broadcast(ExecuteByFilenames); } } } ///////////////////////////////////////////////////////////////////////////// // CCryEditApp initialization bool CCryEditApp::InitInstance() { QElapsedTimer startupTimer; startupTimer.start(); InitDirectory(); // create / attach to the environment: AttachEditorCoreAZEnvironment(AZ::Environment::GetInstance()); m_pEditor = new CEditorImpl(); // parameters must be parsed early to capture arguments for test bootstrap CEditCommandLineInfo cmdInfo; InitFromCommandLine(cmdInfo); InitDirectory(); qobject_cast<Editor::EditorQtApplication*>(qApp)->Initialize(); // Must be done after CEditorImpl() is created m_pEditor->Initialize(); // let anything listening know that they can use the IEditor now AzToolsFramework::EditorEvents::Bus::Broadcast(&AzToolsFramework::EditorEvents::NotifyIEditorAvailable, m_pEditor); if (cmdInfo.m_bShowVersionInfo) { CAboutDialog aboutDlg(FormatVersion(m_pEditor->GetFileVersion()), FormatRichTextCopyrightNotice()); aboutDlg.exec(); return false; } // Reflect property control classes to the serialize context... AZ::SerializeContext* serializeContext = nullptr; AZ::ComponentApplicationBus::BroadcastResult(serializeContext, &AZ::ComponentApplicationRequests::GetSerializeContext); AZ_Assert(serializeContext, "Serialization context not available"); ReflectedVarInit::setupReflection(serializeContext); RegisterReflectedVarHandlers(); CreateSplashScreen(); // Register the application's document templates. Document templates // serve as the connection between documents, frame windows and views CCrySingleDocTemplate* pDocTemplate = CCrySingleDocTemplate::create<CCryEditDoc>(); m_pDocManager = new CCryDocManager; ((CCryDocManager*)m_pDocManager)->SetDefaultTemplate(pDocTemplate); auto mainWindow = new MainWindow(); #ifdef Q_OS_MACOS auto mainWindowWrapper = new AzQtComponents::WindowDecorationWrapper(AzQtComponents::WindowDecorationWrapper::OptionDisabled); #else // No need for mainwindow wrapper for MatEdit mode auto mainWindowWrapper = new AzQtComponents::WindowDecorationWrapper(cmdInfo.m_bMatEditMode ? AzQtComponents::WindowDecorationWrapper::OptionDisabled : AzQtComponents::WindowDecorationWrapper::OptionAutoTitleBarButtons); #endif mainWindowWrapper->setGuest(mainWindow); HWND mainWindowWrapperHwnd = (HWND)mainWindowWrapper->winId(); AZ::IO::FixedMaxPath engineRootPath; if (auto settingsRegistry = AZ::SettingsRegistry::Get(); settingsRegistry != nullptr) { settingsRegistry->Get(engineRootPath.Native(), AZ::SettingsRegistryMergeUtils::FilePathKey_EngineRootFolder); } QDir engineRoot = QString::fromUtf8(engineRootPath.c_str(), aznumeric_cast<int>(engineRootPath.Native().size())); AzQtComponents::StyleManager::addSearchPaths( QStringLiteral("style"), engineRoot.filePath(QStringLiteral("Code/Editor/Style")), QStringLiteral(":/Assets/Editor/Style"), engineRootPath); AzQtComponents::StyleManager::setStyleSheet(mainWindow, QStringLiteral("style:Editor.qss")); // Note: we should use getNativeHandle to get the HWND from the widget, but // it returns an invalid handle unless the widget has been shown and polished and even then // it sometimes returns an invalid handle. // So instead, we use winId(), which does consistently work //mainWindowWrapperHwnd = QtUtil::getNativeHandle(mainWindowWrapper); // Connect to the AssetProcessor at this point // It will be launched if not running ConnectToAssetProcessor(); auto initGameSystemOutcome = InitGameSystem(mainWindowWrapperHwnd); if (!initGameSystemOutcome.IsSuccess()) { return false; } // Process some queued events come from system init // Such as asset catalog loaded notification. // There are some systems need to load configurations from assets for post initialization but before loading level AZ::TickBus::ExecuteQueuedEvents(); qobject_cast<Editor::EditorQtApplication*>(qApp)->LoadSettings(); // Create Sandbox user folder if necessary AZ::IO::FileIOBase::GetDirectInstance()->CreatePath(Path::GetUserSandboxFolder().toUtf8().data()); if (!InitGame()) { if (gEnv && gEnv->pLog) { gEnv->pLog->LogError("Game can not be initialized, InitGame() failed."); } if (!cmdInfo.m_bExport) { QMessageBox::critical(AzToolsFramework::GetActiveWindow(), QString(), QObject::tr("Game can not be initialized, please refer to the editor log file")); } return false; } // Meant to be called before MainWindow::Initialize InitPlugins(); mainWindow->Initialize(); GetIEditor()->GetCommandManager()->RegisterAutoCommands(); GetIEditor()->AddUIEnums(); mainWindowWrapper->enableSaveRestoreGeometry("O3DE", "O3DE", "mainWindowGeometry"); m_pDocManager->OnFileNew(); if (IsInRegularEditorMode()) { // QuickAccessBar creation should be before m_pMainWnd->SetFocus(), // since it receives the focus at creation time. It brakes MainFrame key accelerators. m_pQuickAccessBar = new CQuickAccessBar; m_pQuickAccessBar->setVisible(false); } if (MainWindow::instance()) { if (m_bConsoleMode || IsInAutotestMode()) { AZ::Environment::FindVariable<int>("assertVerbosityLevel").Set(1); m_pConsoleDialog->raise(); } else if (!GetIEditor()->IsInMatEditMode()) { MainWindow::instance()->show(); MainWindow::instance()->raise(); MainWindow::instance()->update(); MainWindow::instance()->setFocus(); #if AZ_TRAIT_OS_PLATFORM_APPLE QWindow* window = mainWindowWrapper->windowHandle(); if (window) { Editor::WindowObserver* observer = new Editor::WindowObserver(window, this); connect(observer, &Editor::WindowObserver::windowIsMovingOrResizingChanged, Editor::EditorQtApplication::instance(), &Editor::EditorQtApplication::setIsMovingOrResizing); } #endif } } if (m_bAutotestMode) { ICVar* const noErrorReportWindowCVar = gEnv && gEnv->pConsole ? gEnv->pConsole->GetCVar("sys_no_error_report_window") : nullptr; if (noErrorReportWindowCVar) { noErrorReportWindowCVar->Set(true); } ICVar* const showErrorDialogOnLoadCVar = gEnv && gEnv->pConsole ? gEnv->pConsole->GetCVar("ed_showErrorDialogOnLoad") : nullptr; if (showErrorDialogOnLoadCVar) { showErrorDialogOnLoadCVar->Set(false); } } SetEditorWindowTitle(nullptr, AZ::Utils::GetProjectName().c_str(), nullptr); if (!GetIEditor()->IsInMatEditMode()) { m_pEditor->InitFinished(); } // Make sure Python is started before we attempt to restore the Editor layout, since the user // might have custom view panes in the saved layout that will need to be registered. auto editorPythonEventsInterface = AZ::Interface<AzToolsFramework::EditorPythonEventsInterface>::Get(); if (editorPythonEventsInterface) { editorPythonEventsInterface->StartPython(); } if (!GetIEditor()->IsInMatEditMode() && !GetIEditor()->IsInConsolewMode()) { bool restoreDefaults = !mainWindowWrapper->restoreGeometryFromSettings(); QtViewPaneManager::instance()->RestoreLayout(restoreDefaults); } CloseSplashScreen(); // DON'T CHANGE ME! // Test scripts listen for this line, so please don't touch this without updating them. // We consider ourselves "initialized enough" at this stage because all further initialization may be blocked by the modal welcome screen. CLogFile::WriteLine(QString("Engine initialized, took %1s.").arg(startupTimer.elapsed() / 1000.0, 0, 'f', 2)); // Init the level after everything else is finished initializing, otherwise, certain things aren't set up yet QTimer::singleShot(0, this, [this, cmdInfo] { InitLevel(cmdInfo); }); #ifdef USE_WIP_FEATURES_MANAGER // load the WIP features file CWipFeatureManager::Instance()->EnableManager(!cmdInfo.m_bDeveloperMode); CWipFeatureManager::Init(); #endif if (!m_bConsoleMode && !m_bPreviewMode) { GetIEditor()->UpdateViews(); if (MainWindow::instance()) { MainWindow::instance()->setFocus(); } } if (!InitConsole()) { return true; } if (IsInRegularEditorMode()) { int startUpMacroIndex = GetIEditor()->GetToolBoxManager()->GetMacroIndex("startup", true); if (startUpMacroIndex >= 0) { CryLogAlways("Executing the startup macro"); GetIEditor()->GetToolBoxManager()->ExecuteMacro(startUpMacroIndex, true); } } if (GetIEditor()->GetCommandManager()->IsRegistered("editor.open_lnm_editor")) { CCommand0::SUIInfo uiInfo; #if !defined(NDEBUG) bool ok = #endif GetIEditor()->GetCommandManager()->GetUIInfo("editor.open_lnm_editor", uiInfo); assert(ok); } RunInitPythonScript(cmdInfo); return true; } void CCryEditApp::RegisterEventLoopHook(IEventLoopHook* pHook) { pHook->pNextHook = m_pEventLoopHook; m_pEventLoopHook = pHook; } void CCryEditApp::UnregisterEventLoopHook(IEventLoopHook* pHookToRemove) { IEventLoopHook* pPrevious = nullptr; for (IEventLoopHook* pHook = m_pEventLoopHook; pHook != nullptr; pHook = pHook->pNextHook) { if (pHook == pHookToRemove) { if (pPrevious) { pPrevious->pNextHook = pHookToRemove->pNextHook; } else { m_pEventLoopHook = pHookToRemove->pNextHook; } pHookToRemove->pNextHook = nullptr; return; } } } ////////////////////////////////////////////////////////////////////////// void CCryEditApp::LoadFile(QString fileName) { if (GetIEditor()->GetViewManager()->GetViewCount() == 0) { return; } LoadTagLocations(); if (MainWindow::instance() || m_pConsoleDialog) { SetEditorWindowTitle(nullptr, AZ::Utils::GetProjectName().c_str(), GetIEditor()->GetGameEngine()->GetLevelName()); } GetIEditor()->SetModifiedFlag(false); GetIEditor()->SetModifiedModule(eModifiedNothing); } ////////////////////////////////////////////////////////////////////////// inline void ExtractMenuName(QString& str) { // eliminate & int pos = str.indexOf('&'); if (pos >= 0) { str = str.left(pos) + str.right(str.length() - pos - 1); } // cut the string for (int i = 0; i < str.length(); i++) { if (str[i] == 9) { str = str.left(i); } } } ////////////////////////////////////////////////////////////////////////// void CCryEditApp::EnableAccelerator([[maybe_unused]] bool bEnable) { /* if (bEnable) { //LoadAccelTable( MAKEINTRESOURCE(IDR_MAINFRAME) ); m_AccelManager.UpdateWndTable(); CLogFile::WriteLine( "Enable Accelerators" ); } else { CMainFrame *mainFrame = (CMainFrame*)m_pMainWnd; if (mainFrame->m_hAccelTable) DestroyAcceleratorTable( mainFrame->m_hAccelTable ); mainFrame->m_hAccelTable = nullptr; mainFrame->LoadAccelTable( MAKEINTRESOURCE(IDR_GAMEACCELERATOR) ); CLogFile::WriteLine( "Disable Accelerators" ); } */ } ////////////////////////////////////////////////////////////////////////// void CCryEditApp::SaveAutoRemind() { // Added a static variable here to avoid multiple messageboxes to // remind the user of saving the file. Many message boxes would appear as this // is triggered by a timer even which does not stop when the message box is called. // Used a static variable instead of a member variable because this value is not // Needed anywhere else. static bool boIsShowingWarning(false); // Ingore in game mode, or if no level created, or level not modified if (GetIEditor()->IsInGameMode() || !GetIEditor()->GetGameEngine()->IsLevelLoaded() || !GetIEditor()->GetDocument()->IsModified()) { return; } if (boIsShowingWarning) { return; } boIsShowingWarning = true; if (QMessageBox::question(AzToolsFramework::GetActiveWindow(), QString(), QObject::tr("Auto Reminder: You did not save level for at least %1 minute(s)\r\nDo you want to save it now?").arg(gSettings.autoRemindTime), QMessageBox::Yes | QMessageBox::No) == QMessageBox::Yes) { // Save now. GetIEditor()->SaveDocument(); } boIsShowingWarning = false; } ////////////////////////////////////////////////////////////////////////// void CCryEditApp::WriteConfig() { IEditor* pEditor = GetIEditor(); if (pEditor && pEditor->GetDisplaySettings()) { pEditor->GetDisplaySettings()->SaveRegistry(); } } // App command to run the dialog void CCryEditApp::OnAppAbout() { CAboutDialog aboutDlg(FormatVersion(m_pEditor->GetFileVersion()), FormatRichTextCopyrightNotice()); aboutDlg.exec(); } // App command to run the Welcome to Open 3D Engine dialog void CCryEditApp::OnAppShowWelcomeScreen() { // This logic is a simplified version of the startup // flow that also shows the Welcome dialog if (m_bIsExportingLegacyData || m_creatingNewLevel || m_openingLevel || m_savingLevel) { QMessageBox::warning(AzToolsFramework::GetActiveWindow(), QString(), "The Welcome screen cannot be displayed because a level load/save is in progress."); return; } QString levelName; bool showWelcomeDialog = true; while (showWelcomeDialog) { // Keep showing the Welcome dialog as long as the user cancels // a level creation/load triggered from the Welcome dialog levelName = ShowWelcomeDialog(); if (levelName == "new") { // The user has clicked on the create new level option bool wasCreateLevelOperationCancelled = false; bool isNewLevelCreationSuccess = false; // This will show the new level dialog until a valid input has been entered by the user or until the user click cancel while (!isNewLevelCreationSuccess && !wasCreateLevelOperationCancelled) { isNewLevelCreationSuccess = CreateLevel(wasCreateLevelOperationCancelled); } if (isNewLevelCreationSuccess) { showWelcomeDialog = false; levelName.clear(); } } else if (levelName == "new slice") { QMessageBox::warning(AzToolsFramework::GetActiveWindow(), "Not implemented", "New Slice is not yet implemented."); } else { // The user has selected an existing level to open showWelcomeDialog = false; } } if (!levelName.isEmpty()) { // load level if (!CFileUtil::Exists(levelName, false)) { QMessageBox::critical(AzToolsFramework::GetActiveWindow(), QObject::tr("Missing level"), QObject::tr("Failed to auto-load last opened level. Level file does not exist:\n\n%1").arg(levelName)); } else { OpenDocumentFile(levelName.toUtf8().data()); } } } void CCryEditApp::OnUpdateShowWelcomeScreen(QAction* action) { action->setEnabled(!m_bIsExportingLegacyData && !m_creatingNewLevel && !m_openingLevel && !m_savingLevel); } void CCryEditApp::OnDocumentationTutorials() { QString webLink = tr("https://o3deorg.netlify.app/docs/learning-guide/"); QDesktopServices::openUrl(QUrl(webLink)); } void CCryEditApp::OnDocumentationGlossary() { QString webLink = tr("https://docs.o3de.org/docs/user-guide/appendix/glossary/"); QDesktopServices::openUrl(QUrl(webLink)); } void CCryEditApp::OnDocumentationO3DE() { QString webLink = tr("https://o3deorg.netlify.app/docs/"); QDesktopServices::openUrl(QUrl(webLink)); } void CCryEditApp::OnDocumentationGamelift() { QString webLink = tr("https://docs.aws.amazon.com/gamelift/"); QDesktopServices::openUrl(QUrl(webLink)); } void CCryEditApp::OnDocumentationReleaseNotes() { QString webLink = tr("https://o3deorg.netlify.app/docs/release-notes/"); QDesktopServices::openUrl(QUrl(webLink)); } void CCryEditApp::OnDocumentationGameDevBlog() { QString webLink = tr("https://aws.amazon.com/blogs/gamedev"); QDesktopServices::openUrl(QUrl(webLink)); } void CCryEditApp::OnDocumentationForums() { QString webLink = tr("https://o3deorg.netlify.app/community/"); QDesktopServices::openUrl(QUrl(webLink)); } void CCryEditApp::OnDocumentationAWSSupport() { QString webLink = tr("https://aws.amazon.com/contact-us"); QDesktopServices::openUrl(QUrl(webLink)); } bool CCryEditApp::FixDanglingSharedMemory(const QString& sharedMemName) const { QSystemSemaphore sem(sharedMemName + "_sem", 1); sem.acquire(); { QSharedMemory fix(sharedMemName); if (!fix.attach()) { if (fix.error() != QSharedMemory::NotFound) { sem.release(); return false; } } // fix.detach() when destructed, taking out any dangling shared memory // on unix } sem.release(); return true; } ///////////////////////////////////////////////////////////////////////////// // CCryEditApp message handlers int CCryEditApp::ExitInstance(int exitCode) { AZ_TracePrintf("Exit", "Called ExitInstance() with exit code: 0x%x", exitCode); if (m_pEditor) { m_pEditor->OnBeginShutdownSequence(); } qobject_cast<Editor::EditorQtApplication*>(qApp)->UnloadSettings(); #ifdef USE_WIP_FEATURES_MANAGER // // close wip features manager // CWipFeatureManager::Shutdown(); #endif if (IsInRegularEditorMode()) { if (GetIEditor()) { int shutDownMacroIndex = GetIEditor()->GetToolBoxManager()->GetMacroIndex("shutdown", true); if (shutDownMacroIndex >= 0) { CryLogAlways("Executing the shutdown macro"); GetIEditor()->GetToolBoxManager()->ExecuteMacro(shutDownMacroIndex, true); } } } if (GetIEditor() && !GetIEditor()->IsInMatEditMode()) { //Nobody seems to know in what case that kind of exit can happen so instrumented to see if it happens at all if (m_pEditor) { m_pEditor->OnEarlyExitShutdownSequence(); } gEnv->pLog->FlushAndClose(); // note: the intention here is to quit immediately without processing anything further // on linux and mac, _exit has that effect // however, on windows, _exit() still invokes CRT functions, unloads, and destructors // so on windows, we need to use TerminateProcess #if defined(AZ_PLATFORM_WINDOWS) TerminateProcess(GetCurrentProcess(), exitCode); #else _exit(exitCode); #endif } SAFE_DELETE(m_pConsoleDialog); SAFE_DELETE(m_pQuickAccessBar); if (GetIEditor()) { GetIEditor()->Notify(eNotify_OnQuit); } // if we're aborting due to an unexpected shutdown then don't call into objects that don't exist yet. if ((gEnv) && (gEnv->pSystem) && (gEnv->pSystem->GetILevelSystem())) { gEnv->pSystem->GetILevelSystem()->UnloadLevel(); } if (GetIEditor()) { GetIEditor()->GetDocument()->DeleteTemporaryLevel(); } m_bExiting = true; HEAP_CHECK //////////////////////////////////////////////////////////////////////// // Executed directly before termination of the editor, just write a // quick note to the log so that we can later see that the editor // terminated flawlessly. Also delete temporary files. //////////////////////////////////////////////////////////////////////// WriteConfig(); if (m_pEditor) { // Ensure component entities are wiped prior to unloading plugins, // since components may be implemented in those plugins. EBUS_EVENT(AzToolsFramework::EditorEntityContextRequestBus, ResetEditorContext); // vital, so that the Qt integration can unhook itself! m_pEditor->UnloadPlugins(); m_pEditor->Uninitialize(); } ////////////////////////////////////////////////////////////////////////// // Quick end for editor. if (gEnv && gEnv->pSystem) { gEnv->pSystem->Quit(); SAFE_RELEASE(gEnv->pSystem); } ////////////////////////////////////////////////////////////////////////// if (m_pEditor) { m_pEditor->DeleteThis(); m_pEditor = nullptr; } // save accelerator manager configuration. //m_AccelManager.SaveOnExit(); #ifdef WIN32 Gdiplus::GdiplusShutdown(m_gdiplusToken); #endif if (m_mutexApplication) { delete m_mutexApplication; } DetachEditorCoreAZEnvironment(); return 0; } bool CCryEditApp::IsWindowInForeground() { return Editor::EditorQtApplication::instance()->IsActive(); } void CCryEditApp::DisableIdleProcessing() { m_disableIdleProcessingCounter++; } void CCryEditApp::EnableIdleProcessing() { m_disableIdleProcessingCounter--; AZ_Assert(m_disableIdleProcessingCounter >= 0, "m_disableIdleProcessingCounter must be nonnegative"); } bool CCryEditApp::OnIdle([[maybe_unused]] LONG lCount) { if (0 == m_disableIdleProcessingCounter) { return IdleProcessing(false); } else { return false; } } int CCryEditApp::IdleProcessing(bool bBackgroundUpdate) { AZ_Assert(m_disableIdleProcessingCounter == 0, "We should not be in IdleProcessing()"); //HEAP_CHECK if (!MainWindow::instance()) { return 0; } if (!GetIEditor()->GetSystem()) { return 0; } // Ensure we don't get called re-entrantly // This can occur when a nested Qt event loop fires (e.g. by way of a modal dialog calling exec) if (m_idleProcessingRunning) { return 0; } QScopedValueRollback<bool> guard(m_idleProcessingRunning, true); //////////////////////////////////////////////////////////////////////// // Call the update function of the engine //////////////////////////////////////////////////////////////////////// if (m_bTestMode && !bBackgroundUpdate) { // Terminate process. CLogFile::WriteLine("Editor: Terminate Process"); exit(0); } bool bIsAppWindow = IsWindowInForeground(); bool bActive = false; int res = 0; if (bIsAppWindow || m_bForceProcessIdle || m_bKeepEditorActive // Automated tests must always keep the editor active, or they can get stuck || m_bAutotestMode || m_bRunPythonTestScript) { res = 1; bActive = true; } if (m_bForceProcessIdle && bIsAppWindow) { m_bForceProcessIdle = false; } // focus changed if (m_bPrevActive != bActive) { GetIEditor()->GetSystem()->GetISystemEventDispatcher()->OnSystemEvent(ESYSTEM_EVENT_CHANGE_FOCUS, bActive, 0); #if defined(AZ_PLATFORM_WINDOWS) // This is required for the audio system to be notified of focus changes in the editor. After discussing it // with the macOS team, they are working on unifying the system events between the editor and standalone // launcher so this is only needed on windows. if (bActive) { EBUS_EVENT(AzFramework::WindowsLifecycleEvents::Bus, OnSetFocus); } else { EBUS_EVENT(AzFramework::WindowsLifecycleEvents::Bus, OnKillFocus); } #endif } m_bPrevActive = bActive; // Don't tick application if we're doing idle processing during an assert. const bool isErrorWindowVisible = (gEnv && gEnv->pSystem->IsAssertDialogVisible()); if (isErrorWindowVisible) { if (m_pEditor) { m_pEditor->Update(); } } else if (bActive || (bBackgroundUpdate && !bIsAppWindow)) { // Update Game GetIEditor()->GetGameEngine()->Update(); if (!GetIEditor()->IsInGameMode()) { if (m_pEditor) { m_pEditor->Update(); } GetIEditor()->Notify(eNotify_OnIdleUpdate); } AZ::ComponentApplication* componentApplication = nullptr; AZ::ComponentApplicationBus::BroadcastResult(componentApplication, &AZ::ComponentApplicationRequests::GetApplication); if (componentApplication) { componentApplication->TickSystem(); } } else if (GetIEditor()->GetSystem() && GetIEditor()->GetSystem()->GetILog()) { GetIEditor()->GetSystem()->GetILog()->Update(); // print messages from other threads } DisplayLevelLoadErrors(); if (CConsoleSCB::GetCreatedInstance()) { CConsoleSCB::GetCreatedInstance()->FlushText(); } return res; } void CCryEditApp::DisplayLevelLoadErrors() { CCryEditDoc* currentLevel = GetIEditor()->GetDocument(); if (currentLevel && currentLevel->IsDocumentReady() && !m_levelErrorsHaveBeenDisplayed) { // Generally it takes a few idle updates for meshes to load and be processed by their components. This value // was picked based on examining when mesh components are updated and their materials are checked for // errors (2 updates) plus one more for good luck. const int IDLE_FRAMES_TO_WAIT = 3; ++m_numBeforeDisplayErrorFrames; if (m_numBeforeDisplayErrorFrames > IDLE_FRAMES_TO_WAIT) { GetIEditor()->CommitLevelErrorReport(); GetIEditor()->GetErrorReport()->Display(); m_numBeforeDisplayErrorFrames = 0; m_levelErrorsHaveBeenDisplayed = true; } } } ////////////////////////////////////////////////////////////////////////// void CCryEditApp::ExportLevel(bool bExportToGame, bool bExportTexture, bool bAutoExport) { bool usePrefabSystemForLevels = false; AzFramework::ApplicationRequests::Bus::BroadcastResult( usePrefabSystemForLevels, &AzFramework::ApplicationRequests::IsPrefabSystemForLevelsEnabled); if (usePrefabSystemForLevels) { AZ_Assert(false, "Prefab system doesn't require level exports."); return; } if (bExportTexture) { CGameExporter gameExporter; gameExporter.SetAutoExportMode(bAutoExport); gameExporter.Export(eExp_SurfaceTexture); } else if (bExportToGame) { CGameExporter gameExporter; gameExporter.SetAutoExportMode(bAutoExport); gameExporter.Export(); } } ////////////////////////////////////////////////////////////////////////// void CCryEditApp::OnEditHold() { GetIEditor()->GetDocument()->Hold(HOLD_FETCH_FILE); } ////////////////////////////////////////////////////////////////////////// void CCryEditApp::OnEditFetch() { GetIEditor()->GetDocument()->Fetch(HOLD_FETCH_FILE); } ////////////////////////////////////////////////////////////////////////// bool CCryEditApp::UserExportToGame(bool bNoMsgBox) { bool usePrefabSystemForLevels = false; AzFramework::ApplicationRequests::Bus::BroadcastResult( usePrefabSystemForLevels, &AzFramework::ApplicationRequests::IsPrefabSystemForLevelsEnabled); if (usePrefabSystemForLevels) { AZ_Assert(false, "Export Level should no longer exist."); return false; } if (!GetIEditor()->GetGameEngine()->IsLevelLoaded()) { if (bNoMsgBox == false) { QMessageBox::warning(AzToolsFramework::GetActiveWindow(), QString(), QObject::tr("Please load a level before attempting to export.")); } return false; } else { EditorUtils::AzWarningAbsorber absorb("Source Control"); // Record errors and display a dialog with them at the end. CErrorsRecorder errRecorder(GetIEditor()); // Temporarily disable auto backup. CScopedVariableSetter<bool> autoBackupEnabledChange(gSettings.autoBackupEnabled, false); CScopedVariableSetter<int> autoRemindTimeChange(gSettings.autoRemindTime, 0); m_bIsExportingLegacyData = true; CGameExporter gameExporter; unsigned int flags = eExp_CoverSurfaces; // Change the cursor to show that we're busy. QWaitCursor wait; if (gameExporter.Export(flags, eLittleEndian, ".")) { m_bIsExportingLegacyData = false; return true; } m_bIsExportingLegacyData = false; return false; } } void CCryEditApp::ExportToGame(bool bNoMsgBox) { bool usePrefabSystemForLevels = false; AzFramework::ApplicationRequests::Bus::BroadcastResult( usePrefabSystemForLevels, &AzFramework::ApplicationRequests::IsPrefabSystemForLevelsEnabled); if (usePrefabSystemForLevels) { AZ_Assert(false, "Prefab system no longer exports levels."); return; } CGameEngine* pGameEngine = GetIEditor()->GetGameEngine(); if (!pGameEngine->IsLevelLoaded()) { if (pGameEngine->GetLevelPath().isEmpty()) { QMessageBox::critical(AzToolsFramework::GetActiveWindow(), QString(), ("Open or create a level first.")); return; } CErrorsRecorder errRecorder(GetIEditor()); // If level not loaded first fast export terrain. m_bIsExportingLegacyData = true; CGameExporter gameExporter; gameExporter.Export(); m_bIsExportingLegacyData = false; } { UserExportToGame(bNoMsgBox); } } void CCryEditApp::OnFileExportToGameNoSurfaceTexture() { UserExportToGame(false); } ////////////////////////////////////////////////////////////////////////// void CCryEditApp::DeleteSelectedEntities([[maybe_unused]] bool includeDescendants) { GetIEditor()->BeginUndo(); CUndo undo("Delete Selected Object"); GetIEditor()->GetObjectManager()->DeleteSelection(); GetIEditor()->AcceptUndo("Delete Selection"); GetIEditor()->SetModifiedFlag(); GetIEditor()->SetModifiedModule(eModifiedBrushes); } void CCryEditApp::OnMoveObject() { //////////////////////////////////////////////////////////////////////// // Move the selected object to the marker position //////////////////////////////////////////////////////////////////////// } void CCryEditApp::OnRenameObj() { } void CCryEditApp::OnViewSwitchToGame() { if (IsInPreviewMode()) { return; } // close all open menus auto activePopup = qApp->activePopupWidget(); if (qobject_cast<QMenu*>(activePopup)) { activePopup->hide(); } // TODO: Add your command handler code here bool inGame = !GetIEditor()->IsInGameMode(); GetIEditor()->SetInGameMode(inGame); } ////////////////////////////////////////////////////////////////////////// void CCryEditApp::OnExportSelectedObjects() { CExportManager* pExportManager = static_cast<CExportManager*> (GetIEditor()->GetExportManager()); QString filename = "untitled"; CBaseObject* pObj = GetIEditor()->GetSelectedObject(); if (pObj) { filename = pObj->GetName(); } else { QString levelName = GetIEditor()->GetGameEngine()->GetLevelName(); if (!levelName.isEmpty()) { filename = levelName; } } QString levelPath = GetIEditor()->GetGameEngine()->GetLevelPath(); pExportManager->Export(filename.toUtf8().data(), "obj", levelPath.toUtf8().data()); } ////////////////////////////////////////////////////////////////////////// void CCryEditApp::OnFileExportOcclusionMesh() { CExportManager* pExportManager = static_cast<CExportManager*> (GetIEditor()->GetExportManager()); QString levelName = GetIEditor()->GetGameEngine()->GetLevelName(); QString levelPath = GetIEditor()->GetGameEngine()->GetLevelPath(); pExportManager->Export(levelName.toUtf8().data(), "ocm", levelPath.toUtf8().data(), false, false, true); } ////////////////////////////////////////////////////////////////////////// void CCryEditApp::OnOpenAssetImporter() { QtViewPaneManager::instance()->OpenPane(LyViewPane::SceneSettings); } ////////////////////////////////////////////////////////////////////////// void CCryEditApp::OnUpdateSelected(QAction* action) { action->setEnabled(!GetIEditor()->GetSelection()->IsEmpty()); } void CCryEditApp::OnShowHelpers() { GetIEditor()->GetDisplaySettings()->DisplayHelpers(!GetIEditor()->GetDisplaySettings()->IsDisplayHelpers()); GetIEditor()->Notify(eNotify_OnDisplayRenderUpdate); } ////////////////////////////////////////////////////////////////////////// void CCryEditApp::OnEditLevelData() { auto dir = QFileInfo(GetIEditor()->GetDocument()->GetLevelPathName()).dir(); CFileUtil::EditTextFile(dir.absoluteFilePath("LevelData.xml").toUtf8().data()); } ////////////////////////////////////////////////////////////////////////// void CCryEditApp::OnFileEditLogFile() { CFileUtil::EditTextFile(CLogFile::GetLogFileName(), 0, IFileUtil::FILE_TYPE_SCRIPT); } void CCryEditApp::OnFileResaveSlices() { AZStd::vector<AZ::Data::AssetInfo> sliceAssetInfos; sliceAssetInfos.reserve(5000); AZ::Data::AssetCatalogRequests::AssetEnumerationCB sliceCountCb = [&sliceAssetInfos]([[maybe_unused]] const AZ::Data::AssetId id, const AZ::Data::AssetInfo& info) { // Only add slices and nothing that has been temporarily added to the catalog with a macro in it (ie @engroot@) if (info.m_assetType == azrtti_typeid<AZ::SliceAsset>() && info.m_relativePath[0] != '@') { sliceAssetInfos.push_back(info); } }; AZ::Data::AssetCatalogRequestBus::Broadcast(&AZ::Data::AssetCatalogRequestBus::Events::EnumerateAssets, nullptr, sliceCountCb, nullptr); QString warningMessage = QString("Resaving all slices can be *extremely* slow depending on source control and on the number of slices in your project!\n\nYou can speed this up dramatically by checking out all your slices before starting this!\n\n Your project has %1 slices.\n\nDo you want to continue?").arg(sliceAssetInfos.size()); if (QMessageBox::Cancel == QMessageBox::warning(MainWindow::instance(), tr("!!!WARNING!!!"), warningMessage, QMessageBox::Ok | QMessageBox::Cancel, QMessageBox::Cancel)) { return; } AZ::SerializeContext* serialize = nullptr; AZ::ComponentApplicationBus::BroadcastResult(serialize, &AZ::ComponentApplicationBus::Events::GetSerializeContext); if (!serialize) { AZ_TracePrintf("Resave Slices", "Couldn't get the serialize context. Something is very wrong. Aborting!!!"); return; } AZ::IO::FileIOBase* fileIO = AZ::IO::FileIOBase::GetInstance(); if (!fileIO) { AZ_Error("Resave Slices", false, "File IO is not initialized."); return; } int numFailures = 0; // Create a lambda for load & save logic to make the lambda below easier to read auto LoadAndSaveSlice = [serialize, &numFailures](const AZStd::string& filePath) { AZ::Entity* newRootEntity = nullptr; // Read in the slice file first { AZ::IO::FileIOStream readStream(filePath.c_str(), AZ::IO::OpenMode::ModeRead); newRootEntity = AZ::Utils::LoadObjectFromStream<AZ::Entity>(readStream, serialize, AZ::ObjectStream::FilterDescriptor(AZ::Data::AssetFilterNoAssetLoading)); } // If we successfully loaded the file if (newRootEntity) { if (!AZ::Utils::SaveObjectToFile(filePath, AZ::DataStream::ST_XML, newRootEntity)) { AZ_TracePrintf("Resave Slices", "Unable to serialize the slice (%s) out to a file. Unable to resave this slice\n", filePath.c_str()); numFailures++; } } else { AZ_TracePrintf("Resave Slices", "Unable to read a slice (%s) file from disk. Unable to resave this slice.\n", filePath.c_str()); numFailures++; } }; const size_t numSlices = sliceAssetInfos.size(); int slicesProcessed = 0; int slicesRequestedForProcessing = 0; if (numSlices > 0) { AzToolsFramework::ProgressShield::LegacyShowAndWait(MainWindow::instance(), tr("Checking out and resaving slices..."), [numSlices, &slicesProcessed, &sliceAssetInfos, &LoadAndSaveSlice, &slicesRequestedForProcessing, &numFailures](int& current, int& max) { const static int numToProcessPerCall = 5; if (slicesRequestedForProcessing < numSlices) { for (int index = 0; index < numToProcessPerCall; index++) { if (slicesRequestedForProcessing < numSlices) { AZStd::string sourceFile; AzToolsFramework::AssetSystemRequestBus::Broadcast(&AzToolsFramework::AssetSystemRequestBus::Events::GetFullSourcePathFromRelativeProductPath, sliceAssetInfos[slicesRequestedForProcessing].m_relativePath, sourceFile); AzToolsFramework::ToolsApplicationRequestBus::Broadcast(&AzToolsFramework::ToolsApplicationRequestBus::Events::RequestEditForFile, sourceFile.c_str(), [&slicesProcessed, sourceFile, &LoadAndSaveSlice, &numFailures](bool success) { slicesProcessed++; if (success) { LoadAndSaveSlice(sourceFile); } else { AZ_TracePrintf("Resave Slices", "Unable to check a slice (%s) out of source control. Unable to resave this slice\n", sourceFile.c_str()); numFailures++; } } ); slicesRequestedForProcessing++; } } } current = slicesProcessed; max = static_cast<int>(numSlices); return slicesProcessed == numSlices; } ); QString completeMessage; if (numFailures > 0) { completeMessage = QString("All slices processed. There were %1 slices that could not be resaved. Please check the console for details.").arg(numFailures); } else { completeMessage = QString("All slices successfully process and re-saved!"); } QMessageBox::information(MainWindow::instance(), tr("Re-saving complete"), completeMessage, QMessageBox::Ok); } else { QMessageBox::information(MainWindow::instance(), tr("No slices found"), tr("There were no slices found to resave."), QMessageBox::Ok); } } ////////////////////////////////////////////////////////////////////////// void CCryEditApp::OnFileEditEditorini() { CFileUtil::EditTextFile(EDITOR_CFG_FILE); } void CCryEditApp::OnPreferences() { /* ////////////////////////////////////////////////////////////////////////////// // Accels edit by CPropertyPage CAcceleratorManager tmpAccelManager; tmpAccelManager = m_AccelManager; CAccelMapPage page(&tmpAccelManager); CPropertySheet sheet; sheet.SetTitle( _T("Preferences") ); sheet.AddPage(&page); if (sheet.DoModal() == IDOK) { m_AccelManager = tmpAccelManager; m_AccelManager.UpdateWndTable(); } */ } void CCryEditApp::OnOpenProjectManagerSettings() { OpenProjectManager("UpdateProject"); } void CCryEditApp::OnOpenProjectManagerNew() { OpenProjectManager("CreateProject"); } void CCryEditApp::OnOpenProjectManager() { OpenProjectManager("Projects"); } void CCryEditApp::OpenProjectManager(const AZStd::string& screen) { // provide the current project path for in case we want to update the project AZ::IO::FixedMaxPathString projectPath = AZ::Utils::GetProjectPath(); #if !AZ_TRAIT_OS_PLATFORM_APPLE && !AZ_TRAIT_OS_USE_WINDOWS_FILE_PATHS const char* argumentQuoteString = R"(")"; #else const char* argumentQuoteString = R"(\")"; #endif const AZStd::string commandLineOptions = AZStd::string::format(R"( --screen %s --project-path %s%s%s)", screen.c_str(), argumentQuoteString, projectPath.c_str(), argumentQuoteString); bool launchSuccess = AzFramework::ProjectManager::LaunchProjectManager(commandLineOptions); if (!launchSuccess) { QMessageBox::critical(AzToolsFramework::GetActiveWindow(), QObject::tr("Failed to launch O3DE Project Manager"), QObject::tr("Failed to find or start the O3dE Project Manager")); } } ////////////////////////////////////////////////////////////////////////// void CCryEditApp::OnUndo() { //GetIEditor()->GetObjectManager()->UndoLastOp(); GetIEditor()->Undo(); } ////////////////////////////////////////////////////////////////////////// void CCryEditApp::OnRedo() { GetIEditor()->Redo(); } ////////////////////////////////////////////////////////////////////////// void CCryEditApp::OnUpdateRedo(QAction* action) { if (GetIEditor()->GetUndoManager()->IsHaveRedo()) { action->setEnabled(true); } else { action->setEnabled(false); } } ////////////////////////////////////////////////////////////////////////// void CCryEditApp::OnUpdateUndo(QAction* action) { if (GetIEditor()->GetUndoManager()->IsHaveUndo()) { action->setEnabled(true); } else { action->setEnabled(false); } } /// Undo command to track entering and leaving Simulation Mode. class SimulationModeCommand : public AzToolsFramework::UndoSystem::URSequencePoint { public: AZ_CLASS_ALLOCATOR(SimulationModeCommand, AZ::SystemAllocator, 0); AZ_RTTI(SimulationModeCommand, "{FB9FB958-5C56-47F6-B168-B5F564F70E69}"); SimulationModeCommand(const AZStd::string& friendlyName); void Undo() override; void Redo() override; bool Changed() const override { return true; } // State will always have changed. private: void UndoRedo() { if (ActionManager* actionManager = MainWindow::instance()->GetActionManager()) { if (auto* action = actionManager->GetAction(ID_SWITCH_PHYSICS)) { action->trigger(); } } } }; SimulationModeCommand::SimulationModeCommand(const AZStd::string& friendlyName) : URSequencePoint(friendlyName) { } void SimulationModeCommand::Undo() { UndoRedo(); } void SimulationModeCommand::Redo() { UndoRedo(); } namespace UndoRedo { static bool IsHappening() { bool undoRedo = false; AzToolsFramework::ToolsApplicationRequestBus::BroadcastResult( undoRedo, &AzToolsFramework::ToolsApplicationRequests::IsDuringUndoRedo); return undoRedo; } } // namespace UndoRedo ////////////////////////////////////////////////////////////////////////// void CCryEditApp::OnSwitchPhysics() { if (GetIEditor()->GetGameEngine() && !GetIEditor()->GetGameEngine()->GetSimulationMode() && !GetIEditor()->GetGameEngine()->IsLevelLoaded()) { // Don't allow physics to be toggled on if we haven't loaded a level yet return; } QWaitCursor wait; AZStd::unique_ptr<AzToolsFramework::ScopedUndoBatch> undoBatch; if (!UndoRedo::IsHappening()) { undoBatch = AZStd::make_unique<AzToolsFramework::ScopedUndoBatch>("Switching Physics Simulation"); auto simulationModeCommand = AZStd::make_unique<SimulationModeCommand>(AZStd::string("Switch Physics")); // simulationModeCommand managed by undoBatch simulationModeCommand->SetParent(undoBatch->GetUndoBatch()); simulationModeCommand.release(); } GetISystem()->GetISystemEventDispatcher()->OnSystemEvent(ESYSTEM_EVENT_EDITOR_SIMULATION_MODE_SWITCH_START, 0, 0); uint32 flags = GetIEditor()->GetDisplaySettings()->GetSettings(); if (flags & SETTINGS_PHYSICS) { flags &= ~SETTINGS_PHYSICS; } else { flags |= SETTINGS_PHYSICS; } GetIEditor()->GetDisplaySettings()->SetSettings(flags); if ((flags & SETTINGS_PHYSICS) == 0) { GetIEditor()->GetGameEngine()->SetSimulationMode(false); GetISystem()->GetISystemEventDispatcher()->OnSystemEvent(ESYSTEM_EVENT_EDITOR_SIMULATION_MODE_CHANGED, 0, 0); } else { GetIEditor()->GetGameEngine()->SetSimulationMode(true); GetISystem()->GetISystemEventDispatcher()->OnSystemEvent(ESYSTEM_EVENT_EDITOR_SIMULATION_MODE_CHANGED, 1, 0); } GetISystem()->GetISystemEventDispatcher()->OnSystemEvent(ESYSTEM_EVENT_EDITOR_SIMULATION_MODE_SWITCH_END, 0, 0); } ////////////////////////////////////////////////////////////////////////// void CCryEditApp::OnSwitchPhysicsUpdate(QAction* action) { Q_ASSERT(action->isCheckable()); action->setChecked(!m_bIsExportingLegacyData && GetIEditor()->GetGameEngine()->GetSimulationMode()); } ////////////////////////////////////////////////////////////////////////// void CCryEditApp::OnSyncPlayer() { GetIEditor()->GetGameEngine()->SyncPlayerPosition(!GetIEditor()->GetGameEngine()->IsSyncPlayerPosition()); } ////////////////////////////////////////////////////////////////////////// void CCryEditApp::OnSyncPlayerUpdate(QAction* action) { Q_ASSERT(action->isCheckable()); action->setChecked(!GetIEditor()->GetGameEngine()->IsSyncPlayerPosition()); } void CCryEditApp::OnUpdateNonGameMode(QAction* action) { action->setEnabled(!GetIEditor()->IsInGameMode()); } void CCryEditApp::OnUpdateNewLevel(QAction* action) { action->setEnabled(!m_bIsExportingLegacyData); } void CCryEditApp::OnUpdatePlayGame(QAction* action) { action->setEnabled(!m_bIsExportingLegacyData && GetIEditor()->IsLevelLoaded()); } ////////////////////////////////////////////////////////////////////////// CCryEditApp::ECreateLevelResult CCryEditApp::CreateLevel(const QString& levelName, QString& fullyQualifiedLevelName /* ={} */) { bool usePrefabSystemForLevels = false; AzFramework::ApplicationRequests::Bus::BroadcastResult( usePrefabSystemForLevels, &AzFramework::ApplicationRequests::IsPrefabSystemForLevelsEnabled); // If we are creating a new level and we're in simulate mode, then switch it off before we do anything else if (GetIEditor()->GetGameEngine() && GetIEditor()->GetGameEngine()->GetSimulationMode()) { // Preserve the modified flag, we don't want this switch of physics to change that flag bool bIsDocModified = GetIEditor()->GetDocument()->IsModified(); OnSwitchPhysics(); GetIEditor()->GetDocument()->SetModifiedFlag(bIsDocModified); if (usePrefabSystemForLevels) { auto* rootSpawnableInterface = AzFramework::RootSpawnableInterface::Get(); if (rootSpawnableInterface) { rootSpawnableInterface->ProcessSpawnableQueue(); } } } const QScopedValueRollback<bool> rollback(m_creatingNewLevel); m_creatingNewLevel = true; GetIEditor()->Notify(eNotify_OnBeginCreate); CrySystemEventBus::Broadcast(&CrySystemEventBus::Events::OnCryEditorBeginCreate); QString currentLevel = GetIEditor()->GetLevelFolder(); if (!currentLevel.isEmpty()) { GetIEditor()->GetSystem()->GetIPak()->ClosePacks(currentLevel.toUtf8().data()); } QString cryFileName = levelName.mid(levelName.lastIndexOf('/') + 1, levelName.length() - levelName.lastIndexOf('/') + 1); QString levelPath = QStringLiteral("%1/Levels/%2/").arg(Path::GetEditingGameDataFolder().c_str(), levelName); fullyQualifiedLevelName = levelPath + cryFileName + EditorUtils::LevelFile::GetDefaultFileExtension(); //_MAX_PATH includes null terminator, so we actually want to cap at _MAX_PATH-1 if (fullyQualifiedLevelName.length() >= _MAX_PATH-1) { GetIEditor()->Notify(eNotify_OnEndCreate); return ECLR_MAX_PATH_EXCEEDED; } // Does the directory already exist ? if (QFileInfo(levelPath).exists()) { GetIEditor()->Notify(eNotify_OnEndCreate); return ECLR_ALREADY_EXISTS; } // Create the directory CLogFile::WriteLine("Creating level directory"); if (!CFileUtil::CreatePath(levelPath)) { GetIEditor()->Notify(eNotify_OnEndCreate); return ECLR_DIR_CREATION_FAILED; } if (GetIEditor()->GetDocument()->IsDocumentReady()) { m_pDocManager->OnFileNew(); } ICVar* sv_map = gEnv->pConsole->GetCVar("sv_map"); if (sv_map) { sv_map->Set(levelName.toUtf8().data()); } GetIEditor()->GetDocument()->InitEmptyLevel(128, 1); GetIEditor()->SetStatusText("Creating Level..."); // Save the document to this folder GetIEditor()->GetDocument()->SetPathName(fullyQualifiedLevelName); GetIEditor()->GetGameEngine()->SetLevelPath(levelPath); if (usePrefabSystemForLevels) { auto* service = AZ::Interface<AzToolsFramework::PrefabEditorEntityOwnershipInterface>::Get(); if (service) { service->CreateNewLevelPrefab(fullyQualifiedLevelName.toUtf8().constData(), DefaultLevelTemplateName); } } if (GetIEditor()->GetDocument()->Save()) { if (!usePrefabSystemForLevels) { m_bIsExportingLegacyData = true; CGameExporter gameExporter; gameExporter.Export(); m_bIsExportingLegacyData = false; } GetIEditor()->GetGameEngine()->LoadLevel(true, true); GetIEditor()->GetSystem()->GetISystemEventDispatcher()->OnSystemEvent(ESYSTEM_EVENT_LEVEL_PRECACHE_START, 0, 0); GetIEditor()->GetSystem()->GetISystemEventDispatcher()->OnSystemEvent(ESYSTEM_EVENT_LEVEL_PRECACHE_END, 0, 0); } if (!usePrefabSystemForLevels) { // No terrain, but still need to export default octree and visarea data. CGameExporter gameExporter; gameExporter.Export(eExp_CoverSurfaces | eExp_SurfaceTexture, eLittleEndian, "."); } GetIEditor()->GetDocument()->CreateDefaultLevelAssets(128, 1); GetIEditor()->GetDocument()->SetDocumentReady(true); GetIEditor()->SetStatusText("Ready"); // At the end of the creating level process, add this level to the MRU list CCryEditApp::instance()->AddToRecentFileList(fullyQualifiedLevelName); GetIEditor()->Notify(eNotify_OnEndCreate); CrySystemEventBus::Broadcast(&CrySystemEventBus::Events::OnCryEditorEndCreate); return ECLR_OK; } ////////////////////////////////////////////////////////////////////////// void CCryEditApp::OnCreateLevel() { if (m_creatingNewLevel) { return; } bool wasCreateLevelOperationCancelled = false; bool isNewLevelCreationSuccess = false; // This will show the new level dialog until a valid input has been entered by the user or until the user click cancel while (!isNewLevelCreationSuccess && !wasCreateLevelOperationCancelled) { wasCreateLevelOperationCancelled = false; isNewLevelCreationSuccess = CreateLevel(wasCreateLevelOperationCancelled); } } ////////////////////////////////////////////////////////////////////////// bool CCryEditApp::CreateLevel(bool& wasCreateLevelOperationCancelled) { bool bIsDocModified = GetIEditor()->GetDocument()->IsModified(); if (GetIEditor()->GetDocument()->IsDocumentReady() && bIsDocModified) { bool usePrefabSystemForLevels = false; AzFramework::ApplicationRequests::Bus::BroadcastResult( usePrefabSystemForLevels, &AzFramework::ApplicationRequests::IsPrefabSystemForLevelsEnabled); if (!usePrefabSystemForLevels) { QString str = QObject::tr("Level %1 has been changed. Save Level?").arg(GetIEditor()->GetGameEngine()->GetLevelName()); int result = QMessageBox::question( AzToolsFramework::GetActiveWindow(), QObject::tr("Save Level"), str, QMessageBox::Yes | QMessageBox::No | QMessageBox::Cancel); if (QMessageBox::Yes == result) { if (!GetIEditor()->GetDocument()->DoFileSave()) { // if the file save operation failed, assume that the user was informed of why // already and treat it as a cancel wasCreateLevelOperationCancelled = true; return false; } bIsDocModified = false; } else if (QMessageBox::No == result) { // Set Modified flag to false to prevent show Save unchanged dialog again GetIEditor()->GetDocument()->SetModifiedFlag(false); } else if (QMessageBox::Cancel == result) { wasCreateLevelOperationCancelled = true; return false; } } else { auto* prefabEditorEntityOwnershipInterface = AZ::Interface<AzToolsFramework::PrefabEditorEntityOwnershipInterface>::Get(); auto* prefabIntegrationInterface = AZ::Interface<AzToolsFramework::Prefab::PrefabIntegrationInterface>::Get(); AZ_Assert(prefabEditorEntityOwnershipInterface != nullptr, "PrefabEditorEntityOwnershipInterface is not found."); AZ_Assert(prefabIntegrationInterface != nullptr, "PrefabIntegrationInterface is not found."); if (prefabEditorEntityOwnershipInterface == nullptr || prefabIntegrationInterface == nullptr) { return false; } AzToolsFramework::Prefab::TemplateId rootPrefabTemplateId = prefabEditorEntityOwnershipInterface->GetRootPrefabTemplateId(); int prefabSaveSelection = prefabIntegrationInterface->ExecuteClosePrefabDialog(rootPrefabTemplateId); // In order to get the accept and reject codes of QDialog and QDialogButtonBox aligned, we do (1-prefabSaveSelection) here. // For example, QDialog::Rejected(0) is emitted when dialog is closed. But the int value corresponds to // QDialogButtonBox::AcceptRole(0). switch (1 - prefabSaveSelection) { case QDialogButtonBox::AcceptRole: bIsDocModified = false; break; case QDialogButtonBox::RejectRole: wasCreateLevelOperationCancelled = true; return false; case QDialogButtonBox::InvalidRole: // Set Modified flag to false to prevent show Save unchanged dialog again GetIEditor()->GetDocument()->SetModifiedFlag(false); break; } } } const char* temporaryLevelName = GetIEditor()->GetDocument()->GetTemporaryLevelName(); CNewLevelDialog dlg; dlg.m_level = ""; if (dlg.exec() != QDialog::Accepted) { wasCreateLevelOperationCancelled = true; GetIEditor()->GetDocument()->SetModifiedFlag(bIsDocModified); return false; } if (!GetIEditor()->GetLevelIndependentFileMan()->PromptChangedFiles()) { return false; } QString levelNameWithPath = dlg.GetLevel(); QString levelName = levelNameWithPath.mid(levelNameWithPath.lastIndexOf('/') + 1); if (levelName == temporaryLevelName && GetIEditor()->GetLevelName() != temporaryLevelName) { GetIEditor()->GetDocument()->DeleteTemporaryLevel(); } if (levelName.length() == 0 || !AZ::StringFunc::Path::IsValid(levelName.toUtf8().data())) { QMessageBox::critical(AzToolsFramework::GetActiveWindow(), QString(), QObject::tr("Level name is invalid, please choose another name.")); return false; } //Verify that we are not using the temporary level name if (QString::compare(levelName, temporaryLevelName) == 0) { QMessageBox::critical(AzToolsFramework::GetActiveWindow(), QString(), QObject::tr("Please enter a level name that is different from the temporary name.")); return false; } // We're about to start creating a level, so start recording errors to display at the end. GetIEditor()->StartLevelErrorReportRecording(); QString fullyQualifiedLevelName; ECreateLevelResult result = CreateLevel(levelNameWithPath, fullyQualifiedLevelName); if (result == ECLR_ALREADY_EXISTS) { QMessageBox::critical(AzToolsFramework::GetActiveWindow(), QString(), QObject::tr("Level with this name already exists, please choose another name.")); return false; } else if (result == ECLR_DIR_CREATION_FAILED) { QString szLevelRoot = QStringLiteral("%1\\Levels\\%2").arg(Path::GetEditingGameDataFolder().c_str(), levelName); QByteArray windowsErrorMessage(ERROR_LEN, 0); QByteArray cwd(ERROR_LEN, 0); DWORD dw = GetLastError(); #ifdef WIN32 wchar_t windowsErrorMessageW[ERROR_LEN]; windowsErrorMessageW[0] = L'\0'; FormatMessageW(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, nullptr, dw, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), windowsErrorMessageW, ERROR_LEN, nullptr); _getcwd(cwd.data(), cwd.length()); AZStd::to_string(windowsErrorMessage.data(), ERROR_LEN, windowsErrorMessageW); #else windowsErrorMessage = strerror(dw); cwd = QDir::currentPath().toUtf8(); #endif QMessageBox::critical(AzToolsFramework::GetActiveWindow(), QString(), QObject::tr("Failed to create level directory: %1\n Error: %2\nCurrent Path: %3").arg(szLevelRoot, windowsErrorMessage, cwd)); return false; } else if (result == ECLR_MAX_PATH_EXCEEDED) { QFileInfo info(fullyQualifiedLevelName); const AZStd::string rawProjectDirectory = Path::GetEditingGameDataFolder(); const QString projectDirectory = QDir::toNativeSeparators(QString::fromUtf8(rawProjectDirectory.data(), static_cast<int>(rawProjectDirectory.size()))); const QString elidedLevelName = QStringLiteral("%1...%2").arg(levelName.left(10)).arg(levelName.right(10)); const QString elidedLevelFileName = QStringLiteral("%1...%2").arg(info.fileName().left(10)).arg(info.fileName().right(10)); const QString message = QObject::tr( "The fully-qualified path for the new level exceeds the maximum supported path length of %1 characters (it's %2 characters long). Please choose a smaller name.\n\n" "The fully-qualified path is made up of the project folder (\"%3\", %4 characters), the \"Levels\" sub-folder, a folder named for the level (\"%5\", %6 characters) and the level file (\"%7\", %8 characters), plus necessary separators.\n\n" "Please also note that on most platforms, individual components of the path (folder/file names can't exceed approximately 255 characters)\n\n" "Click \"Copy to Clipboard\" to copy the fully-qualified name and close this message.") .arg(_MAX_PATH - 1).arg(fullyQualifiedLevelName.size()) .arg(projectDirectory).arg(projectDirectory.size()) .arg(elidedLevelName).arg(levelName.size()) .arg(elidedLevelFileName).arg(info.fileName().size()); QMessageBox messageBox(QMessageBox::Critical, QString(), message, QMessageBox::Ok, AzToolsFramework::GetActiveWindow()); QPushButton* copyButton = messageBox.addButton(QObject::tr("Copy to Clipboard"), QMessageBox::ActionRole); QObject::connect(copyButton, &QPushButton::pressed, this, [fullyQualifiedLevelName]() { QGuiApplication::clipboard()->setText(fullyQualifiedLevelName); }); messageBox.exec(); return false; } // force the level being rendered at least once m_bForceProcessIdle = true; m_levelErrorsHaveBeenDisplayed = false; return true; } ////////////////////////////////////////////////////////////////////////// void CCryEditApp::OnCreateSlice() { QMessageBox::warning(AzToolsFramework::GetActiveWindow(), "Not implemented", "New Slice is not yet implemented."); } ////////////////////////////////////////////////////////////////////////// void CCryEditApp::OnOpenLevel() { CLevelFileDialog levelFileDialog(true); levelFileDialog.show(); levelFileDialog.adjustSize(); if (levelFileDialog.exec() == QDialog::Accepted) { OpenDocumentFile(levelFileDialog.GetFileName().toUtf8().data()); } } ////////////////////////////////////////////////////////////////////////// void CCryEditApp::OnOpenSlice() { QString fileName = QFileDialog::getOpenFileName(MainWindow::instance(), tr("Open Slice"), Path::GetEditingGameDataFolder().c_str(), tr("Slice (*.slice)")); if (!fileName.isEmpty()) { OpenDocumentFile(fileName.toUtf8().data()); } } ////////////////////////////////////////////////////////////////////////// CCryEditDoc* CCryEditApp::OpenDocumentFile(const char* lpszFileName) { if (m_openingLevel) { return GetIEditor()->GetDocument(); } // If we are loading and we're in simulate mode, then switch it off before we do anything else if (GetIEditor()->GetGameEngine() && GetIEditor()->GetGameEngine()->GetSimulationMode()) { // Preserve the modified flag, we don't want this switch of physics to change that flag bool bIsDocModified = GetIEditor()->GetDocument()->IsModified(); OnSwitchPhysics(); GetIEditor()->GetDocument()->SetModifiedFlag(bIsDocModified); } // We're about to start loading a level, so start recording errors to display at the end. GetIEditor()->StartLevelErrorReportRecording(); const QScopedValueRollback<bool> rollback(m_openingLevel, true); MainWindow::instance()->menuBar()->setEnabled(false); CCryEditDoc* doc = nullptr; bool bVisible = false; bool bTriggerConsole = false; doc = GetIEditor()->GetDocument(); bVisible = GetIEditor()->ShowConsole(true); bTriggerConsole = true; if (GetIEditor()->GetLevelIndependentFileMan()->PromptChangedFiles()) { SandboxEditor::StartupTraceHandler openDocTraceHandler; openDocTraceHandler.StartCollection(); if (m_bAutotestMode) { openDocTraceHandler.SetShowWindow(false); } // in this case, we set bAddToMRU to always be true because adding files to the MRU list // automatically culls duplicate and normalizes paths anyway m_pDocManager->OpenDocumentFile(lpszFileName, true); if (openDocTraceHandler.HasAnyErrors()) { doc->SetHasErrors(); } } if (bTriggerConsole) { GetIEditor()->ShowConsole(bVisible); } LoadTagLocations(); MainWindow::instance()->menuBar()->setEnabled(true); if (doc->GetEditMode() == CCryEditDoc::DocumentEditingMode::SliceEdit) { // center camera on entities in slice if (ActionManager* actionManager = MainWindow::instance()->GetActionManager()) { GetIEditor()->GetUndoManager()->Suspend(); actionManager->GetAction(AzToolsFramework::SelectAll)->trigger(); actionManager->GetAction(ID_GOTO_SELECTED)->trigger(); GetIEditor()->GetUndoManager()->Resume(); } } m_levelErrorsHaveBeenDisplayed = false; return doc; // the API wants a CDocument* to be returned. It seems not to be used, though, in our current state. } ////////////////////////////////////////////////////////////////////////// void CCryEditApp::OnResourcesReduceworkingset() { #ifdef WIN32 // no such thing on macOS SetProcessWorkingSetSize(GetCurrentProcess(), std::numeric_limits<SIZE_T>::max(), std::numeric_limits<SIZE_T>::max()); #endif } void CCryEditApp::OnUpdateWireframe(QAction* action) { Q_ASSERT(action->isCheckable()); int nWireframe(R_SOLID_MODE); ICVar* r_wireframe(gEnv->pConsole->GetCVar("r_wireframe")); if (r_wireframe) { nWireframe = r_wireframe->GetIVal(); } action->setChecked(nWireframe == R_WIREFRAME_MODE); } ////////////////////////////////////////////////////////////////////////// void CCryEditApp::OnViewConfigureLayout() { if (GetIEditor()->IsInGameMode()) { // you may not change your viewports while game mode is running. CryLog("You may not change viewport configuration while in game mode."); return; } CLayoutWnd* layout = GetIEditor()->GetViewManager()->GetLayout(); if (layout) { CLayoutConfigDialog dlg; dlg.SetLayout(layout->GetLayout()); if (dlg.exec() == QDialog::Accepted) { // Will kill this Pane. so must be last line in this function. layout->CreateLayout(dlg.GetLayout()); } } } ////////////////////////////////////////////////////////////////////////// void CCryEditApp::TagLocation(int index) { CViewport* pRenderViewport = GetIEditor()->GetViewManager()->GetGameViewport(); if (!pRenderViewport) { return; } Vec3 vPosVec = pRenderViewport->GetViewTM().GetTranslation(); m_tagLocations[index - 1] = vPosVec; m_tagAngles[index - 1] = Ang3::GetAnglesXYZ(Matrix33(pRenderViewport->GetViewTM())); QString sTagConsoleText(""); sTagConsoleText = tr("Camera Tag Point %1 set to the position: x=%2, y=%3, z=%4 ").arg(index).arg(vPosVec.x, 0, 'f', 2).arg(vPosVec.y, 0, 'f', 2).arg(vPosVec.z, 0, 'f', 2); GetIEditor()->WriteToConsole(sTagConsoleText.toUtf8().data()); if (gSettings.bAutoSaveTagPoints) { SaveTagLocations(); } } void CCryEditApp::SaveTagLocations() { // Save to file. QString filename = QFileInfo(GetIEditor()->GetDocument()->GetLevelPathName()).dir().absoluteFilePath("tags.txt"); QFile f(filename); if (f.open(QFile::WriteOnly)) { QTextStream stream(&f); for (int i = 0; i < 12; i++) { stream << m_tagLocations[i].x << "," << m_tagLocations[i].y << "," << m_tagLocations[i].z << "," << m_tagAngles[i].x << "," << m_tagAngles[i].y << "," << m_tagAngles[i].z << Qt::endl; } } } ////////////////////////////////////////////////////////////////////////// void CCryEditApp::GotoTagLocation(int index) { QString sTagConsoleText(""); Vec3 pos = m_tagLocations[index - 1]; if (!IsVectorsEqual(m_tagLocations[index - 1], Vec3(0, 0, 0))) { // Change render viewport view TM to the stored one. CViewport* pRenderViewport = GetIEditor()->GetViewManager()->GetGameViewport(); if (pRenderViewport) { Matrix34 tm = Matrix34::CreateRotationXYZ(m_tagAngles[index - 1]); tm.SetTranslation(pos); pRenderViewport->SetViewTM(tm); Vec3 vPosVec(tm.GetTranslation()); GetISystem()->GetISystemEventDispatcher()->OnSystemEvent(ESYSTEM_BEAM_PLAYER_TO_CAMERA_POS, (UINT_PTR)&tm, 0); sTagConsoleText = tr("Moved Camera To Tag Point %1 (x=%2, y=%3, z=%4)").arg(index).arg(vPosVec.x, 0, 'f', 2).arg(vPosVec.y, 0, 'f', 2).arg(vPosVec.z, 0, 'f', 2); } } else { sTagConsoleText = tr("Camera Tag Point %1 not set").arg(index); } if (!sTagConsoleText.isEmpty()) { GetIEditor()->WriteToConsole(sTagConsoleText.toUtf8().data()); } } ////////////////////////////////////////////////////////////////////////// void CCryEditApp::LoadTagLocations() { QString filename = QFileInfo(GetIEditor()->GetDocument()->GetLevelPathName()).dir().absoluteFilePath("tags.txt"); // Load tag locations from file. ZeroStruct(m_tagLocations); QFile f(filename); if (f.open(QFile::ReadOnly)) { QTextStream stream(&f); for (int i = 0; i < 12; i++) { QStringList line = stream.readLine().split(","); float x = 0, y = 0, z = 0, ax = 0, ay = 0, az = 0; if (line.count() == 6) { x = line[0].toFloat(); y = line[1].toFloat(); z = line[2].toFloat(); ax = line[3].toFloat(); ay = line[4].toFloat(); az = line[5].toFloat(); } m_tagLocations[i] = Vec3(x, y, z); m_tagAngles[i] = Ang3(ax, ay, az); } } } ////////////////////////////////////////////////////////////////////////// void CCryEditApp::OnToolsLogMemoryUsage() { gEnv->pConsole->ExecuteString("SaveLevelStats"); } ////////////////////////////////////////////////////////////////////////// void CCryEditApp::OnTagLocation1() { TagLocation(1); } void CCryEditApp::OnTagLocation2() { TagLocation(2); } void CCryEditApp::OnTagLocation3() { TagLocation(3); } void CCryEditApp::OnTagLocation4() { TagLocation(4); } void CCryEditApp::OnTagLocation5() { TagLocation(5); } void CCryEditApp::OnTagLocation6() { TagLocation(6); } void CCryEditApp::OnTagLocation7() { TagLocation(7); } void CCryEditApp::OnTagLocation8() { TagLocation(8); } void CCryEditApp::OnTagLocation9() { TagLocation(9); } void CCryEditApp::OnTagLocation10() { TagLocation(10); } void CCryEditApp::OnTagLocation11() { TagLocation(11); } void CCryEditApp::OnTagLocation12() { TagLocation(12); } ////////////////////////////////////////////////////////////////////////// void CCryEditApp::OnGotoLocation1() { GotoTagLocation(1); } void CCryEditApp::OnGotoLocation2() { GotoTagLocation(2); } void CCryEditApp::OnGotoLocation3() { GotoTagLocation(3); } void CCryEditApp::OnGotoLocation4() { GotoTagLocation(4); } void CCryEditApp::OnGotoLocation5() { GotoTagLocation(5); } void CCryEditApp::OnGotoLocation6() { GotoTagLocation(6); } void CCryEditApp::OnGotoLocation7() { GotoTagLocation(7); } void CCryEditApp::OnGotoLocation8() { GotoTagLocation(8); } void CCryEditApp::OnGotoLocation9() { GotoTagLocation(9); } void CCryEditApp::OnGotoLocation10() { GotoTagLocation(10); } void CCryEditApp::OnGotoLocation11() { GotoTagLocation(11); } void CCryEditApp::OnGotoLocation12() { GotoTagLocation(12); } ////////////////////////////////////////////////////////////////////////// void CCryEditApp::OnCustomizeKeyboard() { MainWindow::instance()->OnCustomizeToolbar(); } ////////////////////////////////////////////////////////////////////////// void CCryEditApp::OnToolsConfiguretools() { ToolsConfigDialog dlg; if (dlg.exec() == QDialog::Accepted) { MainWindow::instance()->UpdateToolsMenu(); } } ////////////////////////////////////////////////////////////////////////// void CCryEditApp::OnToolsScriptHelp() { AzToolsFramework::CScriptHelpDialog::GetInstance()->show(); } ////////////////////////////////////////////////////////////////////////// void CCryEditApp::OnViewCycle2dviewport() { GetIEditor()->GetViewManager()->Cycle2DViewport(); } ////////////////////////////////////////////////////////////////////////// void CCryEditApp::OnDisplayGotoPosition() { GotoPositionDialog dialog; dialog.exec(); } ////////////////////////////////////////////////////////////////////////// void CCryEditApp::OnFileSavelevelresources() { CGameResourcesExporter saver; saver.GatherAllLoadedResources(); saver.ChooseDirectoryAndSave(); } ////////////////////////////////////////////////////////////////////////// void CCryEditApp::OnClearRegistryData() { if (QMessageBox::warning(AzToolsFramework::GetActiveWindow(), QString(), QObject::tr("Clear all sandbox registry data ?"), QMessageBox::Yes | QMessageBox::No) == QMessageBox::Yes) { QSettings settings; settings.clear(); } } ////////////////////////////////////////////////////////////////////////// void CCryEditApp::OnValidatelevel() { // TODO: Add your command handler code here CLevelInfo levelInfo; levelInfo.Validate(); } ////////////////////////////////////////////////////////////////////////// void CCryEditApp::OnToolsPreferences() { EditorPreferencesDialog dlg(MainWindow::instance()); dlg.exec(); } ////////////////////////////////////////////////////////////////////////// void CCryEditApp::OnSwitchToDefaultCamera() { } ////////////////////////////////////////////////////////////////////////// void CCryEditApp::OnUpdateSwitchToDefaultCamera(QAction* action) { Q_ASSERT(action->isCheckable()); { action->setEnabled(false); } } ////////////////////////////////////////////////////////////////////////// void CCryEditApp::OnSwitchToSequenceCamera() { } ////////////////////////////////////////////////////////////////////////// void CCryEditApp::OnUpdateSwitchToSequenceCamera(QAction* action) { Q_ASSERT(action->isCheckable()); { action->setEnabled(false); } } ////////////////////////////////////////////////////////////////////////// void CCryEditApp::OnSwitchToSelectedcamera() { } ////////////////////////////////////////////////////////////////////////// void CCryEditApp::OnUpdateSwitchToSelectedCamera(QAction* action) { Q_ASSERT(action->isCheckable()); { action->setEnabled(false); } } ////////////////////////////////////////////////////////////////////////// void CCryEditApp::OnSwitchcameraNext() { } ////////////////////////////////////////////////////////////////////////// void CCryEditApp::OnOpenAssetBrowserView() { QtViewPaneManager::instance()->OpenPane(LyViewPane::AssetBrowser); } ////////////////////////////////////////////////////////////////////////// void CCryEditApp::OnOpenTrackView() { QtViewPaneManager::instance()->OpenPane(LyViewPane::TrackView); } ////////////////////////////////////////////////////////////////////////// void CCryEditApp::OnOpenAudioControlsEditor() { QtViewPaneManager::instance()->OpenPane(LyViewPane::AudioControlsEditor); } ////////////////////////////////////////////////////////////////////////// void CCryEditApp::OnOpenUICanvasEditor() { QtViewPaneManager::instance()->OpenPane(LyViewPane::UiEditor); } ////////////////////////////////////////////////////////////////////////// RecentFileList* CCryEditApp::GetRecentFileList() { static RecentFileList list; return &list; }; ////////////////////////////////////////////////////////////////////////// void CCryEditApp::AddToRecentFileList(const QString& lpszPathName) { // In later MFC implementations (WINVER >= 0x0601) files must exist before they can be added to the recent files list. // Here we override the new CWinApp::AddToRecentFileList code with the old implementation to remove this requirement. if (IsInAutotestMode()) { // Never add to the recent file list when in auto test mode // This would cause issues for devs running tests locally impacting their normal workflows/setups return; } if (GetRecentFileList()) { GetRecentFileList()->Add(lpszPathName); } // write the list immediately so it will be remembered even after a crash if (GetRecentFileList()) { GetRecentFileList()->WriteList(); } else { CLogFile::WriteLine("ERROR: Recent File List is NULL!"); } } ////////////////////////////////////////////////////////////////////////// bool CCryEditApp::IsInRegularEditorMode() { return !IsInTestMode() && !IsInPreviewMode() && !IsInExportMode() && !IsInConsoleMode() && !IsInLevelLoadTestMode() && !GetIEditor()->IsInMatEditMode(); } void CCryEditApp::OnOpenQuickAccessBar() { if (m_pQuickAccessBar == nullptr) { return; } QRect geo = m_pQuickAccessBar->geometry(); geo.moveCenter(MainWindow::instance()->geometry().center()); m_pQuickAccessBar->setGeometry(geo); m_pQuickAccessBar->setVisible(true); m_pQuickAccessBar->setFocus(); } void CCryEditApp::SetEditorWindowTitle(QString sTitleStr, QString sPreTitleStr, QString sPostTitleStr) { if (MainWindow::instance() || m_pConsoleDialog) { if (sTitleStr.isEmpty()) { sTitleStr = QObject::tr("O3DE Editor [Developer Preview]"); } if (!sPreTitleStr.isEmpty()) { sTitleStr.insert(sTitleStr.length(), QStringLiteral(" - %1").arg(sPreTitleStr)); } if (!sPostTitleStr.isEmpty()) { sTitleStr.insert(sTitleStr.length(), QStringLiteral(" - %1").arg(sPostTitleStr)); } MainWindow::instance()->setWindowTitle(sTitleStr); if (m_pConsoleDialog) { m_pConsoleDialog->setWindowTitle(sTitleStr); } } } bool CCryEditApp::Command_ExportToEngine() { return CCryEditApp::instance()->UserExportToGame(true); } CMainFrame * CCryEditApp::GetMainFrame() const { return MainWindow::instance()->GetOldMainFrame(); } void CCryEditApp::StartProcessDetached(const char* process, const char* args) { // Build the arguments as a QStringList AZStd::vector<AZStd::string> tokens; // separate the string based on spaces for paths like "-launch", "lua", "-files"; // also separate the string and keep spaces inside the folder path; // Ex: C:\dev\Foundation\dev\Cache\AutomatedTesting\pc\automatedtesting\scripts\components\a a\empty.lua; // Ex: C:\dev\Foundation\dev\Cache\AutomatedTesting\pc\automatedtesting\scripts\components\a a\'empty'.lua; AZStd::string currentStr(args); AZStd::size_t firstQuotePos = AZStd::string::npos; AZStd::size_t secondQuotePos = 0; AZStd::size_t pos = 0; while (!currentStr.empty()) { firstQuotePos = currentStr.find_first_of('\"'); pos = currentStr.find_first_of(" "); if ((firstQuotePos != AZStd::string::npos) && (firstQuotePos < pos || pos == AZStd::string::npos)) { secondQuotePos = currentStr.find_first_of('\"', firstQuotePos + 1); if (secondQuotePos == AZStd::string::npos) { AZ_Warning("StartProcessDetached", false, "String tokenize failed, no matching \" found."); return; } AZStd::string newElement(AZStd::string(currentStr.data() + (firstQuotePos + 1), (secondQuotePos - 1))); tokens.push_back(newElement); currentStr = currentStr.substr(secondQuotePos + 1); firstQuotePos = AZStd::string::npos; secondQuotePos = 0; continue; } else { if (pos != AZStd::string::npos) { AZStd::string newElement(AZStd::string(currentStr.data() + 0, pos)); tokens.push_back(newElement); currentStr = currentStr.substr(pos + 1); } else { tokens.push_back(AZStd::string(currentStr)); break; } } } QStringList argsList; for (const auto& arg : tokens) { argsList.push_back(QString(arg.c_str())); } // Launch the process [[maybe_unused]] bool startDetachedReturn = QProcess::startDetached( process, argsList, QCoreApplication::applicationDirPath() ); AZ_Warning("StartProcessDetached", startDetachedReturn, "Failed to start process:%s args:%s", process, args); } void CCryEditApp::OpenLUAEditor(const char* files) { AZStd::string args = "-launch lua"; if (files && strlen(files) > 0) { AZStd::vector<AZStd::string> resolvedPaths; AZStd::vector<AZStd::string> tokens; AzFramework::StringFunc::Tokenize(files, tokens, '|'); for (const auto& file : tokens) { char resolved[AZ_MAX_PATH_LEN]; AZStd::string fullPath = Path::GamePathToFullPath(file.c_str()).toUtf8().data(); azstrncpy(resolved, AZ_MAX_PATH_LEN, fullPath.c_str(), fullPath.size()); if (AZ::IO::FileIOBase::GetInstance()->Exists(resolved)) { AZStd::string current = '\"' + AZStd::string(resolved) + '\"'; AZStd::replace(current.begin(), current.end(), '\\', '/'); resolvedPaths.push_back(current); } } if (!resolvedPaths.empty()) { for (const auto& resolvedPath : resolvedPaths) { args.append(AZStd::string::format(" -files %s", resolvedPath.c_str())); } } } const char* engineRoot = nullptr; AzFramework::ApplicationRequests::Bus::BroadcastResult(engineRoot, &AzFramework::ApplicationRequests::GetEngineRoot); AZ_Assert(engineRoot != nullptr, "Unable to communicate to AzFramework::ApplicationRequests::Bus"); AZStd::string_view exePath; AZ::ComponentApplicationBus::BroadcastResult(exePath, &AZ::ComponentApplicationRequests::GetExecutableFolder); #if defined(AZ_PLATFORM_LINUX) // On Linux platforms, launching a process is not done through a shell and its arguments are passed in // separately. There is no need to wrap the process path in case of spaces in the path constexpr const char* argumentQuoteString = ""; #else constexpr const char* argumentQuoteString = "\""; #endif AZStd::string process = AZStd::string::format("%s%.*s" AZ_CORRECT_FILESYSTEM_SEPARATOR_STRING "LuaIDE" #if defined(AZ_PLATFORM_WINDOWS) ".exe" #endif "%s", argumentQuoteString, aznumeric_cast<int>(exePath.size()), exePath.data(), argumentQuoteString); AZStd::string processArgs = AZStd::string::format("%s -engine-path \"%s\"", args.c_str(), engineRoot); StartProcessDetached(process.c_str(), processArgs.c_str()); } void CCryEditApp::PrintAlways(const AZStd::string& output) { m_stdoutRedirection.WriteBypassingRedirect(output.c_str(), static_cast<unsigned int>(output.size())); } QString CCryEditApp::GetRootEnginePath() const { return m_rootEnginePath; } void CCryEditApp::RedirectStdoutToNull() { m_stdoutRedirection.RedirectTo(AZ::IO::SystemFile::GetNullFilename()); } void CCryEditApp::OnError(AzFramework::AssetSystem::AssetSystemErrors error) { AZStd::string errorMessage = ""; switch (error) { case AzFramework::AssetSystem::ASSETSYSTEM_FAILED_TO_LAUNCH_ASSETPROCESSOR: errorMessage = AZStd::string::format("Failed to start the Asset Processor.\r\nPlease make sure that AssetProcessor is available in the same folder the Editor is in.\r\n"); break; case AzFramework::AssetSystem::ASSETSYSTEM_FAILED_TO_CONNECT_TO_ASSETPROCESSOR: errorMessage = AZStd::string::format("Failed to connect to the Asset Processor.\r\nPlease make sure that AssetProcessor is available in the same folder the Editor is in and another copy is not already running somewhere else.\r\n"); break; } CryMessageBox(errorMessage.c_str(), "Error", MB_OK | MB_ICONERROR | MB_SETFOREGROUND); } void CCryEditApp::OnOpenProceduralMaterialEditor() { QtViewPaneManager::instance()->OpenPane(LyViewPane::SubstanceEditor); } namespace Editor { //! This function returns the build system target name AZStd::string_view GetBuildTargetName() { #if !defined (LY_CMAKE_TARGET) #error "LY_CMAKE_TARGET must be defined in order to add this source file to a CMake executable target" #endif return AZStd::string_view{ LY_CMAKE_TARGET }; } } #if defined(AZ_PLATFORM_WINDOWS) //Due to some laptops not autoswitching to the discrete gpu correctly we are adding these //dllspecs as defined in the amd and nvidia white papers to 'force on' the use of the //discrete chips. This will be overriden by users setting application profiles //and may not work on older drivers or bios. In theory this should be enough to always force on //the discrete chips. //http://developer.download.nvidia.com/devzone/devcenter/gamegraphics/files/OptimusRenderingPolicies.pdf //https://community.amd.com/thread/169965 // It is unclear if this is also needed for linux or osx at this time(22/02/2017) extern "C" { __declspec(dllexport) int AmdPowerXpressRequestHighPerformance = 1; __declspec(dllexport) DWORD NvOptimusEnablement = 0x00000001; } #endif #ifdef Q_OS_WIN #pragma comment(lib, "Shell32.lib") #endif struct CryAllocatorsRAII { CryAllocatorsRAII() { AZ_Assert(!AZ::AllocatorInstance<AZ::LegacyAllocator>::IsReady(), "Expected allocator to not be initialized, hunt down the static that is initializing it"); AZ::AllocatorInstance<AZ::LegacyAllocator>::Create(); } ~CryAllocatorsRAII() { AZ::AllocatorInstance<AZ::LegacyAllocator>::Destroy(); } }; extern "C" int AZ_DLL_EXPORT CryEditMain(int argc, char* argv[]) { CryAllocatorsRAII cryAllocatorsRAII; // Debugging utilities for (int i = 1; i < argc; ++i) { if (azstricmp(argv[i], "--attach-debugger") == 0) { AZ::Debug::Trace::AttachDebugger(); } else if (azstricmp(argv[i], "--wait-for-debugger") == 0) { AZ::Debug::Trace::WaitForDebugger(); } } // ensure the EditorEventsBus context gets created inside EditorLib [[maybe_unused]] const auto& editorEventsContext = AzToolsFramework::EditorEvents::Bus::GetOrCreateContext(); // connect relevant buses to global settings gSettings.Connect(); auto theApp = AZStd::make_unique<CCryEditApp>(); // this does some magic to set the current directory... { QCoreApplication app(argc, argv); CCryEditApp::InitDirectory(); } // Must be set before QApplication is initialized, so that we support HighDpi monitors, like the Retina displays // on Windows 10 QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling); QCoreApplication::setAttribute(Qt::AA_UseHighDpiPixmaps); QGuiApplication::setHighDpiScaleFactorRoundingPolicy(Qt::HighDpiScaleFactorRoundingPolicy::PassThrough); // QtOpenGL attributes and surface format setup. QCoreApplication::setAttribute(Qt::AA_ShareOpenGLContexts, true); QSurfaceFormat format = QSurfaceFormat::defaultFormat(); format.setDepthBufferSize(24); format.setStencilBufferSize(8); format.setVersion(2, 1); format.setProfile(QSurfaceFormat::CoreProfile); format.setSamples(8); format.setSwapBehavior(QSurfaceFormat::DoubleBuffer); format.setRenderableType(QSurfaceFormat::OpenGL); format.setSwapInterval(0); #ifdef AZ_DEBUG_BUILD format.setOption(QSurfaceFormat::DebugContext); #endif QSurfaceFormat::setDefaultFormat(format); Editor::EditorQtApplication::InstallQtLogHandler(); AzQtComponents::Utilities::HandleDpiAwareness(AzQtComponents::Utilities::SystemDpiAware); Editor::EditorQtApplication app(argc, argv); if (app.arguments().contains("-autotest_mode")) { // Nullroute all stdout to null for automated tests, this way we make sure // that the test result output is not polluted with unrelated output data. theApp->RedirectStdoutToNull(); } // Hook the trace bus to catch errors, boot the AZ app after the QApplication is up int ret = 0; // open a scope to contain the AZToolsApp instance; { EditorInternal::EditorToolsApplication AZToolsApp(&argc, &argv); { CEditCommandLineInfo cmdInfo; if (!cmdInfo.m_bAutotestMode && !cmdInfo.m_bConsoleMode && !cmdInfo.m_bExport && !cmdInfo.m_bExportTexture && !cmdInfo.m_bNullRenderer && !cmdInfo.m_bMatEditMode && !cmdInfo.m_bTest) { if (auto nativeUI = AZ::Interface<AZ::NativeUI::NativeUIRequests>::Get(); nativeUI != nullptr) { nativeUI->SetMode(AZ::NativeUI::Mode::ENABLED); } } } // The settings registry has been created by the AZ::ComponentApplication constructor at this point AZ::SettingsRegistryInterface& registry = *AZ::SettingsRegistry::Get(); AZ::SettingsRegistryMergeUtils::MergeSettingsToRegistry_AddBuildSystemTargetSpecialization( registry, Editor::GetBuildTargetName()); if (!AZToolsApp.Start()) { return -1; } AzToolsFramework::EditorEvents::Bus::Broadcast(&AzToolsFramework::EditorEvents::NotifyQtApplicationAvailable, &app); #if defined(AZ_PLATFORM_MAC) // Native menu bars do not work on macOS due to all the tool dialogs QCoreApplication::setAttribute(Qt::AA_DontUseNativeMenuBar); #endif int exitCode = 0; bool didCryEditStart = CCryEditApp::instance()->InitInstance(); AZ_Error("Editor", didCryEditStart, "O3DE Editor did not initialize correctly, and will close." "\nThis could be because of incorrectly configured components, or missing required gems." "\nSee other errors for more details."); if (didCryEditStart) { app.EnableOnIdle(); ret = app.exec(); } else { exitCode = 1; } CCryEditApp::instance()->ExitInstance(exitCode); } gSettings.Disconnect(); return ret; } extern "C" AZ_DLL_EXPORT void InitializeDynamicModule(void* env) { AZ::Environment::Attach(static_cast<AZ::EnvironmentInstance>(env)); } extern "C" AZ_DLL_EXPORT void UninitializeDynamicModule() { AZ::Environment::Detach(); } #include <moc_CryEdit.cpp>
35.428064
337
0.630256
[ "mesh", "geometry", "render", "object", "vector", "model", "3d" ]
4f307affba0593c140df651c4f383cb57dea2fc8
5,353
cpp
C++
aws-cpp-sdk-panorama/source/model/ApplicationInstanceStatus.cpp
Nexuscompute/aws-sdk-cpp
e7ef485e46e6962c9e084b8c9b104c1bfcceaf26
[ "Apache-2.0" ]
1
2022-01-05T18:20:03.000Z
2022-01-05T18:20:03.000Z
aws-cpp-sdk-panorama/source/model/ApplicationInstanceStatus.cpp
Nexuscompute/aws-sdk-cpp
e7ef485e46e6962c9e084b8c9b104c1bfcceaf26
[ "Apache-2.0" ]
null
null
null
aws-cpp-sdk-panorama/source/model/ApplicationInstanceStatus.cpp
Nexuscompute/aws-sdk-cpp
e7ef485e46e6962c9e084b8c9b104c1bfcceaf26
[ "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/panorama/model/ApplicationInstanceStatus.h> #include <aws/core/utils/HashingUtils.h> #include <aws/core/Globals.h> #include <aws/core/utils/EnumParseOverflowContainer.h> using namespace Aws::Utils; namespace Aws { namespace Panorama { namespace Model { namespace ApplicationInstanceStatusMapper { static const int DEPLOYMENT_PENDING_HASH = HashingUtils::HashString("DEPLOYMENT_PENDING"); static const int DEPLOYMENT_REQUESTED_HASH = HashingUtils::HashString("DEPLOYMENT_REQUESTED"); static const int DEPLOYMENT_IN_PROGRESS_HASH = HashingUtils::HashString("DEPLOYMENT_IN_PROGRESS"); static const int DEPLOYMENT_ERROR_HASH = HashingUtils::HashString("DEPLOYMENT_ERROR"); static const int DEPLOYMENT_SUCCEEDED_HASH = HashingUtils::HashString("DEPLOYMENT_SUCCEEDED"); static const int REMOVAL_PENDING_HASH = HashingUtils::HashString("REMOVAL_PENDING"); static const int REMOVAL_REQUESTED_HASH = HashingUtils::HashString("REMOVAL_REQUESTED"); static const int REMOVAL_IN_PROGRESS_HASH = HashingUtils::HashString("REMOVAL_IN_PROGRESS"); static const int REMOVAL_FAILED_HASH = HashingUtils::HashString("REMOVAL_FAILED"); static const int REMOVAL_SUCCEEDED_HASH = HashingUtils::HashString("REMOVAL_SUCCEEDED"); static const int DEPLOYMENT_FAILED_HASH = HashingUtils::HashString("DEPLOYMENT_FAILED"); ApplicationInstanceStatus GetApplicationInstanceStatusForName(const Aws::String& name) { int hashCode = HashingUtils::HashString(name.c_str()); if (hashCode == DEPLOYMENT_PENDING_HASH) { return ApplicationInstanceStatus::DEPLOYMENT_PENDING; } else if (hashCode == DEPLOYMENT_REQUESTED_HASH) { return ApplicationInstanceStatus::DEPLOYMENT_REQUESTED; } else if (hashCode == DEPLOYMENT_IN_PROGRESS_HASH) { return ApplicationInstanceStatus::DEPLOYMENT_IN_PROGRESS; } else if (hashCode == DEPLOYMENT_ERROR_HASH) { return ApplicationInstanceStatus::DEPLOYMENT_ERROR; } else if (hashCode == DEPLOYMENT_SUCCEEDED_HASH) { return ApplicationInstanceStatus::DEPLOYMENT_SUCCEEDED; } else if (hashCode == REMOVAL_PENDING_HASH) { return ApplicationInstanceStatus::REMOVAL_PENDING; } else if (hashCode == REMOVAL_REQUESTED_HASH) { return ApplicationInstanceStatus::REMOVAL_REQUESTED; } else if (hashCode == REMOVAL_IN_PROGRESS_HASH) { return ApplicationInstanceStatus::REMOVAL_IN_PROGRESS; } else if (hashCode == REMOVAL_FAILED_HASH) { return ApplicationInstanceStatus::REMOVAL_FAILED; } else if (hashCode == REMOVAL_SUCCEEDED_HASH) { return ApplicationInstanceStatus::REMOVAL_SUCCEEDED; } else if (hashCode == DEPLOYMENT_FAILED_HASH) { return ApplicationInstanceStatus::DEPLOYMENT_FAILED; } EnumParseOverflowContainer* overflowContainer = Aws::GetEnumOverflowContainer(); if(overflowContainer) { overflowContainer->StoreOverflow(hashCode, name); return static_cast<ApplicationInstanceStatus>(hashCode); } return ApplicationInstanceStatus::NOT_SET; } Aws::String GetNameForApplicationInstanceStatus(ApplicationInstanceStatus enumValue) { switch(enumValue) { case ApplicationInstanceStatus::DEPLOYMENT_PENDING: return "DEPLOYMENT_PENDING"; case ApplicationInstanceStatus::DEPLOYMENT_REQUESTED: return "DEPLOYMENT_REQUESTED"; case ApplicationInstanceStatus::DEPLOYMENT_IN_PROGRESS: return "DEPLOYMENT_IN_PROGRESS"; case ApplicationInstanceStatus::DEPLOYMENT_ERROR: return "DEPLOYMENT_ERROR"; case ApplicationInstanceStatus::DEPLOYMENT_SUCCEEDED: return "DEPLOYMENT_SUCCEEDED"; case ApplicationInstanceStatus::REMOVAL_PENDING: return "REMOVAL_PENDING"; case ApplicationInstanceStatus::REMOVAL_REQUESTED: return "REMOVAL_REQUESTED"; case ApplicationInstanceStatus::REMOVAL_IN_PROGRESS: return "REMOVAL_IN_PROGRESS"; case ApplicationInstanceStatus::REMOVAL_FAILED: return "REMOVAL_FAILED"; case ApplicationInstanceStatus::REMOVAL_SUCCEEDED: return "REMOVAL_SUCCEEDED"; case ApplicationInstanceStatus::DEPLOYMENT_FAILED: return "DEPLOYMENT_FAILED"; default: EnumParseOverflowContainer* overflowContainer = Aws::GetEnumOverflowContainer(); if(overflowContainer) { return overflowContainer->RetrieveOverflow(static_cast<int>(enumValue)); } return {}; } } } // namespace ApplicationInstanceStatusMapper } // namespace Model } // namespace Panorama } // namespace Aws
39.947761
106
0.666355
[ "model" ]
4f34dc499359efc0a6714cec01f5d5bb2bb3d7fd
28,915
cpp
C++
modules/videoio/src/backend_plugin.cpp
r0l1/opencv
28194a4a798c189a7cc8b6101473be0b8b74fc5e
[ "Apache-2.0" ]
null
null
null
modules/videoio/src/backend_plugin.cpp
r0l1/opencv
28194a4a798c189a7cc8b6101473be0b8b74fc5e
[ "Apache-2.0" ]
null
null
null
modules/videoio/src/backend_plugin.cpp
r0l1/opencv
28194a4a798c189a7cc8b6101473be0b8b74fc5e
[ "Apache-2.0" ]
null
null
null
// This file is part of OpenCV project. // It is subject to the license terms in the LICENSE file found in the top-level directory // of this distribution and at http://opencv.org/license.html. #include "precomp.hpp" #include "backend.hpp" #include "plugin_api.hpp" #include "plugin_capture_api.hpp" #include "plugin_writer_api.hpp" #include "opencv2/core/utils/configuration.private.hpp" #include "opencv2/core/utils/logger.hpp" #include "opencv2/core/private.hpp" #include "videoio_registry.hpp" //================================================================================================== // Dynamic backend implementation #include "opencv2/core/utils/plugin_loader.private.hpp" #include "backend_plugin_legacy.impl.hpp" namespace cv { namespace impl { #if OPENCV_HAVE_FILESYSTEM_SUPPORT && defined(ENABLE_PLUGINS) using namespace cv::plugin::impl; // plugin_loader.hpp static Mutex& getInitializationMutex() { static Mutex initializationMutex; return initializationMutex; } class PluginBackend: public IBackend { protected: void initCaptureAPI() { const char* init_name = "opencv_videoio_capture_plugin_init_v1"; FN_opencv_videoio_capture_plugin_init_t fn_init = reinterpret_cast<FN_opencv_videoio_capture_plugin_init_t>(lib_->getSymbol(init_name)); if (fn_init) { CV_LOG_INFO(NULL, "Found entry: '" << init_name << "'"); for (int supported_api_version = CAPTURE_API_VERSION; supported_api_version >= 0; supported_api_version--) { capture_api_ = fn_init(CAPTURE_ABI_VERSION, supported_api_version, NULL); if (capture_api_) break; } if (!capture_api_) { CV_LOG_INFO(NULL, "Video I/O: plugin is incompatible (can't be initialized): " << lib_->getName()); return; } if (!checkCompatibility( capture_api_->api_header, CAPTURE_ABI_VERSION, CAPTURE_API_VERSION, capture_api_->v0.id != CAP_FFMPEG)) { capture_api_ = NULL; return; } CV_LOG_INFO(NULL, "Video I/O: plugin is ready to use '" << capture_api_->api_header.api_description << "'"); } else { CV_LOG_INFO(NULL, "Video I/O: missing plugin init function: '" << init_name << "', file: " << lib_->getName()); } } void initWriterAPI() { const char* init_name = "opencv_videoio_writer_plugin_init_v1"; FN_opencv_videoio_writer_plugin_init_t fn_init = reinterpret_cast<FN_opencv_videoio_writer_plugin_init_t>(lib_->getSymbol(init_name)); if (fn_init) { CV_LOG_INFO(NULL, "Found entry: '" << init_name << "'"); for (int supported_api_version = WRITER_API_VERSION; supported_api_version >= 0; supported_api_version--) { writer_api_ = fn_init(WRITER_ABI_VERSION, supported_api_version, NULL); if (writer_api_) break; } if (!writer_api_) { CV_LOG_INFO(NULL, "Video I/O: plugin is incompatible (can't be initialized): " << lib_->getName()); return; } if (!checkCompatibility( writer_api_->api_header, WRITER_ABI_VERSION, WRITER_API_VERSION, writer_api_->v0.id != CAP_FFMPEG)) { writer_api_ = NULL; return; } CV_LOG_INFO(NULL, "Video I/O: plugin is ready to use '" << writer_api_->api_header.api_description << "'"); } else { CV_LOG_INFO(NULL, "Video I/O: missing plugin init function: '" << init_name << "', file: " << lib_->getName()); } } void initPluginLegacyAPI() { const char* init_name = "opencv_videoio_plugin_init_v0"; FN_opencv_videoio_plugin_init_t fn_init = reinterpret_cast<FN_opencv_videoio_plugin_init_t>(lib_->getSymbol(init_name)); if (fn_init) { CV_LOG_INFO(NULL, "Found entry: '" << init_name << "'"); for (int supported_api_version = API_VERSION; supported_api_version >= 0; supported_api_version--) { plugin_api_ = fn_init(ABI_VERSION, supported_api_version, NULL); if (plugin_api_) break; } if (!plugin_api_) { CV_LOG_INFO(NULL, "Video I/O: plugin is incompatible (can't be initialized): " << lib_->getName()); return; } if (!checkCompatibility( plugin_api_->api_header, ABI_VERSION, API_VERSION, plugin_api_->v0.captureAPI != CAP_FFMPEG)) { plugin_api_ = NULL; return; } CV_LOG_INFO(NULL, "Video I/O: plugin is ready to use '" << plugin_api_->api_header.api_description << "'"); } else { CV_LOG_INFO(NULL, "Video I/O: plugin is incompatible, missing init function: '" << init_name << "', file: " << lib_->getName()); } } bool checkCompatibility(const OpenCV_API_Header& api_header, unsigned int abi_version, unsigned int api_version, bool checkMinorOpenCVVersion) { if (api_header.opencv_version_major != CV_VERSION_MAJOR) { CV_LOG_ERROR(NULL, "Video I/O: wrong OpenCV major version used by plugin '" << api_header.api_description << "': " << cv::format("%d.%d, OpenCV version is '" CV_VERSION "'", api_header.opencv_version_major, api_header.opencv_version_minor)) return false; } if (!checkMinorOpenCVVersion) { // no checks for OpenCV minor version } else if (api_header.opencv_version_minor != CV_VERSION_MINOR) { CV_LOG_ERROR(NULL, "Video I/O: wrong OpenCV minor version used by plugin '" << api_header.api_description << "': " << cv::format("%d.%d, OpenCV version is '" CV_VERSION "'", api_header.opencv_version_major, api_header.opencv_version_minor)) return false; } CV_LOG_INFO(NULL, "Video I/O: initialized '" << api_header.api_description << "': built with " << cv::format("OpenCV %d.%d (ABI/API = %d/%d)", api_header.opencv_version_major, api_header.opencv_version_minor, api_header.min_api_version, api_header.api_version) << ", current OpenCV version is '" CV_VERSION "' (ABI/API = " << abi_version << "/" << api_version << ")" ); if (api_header.min_api_version != abi_version) // future: range can be here { // actually this should never happen due to checks in plugin's init() function CV_LOG_ERROR(NULL, "Video I/O: plugin is not supported due to incompatible ABI = " << api_header.min_api_version); return false; } if (api_header.api_version != api_version) { CV_LOG_INFO(NULL, "Video I/O: NOTE: plugin is supported, but there is API version mismath: " << cv::format("plugin API level (%d) != OpenCV API level (%d)", api_header.api_version, api_version)); if (api_header.api_version < api_version) { CV_LOG_INFO(NULL, "Video I/O: NOTE: some functionality may be unavailable due to lack of support by plugin implementation"); } } return true; } public: Ptr<cv::plugin::impl::DynamicLib> lib_; const OpenCV_VideoIO_Capture_Plugin_API* capture_api_; const OpenCV_VideoIO_Writer_Plugin_API* writer_api_; const OpenCV_VideoIO_Plugin_API_preview* plugin_api_; //!< deprecated PluginBackend(const Ptr<cv::plugin::impl::DynamicLib>& lib) : lib_(lib) , capture_api_(NULL), writer_api_(NULL) , plugin_api_(NULL) { initCaptureAPI(); initWriterAPI(); if (capture_api_ == NULL && writer_api_ == NULL) { initPluginLegacyAPI(); } } Ptr<IVideoCapture> createCapture(int camera) const; Ptr<IVideoCapture> createCapture(int camera, const VideoCaptureParameters& params) const CV_OVERRIDE; Ptr<IVideoCapture> createCapture(const std::string &filename) const; Ptr<IVideoCapture> createCapture(const std::string &filename, const VideoCaptureParameters& params) const CV_OVERRIDE; Ptr<IVideoWriter> createWriter(const std::string& filename, int fourcc, double fps, const cv::Size& sz, const VideoWriterParameters& params) const CV_OVERRIDE; std::string getCapturePluginVersion(CV_OUT int& version_ABI, CV_OUT int& version_API) { CV_Assert(capture_api_ || plugin_api_); const OpenCV_API_Header& api_header = capture_api_ ? capture_api_->api_header : plugin_api_->api_header; version_ABI = api_header.min_api_version; version_API = api_header.api_version; return api_header.api_description; } std::string getWriterPluginVersion(CV_OUT int& version_ABI, CV_OUT int& version_API) { CV_Assert(writer_api_ || plugin_api_); const OpenCV_API_Header& api_header = writer_api_ ? writer_api_->api_header : plugin_api_->api_header; version_ABI = api_header.min_api_version; version_API = api_header.api_version; return api_header.api_description; } }; class PluginBackendFactory : public IBackendFactory { public: VideoCaptureAPIs id_; const char* baseName_; Ptr<PluginBackend> backend; bool initialized; public: PluginBackendFactory(VideoCaptureAPIs id, const char* baseName) : id_(id), baseName_(baseName), initialized(false) { // nothing, plugins are loaded on demand } Ptr<IBackend> getBackend() const CV_OVERRIDE { initBackend(); return backend.staticCast<IBackend>(); } bool isBuiltIn() const CV_OVERRIDE { return false; } std::string getCapturePluginVersion( CV_OUT int& version_ABI, CV_OUT int& version_API) const { initBackend(); if (!backend) CV_Error_(Error::StsNotImplemented, ("Backend '%s' is not available", baseName_)); return backend->getCapturePluginVersion(version_ABI, version_API); } std::string getWriterPluginVersion( CV_OUT int& version_ABI, CV_OUT int& version_API) const { initBackend(); if (!backend) CV_Error_(Error::StsNotImplemented, ("Backend '%s' is not available", baseName_)); return backend->getWriterPluginVersion(version_ABI, version_API); } protected: inline void initBackend() const { if (!initialized) { const_cast<PluginBackendFactory*>(this)->initBackend_(); } } void initBackend_() { AutoLock lock(getInitializationMutex()); try { if (!initialized) loadPlugin(); } catch (...) { CV_LOG_INFO(NULL, "Video I/O: exception during plugin loading: " << baseName_ << ". SKIP"); } initialized = true; } void loadPlugin(); }; static std::vector<FileSystemPath_t> getPluginCandidates(const std::string& baseName) { using namespace cv::utils; using namespace cv::utils::fs; const std::string baseName_l = toLowerCase(baseName); const std::string baseName_u = toUpperCase(baseName); const FileSystemPath_t baseName_l_fs = toFileSystemPath(baseName_l); std::vector<FileSystemPath_t> paths; const std::vector<std::string> paths_ = getConfigurationParameterPaths("OPENCV_VIDEOIO_PLUGIN_PATH", std::vector<std::string>()); if (paths_.size() != 0) { for (size_t i = 0; i < paths_.size(); i++) { paths.push_back(toFileSystemPath(paths_[i])); } } else { FileSystemPath_t binaryLocation; if (getBinLocation(binaryLocation)) { binaryLocation = getParent(binaryLocation); #ifndef CV_VIDEOIO_PLUGIN_SUBDIRECTORY paths.push_back(binaryLocation); #else paths.push_back(binaryLocation + toFileSystemPath("/") + toFileSystemPath(CV_VIDEOIO_PLUGIN_SUBDIRECTORY_STR)); #endif } } const std::string default_expr = libraryPrefix() + "opencv_videoio_" + baseName_l + "*" + librarySuffix(); const std::string plugin_expr = getConfigurationParameterString((std::string("OPENCV_VIDEOIO_PLUGIN_") + baseName_u).c_str(), default_expr.c_str()); std::vector<FileSystemPath_t> results; #ifdef _WIN32 FileSystemPath_t moduleName = toFileSystemPath(libraryPrefix() + "opencv_videoio_" + baseName_l + librarySuffix()); #ifndef WINRT if (baseName_u == "FFMPEG") // backward compatibility { const wchar_t* ffmpeg_env_path = _wgetenv(L"OPENCV_FFMPEG_DLL_DIR"); if (ffmpeg_env_path) { results.push_back(FileSystemPath_t(ffmpeg_env_path) + L"\\" + moduleName); } } #endif if (plugin_expr != default_expr) { moduleName = toFileSystemPath(plugin_expr); results.push_back(moduleName); } for (const FileSystemPath_t& path : paths) { results.push_back(path + L"\\" + moduleName); } results.push_back(moduleName); #if defined(_DEBUG) && defined(DEBUG_POSTFIX) if (baseName_u == "FFMPEG") // backward compatibility { const FileSystemPath_t templ = toFileSystemPath(CVAUX_STR(DEBUG_POSTFIX) ".dll"); FileSystemPath_t nonDebugName(moduleName); size_t suf = nonDebugName.rfind(templ); if (suf != FileSystemPath_t::npos) { nonDebugName.replace(suf, suf + templ.size(), L".dll"); results.push_back(nonDebugName); } } #endif // _DEBUG && DEBUG_POSTFIX #else CV_LOG_INFO(NULL, "VideoIO plugin (" << baseName << "): glob is '" << plugin_expr << "', " << paths.size() << " location(s)"); for (const std::string& path : paths) { if (path.empty()) continue; std::vector<std::string> candidates; cv::glob(utils::fs::join(path, plugin_expr), candidates); CV_LOG_INFO(NULL, " - " << path << ": " << candidates.size()); copy(candidates.begin(), candidates.end(), back_inserter(results)); } #endif CV_LOG_INFO(NULL, "Found " << results.size() << " plugin(s) for " << baseName); return results; } void PluginBackendFactory::loadPlugin() { for (const FileSystemPath_t& plugin : getPluginCandidates(baseName_)) { auto lib = makePtr<cv::plugin::impl::DynamicLib>(plugin); if (!lib->isLoaded()) continue; try { Ptr<PluginBackend> pluginBackend = makePtr<PluginBackend>(lib); if (!pluginBackend) return; if (pluginBackend->capture_api_) { if (pluginBackend->capture_api_->v0.id != id_) { CV_LOG_ERROR(NULL, "Video I/O: plugin '" << pluginBackend->capture_api_->api_header.api_description << "': unexpected backend ID: " << pluginBackend->capture_api_->v0.id << " vs " << (int)id_ << " (expected)"); return; } } if (pluginBackend->writer_api_) { if (pluginBackend->writer_api_->v0.id != id_) { CV_LOG_ERROR(NULL, "Video I/O: plugin '" << pluginBackend->writer_api_->api_header.api_description << "': unexpected backend ID: " << pluginBackend->writer_api_->v0.id << " vs " << (int)id_ << " (expected)"); return; } } if (pluginBackend->plugin_api_) { if (pluginBackend->plugin_api_->v0.captureAPI != id_) { CV_LOG_ERROR(NULL, "Video I/O: plugin '" << pluginBackend->plugin_api_->api_header.api_description << "': unexpected backend ID: " << pluginBackend->plugin_api_->v0.captureAPI << " vs " << (int)id_ << " (expected)"); return; } } if (pluginBackend->capture_api_ == NULL && pluginBackend->writer_api_ == NULL && pluginBackend->plugin_api_ == NULL) { CV_LOG_ERROR(NULL, "Video I/O: no compatible plugin API for backend ID: " << (int)id_); return; } backend = pluginBackend; return; } catch (...) { CV_LOG_WARNING(NULL, "Video I/O: exception during plugin initialization: " << toPrintablePath(plugin) << ". SKIP"); } } } //================================================================================================== class PluginCapture : public cv::IVideoCapture { const OpenCV_VideoIO_Capture_Plugin_API* plugin_api_; CvPluginCapture capture_; public: static Ptr<PluginCapture> create(const OpenCV_VideoIO_Capture_Plugin_API* plugin_api, const std::string &filename, int camera, const VideoCaptureParameters& params) { CV_Assert(plugin_api); CV_Assert(plugin_api->v0.Capture_release); CvPluginCapture capture = NULL; if (plugin_api->api_header.api_version >= 1 && plugin_api->v1.Capture_open_with_params) { std::vector<int> vint_params = params.getIntVector(); int* c_params = vint_params.data(); unsigned n_params = (unsigned)(vint_params.size() / 2); if (CV_ERROR_OK == plugin_api->v1.Capture_open_with_params( filename.empty() ? 0 : filename.c_str(), camera, c_params, n_params, &capture)) { CV_Assert(capture); return makePtr<PluginCapture>(plugin_api, capture); } } else if (plugin_api->v0.Capture_open) { if (CV_ERROR_OK == plugin_api->v0.Capture_open(filename.empty() ? 0 : filename.c_str(), camera, &capture)) { CV_Assert(capture); Ptr<PluginCapture> cap = makePtr<PluginCapture>(plugin_api, capture); if (cap && !params.empty()) { applyParametersFallback(cap, params); } return cap; } } return Ptr<PluginCapture>(); } PluginCapture(const OpenCV_VideoIO_Capture_Plugin_API* plugin_api, CvPluginCapture capture) : plugin_api_(plugin_api), capture_(capture) { CV_Assert(plugin_api_); CV_Assert(capture_); } ~PluginCapture() { CV_DbgAssert(plugin_api_->v0.Capture_release); if (CV_ERROR_OK != plugin_api_->v0.Capture_release(capture_)) CV_LOG_ERROR(NULL, "Video I/O: Can't release capture by plugin '" << plugin_api_->api_header.api_description << "'"); capture_ = NULL; } double getProperty(int prop) const CV_OVERRIDE { double val = -1; if (plugin_api_->v0.Capture_getProperty) if (CV_ERROR_OK != plugin_api_->v0.Capture_getProperty(capture_, prop, &val)) val = -1; return val; } bool setProperty(int prop, double val) CV_OVERRIDE { if (plugin_api_->v0.Capture_setProperty) if (CV_ERROR_OK == plugin_api_->v0.Capture_setProperty(capture_, prop, val)) return true; return false; } bool grabFrame() CV_OVERRIDE { if (plugin_api_->v0.Capture_grab) if (CV_ERROR_OK == plugin_api_->v0.Capture_grab(capture_)) return true; return false; } static CvResult CV_API_CALL retrieve_callback(int stream_idx, const unsigned char* data, int step, int width, int height, int type, void* userdata) { CV_UNUSED(stream_idx); cv::_OutputArray* dst = static_cast<cv::_OutputArray*>(userdata); if (!dst) return CV_ERROR_FAIL; cv::Mat(cv::Size(width, height), type, (void*)data, step).copyTo(*dst); return CV_ERROR_OK; } bool retrieveFrame(int idx, cv::OutputArray img) CV_OVERRIDE { bool res = false; if (plugin_api_->v0.Capture_retreive) if (CV_ERROR_OK == plugin_api_->v0.Capture_retreive(capture_, idx, retrieve_callback, (cv::_OutputArray*)&img)) res = true; return res; } bool isOpened() const CV_OVERRIDE { return capture_ != NULL; // TODO always true } int getCaptureDomain() CV_OVERRIDE { return plugin_api_->v0.id; } }; //================================================================================================== class PluginWriter : public cv::IVideoWriter { const OpenCV_VideoIO_Writer_Plugin_API* plugin_api_; CvPluginWriter writer_; public: static Ptr<PluginWriter> create(const OpenCV_VideoIO_Writer_Plugin_API* plugin_api, const std::string& filename, int fourcc, double fps, const cv::Size& sz, const VideoWriterParameters& params) { CV_Assert(plugin_api); CV_Assert(plugin_api->v0.Writer_release); CV_Assert(!filename.empty()); CvPluginWriter writer = NULL; if (plugin_api->api_header.api_version >= 1 && plugin_api->v1.Writer_open_with_params) { std::vector<int> vint_params = params.getIntVector(); int* c_params = &vint_params[0]; unsigned n_params = (unsigned)(vint_params.size() / 2); if (CV_ERROR_OK == plugin_api->v1.Writer_open_with_params(filename.c_str(), fourcc, fps, sz.width, sz.height, c_params, n_params, &writer)) { CV_Assert(writer); return makePtr<PluginWriter>(plugin_api, writer); } } else if (plugin_api->v0.Writer_open) { const bool isColor = params.get(VIDEOWRITER_PROP_IS_COLOR, true); const int depth = params.get(VIDEOWRITER_PROP_DEPTH, CV_8U); if (depth != CV_8U) { CV_LOG_WARNING(NULL, "Video I/O plugin doesn't support (due to lower API level) creation of VideoWriter with depth != CV_8U"); return Ptr<PluginWriter>(); } if (params.warnUnusedParameters()) { CV_LOG_ERROR(NULL, "VIDEOIO: unsupported parameters in VideoWriter, see logger INFO channel for details"); return Ptr<PluginWriter>(); } if (CV_ERROR_OK == plugin_api->v0.Writer_open(filename.c_str(), fourcc, fps, sz.width, sz.height, isColor, &writer)) { CV_Assert(writer); return makePtr<PluginWriter>(plugin_api, writer); } } return Ptr<PluginWriter>(); } PluginWriter(const OpenCV_VideoIO_Writer_Plugin_API* plugin_api, CvPluginWriter writer) : plugin_api_(plugin_api), writer_(writer) { CV_Assert(plugin_api_); CV_Assert(writer_); } ~PluginWriter() { CV_DbgAssert(plugin_api_->v0.Writer_release); if (CV_ERROR_OK != plugin_api_->v0.Writer_release(writer_)) CV_LOG_ERROR(NULL, "Video I/O: Can't release writer by plugin '" << plugin_api_->api_header.api_description << "'"); writer_ = NULL; } double getProperty(int prop) const CV_OVERRIDE { double val = -1; if (plugin_api_->v0.Writer_getProperty) if (CV_ERROR_OK != plugin_api_->v0.Writer_getProperty(writer_, prop, &val)) val = -1; return val; } bool setProperty(int prop, double val) CV_OVERRIDE { if (plugin_api_->v0.Writer_setProperty) if (CV_ERROR_OK == plugin_api_->v0.Writer_setProperty(writer_, prop, val)) return true; return false; } bool isOpened() const CV_OVERRIDE { return writer_ != NULL; // TODO always true } void write(cv::InputArray arr) CV_OVERRIDE { cv::Mat img = arr.getMat(); CV_DbgAssert(writer_); CV_Assert(plugin_api_->v0.Writer_write); if (CV_ERROR_OK != plugin_api_->v0.Writer_write(writer_, img.data, (int)img.step[0], img.cols, img.rows, img.channels())) { CV_Error_(Error::StsError, ("Video I/O: Can't write frame by plugin '%s'", plugin_api_->api_header.api_description)); } } int getCaptureDomain() const CV_OVERRIDE { return plugin_api_->v0.id; } }; Ptr<IVideoCapture> PluginBackend::createCapture(int camera, const VideoCaptureParameters& params) const { try { if (capture_api_) return PluginCapture::create(capture_api_, std::string(), camera, params); //.staticCast<IVideoCapture>(); if (plugin_api_) { Ptr<IVideoCapture> cap = legacy::PluginCapture::create(plugin_api_, std::string(), camera); //.staticCast<IVideoCapture>(); if (cap && !params.empty()) { applyParametersFallback(cap, params); } return cap; } } catch (...) { CV_LOG_DEBUG(NULL, "Video I/O: can't create camera capture: " << camera); throw; } return Ptr<IVideoCapture>(); } Ptr<IVideoCapture> PluginBackend::createCapture(const std::string &filename, const VideoCaptureParameters& params) const { try { if (capture_api_) return PluginCapture::create(capture_api_, filename, 0, params); //.staticCast<IVideoCapture>(); if (plugin_api_) { Ptr<IVideoCapture> cap = legacy::PluginCapture::create(plugin_api_, filename, 0); //.staticCast<IVideoCapture>(); if (cap && !params.empty()) { applyParametersFallback(cap, params); } return cap; } } catch (...) { CV_LOG_DEBUG(NULL, "Video I/O: can't open file capture: " << filename); throw; } return Ptr<IVideoCapture>(); } Ptr<IVideoWriter> PluginBackend::createWriter(const std::string& filename, int fourcc, double fps, const cv::Size& sz, const VideoWriterParameters& params) const { try { if (writer_api_) return PluginWriter::create(writer_api_, filename, fourcc, fps, sz, params); //.staticCast<IVideoWriter>(); if (plugin_api_) return legacy::PluginWriter::create(plugin_api_, filename, fourcc, fps, sz, params); //.staticCast<IVideoWriter>(); } catch (...) { CV_LOG_DEBUG(NULL, "Video I/O: can't open writer: " << filename); } return Ptr<IVideoWriter>(); } #endif // OPENCV_HAVE_FILESYSTEM_SUPPORT && defined(ENABLE_PLUGINS) } // namespace Ptr<IBackendFactory> createPluginBackendFactory(VideoCaptureAPIs id, const char* baseName) { #if OPENCV_HAVE_FILESYSTEM_SUPPORT && defined(ENABLE_PLUGINS) return makePtr<impl::PluginBackendFactory>(id, baseName); //.staticCast<IBackendFactory>(); #else CV_UNUSED(id); CV_UNUSED(baseName); return Ptr<IBackendFactory>(); #endif } std::string getCapturePluginVersion( const Ptr<IBackendFactory>& backend_factory, CV_OUT int& version_ABI, CV_OUT int& version_API ) { #if OPENCV_HAVE_FILESYSTEM_SUPPORT && defined(ENABLE_PLUGINS) using namespace impl; CV_Assert(backend_factory); PluginBackendFactory* plugin_backend_factory = dynamic_cast<PluginBackendFactory*>(backend_factory.get()); CV_Assert(plugin_backend_factory); return plugin_backend_factory->getCapturePluginVersion(version_ABI, version_API); #else CV_UNUSED(backend_factory); CV_UNUSED(version_ABI); CV_UNUSED(version_API); CV_Error(Error::StsBadFunc, "Plugins are not available in this build"); #endif } std::string getWriterPluginVersion( const Ptr<IBackendFactory>& backend_factory, CV_OUT int& version_ABI, CV_OUT int& version_API ) { #if OPENCV_HAVE_FILESYSTEM_SUPPORT && defined(ENABLE_PLUGINS) using namespace impl; CV_Assert(backend_factory); PluginBackendFactory* plugin_backend_factory = dynamic_cast<PluginBackendFactory*>(backend_factory.get()); CV_Assert(plugin_backend_factory); return plugin_backend_factory->getWriterPluginVersion(version_ABI, version_API); #else CV_UNUSED(backend_factory); CV_UNUSED(version_ABI); CV_UNUSED(version_API); CV_Error(Error::StsBadFunc, "Plugins are not available in this build"); #endif } } // namespace
37.1181
152
0.603251
[ "vector" ]
4f35337c0cea31fc7cfb6054ab7fab0fd959bdee
11,882
cc
C++
tensorflow/contrib/factorization/kernels/wals_solver_ops.cc
topsun888/tensorflow
bad7c50b9dc9789ad7dd0a62daca40b7269841ed
[ "Apache-2.0" ]
101
2016-12-03T11:40:52.000Z
2017-12-23T02:02:03.000Z
tensorflow/contrib/factorization/kernels/wals_solver_ops.cc
kiliczsh/tensorflow
f49aca4532c155597c669cf2189f211cafbebf96
[ "Apache-2.0" ]
9
2016-12-14T03:27:46.000Z
2017-09-13T02:29:07.000Z
tensorflow/contrib/factorization/kernels/wals_solver_ops.cc
kiliczsh/tensorflow
f49aca4532c155597c669cf2189f211cafbebf96
[ "Apache-2.0" ]
47
2016-12-04T12:37:24.000Z
2018-01-14T18:13:07.000Z
// Copyright 2016 The TensorFlow Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); you may not // use this file except in compliance with the License. You may obtain a copy // of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the // License for the specific language governing permissions and limitations under // the License. // ============================================================================== // TensorFlow kernels and Ops for constructing WALS normal equations. // TODO(agarwal,rmlarsen): Add security checks to the code. #include <algorithm> #include <numeric> #include <vector> // This is only used for std::this_thread::get_id() #include <thread> // NOLINT #include "tensorflow/core/framework/op.h" #include "tensorflow/core/framework/op_kernel.h" #include "tensorflow/core/framework/tensor.h" #include "tensorflow/core/framework/tensor_shape.h" #include "tensorflow/core/framework/types.h" #include "tensorflow/core/lib/core/blocking_counter.h" #include "tensorflow/core/lib/core/errors.h" #include "tensorflow/core/lib/core/threadpool.h" #include "tensorflow/core/platform/mutex.h" using tensorflow::DEVICE_CPU; using tensorflow::DT_BOOL; using tensorflow::DT_FLOAT; using tensorflow::DT_INT64; using tensorflow::OpKernel; using tensorflow::OpKernelConstruction; using tensorflow::OpKernelContext; using tensorflow::Tensor; using tensorflow::TensorShape; using tensorflow::TensorShapeUtils; using tensorflow::errors::InvalidArgument; namespace tensorflow { // TODO(ataei): Consider using RowMajor maps. typedef Eigen::Map< Eigen::Matrix<float, Eigen::Dynamic, Eigen::Dynamic, Eigen::ColMajor>> EigenMatrixFloatMap; typedef Eigen::Map< const Eigen::Matrix<int64, Eigen::Dynamic, Eigen::Dynamic, Eigen::ColMajor>> ConstEigenMatrixInt64Map; typedef Eigen::Map< const Eigen::Matrix<float, Eigen::Dynamic, Eigen::Dynamic, Eigen::ColMajor>> ConstEigenMatrixFloatMap; class WALSComputePartialLhsAndRhsOp : public OpKernel { public: explicit WALSComputePartialLhsAndRhsOp(OpKernelConstruction* context) : OpKernel(context) { OP_REQUIRES_OK(context, context->MatchSignature( {DT_FLOAT, DT_FLOAT, DT_FLOAT, DT_FLOAT, DT_INT64, DT_FLOAT, DT_INT64, DT_BOOL}, {DT_FLOAT, DT_FLOAT})); } void Compute(OpKernelContext* context) override { const Tensor& factors = context->input(0); const Tensor& factor_weights = context->input(1); const Tensor& unobserved_weights = context->input(2); const Tensor& input_weights = context->input(3); const Tensor& input_indices = context->input(4); const Tensor& input_values = context->input(5); const Tensor& input_block_size = context->input(6); const Tensor& input_is_transpose = context->input(7); OP_REQUIRES(context, TensorShapeUtils::IsMatrix(factors.shape()), InvalidArgument("Input factors should be a matrix.")); OP_REQUIRES(context, TensorShapeUtils::IsVector(factor_weights.shape()), InvalidArgument("Input factor_weights should be a vector.")); OP_REQUIRES( context, TensorShapeUtils::IsScalar(unobserved_weights.shape()), InvalidArgument("Input unobserved_weights should be a scalar.")); OP_REQUIRES(context, TensorShapeUtils::IsVector(input_weights.shape()), InvalidArgument("Input input_weights should be a vector.")); OP_REQUIRES(context, TensorShapeUtils::IsMatrix(input_indices.shape()), InvalidArgument("Input input_indices should be a matrix.")); OP_REQUIRES(context, TensorShapeUtils::IsVector(input_values.shape()), InvalidArgument("Input input_values should be a vector")); OP_REQUIRES(context, TensorShapeUtils::IsScalar(input_block_size.shape()), InvalidArgument("Input input_block_size should be a scalar.")); OP_REQUIRES( context, TensorShapeUtils::IsScalar(input_is_transpose.shape()), InvalidArgument("Input input_is_transpose should be a scalar.")); const int64 factor_dim = factors.dim_size(1); const int64 factors_size = factors.dim_size(0); const int64 num_nonzero_elements = input_indices.dim_size(0); const int64 block_size = input_block_size.scalar<int64>()(); const auto& factor_weights_vec = factor_weights.vec<float>(); const auto& input_weights_vec = input_weights.vec<float>(); const float w_0 = unobserved_weights.scalar<float>()(); const auto& input_values_vec = input_values.vec<float>(); ConstEigenMatrixFloatMap factors_mat(factors.matrix<float>().data(), factor_dim, factors_size); ConstEigenMatrixInt64Map indices_mat(input_indices.matrix<int64>().data(), 2, num_nonzero_elements); Tensor* output_lhs_tensor; OP_REQUIRES_OK(context, context->allocate_output( 0, TensorShape({block_size, factor_dim, factor_dim}), &output_lhs_tensor)); auto output_lhs_t = output_lhs_tensor->tensor<float, 3>(); output_lhs_t.setZero(); Tensor* output_rhs_tensor; OP_REQUIRES_OK(context, context->allocate_output( 1, TensorShape({block_size, factor_dim}), &output_rhs_tensor)); EigenMatrixFloatMap rhs_mat(output_rhs_tensor->matrix<float>().data(), factor_dim, block_size); rhs_mat.setZero(); const bool is_transpose = input_is_transpose.scalar<bool>()(); auto get_input_index = [is_transpose, &indices_mat](int64 i) { return is_transpose ? indices_mat(1, i) : indices_mat(0, i); }; auto get_factor_index = [is_transpose, &indices_mat](int64 i) { return is_transpose ? indices_mat(0, i) : indices_mat(1, i); }; // TODO(rmlarsen): In principle, we should be using the SparseTensor class // and machinery for iterating over groups, but the fact that class // SparseTensor makes a complete copy of the matrix makes me reluctant to // use it. std::vector<int64> perm(num_nonzero_elements); std::iota(perm.begin(), perm.end(), 0); typedef std::pair<int64, int64> Shard; std::vector<Shard> shards; auto worker_threads = *(context->device()->tensorflow_cpu_worker_threads()); const int num_threads = worker_threads.num_threads; int64 shard_total = 0; if (num_threads == 1) { shards.emplace_back(0, num_nonzero_elements); shard_total += num_nonzero_elements; } else { // Compute a permutation such that get_input_index(perm[i]) is sorted, use // stable_sort to preserve spatial locality. std::stable_sort(perm.begin(), perm.end(), [&get_input_index](int64 i, int64 j) { return get_input_index(i) < get_input_index(j); }); // Compute the start and end of runs with identical input_index. // These are the shards of work that can be processed in parallel // without locking. int64 start = 0; int64 end = 0; while (end < num_nonzero_elements) { start = end; while (end < num_nonzero_elements && get_input_index(perm[start]) == get_input_index(perm[end])) { ++end; } shards.emplace_back(start, end); shard_total += end - start; } } CHECK_EQ(shard_total, num_nonzero_elements); CHECK_LE(shards.size(), num_nonzero_elements); CHECK_GT(shards.size(), 0); // Batch the rank-one updates into a rank-k update to lower memory traffic const int kMaxBatchSize = 128; // Since we do not have an easy way of generating thread id's within the // range [0,num_threads), we can instead call out to an std::unordered_map // of matrices and initialize the matrix on the first call. // However, this might have a performance penalty, as memory allocation can // cause the OS kernel to enter a critical section and temporarily disable // parallelism, and the unordered_map must be protected with a read/write // mutex. // // TODO(jpoulson): Simplify after the thread rank can be queried std::unordered_map<size_t, Eigen::MatrixXf> factor_batch_map; mutex map_mutex; BlockingCounter counter(shards.size()); // Lambda encapsulating the per-shard computation. auto work = [&](const Shard& shard) { const std::thread::id thread_id = std::this_thread::get_id(); const size_t id_hash = std::hash<std::thread::id>()(thread_id); // If this thread's unique factors_mat.rows() x kMaxBatchSize // batching matrix has not yet been created, then emplace it into the // map using the hash of the thread id as the key. // // TODO(jpoulson): Switch to try_emplace once C++17 is supported map_mutex.lock(); const auto key_count = factor_batch_map.count(id_hash); map_mutex.unlock(); if (!key_count) { map_mutex.lock(); factor_batch_map.emplace( std::piecewise_construct, std::forward_as_tuple(id_hash), std::forward_as_tuple(factors_mat.rows(), kMaxBatchSize)); map_mutex.unlock(); } map_mutex.lock(); auto& factor_batch = factor_batch_map[id_hash]; map_mutex.unlock(); CHECK_GE(shard.first, 0); CHECK_LE(shard.second, perm.size()); CHECK_LE(shard.first, shard.second); const int64 input_index = get_input_index(perm[shard.first]); // Acccumulate the rhs and lhs terms in the normal equations // for the non-zero elements in the row or column of the sparse matrix // corresponding to input_index. int num_batched = 0; EigenMatrixFloatMap lhs_mat(output_lhs_tensor->flat<float>().data() + input_index * factor_dim * factor_dim, factor_dim, factor_dim); auto lhs_symm = lhs_mat.selfadjointView<Eigen::Lower>(); for (int64 p = shard.first; p < shard.second; ++p) { const int64 i = perm[p]; // Check that all entries in the shard have the same input index. CHECK_EQ(input_index, get_input_index(i)); const int64 factor_index = get_factor_index(i); const float input_value = input_values_vec(i); const float weight = input_weights_vec(input_index) * factor_weights_vec(factor_index); CHECK_GE(weight, 0); factor_batch.col(num_batched) = factors_mat.col(factor_index) * std::sqrt(weight); ++num_batched; if (num_batched == kMaxBatchSize) { lhs_symm.rankUpdate(factor_batch); num_batched = 0; } rhs_mat.col(input_index) += input_value * (w_0 + weight) * factors_mat.col(factor_index); } if (num_batched != 0) { auto factor_block = factor_batch.block(0, 0, factors_mat.rows(), num_batched); lhs_symm.rankUpdate(factor_block); } // Copy lower triangular to upper triangular part of normal equation // matrix. lhs_mat = lhs_symm; counter.DecrementCount(); }; for (int i = 1; i < shards.size(); ++i) { worker_threads.workers->Schedule(std::bind(work, shards[i])); } // Inline execute the 1st shard. work(shards[0]); counter.Wait(); } }; REGISTER_KERNEL_BUILDER(Name("WALSComputePartialLhsAndRhs").Device(DEVICE_CPU), WALSComputePartialLhsAndRhsOp); } // namespace tensorflow
43.52381
81
0.665713
[ "shape", "vector" ]
4f38b284de95f5303c1ac6c2599ba03fb12d7f3e
10,563
cpp
C++
src/test/checkdatasig_tests.cpp
kittywhiskers/dash
f329625b67eb1943a2f0b68a12b3bd25052e41ab
[ "MIT" ]
null
null
null
src/test/checkdatasig_tests.cpp
kittywhiskers/dash
f329625b67eb1943a2f0b68a12b3bd25052e41ab
[ "MIT" ]
null
null
null
src/test/checkdatasig_tests.cpp
kittywhiskers/dash
f329625b67eb1943a2f0b68a12b3bd25052e41ab
[ "MIT" ]
null
null
null
// Copyright (c) 2018-2020 The Bitcoin developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <policy/policy.h> #include <script/interpreter.h> #include <test/lcg.h> #include <test/setup_common.h> #include <boost/test/unit_test.hpp> #include <array> typedef std::vector<uint8_t> valtype; typedef std::vector<valtype> stacktype; BOOST_FIXTURE_TEST_SUITE(checkdatasig_tests, BasicTestingSetup) std::array<uint32_t, 2> flagset{{0, STANDARD_SCRIPT_VERIFY_FLAGS}}; const uint8_t vchPrivkey[32] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1}; struct KeyData { CKey privkey, privkeyC; CPubKey pubkey, pubkeyC, pubkeyH; KeyData() { privkey.Set(vchPrivkey, vchPrivkey + 32, false); privkeyC.Set(vchPrivkey, vchPrivkey + 32, true); pubkey = privkey.GetPubKey(); pubkeyH = privkey.GetPubKey(); pubkeyC = privkeyC.GetPubKey(); *const_cast<uint8_t *>(&pubkeyH[0]) = 0x06 | (pubkeyH[64] & 1); } }; static void CheckError(uint32_t flags, const stacktype& original_stack, const CScript& script, ScriptError expected) { BaseSignatureChecker sigchecker; ScriptError err = ScriptError::SCRIPT_ERR_OK; stacktype stack{original_stack}; bool r = EvalScript(stack, script, flags | SCRIPT_ENABLE_DIP0020_OPCODES, sigchecker, SigVersion::BASE, &err); BOOST_CHECK(!r); BOOST_CHECK(err == expected); } static void CheckPass(uint32_t flags, const stacktype& original_stack, const CScript& script, const stacktype& expected) { BaseSignatureChecker sigchecker; ScriptError err = ScriptError::SCRIPT_ERR_OK; stacktype stack{original_stack}; bool r = EvalScript(stack, script, flags | SCRIPT_ENABLE_DIP0020_OPCODES, sigchecker, SigVersion::BASE, &err); BOOST_CHECK(r); BOOST_CHECK(err == ScriptError::SCRIPT_ERR_OK); BOOST_CHECK(stack == expected); } /** * General utility functions to check for script passing/failing. */ static void CheckTestResultForAllFlags(const stacktype& original_stack, const CScript& script, const stacktype& expected) { for (uint32_t flags : flagset) { CheckPass(flags, original_stack, script, expected); } } static void CheckErrorForAllFlags(const stacktype& original_stack, const CScript& script, ScriptError expected) { for (uint32_t flags : flagset) { CheckError(flags, original_stack, script, expected); } } BOOST_AUTO_TEST_CASE(checkdatasig_test) { // Empty stack. CheckErrorForAllFlags({}, CScript() << OP_CHECKDATASIG, ScriptError::SCRIPT_ERR_INVALID_STACK_OPERATION); CheckErrorForAllFlags({{0x00}}, CScript() << OP_CHECKDATASIG, ScriptError::SCRIPT_ERR_INVALID_STACK_OPERATION); CheckErrorForAllFlags({{0x00}, {0x00}}, CScript() << OP_CHECKDATASIG, ScriptError::SCRIPT_ERR_INVALID_STACK_OPERATION); CheckErrorForAllFlags({}, CScript() << OP_CHECKDATASIGVERIFY, ScriptError::SCRIPT_ERR_INVALID_STACK_OPERATION); CheckErrorForAllFlags({{0x00}}, CScript() << OP_CHECKDATASIGVERIFY, ScriptError::SCRIPT_ERR_INVALID_STACK_OPERATION); CheckErrorForAllFlags({{0x00}, {0x00}}, CScript() << OP_CHECKDATASIGVERIFY, ScriptError::SCRIPT_ERR_INVALID_STACK_OPERATION); // Check various pubkey encoding. const valtype message{}; valtype vchHash(32); CSHA256().Write(message.data(), message.size()).Finalize(vchHash.data()); uint256 messageHash(vchHash); KeyData kd; valtype pubkey = ToByteVector(kd.pubkey); valtype pubkeyC = ToByteVector(kd.pubkeyC); valtype pubkeyH = ToByteVector(kd.pubkeyH); CheckTestResultForAllFlags({{}, message, pubkey}, CScript() << OP_CHECKDATASIG, {{}}); CheckTestResultForAllFlags({{}, message, pubkeyC}, CScript() << OP_CHECKDATASIG, {{}}); CheckErrorForAllFlags({{}, message, pubkey}, CScript() << OP_CHECKDATASIGVERIFY, ScriptError::SCRIPT_ERR_CHECKDATASIGVERIFY); CheckErrorForAllFlags({{}, message, pubkeyC}, CScript() << OP_CHECKDATASIGVERIFY, ScriptError::SCRIPT_ERR_CHECKDATASIGVERIFY); // Flags dependent checks. const CScript script = CScript() << OP_CHECKDATASIG << OP_NOT << OP_VERIFY; const CScript scriptverify = CScript() << OP_CHECKDATASIGVERIFY; // Check valid signatures (as in the signature format is valid). valtype validsig; kd.privkey.Sign(messageHash, validsig); validsig.push_back(static_cast<unsigned char>(1)); CheckTestResultForAllFlags({validsig, message, pubkey}, CScript() << OP_CHECKDATASIG, {{0x01}}); CheckTestResultForAllFlags({validsig, message, pubkey}, CScript() << OP_CHECKDATASIGVERIFY, {}); const valtype minimalsig{0x30, 0x06, 0x02, 0x01, 0x01, 0x02, 0x01, 0x01, 0x01}; const valtype nondersig{0x30, 0x80, 0x06, 0x02, 0x01, 0x01, 0x02, 0x01, 0x01, 0x01}; const valtype highSSig{ 0x30, 0x45, 0x02, 0x20, 0x3e, 0x45, 0x16, 0xda, 0x72, 0x53, 0xcf, 0x06, 0x8e, 0xff, 0xec, 0x6b, 0x95, 0xc4, 0x12, 0x21, 0xc0, 0xcf, 0x3a, 0x8e, 0x6c, 0xcb, 0x8c, 0xbf, 0x17, 0x25, 0xb5, 0x62, 0xe9, 0xaf, 0xde, 0x2c, 0x02, 0x21, 0x00, 0xab, 0x1e, 0x3d, 0xa7, 0x3d, 0x67, 0xe3, 0x20, 0x45, 0xa2, 0x0e, 0x0b, 0x99, 0x9e, 0x04, 0x99, 0x78, 0xea, 0x8d, 0x6e, 0xe5, 0x48, 0x0d, 0x48, 0x5f, 0xcf, 0x2c, 0xe0, 0xd0, 0x3b, 0x2e, 0xf0, 0x01}; MMIXLinearCongruentialGenerator lcg; for (int i = 0; i < 4096; i++) { uint32_t flags = lcg.next(); if (flags & SCRIPT_VERIFY_STRICTENC) { // When strict encoding is enforced, hybrid keys are invalid. CheckError(flags, {{}, message, pubkeyH}, script, ScriptError::SCRIPT_ERR_PUBKEYTYPE); CheckError(flags, {{}, message, pubkeyH}, scriptverify, ScriptError::SCRIPT_ERR_PUBKEYTYPE); } else { // Otherwise, hybrid keys are valid. CheckPass(flags, {{}, message, pubkeyH}, script, {}); CheckError(flags, {{}, message, pubkeyH}, scriptverify, ScriptError::SCRIPT_ERR_CHECKDATASIGVERIFY); } // Uncompressed keys are valid. CheckPass(flags, {{}, message, pubkey}, script, {}); CheckError(flags, {{}, message, pubkey}, scriptverify, ScriptError::SCRIPT_ERR_CHECKDATASIGVERIFY); if (flags & SCRIPT_VERIFY_NULLFAIL) { // Invalid signature causes checkdatasig to fail. CheckError(flags, {minimalsig, message, pubkeyC}, script, ScriptError::SCRIPT_ERR_SIG_NULLFAIL); CheckError(flags, {minimalsig, message, pubkeyC}, scriptverify, ScriptError::SCRIPT_ERR_SIG_NULLFAIL); // Invalid message causes checkdatasig to fail. CheckError(flags, {validsig, {0x01}, pubkeyC}, script, ScriptError::SCRIPT_ERR_SIG_NULLFAIL); CheckError(flags, {validsig, {0x01}, pubkeyC}, scriptverify, ScriptError::SCRIPT_ERR_SIG_NULLFAIL); } else { // When nullfail is not enforced, invalid signature are just false. CheckPass(flags, {minimalsig, message, pubkeyC}, script, {}); CheckError(flags, {minimalsig, message, pubkeyC}, scriptverify, ScriptError::SCRIPT_ERR_CHECKDATASIGVERIFY); // Invalid message cause checkdatasig to fail. CheckPass(flags, {validsig, {0x01}, pubkeyC}, script, {}); CheckError(flags, {validsig, {0x01}, pubkeyC}, scriptverify, ScriptError::SCRIPT_ERR_CHECKDATASIGVERIFY); } if (flags & SCRIPT_VERIFY_LOW_S) { // If we do enforce low S, then high S sigs are rejected. CheckError(flags, {highSSig, message, pubkeyC}, script, ScriptError::SCRIPT_ERR_SIG_HIGH_S); CheckError(flags, {highSSig, message, pubkeyC}, scriptverify, ScriptError::SCRIPT_ERR_SIG_HIGH_S); } else if (flags & SCRIPT_VERIFY_NULLFAIL) { // If we do enforce nullfail, these invalid sigs hit this. CheckError(flags, {highSSig, message, pubkeyC}, script, ScriptError::SCRIPT_ERR_SIG_NULLFAIL); CheckError(flags, {highSSig, message, pubkeyC}, scriptverify, ScriptError::SCRIPT_ERR_SIG_NULLFAIL); } else { // If we do not enforce low S, then high S sigs are accepted. CheckPass(flags, {highSSig, message, pubkeyC}, script, {}); CheckError(flags, {highSSig, message, pubkeyC}, scriptverify, ScriptError::SCRIPT_ERR_CHECKDATASIGVERIFY); } if (flags & (SCRIPT_VERIFY_DERSIG | SCRIPT_VERIFY_LOW_S | SCRIPT_VERIFY_STRICTENC)) { // If we get any of the dersig flags, the non canonical dersig // signature fails. CheckError(flags, {nondersig, message, pubkeyC}, script, ScriptError::SCRIPT_ERR_SIG_DER); CheckError(flags, {nondersig, message, pubkeyC}, scriptverify, ScriptError::SCRIPT_ERR_SIG_DER); } else if (flags & SCRIPT_VERIFY_NULLFAIL) { // If we do enforce nullfail, these invalid sigs hit this. CheckError(flags, {nondersig, message, pubkeyC}, script, ScriptError::SCRIPT_ERR_SIG_NULLFAIL); CheckError(flags, {nondersig, message, pubkeyC}, scriptverify, ScriptError::SCRIPT_ERR_SIG_NULLFAIL); } else { // If we do not check, then it is accepted. CheckPass(flags, {nondersig, message, pubkeyC}, script, {}); CheckError(flags, {nondersig, message, pubkeyC}, scriptverify, ScriptError::SCRIPT_ERR_CHECKDATASIGVERIFY); } } } BOOST_AUTO_TEST_SUITE_END()
45.141026
114
0.619142
[ "vector" ]
4f391e2918807d56a520dd38b68cfd9fef901532
1,786
cpp
C++
aws-cpp-sdk-waf-regional/source/model/TagInfoForResource.cpp
Neusoft-Technology-Solutions/aws-sdk-cpp
88c041828b0dbee18a297c3cfe98c5ecd0706d0b
[ "Apache-2.0" ]
1
2022-02-10T08:06:54.000Z
2022-02-10T08:06:54.000Z
aws-cpp-sdk-waf-regional/source/model/TagInfoForResource.cpp
Neusoft-Technology-Solutions/aws-sdk-cpp
88c041828b0dbee18a297c3cfe98c5ecd0706d0b
[ "Apache-2.0" ]
1
2022-01-03T23:59:37.000Z
2022-01-03T23:59:37.000Z
aws-cpp-sdk-waf-regional/source/model/TagInfoForResource.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/waf-regional/model/TagInfoForResource.h> #include <aws/core/utils/json/JsonSerializer.h> #include <utility> using namespace Aws::Utils::Json; using namespace Aws::Utils; namespace Aws { namespace WAFRegional { namespace Model { TagInfoForResource::TagInfoForResource() : m_resourceARNHasBeenSet(false), m_tagListHasBeenSet(false) { } TagInfoForResource::TagInfoForResource(JsonView jsonValue) : m_resourceARNHasBeenSet(false), m_tagListHasBeenSet(false) { *this = jsonValue; } TagInfoForResource& TagInfoForResource::operator =(JsonView jsonValue) { if(jsonValue.ValueExists("ResourceARN")) { m_resourceARN = jsonValue.GetString("ResourceARN"); m_resourceARNHasBeenSet = true; } if(jsonValue.ValueExists("TagList")) { Array<JsonView> tagListJsonList = jsonValue.GetArray("TagList"); for(unsigned tagListIndex = 0; tagListIndex < tagListJsonList.GetLength(); ++tagListIndex) { m_tagList.push_back(tagListJsonList[tagListIndex].AsObject()); } m_tagListHasBeenSet = true; } return *this; } JsonValue TagInfoForResource::Jsonize() const { JsonValue payload; if(m_resourceARNHasBeenSet) { payload.WithString("ResourceARN", m_resourceARN); } if(m_tagListHasBeenSet) { Array<JsonValue> tagListJsonList(m_tagList.size()); for(unsigned tagListIndex = 0; tagListIndex < tagListJsonList.GetLength(); ++tagListIndex) { tagListJsonList[tagListIndex].AsObject(m_tagList[tagListIndex].Jsonize()); } payload.WithArray("TagList", std::move(tagListJsonList)); } return payload; } } // namespace Model } // namespace WAFRegional } // namespace Aws
21.518072
94
0.730123
[ "model" ]
4f3a331fff8f8a82e27a81b643503f504268a854
1,391
cpp
C++
libs/geometry/doc/src/examples/geometries/register/multi_linestring.cpp
jmuskaan72/Boost
047e36c01841a8cd6a5c74d4e3034da46e327bc1
[ "BSL-1.0" ]
198
2015-01-13T05:47:18.000Z
2022-03-09T04:46:46.000Z
libs/geometry/doc/src/examples/geometries/register/multi_linestring.cpp
xiaoliang2121/Boost
fc90c3fde129c62565c023f091eddc4a7ed9902b
[ "BSL-1.0" ]
4
2015-03-19T08:23:23.000Z
2019-06-24T07:48:47.000Z
libs/geometry/doc/src/examples/geometries/register/multi_linestring.cpp
xiaoliang2121/Boost
fc90c3fde129c62565c023f091eddc4a7ed9902b
[ "BSL-1.0" ]
139
2015-01-15T20:09:31.000Z
2022-01-31T15:21:16.000Z
// Boost.Geometry (aka GGL, Generic Geometry Library) // QuickBook Example // Copyright (c) 2011-2012 Barend Gehrels, Amsterdam, the Netherlands. // Use, modification and distribution is subject to 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) //[register_multi_linestring //` Show the use of the macro BOOST_GEOMETRY_REGISTER_MULTI_LINESTRING #include <iostream> #include <boost/geometry.hpp> #include <boost/geometry/geometries/linestring.hpp> #include <boost/geometry/geometries/adapted/boost_tuple.hpp> #include <boost/geometry/multi/geometries/register/multi_linestring.hpp> typedef boost::geometry::model::linestring < boost::tuple<float, float> > linestring_type; BOOST_GEOMETRY_REGISTER_BOOST_TUPLE_CS(cs::cartesian) BOOST_GEOMETRY_REGISTER_MULTI_LINESTRING(std::deque<linestring_type>) int main() { // Normal usage of std:: std::deque<linestring_type> lines(2); boost::geometry::read_wkt("LINESTRING(0 0,1 1)", lines[0]); boost::geometry::read_wkt("LINESTRING(2 2,3 3)", lines[1]); // Usage of Boost.Geometry std::cout << "LENGTH: " << boost::geometry::length(lines) << std::endl; return 0; } //] //[register_multi_linestring_output /*` Output: [pre LENGTH: 2.82843 ] */ //]
26.75
80
0.699497
[ "geometry", "model" ]
4f3cb654b1a1a0918ed6e04d172a2610e27d6203
2,917
cpp
C++
2. Рекуррентные соотношения/47.1. Делимость и сумма #1386/[OK]226002.cpp
godnoTA/acm.bsu.by
3e1cf1c545c691de82b5e1d2e0768b41ea581734
[ "Unlicense" ]
19
2018-05-19T16:37:14.000Z
2022-03-23T20:13:43.000Z
2. Рекуррентные соотношения/47.1. Делимость и сумма #1386/[OK]226002.cpp
godnoTA/acm.bsu.by
3e1cf1c545c691de82b5e1d2e0768b41ea581734
[ "Unlicense" ]
6
2020-05-07T21:06:48.000Z
2020-06-05T17:52:57.000Z
2. Рекуррентные соотношения/47.1. Делимость и сумма #1386/[OK]226002.cpp
godnoTA/acm.bsu.by
3e1cf1c545c691de82b5e1d2e0768b41ea581734
[ "Unlicense" ]
31
2019-03-01T21:41:38.000Z
2022-03-27T17:56:39.000Z
#include <iostream> #include <fstream> #include <algorithm> #include <set> #include <vector> #include <iterator> #include <utility> #include <map> #include "math.h" #include <string> #include <iterator> using namespace std; unsigned long long plusik(unsigned long long a, unsigned long long b) { return a + b; } int sum_c(unsigned long long a) { int k = 0; while (a > 0) { k += a % 10; a /= 10; } return k; } void main() { ifstream in; in.open("input.txt"); int k, p, q; unsigned long long a, b; char *aa = new char[40]; char *bb = new char[40]; in >> k; in >> a >> b; in >> p >> q; int a_length = log10(a)+1; int b_length = log10(b)+1; in.close(); cout << sum_c(b) << endl; unsigned long long ans1 = 0; unsigned long long ans2 = 0; unsigned long long c = 0; unsigned long long*** kol = new unsigned long long**[20]; for (int i = 0; i < 20; i++) { kol[i] = new unsigned long long*[180]; for (int j = 0; j < 180; j++) { kol[i][j] = new unsigned long long[k]; } } for (int i = 0; i < 20; i++) { for (int j = 0; j < 180; j++) { for (int x = 0; x < k; x++) { kol[i][j][x] = 0; } } } kol[0][0][0] = 1; for (int i = 0; i <= 18; i++) { for (int j = 0; j <= i * 9; j++) { for (int x = 0; x < k; x++) { for (int last_digit = 0; last_digit < 10; last_digit++) { kol[i+1][j + last_digit][(x * 10 + last_digit) % k] +=kol[i][j][x]; } } } } c = pow(10, a_length-1); if (c > a) { c / 10; a_length--; } for (int j = p; j <= q; j++) { ans1 += kol[a_length - 1][j][0]; } int sum = 1; int r = a_length-1; while (c != a) { if (plusik(c, pow(10, r)) <= a) { int e = c%k; for (int j = 0; j <= 9*r; j++) { for (int x = 0; x < k; x++) { if (kol[r][j][x] > 0) { if (sum + j >= p&&sum + j <= q && (x + e) % k == 0) { ans1 =plusik( ans1, kol[r][j][x]); } } } } c = plusik(c, pow(10, r)); sum++; } else { r--; } } c = pow(10, b_length-1); while(c > b) { b_length--; c = pow(10, b_length - 1); } for (int j = p; j <= q; j++) { ans2 += kol[b_length - 1][j][0]; } sum = 1; r = b_length-1; while (c != b) { if (plusik(c, pow(10, r)) <= b) { int e = c%k; for (int j = 0; j <= 9 * r; j++) { for (int x = 0; x < k; x++) { if (kol[r][j][x] > 0) { if (sum + j >= p&&sum + j <= q && (x + e) % k == 0) { ans2 = plusik(ans2, kol[r][j][x]); } } } } c = plusik(c, pow(10, r)); sum++; } else { r--; } } ofstream out; cout << ans1 << " " << ans2 << endl; out.open("output.txt"); if (b%k == 0 && p <= sum_c(b) && q >= sum_c(b)) { ans2++; } if (a == b&&a%k == 0 && p <= sum_c(a) && q >= sum_c(a)) { out << 1; } else out << ans2 - ans1; cout << ans2 - ans1; system("pause"); }
21.448529
73
0.446692
[ "vector" ]
4f3effbbc6fdb4e2528f608efda223ec63cd3db9
2,095
cpp
C++
aws-cpp-sdk-acm-pca/source/model/CertificateAuthorityType.cpp
Neusoft-Technology-Solutions/aws-sdk-cpp
88c041828b0dbee18a297c3cfe98c5ecd0706d0b
[ "Apache-2.0" ]
1
2022-02-10T08:06:54.000Z
2022-02-10T08:06:54.000Z
aws-cpp-sdk-acm-pca/source/model/CertificateAuthorityType.cpp
Neusoft-Technology-Solutions/aws-sdk-cpp
88c041828b0dbee18a297c3cfe98c5ecd0706d0b
[ "Apache-2.0" ]
1
2022-01-03T23:59:37.000Z
2022-01-03T23:59:37.000Z
aws-cpp-sdk-acm-pca/source/model/CertificateAuthorityType.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/acm-pca/model/CertificateAuthorityType.h> #include <aws/core/utils/HashingUtils.h> #include <aws/core/Globals.h> #include <aws/core/utils/EnumParseOverflowContainer.h> using namespace Aws::Utils; namespace Aws { namespace ACMPCA { namespace Model { namespace CertificateAuthorityTypeMapper { static const int ROOT_HASH = HashingUtils::HashString("ROOT"); static const int SUBORDINATE_HASH = HashingUtils::HashString("SUBORDINATE"); CertificateAuthorityType GetCertificateAuthorityTypeForName(const Aws::String& name) { int hashCode = HashingUtils::HashString(name.c_str()); if (hashCode == ROOT_HASH) { return CertificateAuthorityType::ROOT; } else if (hashCode == SUBORDINATE_HASH) { return CertificateAuthorityType::SUBORDINATE; } EnumParseOverflowContainer* overflowContainer = Aws::GetEnumOverflowContainer(); if(overflowContainer) { overflowContainer->StoreOverflow(hashCode, name); return static_cast<CertificateAuthorityType>(hashCode); } return CertificateAuthorityType::NOT_SET; } Aws::String GetNameForCertificateAuthorityType(CertificateAuthorityType enumValue) { switch(enumValue) { case CertificateAuthorityType::ROOT: return "ROOT"; case CertificateAuthorityType::SUBORDINATE: return "SUBORDINATE"; default: EnumParseOverflowContainer* overflowContainer = Aws::GetEnumOverflowContainer(); if(overflowContainer) { return overflowContainer->RetrieveOverflow(static_cast<int>(enumValue)); } return {}; } } } // namespace CertificateAuthorityTypeMapper } // namespace Model } // namespace ACMPCA } // namespace Aws
29.507042
92
0.636754
[ "model" ]
4f3fffaa992665f9628620828126536e0955491d
3,146
hpp
C++
src/Elliptic/BoundaryConditions/ApplyBoundaryCondition.hpp
trami18/spectre
6b1f6497bf2e26d1474bfadf143b3321942c40b4
[ "MIT" ]
2
2021-04-11T04:07:42.000Z
2021-04-11T05:07:54.000Z
src/Elliptic/BoundaryConditions/ApplyBoundaryCondition.hpp
trami18/spectre
6b1f6497bf2e26d1474bfadf143b3321942c40b4
[ "MIT" ]
1
2022-03-25T18:26:16.000Z
2022-03-25T19:30:39.000Z
src/Elliptic/BoundaryConditions/ApplyBoundaryCondition.hpp
isaaclegred/spectre
5765da85dad680cad992daccd479376c67458a8c
[ "MIT" ]
null
null
null
// Distributed under the MIT License. // See LICENSE.txt for details. #pragma once #include <cstddef> #include <type_traits> #include "DataStructures/DataBox/DataBox.hpp" #include "Domain/InterfaceHelpers.hpp" #include "Domain/Structure/Direction.hpp" #include "Domain/Tags.hpp" #include "Elliptic/BoundaryConditions/BoundaryCondition.hpp" #include "Elliptic/Utilities/ApplyAt.hpp" #include "Utilities/FakeVirtual.hpp" #include "Utilities/Gsl.hpp" #include "Utilities/TMPL.hpp" namespace elliptic { /*! * \brief Apply the `boundary_condition` to the `fields_and_fluxes` with * arguments from interface tags in the DataBox. * * This functions assumes the arguments for the `boundary_condition` are stored * in the DataBox in tags * `domain::Tags::Interface<domain::Tags::BoundaryDirectionsInterior<Dim>, * Tag>`. This may turn out not to be the most efficient setup, so code that * uses the boundary conditions doesn't have to use this function but can * procure the arguments differently. For example, future optimizations may * involve storing a subset of arguments that don't change during an elliptic * solve in direction-maps in the DataBox, and slicing other arguments to the * interface every time the boundary conditions are applied. */ template <bool Linearized, size_t Dim, typename Registrars, typename DbTagsList, typename... FieldsAndFluxes> void apply_boundary_condition( const elliptic::BoundaryConditions::BoundaryCondition<Dim, Registrars>& boundary_condition, const db::DataBox<DbTagsList>& box, const Direction<Dim>& direction, const gsl::not_null<FieldsAndFluxes*>... fields_and_fluxes) noexcept { call_with_dynamic_type< void, typename elliptic::BoundaryConditions::BoundaryCondition< Dim, Registrars>::creatable_classes>( &boundary_condition, [&direction, &box, &fields_and_fluxes...]( const auto* const derived) noexcept { using Derived = std::decay_t<std::remove_pointer_t<decltype(derived)>>; using argument_tags = tmpl::conditional_t<Linearized, typename Derived::argument_tags_linearized, typename Derived::argument_tags>; using volume_tags = tmpl::conditional_t<Linearized, typename Derived::volume_tags_linearized, typename Derived::volume_tags>; elliptic::util::apply_at< tmpl::transform< argument_tags, make_interface_tag< tmpl::_1, tmpl::pin<domain::Tags::BoundaryDirectionsInterior<Dim>>, tmpl::pin<volume_tags>>>, volume_tags>( [&derived, &fields_and_fluxes...](const auto&... args) noexcept { if constexpr (Linearized) { derived->apply_linearized(fields_and_fluxes..., args...); } else { derived->apply(fields_and_fluxes..., args...); } }, box, direction); }); } } // namespace elliptic
42.513514
80
0.656071
[ "transform" ]
4f46e29221029585e67c6962cdcbf2dc2e2c02d5
17,030
cc
C++
tensorflow/compiler/xla/service/gpu/nvptx_compiler.cc
chuanqi129/tensorflow
84eb083bb5328912dde064b8b0f61d28c6edbe43
[ "Apache-2.0" ]
57
2017-09-03T07:08:31.000Z
2022-02-28T04:33:42.000Z
tensorflow/compiler/xla/service/gpu/nvptx_compiler.cc
chuanqi129/tensorflow
84eb083bb5328912dde064b8b0f61d28c6edbe43
[ "Apache-2.0" ]
8
2019-03-13T23:13:47.000Z
2020-01-31T21:08:21.000Z
tensorflow/compiler/xla/service/gpu/nvptx_compiler.cc
chuanqi129/tensorflow
84eb083bb5328912dde064b8b0f61d28c6edbe43
[ "Apache-2.0" ]
28
2017-03-25T13:48:09.000Z
2021-10-14T00:10:50.000Z
/* Copyright 2017 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include "tensorflow/compiler/xla/service/gpu/nvptx_compiler.h" #include <stdlib.h> #include <fstream> #include "absl/base/call_once.h" #include "tensorflow/compiler/xla/service/algebraic_simplifier.h" #include "tensorflow/compiler/xla/service/dump.h" #include "tensorflow/compiler/xla/service/gpu/cublas_gemm_pad_for_tensor_cores.h" #include "tensorflow/compiler/xla/service/gpu/cudnn_fused_conv_rewriter.h" #include "tensorflow/compiler/xla/service/gpu/cudnn_pad_for_convolutions.h" #include "tensorflow/compiler/xla/service/gpu/cusolver_rewriter.h" #include "tensorflow/compiler/xla/service/gpu/gemm_algorithm_picker.h" #include "tensorflow/compiler/xla/service/gpu/gpu_conv_padding_legalization.h" #include "tensorflow/compiler/xla/service/gpu/gpu_conv_rewriter.h" #include "tensorflow/compiler/xla/service/gpu/gpu_layout_assignment.h" #include "tensorflow/compiler/xla/service/gpu/ir_emission_utils.h" #include "tensorflow/compiler/xla/service/gpu/llvm_gpu_backend/gpu_backend_lib.h" #include "tensorflow/compiler/xla/service/gpu/stream_executor_util.h" #include "tensorflow/compiler/xla/service/gpu/target_constants.h" #include "tensorflow/compiler/xla/service/hlo_constant_folding.h" #include "tensorflow/compiler/xla/service/hlo_cse.h" #include "tensorflow/compiler/xla/service/hlo_pass_fix.h" #include "tensorflow/compiler/xla/service/hlo_pass_pipeline.h" #include "tensorflow/compiler/xla/service/hlo_verifier.h" #include "tensorflow/compiler/xla/service/llvm_ir/llvm_util.h" #include "tensorflow/compiler/xla/service/tuple_simplifier.h" #include "tensorflow/compiler/xla/status_macros.h" #include "tensorflow/compiler/xla/types.h" #include "tensorflow/compiler/xla/util.h" #include "tensorflow/core/lib/core/status.h" #include "tensorflow/core/lib/io/path.h" #include "tensorflow/core/platform/cuda_libdevice_path.h" #include "tensorflow/core/platform/tracing.h" #include "tensorflow/core/profiler/lib/traceme.h" #include "tensorflow/stream_executor/cuda/cuda_diagnostics.h" #include "tensorflow/stream_executor/gpu/asm_compiler.h" namespace xla { namespace gpu { namespace { namespace tracing = tensorflow::tracing; static std::vector<std::string> CandidateCudaRoots( const HloModuleConfig& config) { return tensorflow::CandidateCudaRoots( config.debug_options().xla_gpu_cuda_data_dir()); } void PrintCantFindCudaMessage(absl::string_view msg, const HloModuleConfig& hlo_module_config) { LOG(WARNING) << msg; LOG(WARNING) << "Searched for CUDA in the following directories:"; for (const auto& dir : CandidateCudaRoots(hlo_module_config)) { LOG(WARNING) << " " << dir; } LOG(WARNING) << "You can choose the search directory by setting xla_gpu_cuda_data_dir " "in HloModule's DebugOptions. For most apps, setting the environment " "variable XLA_FLAGS=--xla_gpu_cuda_data_dir=/path/to/cuda will work."; } // Returns the directory containing nvvm libdevice files. string GetLibdeviceDir(const HloModuleConfig& hlo_module_config) { for (const string& cuda_root : CandidateCudaRoots(hlo_module_config)) { string libdevice_dir = tensorflow::io::JoinPath(cuda_root, "nvvm", "libdevice"); VLOG(2) << "Looking for libdevice at " << libdevice_dir; if (tensorflow::Env::Default()->IsDirectory(libdevice_dir).ok()) { VLOG(2) << "Found libdevice dir " << libdevice_dir; return libdevice_dir; } } PrintCantFindCudaMessage( "Can't find libdevice directory ${CUDA_DIR}/nvvm/libdevice. This may " "result in compilation or runtime failures, if the program we try to run " "uses routines from libdevice.", hlo_module_config); // GetCudaRootCandidates always includes ".", but but if everything fails, we // return it anyway. Better than returning the empty string. return "."; } } // namespace Status NVPTXCompiler::OptimizeHloConvolutionCanonicalization( HloModule* hlo_module, se::StreamExecutor* stream_exec, se::DeviceMemoryAllocator* device_allocator) { // Convert convolutions into CustomCalls to cudnn, then canonicalize them // (GpuConvPaddingLegalization). Also expand cuSolver calls. HloPassPipeline pipeline("conv_canonicalization"); pipeline.AddInvariantChecker<HloVerifier>(/*layout_sensitive=*/false, /*allow_mixed_precision=*/false); pipeline.AddPass<CusolverRewriter>(); pipeline.AddPass<GpuConvRewriter>(); pipeline.AddPass<CudnnFusedConvRewriter>(); pipeline.AddPass<GpuConvPaddingLegalization>(); pipeline.AddPass<CudnnPadForConvolutions>(IsVoltaOrLater(*stream_exec)); // CudnnConvPadForIntegerConvolutions and CudnnConvPadForTensorCores leaves // behind unnecessary tuple/get-tuple-element pairs that TupleSimplifier // fixes. pipeline.AddPass<TupleSimplifier>(); // tf2xla bridge, DepthwiseConvolutionConverter and GpuConvRewriter // introduces reshapes and transposes that can be eliminated using // AlgebraicSimplifier { auto& pass = pipeline.AddPass<HloPassFix<HloPassPipeline>>( "algebraic_simplification_post_conv_rewriter"); pass.AddInvariantChecker<HloVerifier>(/*layout_sensitive=*/false, /*allow_mixed_precision=*/false); AlgebraicSimplifierOptions options; options.set_cudnn_batchnorm_forward_training_metadata( kCudnnBatchNormForwardTrainingCallTarget); pass.AddPass<AlgebraicSimplifier>(options); } // GpuConvRewriter, GpuConvPaddingLegalization and // CudnnConvPadForTensorCores may add instructions which can be simplified // by constant folding. pipeline.AddPass<HloConstantFolding>(); TF_RETURN_IF_ERROR(pipeline.Run(hlo_module).status()); return Status::OK(); } Status NVPTXCompiler::OptimizeHloPostLayoutAssignment( HloModule* hlo_module, se::StreamExecutor* stream_exec, se::DeviceMemoryAllocator* device_allocator) { HloPassPipeline pre_pipeline("nvptx post-layout_assignment part 1"); // Pad the dimensions of matrices in dot operations to multiples of 8. // This needs to run before GemmRewriter, which is part of // OptimizeHloPostLayoutAssignment(). if (IsVoltaOrLater(*stream_exec)) { pre_pipeline.AddPass<CublasGemmPadForTensorCores>(); } TF_RETURN_IF_ERROR(pre_pipeline.Run(hlo_module).status()); TF_RETURN_IF_ERROR(GpuCompiler::OptimizeHloPostLayoutAssignment( hlo_module, stream_exec, device_allocator)); HloPassPipeline post_pipeline("nvptx post-layout_assignment part 2"); // Find the fastest algorithm for GEMMs. post_pipeline.AddPass<GemmAlgorithmPicker>(stream_exec, device_allocator); TF_RETURN_IF_ERROR(post_pipeline.Run(hlo_module).status()); return Status::OK(); } namespace { absl::optional<bool> CanShareBufferHint(const HloInstruction* user, const HloInstruction* operand, const ShapeIndex& user_index) { // Share the bias buffer with the parent instruction. if (IsCublasGemm(*user)) { if (user->operand_count() == 3 && user->operand(2) == operand) { return true; } } // The operand of cholesky can be shared with the first output. if (user->opcode() == HloOpcode::kCustomCall && user->custom_call_target() == kCusolverCholeskyCallTarget) { return user_index.size() == 1 && user_index[0] == 0; } return absl::nullopt; } // Prints a warning if the ptx->sass JIT in the driver has known bugs. // // Using such a driver only a problem if we fail to use ptxas to compile our ptx // and have to use the driver instead, so you should only call this function if // we're going to use the driver JIT. // // Only prints a warning the first time it's called. void WarnIfBadDriverJITVersion() { static absl::once_flag run_once; absl::call_once(run_once, [] { auto version_or_status = se::cuda::Diagnostician::FindKernelDriverVersion(); if (!version_or_status.ok()) { LOG(WARNING) << "Couldn't read CUDA driver version."; return; } se::cuda::DriverVersion version = version_or_status.ValueOrDie(); // The following versions of the driver JIT miscompile some address // calculations with large offsets (e.g. "load ptr + large_constant"), // b/70245379: // // - 384.x before 384.108 // - 387.x before 387.40 // - 390.x before 390.10. // // In addition, only >= 396.20 contains ptxas >= 9.2.88, which contains the // fix for the "large multioutput fusions" miscompile, b/111107644. if (version < std::make_tuple(396, 20, 0)) { LOG(WARNING) << "*** WARNING *** Invoking the PTX->SASS JIT from driver version " << se::cuda::DriverVersionToString(version) << ", which is older than 396.20.0. These versions are known to " "miscompile XLA code, leading to incorrect results or " "invalid-address errors.\nXLA only uses the driver JIT if it " "cannot find ptxas; you don't need to update your driver if " "you can point XLA to ptxas 9.2.88 or newer."; } }); } // Try to load ptx from files defined in the FLAGS. If successful, return true. bool MaybeLoadPtxFromFile(const HloModule* module, std::string* ptx) { // If the xla_gpu_ptx_file options is set, be explicit when a file is used // and warn when a file is not used to ease catching typo in filename. std::string prefix = xla::FilenameFor(*module, "", *ptx); std::string matched_filename; for (const string full_filename : module->config().debug_options().xla_gpu_ptx_file()) { // To ease comparing many PTX versions, accept different suffixes then // the original filename. auto filename = tensorflow::io::Basename(full_filename); if (absl::StartsWith(filename, prefix)) { matched_filename = full_filename; VLOG(0) << "RunBackend() - Will load PTX from file: " << full_filename; break; } } if (module->config().debug_options().xla_gpu_ptx_file().size() > 0 && matched_filename.empty()) { VLOG(0) << "RunBackend() - For module with prefix '" << prefix << "', we did not found a PTX file to load."; } if (!matched_filename.empty()) { std::ifstream ifs(matched_filename, std::ifstream::in); *ptx = std::string(std::istreambuf_iterator<char>(ifs), std::istreambuf_iterator<char>()); CHECK(!ptx->empty()) << "Empty or non existing PTX file: " << matched_filename; return true; } return false; } } // namespace NVPTXCompiler::NVPTXCompiler() : GpuCompiler(stream_executor::cuda::kCudaPlatformId, nvptx::kTargetTriple, nvptx::kDataLayout) {} HloDataflowAnalysis::CanShareBuffer NVPTXCompiler::GetCanShareBuffer() { return &CanShareBufferHint; } GpuVersion NVPTXCompiler::GetGpuVersion(se::StreamExecutor* stream_exec) { int cc_major, cc_minor; if (!stream_exec->GetDeviceDescription().cuda_compute_capability(&cc_major, &cc_minor)) { LOG(WARNING) << "Couldn't get compute capability for device; assuming sm_20."; cc_major = 2; cc_minor = 0; } return std::make_pair(cc_major, cc_minor); } StatusOr<std::pair<std::string, std::vector<uint8>>> NVPTXCompiler::CompileTargetBinary(const HloModule* module, llvm::Module* llvm_module, GpuVersion gpu_version, se::StreamExecutor* stream_exec) { std::pair<int, int> compute_capability = absl::get<std::pair<int, int>>(gpu_version); std::string libdevice_dir; { tensorflow::mutex_lock lock(mutex_); // Find the directory containing libdevice. To avoid searching for it every // time, we have a one-element cache, keyed on the module's config's // cuda_data_dir. if (cached_libdevice_dir_.empty()) { cached_libdevice_dir_ = GetLibdeviceDir(module->config()); } libdevice_dir = cached_libdevice_dir_; } VLOG(2) << "Libdevice dir = " << libdevice_dir << "\n"; string ptx; if (!MaybeLoadPtxFromFile(module, &ptx)) { XLA_SCOPED_LOGGING_TIMER( "NVPTXCompiler::CompileTargetBinary - CompileToPtx"); TF_ASSIGN_OR_RETURN( ptx, nvptx::CompileToPtx(llvm_module, gpu_version, module->config(), libdevice_dir)); } llvm_ir::DumpIrIfEnabled(*module, *llvm_module, /*optimized=*/true); if (user_post_optimization_hook_) { user_post_optimization_hook_(*llvm_module); } // Write PTX to IR dump directory, if IR dumping was requested. if (DumpingEnabledForHloModule(*module)) { DumpToFileInDirOrStdout(*module, "", "ptx", ptx); } std::vector<uint8> cubin = CompileGpuAsmOrGetCachedResult( stream_exec, ptx, compute_capability.first, compute_capability.second, module->config()); return std::pair<std::string, std::vector<uint8>>(std::move(ptx), std::move(cubin)); } std::vector<uint8> NVPTXCompiler::CompileGpuAsmOrGetCachedResult( se::StreamExecutor* stream_exec, const string& ptx, int cc_major, int cc_minor, const HloModuleConfig& hlo_module_config) { XLA_SCOPED_LOGGING_TIMER("NVPTXCompiler::CompileGpuAsmOrGetCachedResult"); tensorflow::profiler::TraceMe activity( "PTX->CUBIN", tensorflow::profiler::TraceMeLevel::kInfo); bool inserted; decltype(compilation_cache_.begin()) iter; // Pointers into compilation_cache_ where the ptx and (optional) cubin are // stored. const string* cache_ptx = nullptr; CompilationCacheValue* cache_value = nullptr; { tensorflow::mutex_lock lock(mutex_); std::tie(iter, inserted) = compilation_cache_.emplace( std::piecewise_construct, std::forward_as_tuple(ptx, cc_major, cc_minor), std::forward_as_tuple()); cache_ptx = &iter->first.ptx; cache_value = &iter->second; } // Compile the ptx if it wasn't in the cache before we called this function. // Other threads asking for the same compilation key will block on // cache_value->mutex_ until compilation is done. { tensorflow::mutex_lock lock(cache_value->mutex_); if (inserted) { CHECK(!cache_value->compilation_done); if (!ptx.empty()) { StatusOr<std::vector<uint8>> maybe_cubin = se::CompileGpuAsm(stream_exec->device_ordinal(), cache_ptx->c_str(), PtxOptsFromConfig(hlo_module_config)); if (maybe_cubin.ok()) { cache_value->cubin_data = std::move(maybe_cubin).ValueOrDie(); VLOG(2) << "Compiled PTX size:" << ptx.size() << " CUBIN size: " << cache_value->cubin_data.size(); } else { bool log_warning = true; if (maybe_cubin.status().code() == tensorflow::error::Code::NOT_FOUND) { // Missing ptxas is expected in some environments where CUDA SDK // binaries are not available. We don't want to spam logs with // identical warnings in this case. // TODO(jlebar): we should implement a LOG_FIRST_N and LOG_EVERY_N // for more general usage. static std::atomic<bool> warning_done(false); log_warning = !warning_done.exchange(true); } if (log_warning) { PrintCantFindCudaMessage( "Can't find ptxas binary in ${CUDA_DIR}/bin. Will back to the " "GPU driver for PTX -> sass compilation. This is OK so long " "as you don't see a warning below about an out-of-date driver " "version. Custom ptxas location can be specified using $PATH.", hlo_module_config); } // We're going to use the driver to JIT our PTX->SASS, so warn if // the JIT in the driver has known bugs. WarnIfBadDriverJITVersion(); } } cache_value->compilation_done = true; cache_value->compilation_done_cv_.notify_all(); } else { while (!cache_value->compilation_done) { cache_value->compilation_done_cv_.wait(lock); } } } CHECK(cache_value != nullptr); CHECK(cache_value->compilation_done); return cache_value->cubin_data; } } // namespace gpu } // namespace xla
40.839329
81
0.691016
[ "vector" ]
4f46e75b49d22fb1f8c17134f945a9796e887dc1
13,812
hpp
C++
include/GlobalNamespace/ScaleAnimator.hpp
marksteward/BeatSaber-Quest-Codegen
a76f063f71cef207a9f048ad7613835f554911a7
[ "Unlicense" ]
null
null
null
include/GlobalNamespace/ScaleAnimator.hpp
marksteward/BeatSaber-Quest-Codegen
a76f063f71cef207a9f048ad7613835f554911a7
[ "Unlicense" ]
null
null
null
include/GlobalNamespace/ScaleAnimator.hpp
marksteward/BeatSaber-Quest-Codegen
a76f063f71cef207a9f048ad7613835f554911a7
[ "Unlicense" ]
null
null
null
// Autogenerated from CppHeaderCreator // Created by Sc2ad // ========================================================================= #pragma once // Begin includes #include "extern/beatsaber-hook/shared/utils/typedefs.h" #include "extern/beatsaber-hook/shared/utils/byref.hpp" // Including type: UnityEngine.MonoBehaviour #include "UnityEngine/MonoBehaviour.hpp" #include "extern/beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp" #include "extern/beatsaber-hook/shared/utils/il2cpp-utils-properties.hpp" #include "extern/beatsaber-hook/shared/utils/il2cpp-utils-fields.hpp" #include "extern/beatsaber-hook/shared/utils/utils.h" // Completed includes // Begin forward declares // Forward declaring namespace: UnityEngine namespace UnityEngine { // Forward declaring type: Transform class Transform; // Skipping declaration: Vector3 because it is already included! // Skipping declaration: Quaternion because it is already included! } // Forward declaring namespace: Tweening namespace Tweening { // Forward declaring type: TweeningManager class TweeningManager; // Forward declaring type: Tween`1<T> template<typename T> class Tween_1; // Forward declaring type: EaseType struct EaseType; } // Completed forward declares // Type namespace: namespace GlobalNamespace { // Size: 0x41 #pragma pack(push, 1) // Autogenerated type: ScaleAnimator // [TokenAttribute] Offset: FFFFFFFF class ScaleAnimator : public UnityEngine::MonoBehaviour { public: // private System.Single _displayedScale // Size: 0x4 // Offset: 0x18 float displayedScale; // Field size check static_assert(sizeof(float) == 0x4); // Padding between fields: displayedScale and: targetTransform char __padding0[0x4] = {}; // private UnityEngine.Transform _targetTransform // Size: 0x8 // Offset: 0x20 UnityEngine::Transform* targetTransform; // Field size check static_assert(sizeof(UnityEngine::Transform*) == 0x8); // [InjectAttribute] Offset: 0xEB5CC0 // private readonly Tweening.TweeningManager _tweeningManager // Size: 0x8 // Offset: 0x28 Tweening::TweeningManager* tweeningManager; // Field size check static_assert(sizeof(Tweening::TweeningManager*) == 0x8); // private Tweening.Tween`1<System.Single> _scaleUpTween // Size: 0x8 // Offset: 0x30 Tweening::Tween_1<float>* scaleUpTween; // Field size check static_assert(sizeof(Tweening::Tween_1<float>*) == 0x8); // private Tweening.Tween`1<System.Single> _scaleDownTween // Size: 0x8 // Offset: 0x38 Tweening::Tween_1<float>* scaleDownTween; // Field size check static_assert(sizeof(Tweening::Tween_1<float>*) == 0x8); // private System.Boolean _initialized // Size: 0x1 // Offset: 0x40 bool initialized; // Field size check static_assert(sizeof(bool) == 0x1); // Creating value type constructor for type: ScaleAnimator ScaleAnimator(float displayedScale_ = {}, UnityEngine::Transform* targetTransform_ = {}, Tweening::TweeningManager* tweeningManager_ = {}, Tweening::Tween_1<float>* scaleUpTween_ = {}, Tweening::Tween_1<float>* scaleDownTween_ = {}, bool initialized_ = {}) noexcept : displayedScale{displayedScale_}, targetTransform{targetTransform_}, tweeningManager{tweeningManager_}, scaleUpTween{scaleUpTween_}, scaleDownTween{scaleDownTween_}, initialized{initialized_} {} // Deleting conversion operator: operator System::IntPtr constexpr operator System::IntPtr() const noexcept = delete; // Get instance field: private System.Single _displayedScale float _get__displayedScale(); // Set instance field: private System.Single _displayedScale void _set__displayedScale(float value); // Get instance field: private UnityEngine.Transform _targetTransform UnityEngine::Transform* _get__targetTransform(); // Set instance field: private UnityEngine.Transform _targetTransform void _set__targetTransform(UnityEngine::Transform* value); // Get instance field: private readonly Tweening.TweeningManager _tweeningManager Tweening::TweeningManager* _get__tweeningManager(); // Set instance field: private readonly Tweening.TweeningManager _tweeningManager void _set__tweeningManager(Tweening::TweeningManager* value); // Get instance field: private Tweening.Tween`1<System.Single> _scaleUpTween Tweening::Tween_1<float>* _get__scaleUpTween(); // Set instance field: private Tweening.Tween`1<System.Single> _scaleUpTween void _set__scaleUpTween(Tweening::Tween_1<float>* value); // Get instance field: private Tweening.Tween`1<System.Single> _scaleDownTween Tweening::Tween_1<float>* _get__scaleDownTween(); // Set instance field: private Tweening.Tween`1<System.Single> _scaleDownTween void _set__scaleDownTween(Tweening::Tween_1<float>* value); // Get instance field: private System.Boolean _initialized bool _get__initialized(); // Set instance field: private System.Boolean _initialized void _set__initialized(bool value); // protected System.Void OnDestroy() // Offset: 0x1F806F0 void OnDestroy(); // private System.Void InitIfNeeded() // Offset: 0x1F80788 void InitIfNeeded(); // public System.Void SetPositionAndRotation(UnityEngine.Vector3 position, UnityEngine.Quaternion rotation) // Offset: 0x1F80978 void SetPositionAndRotation(UnityEngine::Vector3 position, UnityEngine::Quaternion rotation); // public System.Void HideInstant() // Offset: 0x1F809F4 void HideInstant(); // public System.Void ShowInstant() // Offset: 0x1F80AB8 void ShowInstant(); // public System.Void Animate(System.Boolean show, System.Single duration, Tweening.EaseType easeType, System.Single delay) // Offset: 0x1F80B60 void Animate(bool show, float duration, Tweening::EaseType easeType, float delay); // private System.Void <InitIfNeeded>b__7_0(System.Single val) // Offset: 0x1F80C9C void $InitIfNeeded$b__7_0(float val); // private System.Void <InitIfNeeded>b__7_2() // Offset: 0x1F80CF8 void $InitIfNeeded$b__7_2(); // private System.Void <InitIfNeeded>b__7_1(System.Single val) // Offset: 0x1F80D28 void $InitIfNeeded$b__7_1(float val); // private System.Void <InitIfNeeded>b__7_3() // Offset: 0x1F80D84 void $InitIfNeeded$b__7_3(); // public System.Void .ctor() // Offset: 0x1F80C8C // Implemented from: UnityEngine.MonoBehaviour // Base method: System.Void MonoBehaviour::.ctor() // Base method: System.Void Behaviour::.ctor() // Base method: System.Void Component::.ctor() // Base method: System.Void Object::.ctor() // Base method: System.Void Object::.ctor() template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary> static ScaleAnimator* New_ctor() { static auto ___internal__logger = ::Logger::get().WithContext("GlobalNamespace::ScaleAnimator::.ctor"); return THROW_UNLESS((::il2cpp_utils::New<ScaleAnimator*, creationType>())); } }; // ScaleAnimator #pragma pack(pop) static check_size<sizeof(ScaleAnimator), 64 + sizeof(bool)> __GlobalNamespace_ScaleAnimatorSizeCheck; static_assert(sizeof(ScaleAnimator) == 0x41); } DEFINE_IL2CPP_ARG_TYPE(GlobalNamespace::ScaleAnimator*, "", "ScaleAnimator"); #include "extern/beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp" // Writing MetadataGetter for method: GlobalNamespace::ScaleAnimator::OnDestroy // Il2CppName: OnDestroy template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::ScaleAnimator::*)()>(&GlobalNamespace::ScaleAnimator::OnDestroy)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::ScaleAnimator*), "OnDestroy", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: GlobalNamespace::ScaleAnimator::InitIfNeeded // Il2CppName: InitIfNeeded template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::ScaleAnimator::*)()>(&GlobalNamespace::ScaleAnimator::InitIfNeeded)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::ScaleAnimator*), "InitIfNeeded", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: GlobalNamespace::ScaleAnimator::SetPositionAndRotation // Il2CppName: SetPositionAndRotation template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::ScaleAnimator::*)(UnityEngine::Vector3, UnityEngine::Quaternion)>(&GlobalNamespace::ScaleAnimator::SetPositionAndRotation)> { static const MethodInfo* get() { static auto* position = &::il2cpp_utils::GetClassFromName("UnityEngine", "Vector3")->byval_arg; static auto* rotation = &::il2cpp_utils::GetClassFromName("UnityEngine", "Quaternion")->byval_arg; return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::ScaleAnimator*), "SetPositionAndRotation", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{position, rotation}); } }; // Writing MetadataGetter for method: GlobalNamespace::ScaleAnimator::HideInstant // Il2CppName: HideInstant template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::ScaleAnimator::*)()>(&GlobalNamespace::ScaleAnimator::HideInstant)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::ScaleAnimator*), "HideInstant", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: GlobalNamespace::ScaleAnimator::ShowInstant // Il2CppName: ShowInstant template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::ScaleAnimator::*)()>(&GlobalNamespace::ScaleAnimator::ShowInstant)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::ScaleAnimator*), "ShowInstant", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: GlobalNamespace::ScaleAnimator::Animate // Il2CppName: Animate template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::ScaleAnimator::*)(bool, float, Tweening::EaseType, float)>(&GlobalNamespace::ScaleAnimator::Animate)> { static const MethodInfo* get() { static auto* show = &::il2cpp_utils::GetClassFromName("System", "Boolean")->byval_arg; static auto* duration = &::il2cpp_utils::GetClassFromName("System", "Single")->byval_arg; static auto* easeType = &::il2cpp_utils::GetClassFromName("Tweening", "EaseType")->byval_arg; static auto* delay = &::il2cpp_utils::GetClassFromName("System", "Single")->byval_arg; return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::ScaleAnimator*), "Animate", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{show, duration, easeType, delay}); } }; // Writing MetadataGetter for method: GlobalNamespace::ScaleAnimator::$InitIfNeeded$b__7_0 // Il2CppName: <InitIfNeeded>b__7_0 template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::ScaleAnimator::*)(float)>(&GlobalNamespace::ScaleAnimator::$InitIfNeeded$b__7_0)> { static const MethodInfo* get() { static auto* val = &::il2cpp_utils::GetClassFromName("System", "Single")->byval_arg; return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::ScaleAnimator*), "<InitIfNeeded>b__7_0", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{val}); } }; // Writing MetadataGetter for method: GlobalNamespace::ScaleAnimator::$InitIfNeeded$b__7_2 // Il2CppName: <InitIfNeeded>b__7_2 template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::ScaleAnimator::*)()>(&GlobalNamespace::ScaleAnimator::$InitIfNeeded$b__7_2)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::ScaleAnimator*), "<InitIfNeeded>b__7_2", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: GlobalNamespace::ScaleAnimator::$InitIfNeeded$b__7_1 // Il2CppName: <InitIfNeeded>b__7_1 template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::ScaleAnimator::*)(float)>(&GlobalNamespace::ScaleAnimator::$InitIfNeeded$b__7_1)> { static const MethodInfo* get() { static auto* val = &::il2cpp_utils::GetClassFromName("System", "Single")->byval_arg; return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::ScaleAnimator*), "<InitIfNeeded>b__7_1", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{val}); } }; // Writing MetadataGetter for method: GlobalNamespace::ScaleAnimator::$InitIfNeeded$b__7_3 // Il2CppName: <InitIfNeeded>b__7_3 template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::ScaleAnimator::*)()>(&GlobalNamespace::ScaleAnimator::$InitIfNeeded$b__7_3)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::ScaleAnimator*), "<InitIfNeeded>b__7_3", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: GlobalNamespace::ScaleAnimator::New_ctor // Il2CppName: .ctor // Cannot get method pointer of value based method overload from template for constructor! // Try using FindMethod instead!
55.027888
466
0.730814
[ "object", "vector", "transform" ]
4f47b098bbbfaf45d84d600f9dfa43d80e50ae9b
7,198
cpp
C++
src/esp/geo/OBB.cpp
shacklettbp/habitat-sim
1d5f7a4a3bfc30b620cf99f75a09db124b7aa1a5
[ "MIT" ]
1
2019-04-22T06:04:48.000Z
2019-04-22T06:04:48.000Z
src/esp/geo/OBB.cpp
shacklettbp/habitat-sim
1d5f7a4a3bfc30b620cf99f75a09db124b7aa1a5
[ "MIT" ]
null
null
null
src/esp/geo/OBB.cpp
shacklettbp/habitat-sim
1d5f7a4a3bfc30b620cf99f75a09db124b7aa1a5
[ "MIT" ]
null
null
null
// Copyright (c) Facebook, Inc. and its affiliates. // This source code is licensed under the MIT license found in the // LICENSE file in the root directory of this source tree. #include "OBB.h" #include <vector> #include "esp/geo/geo.h" namespace esp { namespace geo { OBB::OBB() { center_.setZero(); halfExtents_.setZero(); rotation_.setIdentity(); box3f box; } OBB::OBB(const vec3f& center, const vec3f& dimensions, const quatf& rotation) : center_(center), halfExtents_(dimensions * 0.5), rotation_(rotation) { recomputeTransforms(); } OBB::OBB(const box3f& aabb) : OBB(aabb.center(), aabb.sizes(), quatf::Identity()) {} static const vec3f kCorners[8] = { vec3f(-1, -1, -1), vec3f(-1, -1, +1), vec3f(-1, +1, -1), vec3f(-1, +1, +1), vec3f(+1, -1, -1), vec3f(+1, -1, +1), vec3f(+1, +1, -1), vec3f(+1, +1, +1)}; box3f OBB::toAABB() const { box3f bbox; for (int i = 0; i < 8; i++) { const vec3f worldPoint = center_ + (rotation_ * kCorners[i].cwiseProduct(halfExtents_)); bbox.extend(worldPoint); } return bbox; } void OBB::recomputeTransforms() { ASSERT(center_.allFinite()); ASSERT(halfExtents_.allFinite()); ASSERT(rotation_.coeffs().allFinite()); // TODO(MS): these can be composed more efficiently and directly const mat3f R = rotation_.matrix(); // Local-to-world transform for (int i = 0; i < 3; i++) { localToWorld_.linear().col(i) = R.col(i) * halfExtents_[i]; } localToWorld_.translation() = center_; // World-to-local transform. Points within OBB are in [0,1]^3 for (int i = 0; i < 3; i++) { worldToLocal_.linear().row(i) = R.col(i) * (1.0f / halfExtents_[i]); } worldToLocal_.translation() = -worldToLocal_.linear() * center_; } bool OBB::contains(const vec3f& p, float eps /* = 1e-6f */) const { const vec3f pLocal = worldToLocal() * p; const float bound = 1.0f + eps; for (int i = 0; i < 3; i++) { if (std::abs(pLocal[i]) > bound) { return false; } } return true; // Here only if all three coords within bounds } float OBB::distance(const vec3f& p) const { if (contains(p)) { return 0; } const vec3f closest = closestPoint(p); return (p - closest).norm(); } vec3f OBB::closestPoint(const vec3f& p) const { const vec3f d = p - center_; vec3f closest = center_; const mat3f R = rotation_.matrix(); for (int i = 0; i < 3; i++) { closest += clamp(R.col(i).dot(d), -halfExtents_[i], halfExtents_[i]) * R.col(i); } return closest; } OBB& OBB::rotate(const quatf& q) { rotation_ = q * rotation_; recomputeTransforms(); return *this; } // https://geidav.wordpress.com/tag/minimum-obb/ OBB computeGravityAlignedMOBB(const vec3f& gravity, const std::vector<vec3f>& points) { const auto align_gravity = quatf::FromTwoVectors(gravity, -vec3f::UnitZ()); static auto ortho = [](const vec2f& v) { return vec2f(v[1], -v[0]); }; static auto intersect_lines = [](const vec2f& s0, const vec2f& d0, const vec2f& s1, const vec2f& d1) { const float dd = d0[0] * d1[1] - d0[1] * d1[0]; const float dx = s1[0] - s0[0]; const float dy = s1[1] - s0[0]; const float t = (dx * d1[1] - dy * d1[0]) / dd; return s0 + t * d0; }; static auto mobb_area = [](const vec2f& left_start, const vec2f& left_dir, const vec2f& right_start, const vec2f& right_dir, const vec2f& top_start, const vec2f& top_dir, const vec2f& bottom_start, const vec2f& bottom_dir) { const vec2f upper_left = intersect_lines(left_start, left_dir, top_start, top_dir); const vec2f upper_right = intersect_lines(right_start, right_dir, top_start, top_dir); const vec2f bottom_left = intersect_lines(bottom_start, bottom_dir, left_start, left_dir); return (upper_left - upper_right).norm() * (upper_left - bottom_left).norm(); }; std::vector<vec2f> in_plane_points; for (const auto& pt : points) { vec3f aligned_pt = align_gravity * pt; in_plane_points.emplace_back(aligned_pt[0], aligned_pt[1]); } const auto hull = convexHull2D(in_plane_points); std::vector<vec2f> edge_dirs; for (size_t i = 0; i < hull.size(); ++i) { edge_dirs.emplace_back( (hull[(i + 1) % hull.size()] - hull[i]).normalized()); } vec2f min_pt = hull[0], max_pt = hull[0]; int left_idx = 0, right_idx = 0, top_idx = 0, bottom_idx = 0; for (size_t i = 0; i < hull.size(); ++i) { const auto& pt = hull[i]; if (pt[0] < min_pt[0]) { min_pt[0] = pt[0]; left_idx = i; } if (pt[0] > max_pt[0]) { max_pt[0] = pt[0]; right_idx = i; } if (pt[1] < min_pt[1]) { min_pt[1] = pt[1]; bottom_idx = i; } if (pt[1] > max_pt[1]) { max_pt[1] = pt[1]; top_idx = i; } } vec2f left_dir = vec2f(0, -1), right_dir = vec2f(0, 1), top_dir = vec2f(-1, 0), bottom_dir = vec2f(1, 0); float best_area = 1e10; vec2f best_bottom_dir; for (size_t i = 0; i < hull.size(); ++i) { const std::vector<float> angles( {std::acos(left_dir.dot(edge_dirs[left_idx])), std::acos(right_dir.dot(edge_dirs[right_idx])), std::acos(top_dir.dot(edge_dirs[top_idx])), std::acos(bottom_dir.dot(edge_dirs[bottom_idx]))}); float min_angle = 1e10; size_t best_line = 0; for (size_t i = 0; i < angles.size(); ++i) { if (angles[i] < min_angle) { best_line = i; min_angle = angles[i]; } } switch (best_line) { case 0: left_dir = edge_dirs[left_idx]; right_dir = -left_dir; top_dir = ortho(left_dir); bottom_dir = -top_dir; left_idx = (left_idx + 1) % hull.size(); break; case 1: right_dir = edge_dirs[right_idx]; left_dir = -right_dir; top_dir = ortho(left_dir); bottom_dir = -top_dir; right_idx = (right_idx + 1) % hull.size(); break; case 2: top_dir = edge_dirs[top_idx]; bottom_dir = -top_dir; left_dir = ortho(bottom_dir); right_dir = -left_dir; top_idx = (top_idx + 1) % hull.size(); break; case 3: bottom_dir = edge_dirs[bottom_idx]; top_dir = -bottom_dir; left_dir = ortho(bottom_dir); right_dir = -left_dir; bottom_idx = (bottom_idx + 1) % hull.size(); break; default: ASSERT(false); } const float area = mobb_area(hull[left_idx], left_dir, hull[right_idx], right_dir, hull[top_idx], top_dir, hull[bottom_idx], bottom_dir); if (area < best_area) { best_bottom_dir = bottom_dir; best_area = area; } } const auto T_w2b = quatf::FromTwoVectors(vec3f(best_bottom_dir[0], best_bottom_dir[1], 0), vec3f::UnitX()) * align_gravity; box3f aabb; aabb.setEmpty(); for (auto& pt : points) { aabb.extend(T_w2b * pt); } return OBB{aabb.center(), aabb.sizes(), T_w2b.inverse()}; } } // namespace geo } // namespace esp
29.024194
80
0.58683
[ "vector", "transform" ]
4f49061ec90ecf84a89dd1844d5e9f4f6d49916f
8,410
cpp
C++
src/rpcclient.cpp
coinkeeper/2015-06-22_18-55_clams
f5575011523bf710d73f748d43f07a4214005374
[ "MIT" ]
1
2018-02-06T22:33:13.000Z
2018-02-06T22:33:13.000Z
src/rpcclient.cpp
coinkeeper/2015-06-22_18-55_clams
f5575011523bf710d73f748d43f07a4214005374
[ "MIT" ]
null
null
null
src/rpcclient.cpp
coinkeeper/2015-06-22_18-55_clams
f5575011523bf710d73f748d43f07a4214005374
[ "MIT" ]
null
null
null
// Copyright (c) 2010 Satoshi Nakamoto // Copyright (c) 2009-2013 The Bitcoin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <set> #include "rpcclient.h" #include "rpcprotocol.h" #include "util.h" #include "ui_interface.h" #include "chainparams.h" // for Params().RPCPort() #include <stdint.h> #include <boost/algorithm/string.hpp> #include <boost/asio.hpp> #include <boost/asio/ssl.hpp> #include <boost/bind.hpp> #include <boost/filesystem.hpp> #include <boost/foreach.hpp> #include <boost/iostreams/concepts.hpp> #include <boost/iostreams/stream.hpp> #include <boost/lexical_cast.hpp> #include <boost/shared_ptr.hpp> #include "json/json_spirit_writer_template.h" using namespace std; using namespace boost; using namespace boost::asio; using namespace json_spirit; Object CallRPC(const string& strMethod, const Array& params) { if (mapArgs["-rpcuser"] == "" && mapArgs["-rpcpassword"] == "") throw runtime_error(strprintf( _("You must set rpcpassword=<password> in the configuration file:\n%s\n" "If the file does not exist, create it with owner-readable-only file permissions."), GetConfigFile().string())); // Connect to localhost bool fUseSSL = GetBoolArg("-rpcssl", false); asio::io_service io_service; ssl::context context(io_service, ssl::context::sslv23); context.set_options(ssl::context::no_sslv2); asio::ssl::stream<asio::ip::tcp::socket> sslStream(io_service, context); SSLIOStreamDevice<asio::ip::tcp> d(sslStream, fUseSSL); iostreams::stream< SSLIOStreamDevice<asio::ip::tcp> > stream(d); bool fWait = GetBoolArg("-rpcwait", false); // -rpcwait means try until server has started do { bool fConnected = d.connect(GetArg("-rpcconnect", "127.0.0.1"), GetArg("-rpcport", itostr(Params().RPCPort()))); if (fConnected) break; if (fWait) MilliSleep(1000); else throw runtime_error("couldn't connect to server"); } while (fWait); // HTTP basic authentication string strUserPass64 = EncodeBase64(mapArgs["-rpcuser"] + ":" + mapArgs["-rpcpassword"]); map<string, string> mapRequestHeaders; mapRequestHeaders["Authorization"] = string("Basic ") + strUserPass64; // Send request string strRequest = JSONRPCRequest(strMethod, params, 1); string strPost = HTTPPost(strRequest, mapRequestHeaders); stream << strPost << std::flush; // Receive HTTP reply status int nProto = 0; int nStatus = ReadHTTPStatus(stream, nProto); // Receive HTTP reply message headers and body map<string, string> mapHeaders; string strReply; ReadHTTPMessage(stream, mapHeaders, strReply, nProto); if (nStatus == HTTP_UNAUTHORIZED) throw runtime_error("incorrect rpcuser or rpcpassword (authorization failed)"); else if (nStatus >= 400 && nStatus != HTTP_BAD_REQUEST && nStatus != HTTP_NOT_FOUND && nStatus != HTTP_INTERNAL_SERVER_ERROR) throw runtime_error(strprintf("server returned HTTP error %d", nStatus)); else if (strReply.empty()) throw runtime_error("no response from server"); // Parse reply Value valReply; if (!read_string(strReply, valReply)) throw runtime_error("couldn't parse reply from server"); const Object& reply = valReply.get_obj(); if (reply.empty()) throw runtime_error("expected reply to have result, error and id properties"); return reply; } class CRPCConvertParam { public: std::string methodName; // method whose params want conversion int paramIdx; // 0-based idx of param to convert }; static const CRPCConvertParam vRPCConvertParams[] = { { "stop", 0 }, { "getaddednodeinfo", 0 }, { "sendtoaddress", 1 }, { "settxfee", 0 }, { "getstakedbyaddress", 1 }, { "getreceivedbyaddress", 1 }, { "getreceivedbyaccount", 1 }, { "listreceivedbyaddress", 0 }, { "listreceivedbyaddress", 1 }, { "listreceivedbyaccount", 0 }, { "listreceivedbyaccount", 1 }, { "getbalance", 1 }, { "getblock", 1 }, { "getblockbynumber", 0 }, { "getblockbynumber", 1 }, { "getblockhash", 0 }, { "move", 2 }, { "move", 3 }, { "sendfrom", 2 }, { "sendfrom", 3 }, { "listtransactions", 1 }, { "listtransactions", 2 }, { "listbalances", 0 }, { "listbalances", 1 }, { "listbalances", 2 }, { "listaccounts", 0 }, { "walletpassphrase", 1 }, { "walletpassphrase", 2 }, { "getblocktemplate", 0 }, { "listsinceblock", 1 }, { "sendalert", 2 }, { "sendalert", 3 }, { "sendalert", 4 }, { "sendalert", 5 }, { "sendalert", 6 }, { "sendmany", 1 }, { "sendmany", 2 }, { "reservebalance", 0 }, { "reservebalance", 1 }, { "addmultisigaddress", 0 }, { "addmultisigaddress", 1 }, { "listunspent", 0 }, { "listunspent", 1 }, { "listunspent", 2 }, { "listunspent", 3 }, { "getrawtransaction", 1 }, { "createrawtransaction", 0 }, { "createrawtransaction", 1 }, { "signrawtransaction", 1 }, { "signrawtransaction", 2 }, { "keypoolrefill", 0 }, { "importprivkey", 2 }, { "importwallet", 2 }, { "dumpbootstrap", 1 }, { "validateoutputs", 0 }, }; class CRPCConvertTable { private: std::set<std::pair<std::string, int> > members; public: CRPCConvertTable(); bool convert(const std::string& method, int idx) { return (members.count(std::make_pair(method, idx)) > 0); } }; CRPCConvertTable::CRPCConvertTable() { const unsigned int n_elem = (sizeof(vRPCConvertParams) / sizeof(vRPCConvertParams[0])); for (unsigned int i = 0; i < n_elem; i++) { members.insert(std::make_pair(vRPCConvertParams[i].methodName, vRPCConvertParams[i].paramIdx)); } } static CRPCConvertTable rpcCvtTable; // Convert strings to command-specific RPC representation Array RPCConvertValues(const std::string &strMethod, const std::vector<std::string> &strParams) { Array params; for (unsigned int idx = 0; idx < strParams.size(); idx++) { const std::string& strVal = strParams[idx]; // insert string value directly if (!rpcCvtTable.convert(strMethod, idx)) { params.push_back(strVal); } // parse string as JSON, insert bool/number/object/etc. value else { Value jVal; if (!read_string(strVal, jVal)) throw runtime_error(string("Error parsing JSON:")+strVal); params.push_back(jVal); } } return params; } int CommandLineRPC(int argc, char *argv[]) { string strPrint; int nRet = 0; try { // Skip switches while (argc > 1 && IsSwitchChar(argv[1][0])) { argc--; argv++; } // Method if (argc < 2) throw runtime_error("too few parameters"); string strMethod = argv[1]; // Parameters default to strings std::vector<std::string> strParams(&argv[2], &argv[argc]); Array params = RPCConvertValues(strMethod, strParams); // Execute Object reply = CallRPC(strMethod, params); // Parse reply const Value& result = find_value(reply, "result"); const Value& error = find_value(reply, "error"); if (error.type() != null_type) { // Error strPrint = "error: " + write_string(error, false); int code = find_value(error.get_obj(), "code").get_int(); nRet = abs(code); } else { // Result if (result.type() == null_type) strPrint = ""; else if (result.type() == str_type) strPrint = result.get_str(); else strPrint = write_string(result, true); } } catch (boost::thread_interrupted) { throw; } catch (std::exception& e) { strPrint = string("error: ") + e.what(); nRet = 87; } catch (...) { PrintException(NULL, "CommandLineRPC()"); } if (strPrint != "") { fprintf((nRet == 0 ? stdout : stderr), "%s\n", strPrint.c_str()); } return nRet; }
30.143369
129
0.602259
[ "object", "vector" ]
4f492feb2fab217a4ec7a94ae1e96ca43bd8fdec
1,707
cpp
C++
src/luogu/P1120/23759154_ua_66_7799ms_800k_noO2.cpp
lnkkerst/oj-codes
d778489182d644370b2a690aa92c3df6542cc306
[ "MIT" ]
null
null
null
src/luogu/P1120/23759154_ua_66_7799ms_800k_noO2.cpp
lnkkerst/oj-codes
d778489182d644370b2a690aa92c3df6542cc306
[ "MIT" ]
null
null
null
src/luogu/P1120/23759154_ua_66_7799ms_800k_noO2.cpp
lnkkerst/oj-codes
d778489182d644370b2a690aa92c3df6542cc306
[ "MIT" ]
null
null
null
#include <cstdio> #include <cctype> #include <cstring> #include <cstdlib> #include <iomanip> #include <iostream> #include <algorithm> #include <set> #include <vector> #include <stack> #include <queue> #include <map> #include <functional> #include <cmath> #include <ctime> #define MAXN 66 using namespace std; int read() { int ret; char ch; bool f = 0; while(!isdigit(ch = getchar())) (ch == '-') && (f = 1); for(ret = ch - '0'; isdigit(ch = getchar()); ret *= 10, ret += ch - '0'); return f ? -ret : ret; } void print(int x) { if(x < 0) { putchar('-'); x = -x; } if(x > 9) { print(x / 10); } putchar(x % 10 + '0'); } int a[MAXN], n, m, next[MAXN], cnt, sum, l; bool vis[MAXN], f; bool cmp(int a, int b) { return a > b; } void dfs(int k, int last, int rest) { int i; if(!rest) { if(k == m) { f = 1; return ; } for(i = 1; i <= cnt; ++i) if(!vis[i]) break; vis[i] = 1; dfs(k + 1, i, l - a[i]); vis[i] = 0; if(f) return ; } for(i = 1; i <= cnt; ++i) { if(a[i] <= rest) break; } while(i <= cnt) { if(!vis[i]) { vis[i] = 1; dfs(k, i, rest - a[i]); vis[i] = 0; if(f) return ; if(rest == a[i] || rest == l) return ; for(; i <= cnt; ++i) if(a[i] != a[i + 1]) { break; } if(i == cnt) return ; } ++i; } } int main() { n = read(); cnt = 0; int tmp; for(int i = 1; i <= n; ++i) { tmp = read(); if(tmp <= 50) { a[++cnt] = tmp; sum += tmp; } } sort(a + 1, a + 1 + cnt, cmp); for(l = a[1]; l <= sum / 2; l++) { if(sum % l) continue; m = sum / l; f = false; vis[1] = true; dfs(1, 1, l - a[1]); vis[1] = false; if(f) { print(l); return 0; } } print(sum); return 0; }
15.953271
77
0.478617
[ "vector" ]
4f4963e95f3a6d02af7b293c4f2dcd2e318f8a40
7,299
cpp
C++
Source/FieldSolver/SpectralSolver/SpectralAlgorithms/PsatdAlgorithm.cpp
guj/WarpX
7833e281dd9fa695a57d097eac31acef7ccaa3eb
[ "BSD-3-Clause-LBNL" ]
null
null
null
Source/FieldSolver/SpectralSolver/SpectralAlgorithms/PsatdAlgorithm.cpp
guj/WarpX
7833e281dd9fa695a57d097eac31acef7ccaa3eb
[ "BSD-3-Clause-LBNL" ]
null
null
null
Source/FieldSolver/SpectralSolver/SpectralAlgorithms/PsatdAlgorithm.cpp
guj/WarpX
7833e281dd9fa695a57d097eac31acef7ccaa3eb
[ "BSD-3-Clause-LBNL" ]
null
null
null
/* Copyright 2019 Remi Lehe, Revathi Jambunathan * * This file is part of WarpX. * * License: BSD-3-Clause-LBNL */ #include <PsatdAlgorithm.H> #include <WarpXConst.H> #include <cmath> using namespace amrex; /* \brief Initialize coefficients for the update equation */ PsatdAlgorithm::PsatdAlgorithm(const SpectralKSpace& spectral_kspace, const DistributionMapping& dm, const int norder_x, const int norder_y, const int norder_z, const bool nodal, const Real dt) // Initialize members of base class : SpectralBaseAlgorithm( spectral_kspace, dm, norder_x, norder_y, norder_z, nodal ) { const BoxArray& ba = spectral_kspace.spectralspace_ba; // Allocate the arrays of coefficients C_coef = SpectralCoefficients(ba, dm, 1, 0); S_ck_coef = SpectralCoefficients(ba, dm, 1, 0); X1_coef = SpectralCoefficients(ba, dm, 1, 0); X2_coef = SpectralCoefficients(ba, dm, 1, 0); X3_coef = SpectralCoefficients(ba, dm, 1, 0); InitializeSpectralCoefficients(spectral_kspace, dm, dt); } /* Advance the E and B field in spectral space (stored in `f`) * over one time step */ void PsatdAlgorithm::pushSpectralFields(SpectralFieldData& f) const{ // Loop over boxes for (MFIter mfi(f.fields); mfi.isValid(); ++mfi){ const Box& bx = f.fields[mfi].box(); // Extract arrays for the fields to be updated Array4<Complex> fields = f.fields[mfi].array(); // Extract arrays for the coefficients Array4<const Real> C_arr = C_coef[mfi].array(); Array4<const Real> S_ck_arr = S_ck_coef[mfi].array(); Array4<const Real> X1_arr = X1_coef[mfi].array(); Array4<const Real> X2_arr = X2_coef[mfi].array(); Array4<const Real> X3_arr = X3_coef[mfi].array(); // Extract pointers for the k vectors const Real* modified_kx_arr = modified_kx_vec[mfi].dataPtr(); #if (AMREX_SPACEDIM==3) const Real* modified_ky_arr = modified_ky_vec[mfi].dataPtr(); #endif const Real* modified_kz_arr = modified_kz_vec[mfi].dataPtr(); // Loop over indices within one box ParallelFor(bx, [=] AMREX_GPU_DEVICE(int i, int j, int k) noexcept { // Record old values of the fields to be updated using Idx = SpectralFieldIndex; const Complex Ex_old = fields(i,j,k,Idx::Ex); const Complex Ey_old = fields(i,j,k,Idx::Ey); const Complex Ez_old = fields(i,j,k,Idx::Ez); const Complex Bx_old = fields(i,j,k,Idx::Bx); const Complex By_old = fields(i,j,k,Idx::By); const Complex Bz_old = fields(i,j,k,Idx::Bz); // Shortcut for the values of J and rho const Complex Jx = fields(i,j,k,Idx::Jx); const Complex Jy = fields(i,j,k,Idx::Jy); const Complex Jz = fields(i,j,k,Idx::Jz); const Complex rho_old = fields(i,j,k,Idx::rho_old); const Complex rho_new = fields(i,j,k,Idx::rho_new); // k vector values, and coefficients const Real kx = modified_kx_arr[i]; #if (AMREX_SPACEDIM==3) const Real ky = modified_ky_arr[j]; const Real kz = modified_kz_arr[k]; #else constexpr Real ky = 0; const Real kz = modified_kz_arr[j]; #endif constexpr Real c2 = PhysConst::c*PhysConst::c; constexpr Real inv_ep0 = 1./PhysConst::ep0; const Complex I = Complex{0,1}; const Real C = C_arr(i,j,k); const Real S_ck = S_ck_arr(i,j,k); const Real X1 = X1_arr(i,j,k); const Real X2 = X2_arr(i,j,k); const Real X3 = X3_arr(i,j,k); // Update E (see WarpX online documentation: theory section) fields(i,j,k,Idx::Ex) = C*Ex_old + S_ck*(c2*I*(ky*Bz_old - kz*By_old) - inv_ep0*Jx) - I*(X2*rho_new - X3*rho_old)*kx; fields(i,j,k,Idx::Ey) = C*Ey_old + S_ck*(c2*I*(kz*Bx_old - kx*Bz_old) - inv_ep0*Jy) - I*(X2*rho_new - X3*rho_old)*ky; fields(i,j,k,Idx::Ez) = C*Ez_old + S_ck*(c2*I*(kx*By_old - ky*Bx_old) - inv_ep0*Jz) - I*(X2*rho_new - X3*rho_old)*kz; // Update B (see WarpX online documentation: theory section) fields(i,j,k,Idx::Bx) = C*Bx_old - S_ck*I*(ky*Ez_old - kz*Ey_old) + X1*I*(ky*Jz - kz*Jy); fields(i,j,k,Idx::By) = C*By_old - S_ck*I*(kz*Ex_old - kx*Ez_old) + X1*I*(kz*Jx - kx*Jz); fields(i,j,k,Idx::Bz) = C*Bz_old - S_ck*I*(kx*Ey_old - ky*Ex_old) + X1*I*(kx*Jy - ky*Jx); }); } }; void PsatdAlgorithm::InitializeSpectralCoefficients(const SpectralKSpace& spectral_kspace, const amrex::DistributionMapping& dm, const amrex::Real dt) { const BoxArray& ba = spectral_kspace.spectralspace_ba; // Fill them with the right values: // Loop over boxes and allocate the corresponding coefficients // for each box owned by the local MPI proc for (MFIter mfi(ba, dm); mfi.isValid(); ++mfi){ const Box& bx = ba[mfi]; // Extract pointers for the k vectors const Real* modified_kx = modified_kx_vec[mfi].dataPtr(); #if (AMREX_SPACEDIM==3) const Real* modified_ky = modified_ky_vec[mfi].dataPtr(); #endif const Real* modified_kz = modified_kz_vec[mfi].dataPtr(); // Extract arrays for the coefficients Array4<Real> C = C_coef[mfi].array(); Array4<Real> S_ck = S_ck_coef[mfi].array(); Array4<Real> X1 = X1_coef[mfi].array(); Array4<Real> X2 = X2_coef[mfi].array(); Array4<Real> X3 = X3_coef[mfi].array(); // Loop over indices within one box ParallelFor(bx, [=] AMREX_GPU_DEVICE(int i, int j, int k) noexcept { // Calculate norm of vector const Real k_norm = std::sqrt( std::pow(modified_kx[i], 2) + #if (AMREX_SPACEDIM==3) std::pow(modified_ky[j], 2) + std::pow(modified_kz[k], 2)); #else std::pow(modified_kz[j], 2)); #endif // Calculate coefficients constexpr Real c = PhysConst::c; constexpr Real ep0 = PhysConst::ep0; if (k_norm != 0){ C(i,j,k) = std::cos(c*k_norm*dt); S_ck(i,j,k) = std::sin(c*k_norm*dt)/(c*k_norm); X1(i,j,k) = (1. - C(i,j,k))/(ep0 * c*c * k_norm*k_norm); X2(i,j,k) = (1. - S_ck(i,j,k)/dt)/(ep0 * k_norm*k_norm); X3(i,j,k) = (C(i,j,k) - S_ck(i,j,k)/dt)/(ep0 * k_norm*k_norm); } else { // Handle k_norm = 0, by using the analytical limit C(i,j,k) = 1.; S_ck(i,j,k) = dt; X1(i,j,k) = 0.5 * dt*dt / ep0; X2(i,j,k) = c*c * dt*dt / (6.*ep0); X3(i,j,k) = - c*c * dt*dt / (3.*ep0); } }); } }
40.776536
90
0.548431
[ "vector" ]
4f4be83679b360732db58fee93631f3dac663616
4,577
hpp
C++
include/Mono/Security/PKCS7_ContentInfo.hpp
darknight1050/BeatSaber-Quest-Codegen
a6eeecc3f0e8f6079630f9a9a72b3121ac7b2032
[ "Unlicense" ]
null
null
null
include/Mono/Security/PKCS7_ContentInfo.hpp
darknight1050/BeatSaber-Quest-Codegen
a6eeecc3f0e8f6079630f9a9a72b3121ac7b2032
[ "Unlicense" ]
null
null
null
include/Mono/Security/PKCS7_ContentInfo.hpp
darknight1050/BeatSaber-Quest-Codegen
a6eeecc3f0e8f6079630f9a9a72b3121ac7b2032
[ "Unlicense" ]
null
null
null
// Autogenerated from CppHeaderCreator // Created by Sc2ad // ========================================================================= #pragma once // Begin includes #include "extern/beatsaber-hook/shared/utils/typedefs.h" // Including type: Mono.Security.PKCS7 #include "Mono/Security/PKCS7.hpp" #include "extern/beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp" #include "extern/beatsaber-hook/shared/utils/il2cpp-utils-properties.hpp" #include "extern/beatsaber-hook/shared/utils/il2cpp-utils-fields.hpp" #include "extern/beatsaber-hook/shared/utils/utils.h" // Completed includes // Begin forward declares // Forward declaring namespace: Mono::Security namespace Mono::Security { // Forward declaring type: ASN1 class ASN1; } // Completed forward declares // Type namespace: Mono.Security namespace Mono::Security { // Size: 0x20 #pragma pack(push, 1) // Autogenerated type: Mono.Security.PKCS7/ContentInfo class PKCS7::ContentInfo : public ::Il2CppObject { public: // private System.String contentType // Size: 0x8 // Offset: 0x10 ::Il2CppString* contentType; // Field size check static_assert(sizeof(::Il2CppString*) == 0x8); // private Mono.Security.ASN1 content // Size: 0x8 // Offset: 0x18 Mono::Security::ASN1* content; // Field size check static_assert(sizeof(Mono::Security::ASN1*) == 0x8); // Creating value type constructor for type: ContentInfo ContentInfo(::Il2CppString* contentType_ = {}, Mono::Security::ASN1* content_ = {}) noexcept : contentType{contentType_}, content{content_} {} // public System.Void .ctor(System.String oid) // Offset: 0x1D5D4EC template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary> static PKCS7::ContentInfo* New_ctor(::Il2CppString* oid) { static auto ___internal__logger = ::Logger::get().WithContext("Mono::Security::PKCS7::ContentInfo::.ctor"); return THROW_UNLESS((::il2cpp_utils::New<PKCS7::ContentInfo*, creationType>(oid))); } // public System.Void .ctor(System.Byte[] data) // Offset: 0x1D5D514 template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary> static PKCS7::ContentInfo* New_ctor(::Array<uint8_t>* data) { static auto ___internal__logger = ::Logger::get().WithContext("Mono::Security::PKCS7::ContentInfo::.ctor"); return THROW_UNLESS((::il2cpp_utils::New<PKCS7::ContentInfo*, creationType>(data))); } // public System.Void .ctor(Mono.Security.ASN1 asn1) // Offset: 0x1D5D584 template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary> static PKCS7::ContentInfo* New_ctor(Mono::Security::ASN1* asn1) { static auto ___internal__logger = ::Logger::get().WithContext("Mono::Security::PKCS7::ContentInfo::.ctor"); return THROW_UNLESS((::il2cpp_utils::New<PKCS7::ContentInfo*, creationType>(asn1))); } // public Mono.Security.ASN1 get_ASN1() // Offset: 0x1D5D720 Mono::Security::ASN1* get_ASN1(); // public Mono.Security.ASN1 get_Content() // Offset: 0x1D5D7E0 Mono::Security::ASN1* get_Content(); // public System.Void set_Content(Mono.Security.ASN1 value) // Offset: 0x1D5D7E8 void set_Content(Mono::Security::ASN1* value); // public System.String get_ContentType() // Offset: 0x1D5D7F0 ::Il2CppString* get_ContentType(); // public System.Void set_ContentType(System.String value) // Offset: 0x1D5D7F8 void set_ContentType(::Il2CppString* value); // Mono.Security.ASN1 GetASN1() // Offset: 0x1D5D724 Mono::Security::ASN1* GetASN1(); // public System.Void .ctor() // Offset: 0x1D5D474 // Implemented from: System.Object // Base method: System.Void Object::.ctor() template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary> static PKCS7::ContentInfo* New_ctor() { static auto ___internal__logger = ::Logger::get().WithContext("Mono::Security::PKCS7::ContentInfo::.ctor"); return THROW_UNLESS((::il2cpp_utils::New<PKCS7::ContentInfo*, creationType>())); } }; // Mono.Security.PKCS7/ContentInfo #pragma pack(pop) static check_size<sizeof(PKCS7::ContentInfo), 24 + sizeof(Mono::Security::ASN1*)> __Mono_Security_PKCS7_ContentInfoSizeCheck; static_assert(sizeof(PKCS7::ContentInfo) == 0x20); } DEFINE_IL2CPP_ARG_TYPE(Mono::Security::PKCS7::ContentInfo*, "Mono.Security", "PKCS7/ContentInfo");
47.677083
147
0.685602
[ "object" ]
4f538d8e9f17cf74798642e3563f0379d47b5262
4,721
cpp
C++
libs/graph/test/subgraph.cpp
coxlab/boost_patched_for_objcplusplus
5316cd54bbd03994ae785185efcde62b57fd5e93
[ "BSL-1.0" ]
1
2017-07-31T02:19:48.000Z
2017-07-31T02:19:48.000Z
libs/graph/test/subgraph.cpp
boost-cmake/vintage
dcfb7da3177134eddaee6789d6f582259cb0d6ee
[ "BSL-1.0" ]
null
null
null
libs/graph/test/subgraph.cpp
boost-cmake/vintage
dcfb7da3177134eddaee6789d6f582259cb0d6ee
[ "BSL-1.0" ]
1
2021-03-07T05:20:43.000Z
2021-03-07T05:20:43.000Z
// (C) Copyright Jeremy Siek 2004 // 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 <set> #include <boost/test/minimal.hpp> #include <boost/graph/subgraph.hpp> #include <boost/graph/adjacency_list.hpp> #include <boost/graph/random.hpp> #include <boost/graph/graph_test.hpp> #include <boost/graph/iteration_macros.hpp> #include <boost/random/mersenne_twister.hpp> #include "test_graph.hpp" // UNDER CONSTRUCTION int test_main(int argc, char* argv[]) { using namespace boost; typedef adjacency_list<vecS, vecS, bidirectionalS, property<vertex_color_t, int>, property<edge_index_t, std::size_t, property<edge_weight_t, int> > > graph_t; typedef subgraph<graph_t> subgraph_t; typedef graph_traits<subgraph_t>::vertex_descriptor vertex_t; typedef graph_traits<subgraph_t>::edge_descriptor edge_t; mt19937 gen; for (int t = 0; t < 100; t += 5) { subgraph_t g; int N = t + 2; std::vector<vertex_t> vertex_set; std::vector< std::pair<vertex_t, vertex_t> > edge_set; generate_random_graph(g, N, N * 2, gen, std::back_inserter(vertex_set), std::back_inserter(edge_set)); graph_test< subgraph_t > gt; gt.test_incidence_graph(vertex_set, edge_set, g); gt.test_bidirectional_graph(vertex_set, edge_set, g); gt.test_adjacency_graph(vertex_set, edge_set, g); gt.test_vertex_list_graph(vertex_set, g); gt.test_edge_list_graph(vertex_set, edge_set, g); gt.test_adjacency_matrix(vertex_set, edge_set, g); std::vector<vertex_t> sub_vertex_set; std::vector<vertex_t> sub_global_map; std::vector<vertex_t> global_sub_map(num_vertices(g)); std::vector< std::pair<vertex_t, vertex_t> > sub_edge_set; subgraph_t& g_s = g.create_subgraph(); const std::set<vertex_t>::size_type Nsub = N/2; // Collect a set of random vertices to put in the subgraph std::set<vertex_t> verts; while (verts.size() < Nsub) verts.insert(random_vertex(g, gen)); for (std::set<vertex_t>::iterator it = verts.begin(); it != verts.end(); ++it) { vertex_t v_global = *it; vertex_t v = add_vertex(v_global, g_s); sub_vertex_set.push_back(v); sub_global_map.push_back(v_global); global_sub_map[v_global] = v; } // compute induced edges BGL_FORALL_EDGES(e, g, subgraph_t) if (container_contains(sub_global_map, source(e, g)) && container_contains(sub_global_map, target(e, g))) sub_edge_set.push_back(std::make_pair(global_sub_map[source(e, g)], global_sub_map[target(e, g)])); gt.test_incidence_graph(sub_vertex_set, sub_edge_set, g_s); gt.test_bidirectional_graph(sub_vertex_set, sub_edge_set, g_s); gt.test_adjacency_graph(sub_vertex_set, sub_edge_set, g_s); gt.test_vertex_list_graph(sub_vertex_set, g_s); gt.test_edge_list_graph(sub_vertex_set, sub_edge_set, g_s); gt.test_adjacency_matrix(sub_vertex_set, sub_edge_set, g_s); if (num_vertices(g_s) == 0) return 0; std::vector<int> weights; for (unsigned i = 0; i < num_vertices(g_s); ++i) weights.push_back(i*2); gt.test_vertex_property_graph(weights, vertex_color_t(), g_s); // A regression test: the copy constructor of subgraph did not // copy one of the members, so local_edge->global_edge mapping // was broken. { subgraph_t g; graph_t::vertex_descriptor v1, v2; v1 = add_vertex(g); v2 = add_vertex(g); add_edge(v1, v2, g); subgraph_t sub = g.create_subgraph(vertices(g).first, vertices(g).second); graph_t::edge_iterator ei, ee; for (tie(ei, ee) = edges(sub); ei != ee; ++ei) { // This used to segfault. get(edge_weight, sub, *ei); } } // Bootstrap the test_graph framework. // TODO: Subgraph is fundamentally broken for property types. // TODO: Under construction. { using namespace boost; typedef property<edge_index_t, size_t, EdgeBundle> EdgeProp; typedef adjacency_list<vecS, vecS, directedS, VertexBundle, EdgeProp> BaseGraph; typedef subgraph<BaseGraph> Graph; typedef graph_traits<Graph>::vertex_descriptor Vertex; Graph g; Vertex v = add_vertex(g); typedef property_map<Graph, int VertexBundle::*>::type BundleMap; BundleMap map = get(&VertexBundle::value, g); get(map, v); // put(map, v, 5); // BOOST_ASSERT(get(map, v) == 5); // test_graph(g); return 0; } } return 0; }
34.210145
88
0.662783
[ "vector" ]
4f53e45c06407c6de669715e41ee26c3d6d81bd0
10,866
cpp
C++
src/qt/src/gui/text/qglyphrun.cpp
ant0ine/phantomjs
8114d44a28134b765ab26b7e13ce31594fa81253
[ "BSD-3-Clause" ]
46
2015-01-08T14:32:34.000Z
2022-02-05T16:48:26.000Z
src/qt/src/gui/text/qglyphrun.cpp
ant0ine/phantomjs
8114d44a28134b765ab26b7e13ce31594fa81253
[ "BSD-3-Clause" ]
7
2015-01-20T14:28:12.000Z
2017-01-18T17:21:44.000Z
src/qt/src/gui/text/qglyphrun.cpp
ant0ine/phantomjs
8114d44a28134b765ab26b7e13ce31594fa81253
[ "BSD-3-Clause" ]
14
2015-10-27T06:17:48.000Z
2020-03-03T06:15:50.000Z
/**************************************************************************** ** ** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies). ** Contact: http://www.qt-project.org/legal ** ** This file is part of the QtGui module of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Digia. For licensing terms and ** conditions see http://qt.digia.com/licensing. For further information ** use the contact form at http://qt.digia.com/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Digia gives you certain additional ** rights. These rights are described in the Digia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 3.0 as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU General Public License version 3.0 requirements will be ** met: http://www.gnu.org/copyleft/gpl.html. ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "qglobal.h" #if !defined(QT_NO_RAWFONT) #include "qglyphrun.h" #include "qglyphrun_p.h" QT_BEGIN_NAMESPACE /*! \class QGlyphRun \brief The QGlyphRun class provides direct access to the internal glyphs in a font. \since 4.8 \ingroup text \mainclass When Qt displays a string of text encoded in Unicode, it will first convert the Unicode points into a list of glyph indexes and a list of positions based on one or more fonts. The Unicode representation of the text and the QFont object will in this case serve as a convenient abstraction that hides the details of what actually takes place when displaying the text on-screen. For instance, by the time the text actually reaches the screen, it may be represented by a set of fonts in addition to the one specified by the user, e.g. in case the originally selected font did not support all the writing systems contained in the text. Under certain circumstances, it can be useful as an application developer to have more low-level control over which glyphs in a specific font are drawn to the screen. This could for instance be the case in applications that use an external font engine and text shaper together with Qt. QGlyphRun provides an interface to the raw data needed to get text on the screen. It contains a list of glyph indexes, a position for each glyph and a font. It is the user's responsibility to ensure that the selected font actually contains the provided glyph indexes. QTextLayout::glyphRuns() or QTextFragment::glyphRuns() can be used to convert unicode encoded text into a list of QGlyphRun objects, and QPainter::drawGlyphRun() can be used to draw the glyphs. \note Please note that QRawFont is considered local to the thread in which it is constructed. This in turn means that a new QRawFont will have to be created and set on the QGlyphRun if it is moved to a different thread. If the QGlyphRun contains a reference to a QRawFont from a different thread than the current, it will not be possible to draw the glyphs using a QPainter, as the QRawFont is considered invalid and inaccessible in this case. */ /*! Constructs an empty QGlyphRun object. */ QGlyphRun::QGlyphRun() : d(new QGlyphRunPrivate) { } /*! Constructs a QGlyphRun object which is a copy of \a other. */ QGlyphRun::QGlyphRun(const QGlyphRun &other) { d = other.d; } /*! Destroys the QGlyphRun. */ QGlyphRun::~QGlyphRun() { // Required for QExplicitlySharedDataPointer } /*! \internal */ void QGlyphRun::detach() { if (d->ref != 1) d.detach(); } /*! Assigns \a other to this QGlyphRun object. */ QGlyphRun &QGlyphRun::operator=(const QGlyphRun &other) { d = other.d; return *this; } /*! Compares \a other to this QGlyphRun object. Returns true if the list of glyph indexes, the list of positions and the font are all equal, otherwise returns false. */ bool QGlyphRun::operator==(const QGlyphRun &other) const { if (d == other.d) return true; if ((d->glyphIndexDataSize != other.d->glyphIndexDataSize) || (d->glyphPositionDataSize != other.d->glyphPositionDataSize)) { return false; } if (d->glyphIndexData != other.d->glyphIndexData) { for (int i = 0; i < d->glyphIndexDataSize; ++i) { if (d->glyphIndexData[i] != other.d->glyphIndexData[i]) return false; } } if (d->glyphPositionData != other.d->glyphPositionData) { for (int i = 0; i < d->glyphPositionDataSize; ++i) { if (d->glyphPositionData[i] != other.d->glyphPositionData[i]) return false; } } return (d->overline == other.d->overline && d->underline == other.d->underline && d->strikeOut == other.d->strikeOut && d->rawFont == other.d->rawFont); } /*! \fn bool QGlyphRun::operator!=(const QGlyphRun &other) const Compares \a other to this QGlyphRun object. Returns true if any of the list of glyph indexes, the list of positions or the font are different, otherwise returns false. */ /*! Returns the font selected for this QGlyphRun object. \sa setRawFont() */ QRawFont QGlyphRun::rawFont() const { return d->rawFont; } /*! Sets the font specified by \a rawFont to be the font used to look up the glyph indexes. \sa rawFont(), setGlyphIndexes() */ void QGlyphRun::setRawFont(const QRawFont &rawFont) { detach(); d->rawFont = rawFont; } /*! Returns the glyph indexes for this QGlyphRun object. \sa setGlyphIndexes(), setPositions() */ QVector<quint32> QGlyphRun::glyphIndexes() const { if (d->glyphIndexes.constData() == d->glyphIndexData) { return d->glyphIndexes; } else { QVector<quint32> indexes(d->glyphIndexDataSize); qMemCopy(indexes.data(), d->glyphIndexData, d->glyphIndexDataSize * sizeof(quint32)); return indexes; } } /*! Set the glyph indexes for this QGlyphRun object to \a glyphIndexes. The glyph indexes must be valid for the selected font. */ void QGlyphRun::setGlyphIndexes(const QVector<quint32> &glyphIndexes) { detach(); d->glyphIndexes = glyphIndexes; // Keep a reference to the QVector to avoid copying d->glyphIndexData = glyphIndexes.constData(); d->glyphIndexDataSize = glyphIndexes.size(); } /*! Returns the position of the edge of the baseline for each glyph in this set of glyph indexes. */ QVector<QPointF> QGlyphRun::positions() const { if (d->glyphPositions.constData() == d->glyphPositionData) { return d->glyphPositions; } else { QVector<QPointF> glyphPositions(d->glyphPositionDataSize); qMemCopy(glyphPositions.data(), d->glyphPositionData, d->glyphPositionDataSize * sizeof(QPointF)); return glyphPositions; } } /*! Sets the positions of the edge of the baseline for each glyph in this set of glyph indexes to \a positions. */ void QGlyphRun::setPositions(const QVector<QPointF> &positions) { detach(); d->glyphPositions = positions; // Keep a reference to the vector to avoid copying d->glyphPositionData = positions.constData(); d->glyphPositionDataSize = positions.size(); } /*! Clears all data in the QGlyphRun object. */ void QGlyphRun::clear() { detach(); d->rawFont = QRawFont(); d->strikeOut = false; d->overline = false; d->underline = false; setPositions(QVector<QPointF>()); setGlyphIndexes(QVector<quint32>()); } /*! Sets the glyph indexes and positions of this QGlyphRun to use the first \a size elements in the arrays \a glyphIndexArray and \a glyphPositionArray. The data is \e not copied. The caller must guarantee that the arrays are not deleted as long as this QGlyphRun and any copies of it exists. \sa setGlyphIndexes(), setPositions() */ void QGlyphRun::setRawData(const quint32 *glyphIndexArray, const QPointF *glyphPositionArray, int size) { detach(); d->glyphIndexes.clear(); d->glyphPositions.clear(); d->glyphIndexData = glyphIndexArray; d->glyphPositionData = glyphPositionArray; d->glyphIndexDataSize = d->glyphPositionDataSize = size; } /*! Returns true if this QGlyphRun should be painted with an overline decoration. \sa setOverline() */ bool QGlyphRun::overline() const { return d->overline; } /*! Indicates that this QGlyphRun should be painted with an overline decoration if \a overline is true. Otherwise the QGlyphRun should be painted with no overline decoration. \sa overline() */ void QGlyphRun::setOverline(bool overline) { if (d->overline == overline) return; detach(); d->overline = overline; } /*! Returns true if this QGlyphRun should be painted with an underline decoration. \sa setUnderline() */ bool QGlyphRun::underline() const { return d->underline; } /*! Indicates that this QGlyphRun should be painted with an underline decoration if \a underline is true. Otherwise the QGlyphRun should be painted with no underline decoration. \sa underline() */ void QGlyphRun::setUnderline(bool underline) { if (d->underline == underline) return; detach(); d->underline = underline; } /*! Returns true if this QGlyphRun should be painted with a strike out decoration. \sa setStrikeOut() */ bool QGlyphRun::strikeOut() const { return d->strikeOut; } /*! Indicates that this QGlyphRun should be painted with an strike out decoration if \a strikeOut is true. Otherwise the QGlyphRun should be painted with no strike out decoration. \sa strikeOut() */ void QGlyphRun::setStrikeOut(bool strikeOut) { if (d->strikeOut == strikeOut) return; detach(); d->strikeOut = strikeOut; } QT_END_NAMESPACE #endif // QT_NO_RAWFONT
30.267409
101
0.690134
[ "object", "vector" ]
4f541a7b28a27eef32ffe9998749c3b0dbd5d5c5
2,188
cpp
C++
test/cpp-raw/interface_params.cpp
adrianwithah/intercom-example
30e6860af2a493447753b620370d5136613d00c5
[ "MIT" ]
null
null
null
test/cpp-raw/interface_params.cpp
adrianwithah/intercom-example
30e6860af2a493447753b620370d5136613d00c5
[ "MIT" ]
null
null
null
test/cpp-raw/interface_params.cpp
adrianwithah/intercom-example
30e6860af2a493447753b620370d5136613d00c5
[ "MIT" ]
null
null
null
#include "../cpp-utility/os.hpp" #include "../cpp-utility/catch.hpp" #define INTERCOM_FLATTEN_DECLARATIONS #include "testlib.hpp" #include <intercom.hpp> class CppImplementation : public ISharedInterface_Automation { virtual unsigned int INTERCOM_CC GetValue() { return 5; } // These two are not used. virtual void INTERCOM_CC SetValue( unsigned int v ) { } virtual intercom::HRESULT INTERCOM_CC DivideBy( ISharedInterface_Automation* divisor, OUT unsigned int* result ) { return intercom::EC_NOTIMPL; } virtual intercom::HRESULT INTERCOM_CC QueryInterface( const intercom::IID& riid, void** out ) { return intercom::EC_NOTIMPL; } virtual intercom::REF_COUNT_32 INTERCOM_CC AddRef() { return 1; } virtual intercom::REF_COUNT_32 INTERCOM_CC Release() { return 1; } }; TEST_CASE( "Methods accept COM interfaces as parameters." ) { // Initialize COM. InitializeRuntime(); // Get the first SharedImplementation object. ISharedInterface_Automation* pItf1 = nullptr; intercom::HRESULT hr = CreateInstance( CLSID_SharedImplementation, IID_ISharedInterface_Automation, &pItf1 ); REQUIRE( hr == intercom::SC_OK ); // Get the second SharedImplementation object. ISharedInterface_Automation* pItf2 = nullptr; hr = CreateInstance( CLSID_SharedImplementation, IID_ISharedInterface_Automation, &pItf2 ); REQUIRE( hr == intercom::SC_OK ); REQUIRE( pItf1 != nullptr ); REQUIRE( pItf2 != nullptr ); SECTION( "Rust CoClass can be used as a parameter." ) { pItf1->SetValue( 10 ); pItf2->SetValue( 2 ); unsigned int value = 0; hr = pItf1->DivideBy( pItf2, OUT &value ); REQUIRE( hr == intercom::SC_OK ); REQUIRE( value == 5 ); } SECTION( "C++ implementation can be used as a parameter." ) { pItf1->SetValue( 10 ); CppImplementation cppImpl; unsigned int value = 0; hr = pItf1->DivideBy( &cppImpl, OUT &value ); REQUIRE( hr == intercom::SC_OK ); REQUIRE( value == 2 ); } pItf1->Release(); pItf2->Release(); UninitializeRuntime(); }
28.789474
130
0.655393
[ "object" ]
4f543db12a5a4800a9e5c9742fadfe2e6393a3b4
42,476
cpp
C++
ugene/src/plugins_3rdparty/hmm3/src/hmmer3/easel/esl_tree.cpp
iganna/lspec
c75cba3e4fa9a46abeecbf31b5d467827cf4fec0
[ "MIT" ]
null
null
null
ugene/src/plugins_3rdparty/hmm3/src/hmmer3/easel/esl_tree.cpp
iganna/lspec
c75cba3e4fa9a46abeecbf31b5d467827cf4fec0
[ "MIT" ]
null
null
null
ugene/src/plugins_3rdparty/hmm3/src/hmmer3/easel/esl_tree.cpp
iganna/lspec
c75cba3e4fa9a46abeecbf31b5d467827cf4fec0
[ "MIT" ]
null
null
null
/* Phylogenetic trees. * * Contents: * 1. The ESL_TREE object. * 2. Newick format i/o * 3. Tree comparison algorithms. * 4. Clustering algorithms for distance-based tree construction. * 5. Generating simulated trees. * 9. Copyright notice and license. * * SVN $Id: esl_tree.c 326 2009-02-28 15:49:07Z eddys $ * SRE, Tue May 2 14:08:42 2006 [St. Louis] */ #include <hmmer3/easel/esl_config.h> #include <math.h> #include <string.h> #include <ctype.h> #include <assert.h> #include <hmmer3/easel/easel.h> #include <hmmer3/hmmer.h> #include <hmmer3/easel/esl_dmatrix.h> #include <hmmer3/easel/esl_stack.h> #include <hmmer3/easel/esl_vectorops.h> #include <hmmer3/easel/esl_random.h> #include "esl_tree.h" /***************************************************************** * 1. The ESL_TREE object. *****************************************************************/ /* Function: esl_tree_Create() * Incept: SRE, Tue May 2 14:10:17 2006 [St. Louis] * * Purpose: Allocate an empty tree structure for <ntaxa> taxa * and return a pointer to it. <ntaxa> must be $\geq 2$. * * Args: <ntaxa> - number of taxa * * Returns: pointer to the new <ESL_TREE> object; caller frees * this with <esl_tree_Destroy()>. * * Throws: <NULL> if allocation fails. */ ESL_TREE * esl_tree_Create(int ntaxa) { ESL_TREE *T = NULL; int i; int status; /* Contract verification */ ESL_DASSERT1((ntaxa >= 2)); /* 1st allocation round */ ESL_ALLOC_WITH_TYPE(T, ESL_TREE*, sizeof(ESL_TREE)); T->parent = NULL; T->left = NULL; T->right = NULL; T->ld = NULL; T->rd = NULL; /* 2nd allocation round */ T->N = ntaxa; ESL_ALLOC_WITH_TYPE(T->parent, int*, sizeof(int) * (ntaxa-1)); ESL_ALLOC_WITH_TYPE(T->left, int*, sizeof(int) * (ntaxa-1)); ESL_ALLOC_WITH_TYPE(T->right, int*, sizeof(int) * (ntaxa-1)); ESL_ALLOC_WITH_TYPE(T->ld, double*, sizeof(double) * (ntaxa-1)); ESL_ALLOC_WITH_TYPE(T->rd, double*, sizeof(double) * (ntaxa-1)); for (i = 0; i < ntaxa-1; i++) { T->parent[i] = 0; T->left[i ] = 0; T->right[i] = 0; T->ld[i] = 0.; T->rd[i] = 0.; } /* Optional info starts NULL */ T->taxaparent = NULL; T->cladesize = NULL; T->taxonlabel = NULL; T->nodelabel = NULL; /* Additive trees are assumed by default, as opposed to linkage trees */ T->is_linkage_tree = FALSE; /* Tree output options default to PHYLIP style */ T->show_unrooted = FALSE; T->show_node_labels = TRUE; T->show_root_branchlength = FALSE; T->show_branchlengths = TRUE; T->show_quoted_labels = FALSE; T->show_numeric_taxonlabels = TRUE; T->nalloc = ntaxa; return T; ERROR: esl_tree_Destroy(T); return NULL; } /* Function: esl_tree_CreateGrowable() * Incept: SRE, Mon Nov 13 14:22:22 2006 [Janelia] * * Purpose: Allocate a growable tree structure for an initial * allocation of <nalloc> taxa, and return a pointer to it. * <nalloc> must be $\geq 2$. * * Args: <nalloc> - initial allocation size for number of taxa * * Returns: pointer to a new growable <ESL_TREE> object; caller frees * this with <esl_tree_Destroy()>. * * Throws: <NULL> if allocation fails. */ ESL_TREE * esl_tree_CreateGrowable(int nalloc) { ESL_TREE *T = esl_tree_Create(nalloc); if (T == NULL) return NULL; T->N = 0; return T; } // ! Here was esl_treeCreateFromString function // ! but we don't need it and it uses ReadNewick format function /* Function: esl_tree_Grow() * Incept: SRE, Fri Oct 27 08:49:47 2006 [Janelia] * * Purpose: Given a tree <T>, make sure it can hold one more taxon; * reallocate internally if necessary by doubling the * number of taxa it is currently allocated to hold. * * Returns: <eslOK> on success. * * Throws: <eslEMEM> on allocation failure. In this case, * the data in the tree are unaffected. */ int esl_tree_Grow(ESL_TREE *T) { void *tmp; int nnew; int status; int i; if (T->N < T->nalloc) return eslOK; /* do we have room for next taxon? */ nnew = T->nalloc * 2; /* There are N-1 interior nodes, so arrays of info for * interior nodes are allocated for (nnew-1), whereas * arrays of info for the N taxa are allocated (nnew). */ ESL_RALLOC_WITH_TYPE(T->parent, int*, tmp, sizeof(int) * (nnew-1)); ESL_RALLOC_WITH_TYPE(T->left, int*, tmp, sizeof(int) * (nnew-1)); ESL_RALLOC_WITH_TYPE(T->right, int*, tmp, sizeof(int) * (nnew-1)); ESL_RALLOC_WITH_TYPE(T->ld, double*, tmp, sizeof(double) * (nnew-1)); ESL_RALLOC_WITH_TYPE(T->rd, double*, tmp, sizeof(double) * (nnew-1)); /* 0..N-2 were already initialized or used. * Initialize newly alloced space N-1..nnew-2. */ for (i = T->nalloc-1; i < nnew-1; i++) { T->parent[i] = 0; T->left[i ] = 0; T->right[i] = 0; T->ld[i] = 0.; T->rd[i] = 0.; } if (T->taxaparent != NULL) { ESL_RALLOC_WITH_TYPE(T->taxaparent, int*, tmp, sizeof(int) * nnew); for (i = T->nalloc; i < nnew; i++) T->taxaparent[i] = 0; } if (T->cladesize != NULL) { ESL_RALLOC_WITH_TYPE(T->cladesize, int*, tmp, sizeof(int) * nnew); for (i = T->nalloc; i < nnew; i++) T->cladesize[i] = 0; } if (T->taxonlabel != NULL) { ESL_RALLOC_WITH_TYPE(T->taxonlabel, char**, tmp, sizeof(char *) * nnew); for (i = T->nalloc; i < nnew; i++) T->taxonlabel[i] = NULL; } if (T->nodelabel != NULL) { ESL_RALLOC_WITH_TYPE(T->nodelabel, char**, tmp, sizeof(char *) * (nnew-1)); for (i = T->nalloc-1; i < nnew-1; i++) T->nodelabel[i] = NULL; } T->nalloc = nnew; return eslOK; ERROR: return eslEMEM; } /* Function: esl_tree_SetTaxaParents() * Incept: SRE, Fri Sep 22 13:39:49 2006 [Janelia] * * Purpose: Constructs the <T->taxaparent[]> array in the tree * structure <T>, by an O(N) traversal of the tree. * Upon return, <T->taxaparent[i]> is the index * of the internal node that taxon <i> is a child of. * * Args: T - the tree structure to map * * Returns: <eslOK> on success. * * Throws: <eslEMEM> on internal allocation error. In this case, the tree is * returned unchanged. * * Xref: STL11/63 */ int esl_tree_SetTaxaParents(ESL_TREE *T) { int i; int status; if (T->taxaparent != NULL) return eslOK; /* map already exists. */ ESL_ALLOC_WITH_TYPE(T->taxaparent, int*, sizeof(int) * T->N); for (i = 0; i < T->N-1; i++) /* traversal order doesn't matter */ { if (T->left[i] <= 0) T->taxaparent[-(T->left[i])] = i; if (T->right[i] <= 0) T->taxaparent[-(T->right[i])] = i; } return eslOK; ERROR: if (T->taxaparent != NULL) { free(T->taxaparent); T->taxaparent = NULL; } return status; } /* Function: esl_tree_SetCladesizes() * Incept: SRE, Thu Nov 9 10:03:17 2006 [Janelia] * * Purpose: Constructs the <T->cladesize[]> array in tree structure * <T>. Upon successful return, <T->cladesize[i]> is the * number of taxa contained by the clade rooted at node <i> * in the tree. For example, <T->cladesize[0]> is $N$ by * definition, because 0 is the root of the tree. * * Returns: <eslOK> on success. * * Throws: <eslEMEM> on allocation error; in this case, the * original <T> is unmodified. */ int esl_tree_SetCladesizes(ESL_TREE *T) { int i; int status; if (T->cladesize != NULL) return eslOK; /* already set. */ ESL_ALLOC_WITH_TYPE(T->cladesize, int*, sizeof(int) * (T->N-1)); esl_vec_ISet(T->cladesize, T->N-1, 0); for (i = T->N-2; i >= 0; i--) { /* taxon: ...else... internal node: */ if (T->left[i] <= 0) T->cladesize[i]++; else T->cladesize[i] += T->cladesize[T->left[i]]; if (T->right[i] <= 0) T->cladesize[i]++; else T->cladesize[i] += T->cladesize[T->right[i]]; } return eslOK; ERROR: if (T->cladesize != NULL) { free(T->cladesize); T->cladesize = NULL; } return status; } /* Function: esl_tree_SetTaxonlabels() * Incept: SRE, Tue Nov 14 19:29:00 2006 [UA 921, IAD-SFO] * * Purpose: Given an array of taxon names <names[0..N-1]> with the * same order and number as the taxa in tree <T>, make a * copy of those names in <T>. For example, <names> might * be the sequence names in a multiple alignment, * <msa->sqname>. * * If the tree already had taxon names assigned to it, they * are replaced. * * As a special case, if the <names> argument is passed as * <NULL>, then the taxon labels are set to a string * corresponding to their internal index; that is, taxon 0 * is labeled "0". * * Returns: <eslOK> on success, and internal state of <T> * (specifically, <T->taxonlabel[]>) now contains a copy * of the taxa names. * * Throws: <eslEMEM> on allocation failure. <T->taxonlabel[]> will be * <NULL> (even if it was already set). */ int esl_tree_SetTaxonlabels(ESL_TREE *T, char **names) { int i; int status; if (T->taxonlabel != NULL) esl_Free2D((void **) T->taxonlabel, T->N); ESL_ALLOC_WITH_TYPE(T->taxonlabel, char**, sizeof(char **) * T->nalloc); for (i = 0; i < T->nalloc; i++) T->taxonlabel[i] = NULL; if (names != NULL) { for (i = 0; i < T->N; i++) if ((status = esl_strdup(names[i], -1, &(T->taxonlabel[i]))) != eslOK) goto ERROR; } else { for (i = 0; i < T->N; i++) { ESL_ALLOC_WITH_TYPE(T->taxonlabel[i], char*, sizeof(char) * 32); /* enough width for any conceivable int */ snprintf(T->taxonlabel[i], 32, "%d", i); } } return eslOK; ERROR: if (T->taxonlabel != NULL) esl_Free2D((void **) T->taxonlabel, T->nalloc); return status; } /* Function: esl_tree_RenumberNodes() * Synopsis: Assure nodes are numbered in preorder. * Incept: SRE, Fri Oct 27 09:33:26 2006 [Janelia] * * Purpose: Given a tree <T> whose internal nodes might be numbered in * any order, with the sole requirement that node 0 is the * root; renumber the internal nodes (if necessary) to be in Easel's * convention of preorder traversal. No other aspect of <T> is * altered (including its allocation size). * * Returns: <eslOK> on success. * * Throws: <eslEMEM> on allocation failure. * * Xref: STL11/77 */ int esl_tree_RenumberNodes(ESL_TREE *T) { ESL_TREE *T2 = NULL; ESL_STACK *vs = NULL; int *map = NULL; int v,newI; int status; int needs_rearranging = FALSE; /* Pass 1. Preorder traverse of T by its children links; * construct map[old] -> new. */ ESL_ALLOC_WITH_TYPE(map, int*, sizeof(int) * (T->N-1)); if (( vs = esl_stack_ICreate()) == NULL) { status = eslEMEM; goto ERROR; }; if (esl_stack_IPush(vs, 0) != eslOK) { status = eslEMEM; goto ERROR; }; newI = 0; while (esl_stack_IPop(vs, &v) == eslOK) { if (v != newI) needs_rearranging = TRUE; map[v] = newI++; if (T->right[v] > 0 && esl_stack_IPush(vs, T->right[v]) != eslOK) { status = eslEMEM; goto ERROR; }; if (T->left[v] > 0 && esl_stack_IPush(vs, T->left[v]) != eslOK) { status = eslEMEM; goto ERROR; }; } if (! needs_rearranging) { status = eslOK; goto ERROR; } /* not an error; just cleaning up & returning eslOK. */ /* Pass 2. Construct the guts of correctly numbered new T2. * (traversal order doesn't matter here) */ if (( T2 = esl_tree_Create(T->nalloc)) == NULL) { status = eslEMEM; goto ERROR; }; T2->N = T->N; if (T->nodelabel != NULL) { ESL_ALLOC_WITH_TYPE(T2->nodelabel, char**, sizeof(char *) * (T2->nalloc-1)); for (v = 0; v < T2->nalloc-1; v++) T2->nodelabel[v] = NULL; } if (T->taxaparent != NULL) { ESL_ALLOC_WITH_TYPE(T2->taxaparent, int*, sizeof(int) * (T2->nalloc)); for (v = 0; v < T2->nalloc; v++) T2->taxaparent[v] = 0; } for (v = 0; v < T->N-1; v++) { T2->parent[map[v]] = map[T->parent[v]]; if (T->left[v] > 0) T2->left[map[v]] = map[T->left[v]]; /* internal nodes renumbered... */ else T2->left[map[v]] = T->left[v]; /* ...taxon indices unchanged */ if (T->right[v] > 0) T2->right[map[v]] = map[T->right[v]]; else T2->right[map[v]] = T->right[v]; T2->ld[map[v]] = T->ld[v]; T2->rd[map[v]] = T->rd[v]; if (T->taxaparent != NULL) { if (T->left[v] <= 0) T2->taxaparent[T->left[v]] = map[v]; if (T->right[v] <= 0) T2->taxaparent[T->right[v]] = map[v]; } if (T->nodelabel != NULL) T2->nodelabel[map[v]] = T2->nodelabel[v]; } /* Finally, swap the new guts of T2 with the old guts of T; * destroy T2 and return. T is now renumbered. */ ESL_SWAP(T->parent, T2->parent, int *); ESL_SWAP(T->left, T2->left, int *); ESL_SWAP(T->right, T2->right, int *); ESL_SWAP(T->ld, T2->ld, double *); ESL_SWAP(T->rd, T2->rd, double *); ESL_SWAP(T->taxaparent, T2->taxaparent, int *); ESL_SWAP(T->nodelabel, T2->nodelabel, char **); free(map); esl_stack_Destroy(vs); esl_tree_Destroy(T2); return eslOK; ERROR: if (map != NULL) free(map); if (vs != NULL) esl_stack_Destroy(vs); if (T2 != NULL) esl_tree_Destroy(T2); return status; } /* Function: esl_tree_VerifyUltrametric() * Incept: SRE, Tue Nov 7 15:25:40 2006 [Janelia] * * Purpose: Verify that tree <T> is ultrametric. * * Returns: <eslOK> if so; <eslFAIL> if not. * * Throws: <eslEMEM> on an allocation failure. */ int esl_tree_VerifyUltrametric(ESL_TREE *T) { double *d = NULL; /* Distance from root for each OTU */ int status; int i, child, parent; /* First, calculate distance from root to each taxon. * (This chunk of code might be useful to put on its own someday.) */ ESL_ALLOC_WITH_TYPE(d, double*, sizeof(double) * T->N); if ((status = esl_tree_SetTaxaParents(T)) != eslOK) goto ERROR; for (i = 0; i < T->N; i++) { d[i] = 0.0; child = i; parent = T->taxaparent[i]; if (T->left[parent] == -i) d[i] += T->ld[parent]; else if (T->right[parent] == -i) d[i] += T->rd[parent]; else ESL_XEXCEPTION(eslEINCONCEIVABLE, "oops"); while (parent != 0) /* upwards to the root */ { child = parent; parent = T->parent[child]; if (T->left[parent] == child) d[i] += T->ld[parent]; else if (T->right[parent] == child) d[i] += T->rd[parent]; else ESL_XEXCEPTION(eslEINCONCEIVABLE, "oops"); } } /* In an ultrametric tree, all those distances must be equal. */ for (i = 1; i < T->N; i++) if ((status = esl_DCompare(d[0], d[i], 0.0001)) != eslOK) break; free(d); return status; ERROR: if (d != NULL) free(d); return status; } /* Function: esl_tree_Validate() * Incept: SRE, Thu Nov 9 11:03:04 2006 [Janelia] * * Purpose: Validates the integrity of the data structure in <T>. * Returns <eslOK> if the internal data in <T> are * consistent and valid. Returns <eslFAIL> if not, * and if a non-<NULL> message buffer <errbuf> has been * provided by the caller, an informative message is * left in <errbuf> describing the reason for the * failure. * * Args: T - tree structure to validate * errbuf - NULL, or a buffer of at least p7_ERRBUFSIZE * chars to contain an error message upon * any validation failure. */ int esl_tree_Validate(ESL_TREE *T, char *errbuf) { int N; int i, c; int shouldbe; int status; if (errbuf != NULL) *errbuf = 0; N = T->N; /* just to save writing T->N so many times below */ if (N < 2) ESL_XFAIL(eslFAIL, errbuf, "number of taxa is less than 2"); if (T->parent[0] != 0) ESL_XFAIL(eslFAIL, errbuf, "parent of root 0 should be set to 0"); if (T->nalloc < N) ESL_XFAIL(eslFAIL, errbuf, "number of taxa N is less than allocation"); /* Verify preorder tree numbering. */ for (i = 0; i < N-1; i++) { if (T->left[i] > 0 && T->left[i] < i) ESL_XFAIL(eslFAIL, errbuf, "l child of node %d not in preorder", i); if (T->right[i] > 0 && T->right[i] < i) ESL_XFAIL(eslFAIL, errbuf, "r child of node %d not in preorder", i); } /* Range checks on values. */ for (i = 0; i < N-1; i++) { if (T->parent[i] < 0 || T->parent[i] > N-2) ESL_XFAIL(eslFAIL, errbuf, "parent idx of node %d invalid", i); if (T->left[i] < -(N-1) || T->left[i] > N-2) ESL_XFAIL(eslFAIL, errbuf, "left child idx of node %d invalid", i); if (T->right[i] < -(N-1) || T->right[i] > N-2) ESL_XFAIL(eslFAIL, errbuf, "right child idx of node %d invalid", i); if (T->ld[i] < 0.) ESL_XFAIL(eslFAIL, errbuf, "negative l branch length at node %d", i); if (T->rd[i] < 0.) ESL_XFAIL(eslFAIL, errbuf, "negative r branch length at node %d", i); if (T->cladesize != NULL && (T->cladesize[i] < 0 || T->cladesize[i] > N)) ESL_XFAIL(eslFAIL, errbuf, "invalid cladesize at node %d", i); } for (c = 0; c < N; c++) if (T->taxaparent != NULL && (T->taxaparent[c] < 0 || T->taxaparent[c] > N-2)) ESL_XFAIL(eslFAIL, errbuf, "invalid taxaparent at node %d", c); /* more sophisticated integrity checks on parent-child relations in nodes ...*/ for (i = 1; i < T->N-1; i++) if (T->left[T->parent[i]] != i && T->right[T->parent[i]] != i) ESL_XFAIL(eslFAIL, errbuf, "parent/child link discrepancy at internal node %d\n", i); /* ...and between terminal nodes and taxa. */ if (T->taxaparent != NULL) for (c = 0; c < T->N; c++) if (T->left[T->taxaparent[c]] != -c && T->right[T->taxaparent[c]] != -c) ESL_XFAIL(eslFAIL, errbuf, "parent/child link discrepancy at taxon %d\n", c); /* check on cladesizes */ if (T->cladesize != NULL) for (i = 0; i < T->N-1; i++) { shouldbe = 0; if (T->left[i] > 0) shouldbe += T->cladesize[T->left[i]]; else shouldbe++; if (T->right[i] > 0) shouldbe += T->cladesize[T->right[i]]; else shouldbe++; if (shouldbe != T->cladesize[i]) ESL_XFAIL(eslFAIL, errbuf, "incorrect cladesize at node %d", i); } return eslOK; ERROR: return status; } /* Function: esl_tree_Destroy() * Incept: SRE, Tue May 2 14:18:31 2006 [St. Louis] * * Purpose: Frees an <ESL_TREE> object. */ void esl_tree_Destroy(ESL_TREE *T) { if (T == NULL) return; if (T->parent != NULL) free(T->parent); if (T->left != NULL) free(T->left); if (T->right != NULL) free(T->right); if (T->ld != NULL) free(T->ld); if (T->rd != NULL) free(T->rd); if (T->taxaparent != NULL) free(T->taxaparent); if (T->cladesize != NULL) free(T->cladesize); if (T->taxonlabel != NULL) esl_Free2D((void **) T->taxonlabel, T->nalloc); if (T->nodelabel != NULL) esl_Free2D((void **) T->nodelabel, T->nalloc-1); free(T); return; } /*----------------- end, ESL_TREE object -----------------------*/ // ! here were Newick format io functions. We don't need them /***************************************************************** * 3. Tree comparison algorithms *****************************************************************/ /* Function: esl_tree_Compare() * Incept: SRE, Fri Sep 22 14:05:09 2006 [Janelia] * * Purpose: Given two trees <T1> and <T2> for the same * set of <N> taxa, compare the topologies of the * two trees. * * The routine must be able to determine which taxa are * equivalent in <T1> and <T2>. If <T1> and <T2> both have * taxon labels set, then the routine compares labels. * This is the usual case. (Therefore, the <N> labels must * all be different, or the routine will be unable to do * this mapping uniquely.) As a special case, if neither * <T1> nor <T2> has taxon labels, then the indexing of * taxa <0..N-1> is assumed to be exactly the same in the * two trees. (And if one tree has labels and the other * does not, an <eslEINVAL> exception is thrown.) * * For comparing unrooted topologies, be sure that <T1> and * <T2> both obey the unrooted tree convention that the * "root" is placed on the branch to taxon 0. (That is, * <T->left[0] = 0>.) * * Returns: <eslOK> if tree topologies are identical. <eslFAIL> * if they aren't. * * Throws: <eslEMEM> on allocation error. <eslEINVAL> if the taxa in * the trees can't be mapped uniquely and completely to * each other (because one tree doesn't have labels and * one does, or because the labels aren't unique, or the * two trees have different taxa). */ int esl_tree_Compare(ESL_TREE *T1, ESL_TREE *T2) { int *Mg = NULL; /* the M(g) tree-mapping function for internal nodes [0..N-2] */ int *Mgt = NULL; /* the M(g) tree-mapping function for leaves (taxa), [0..N-1] */ int g, child; /* node indices for parent, children */ int a,b; int status; if (T1->N != T2->N) ESL_EXCEPTION(eslEINVAL, "trees don't have the same # of taxa"); /* We need taxon parent map in tree 2, but not tree 1. */ if ((status = esl_tree_SetTaxaParents(T2)) != eslOK) goto ERROR; /* We're going to use the tree mapping function M(g) [Goodman79]. * In the implementation here, we split it into two, Mg[] for internal * nodes 0..N-2 and Mgt[] for taxa 0..N-1. * * Mg[g] for node g in T1 is the index of the lowest node in T2 * that contains the same children taxa as the subtree * under g in T1. * * For the taxa, Mgt[g] for taxon g in T1 is the index of the * corresponding taxon in T2. If neither tree has taxon labels * Mgt[g] = g for all g. Otherwise we have to compare labels. Right * now, we do this by brute force, which is O(N^2); if this ever * becomes rate limiting, replace it with a keyhash to make it O(N) * (and in fact, the keyhash of taxon names could even become part * of the ESL_TREE). */ ESL_ALLOC_WITH_TYPE(Mg, int*, sizeof(int) * (T1->N-1)); ESL_ALLOC_WITH_TYPE(Mgt, int*, sizeof(int) * (T1->N)); if (T1->taxonlabel != NULL && T2->taxonlabel != NULL) { esl_vec_ISet(Mgt, T1->N, -1); /* flags for "unset" */ for (a = 0; a < T1->N; a++) { for (b = 0; b < T1->N; b++) if (strcmp(T1->taxonlabel[a], T2->taxonlabel[b]) == 0) { Mgt[a] = b; break; } } for (a = 0; a < T1->N; a++) if (Mgt[a] == -1) ESL_XEXCEPTION(eslEINVAL, "couldn't map taxa"); } else if (T1->taxonlabel == NULL && T2->taxonlabel == NULL) { for (a = 0; a < T1->N; a++) Mgt[a] = a; } else ESL_XEXCEPTION(eslEINVAL, "either both trees must have taxon labels, or neither"); /* Finally, we use the SDI algorithm [ZmasekEddy01] to construct * M(g) for internal nodes, by postorder traversal of T1. */ for (g = T1->N-2; g >= 0; g--) { child = T1->left[g]; if (child <= 0) a = T2->taxaparent[Mgt[-child]]; else a = T2->parent[Mg[child]]; child = T1->right[g]; if (child <= 0) b = T2->taxaparent[Mgt[-child]]; else b = T2->parent[Mg[child]]; /* a shortcut in SDI: special case for exact tree comparison: */ if (a != b) { free(Mg); free(Mgt); return eslFAIL; } Mg[g] = a; } free(Mg); free(Mgt); return eslOK; ERROR: if (Mg != NULL) free(Mg); if (Mgt != NULL) free(Mgt); return status; } /*----------------- end, tree comparison -----------------------*/ /***************************************************************** * 4. Clustering algorithms for tree construction. *****************************************************************/ /* cluster_engine() * * Implements four clustering algorithms for tree construction: * UPGMA, WPGMA, single-linkage, and maximum-linkage. These differ * only by the rule used to construct new distances after joining * two clusters i,j. * * Input <D_original> is a symmetric distance matrix, for <D->n> taxa. * The diagonal is all 0's, and off-diagonals are $\geq 0$. <D->n> * must be at least two. * * <mode> is one of <eslUPGMA>, <eslWPGMA>, <eslSINGLE_LINKAGE>, or * <eslCOMPLETE_LINKAGE>: a flag specifying which algorithm to use. * * The output is a tree structure, returned in <ret_T>. * * Returns <eslOK> on success. * * Throws <eslEMEM> on allocation failure. * * Complexity: O(N^2) in memory, O(N^3) in time. * * This function can be optimized. Memory usage is at least * 4x more than necessary. First, we don't need to make a copy of D * if the caller doesn't mind it being consumed. Second, D only * needs to be lower- or upper-triangular, because it's symmetric, * but that requires changing dmatrix module. In time, * O(N^2 log N) if not O(N^2) should be possible, by being more * sophisticated about identifying the minimum element; * see Gronau and Moran (2006). * */ static int cluster_engine(ESL_DMATRIX *D_original, int mode, ESL_TREE **ret_T) { ESL_DMATRIX *D = NULL; ESL_TREE *T = NULL; double *height = NULL; /* height of internal nodes [0..N-2] */ int *idx = NULL; /* taxa or node index of row/col in D [0..N-1] */ int *nin = NULL; /* # of taxa in clade in row/col in D [0..N-1] */ int N; int i = 0, j = 0; int row,col; double minD; int status; /* Contract checks. */ ESL_DASSERT1((D_original != NULL)); /* matrix exists */ ESL_DASSERT1((D_original->n == D_original->m)); /* D is NxN square */ ESL_DASSERT1((D_original->n >= 2)); /* >= 2 taxa */ #if (eslDEBUGLEVEL >=1) for (i = 0; i < D_original->n; i++) { assert(D_original->mx[i][i] == 0.); /* self-self d = 0 */ for (j = i+1; j < D_original->n; j++) /* D symmetric */ assert(D_original->mx[i][j] == D_original->mx[j][i]); } #endif /* Allocations. * NxN copy of the distance matrix, which we'll iteratively whittle down to 2x2; * tree for N taxa; */ if ((D = esl_dmatrix_Clone(D_original)) == NULL) return eslEMEM; if ((T = esl_tree_Create(D->n)) == NULL) return eslEMEM; ESL_ALLOC_WITH_TYPE(idx, int*, sizeof(int) * D->n); ESL_ALLOC_WITH_TYPE(nin, int*, sizeof(int) * D->n); ESL_ALLOC_WITH_TYPE(height, double*, sizeof(double) * (D->n-1)); for (i = 0; i < D->n; i++) idx[i] = -i; /* assign taxa indices to row/col coords */ for (i = 0; i < D->n; i++) nin[i ] = 1; /* each cluster starts as 1 */ for (i = 0; i < D->n-1; i++) height[i] = 0.; /* If we're doing either single linkage or complete linkage clustering, * we will construct a "linkage tree", where ld[v], rd[v] "branch lengths" * below node v are the linkage value for clustering node v; thus * ld[v] == rd[v] in a linkage tree. * For UPGMA or WPGMA, we're building an additive tree, where ld[v] and * rd[v] are branch lengths. */ if (mode == eslSINGLE_LINKAGE || mode == eslCOMPLETE_LINKAGE) T->is_linkage_tree = TRUE; for (N = D->n; N >= 2; N--) { /* Find minimum in our current N x N matrix. * (Don't init minD to -infinity; linkage trees use sparse distance matrices * with -infinity representing unlinked.) */ minD = D->mx[0][1]; i = 0; j = 1; /* init with: if nothing else, try to link 0-1 */ for (row = 0; row < N; row++) for (col = row+1; col < N; col++) if (D->mx[row][col] < minD) { minD = D->mx[row][col]; i = row; j = col; } /* We're joining node at row/col i with node at row/col j. * Add node (index = N-2) to the tree at height minD/2. */ T->left[N-2] = idx[i]; T->right[N-2] = idx[j]; if (T->is_linkage_tree) height[N-2] = minD; else height[N-2] = minD / 2.; /* Set the branch lengths (additive trees) or heights (linkage trees) */ T->ld[N-2] = T->rd[N-2] = height[N-2]; if (! T->is_linkage_tree) { if (idx[i] > 0) T->ld[N-2] -= height[idx[i]]; if (idx[j] > 0) T->rd[N-2] -= height[idx[j]]; } /* If either node was an internal node, record parent in it. */ if (idx[i] > 0) T->parent[idx[i]] = N-2; if (idx[j] > 0) T->parent[idx[j]] = N-2; /* Now, build a new matrix by merging row i+j and col i+j. * 1. move j to N-1 (unless it's already there) * 2. move i to N-2 (unless it's already there) */ if (j != N-1) { for (row = 0; row < N; row++) ESL_SWAP(D->mx[row][N-1], D->mx[row][j], double); for (col = 0; col < N; col++) ESL_SWAP(D->mx[N-1][col], D->mx[j][col], double); ESL_SWAP(idx[j], idx[N-1], int); ESL_SWAP(nin[j], nin[N-1], int); } if (i != N-2) { for (row = 0; row < N; row++) ESL_SWAP(D->mx[row][N-2], D->mx[row][i], double); for (col = 0; col < N; col++) ESL_SWAP(D->mx[N-2][col], D->mx[i][col], double); ESL_SWAP(idx[i], idx[N-2], int); ESL_SWAP(nin[i], nin[N-2], int); } i = N-2; j = N-1; /* 3. merge i (now at N-2) with j (now at N-1) * according to the desired clustering rule. */ for (col = 0; col < N; col++) { switch (mode) { case eslUPGMA: D->mx[i][col] = (nin[i] * D->mx[i][col] + nin[j] * D->mx[j][col]) / (double) (nin[i] + nin[j]); break; case eslWPGMA: D->mx[i][col] = (D->mx[i][col] + D->mx[j][col]) / 2.; break; case eslSINGLE_LINKAGE: D->mx[i][col] = ESL_MIN(D->mx[i][col], D->mx[j][col]); break; case eslCOMPLETE_LINKAGE: D->mx[i][col] = ESL_MAX(D->mx[i][col], D->mx[j][col]); break; default: ESL_XEXCEPTION(eslEINCONCEIVABLE, "no such strategy"); } D->mx[col][i] = D->mx[i][col]; } /* row/col i is now the new cluster, and it corresponds to node N-2 * in the tree (remember, N is decrementing at each iteration). * row/col j (N-1) falls away when we go back to the start of the loop * and decrement N. */ nin[i] += nin[j]; idx[i] = N-2; } esl_dmatrix_Destroy(D); free(height); free(idx); free(nin); if (ret_T != NULL) *ret_T = T; return eslOK; ERROR: if (D != NULL) esl_dmatrix_Destroy(D); if (T != NULL) esl_tree_Destroy(T); if (height != NULL) free(height); if (idx != NULL) free(idx); if (nin != NULL) free(nin); if (ret_T != NULL) *ret_T = NULL; return status; } /* Function: esl_tree_UPGMA() * Incept: SRE, Wed May 3 15:14:17 2006 [St. Louis] * * Purpose: Given distance matrix <D>, use the UPGMA algorithm * to construct a tree <T>. * * Returns: <eslOK> on success; the tree is returned in <ret_T>, * and must be freed by the caller with <esl_tree_Destroy()>. * * Throws: <eslEMEM> on allocation problem, and <ret_T> is set <NULL>. */ int esl_tree_UPGMA(ESL_DMATRIX *D, ESL_TREE **ret_T) { return cluster_engine(D, eslUPGMA, ret_T); } /* Function: esl_tree_WPGMA() * Incept: SRE, Wed May 3 15:47:13 2006 [St. Louis] * * Purpose: Given distance matrix <D>, use the WPGMA algorithm * to construct a tree <T>. * * Returns: <eslOK> on success; the tree is returned in <ret_T>, * and must be freed by the caller with <esl_tree_Destroy()>. * * Throws: <eslEMEM> on allocation problem, and <ret_T> is set <NULL>. */ int esl_tree_WPGMA(ESL_DMATRIX *D, ESL_TREE **ret_T) { return cluster_engine(D, eslWPGMA, ret_T); } /* Function: esl_tree_SingleLinkage() * Incept: SRE, Wed May 3 15:49:06 2006 [St. Louis] * * Purpose: Given distance matrix <D>, construct a single-linkage * (minimum distances) clustering tree <T>. * * Returns: <eslOK> on success; the tree is returned in <ret_T>, * and must be freed by the caller with <esl_tree_Destroy()>. * * Throws: <eslEMEM> on allocation problem, and <ret_T> is set <NULL>. */ int esl_tree_SingleLinkage(ESL_DMATRIX *D, ESL_TREE **ret_T) { return cluster_engine(D, eslSINGLE_LINKAGE, ret_T); } /* Function: esl_tree_CompleteLinkage() * Incept: SRE, Wed May 3 15:49:14 2006 [St. Louis] * * Purpose: Given distance matrix <D>, construct a complete-linkage * (maximum distances) clustering tree <T>. * * Returns: <eslOK> on success; the tree is returned in <ret_T>, * and must be freed by the caller with <esl_tree_Destroy()>. * * Throws: <eslEMEM> on allocation problem, and <ret_T> is set <NULL>. */ int esl_tree_CompleteLinkage(ESL_DMATRIX *D, ESL_TREE **ret_T) { return cluster_engine(D, eslCOMPLETE_LINKAGE, ret_T); } /*----------------- end, clustering algorithms ----------------*/ /***************************************************************** * 5. Generating simulated trees *****************************************************************/ /* Function: esl_tree_Simulate() * Synopsis: Generate a random rooted ultrametric tree. * Incept: SRE, Mon Oct 2 11:36:22 2006 [Janelia] * * Purpose: Generate a random rooted ultrametric tree of <N> taxa, * using the algorithm of Kuhner and Felsenstein (1994). * * The branch lengths are generated by choosing <N-1> * exponentially distributed split times, with decreasing * expectations of $\frac{1}{2},\frac{1}{3}..\frac{1}{N}$ * as the simulation proceeds from the root. Thus the * total expected branch length on the tree is * $\sum_{k=2}^{N} \frac{1}{k}$. * * Args: r - random number source * N - number of taxa (>= 2) * ret_T - RETURN: sampled tree * * Returns: <eslOK> on success, and the new tree is allocated * here and returned via <ret_tree>; caller is * responsible for free'ing it. * * Throws: <eslEMEM> on allocation failure, in which case * the <ret_T> is returned <NULL>. * * Xref: STL11/65. */ int esl_tree_Simulate(ESL_RANDOMNESS *r, int N, ESL_TREE **ret_T) { ESL_TREE *T = NULL; int *branchpapa = NULL; int *branchside = NULL; int nactive; double d; int node; int bidx; /* index of an active branch */ int status; ESL_DASSERT1( (r != NULL) ); ESL_DASSERT1( (N >= 2) ); /* Kuhner/Felsenstein uses a list of active branches, * which we implement by tracking the index of the parent * node (in <branchpapa>) and a 0/1 flag (in <branchside>) * for the branch to the left vs. right child. */ if ((T = esl_tree_Create(N)) == NULL) goto ERROR; ESL_ALLOC_WITH_TYPE(branchpapa, int*, sizeof(int) * N); ESL_ALLOC_WITH_TYPE(branchside, int*, sizeof(int) * N); /* Initialize: add two branches from the root * onto the active list, and set internal node * counter to start at 1. */ branchpapa[0] = 0; branchside[0] = 0; branchpapa[1] = 0; branchside[1] = 1; nactive = 2; node = 1; /* Algorithm proceeds by iterating: * 1. choose random time <d> from exponential(1/nactive) * 2. choose random active branch, <bidx> * 3. add new <node> to active branch at length d * 4. add d to all other active branches * 5. delete the old parent branch from the active list, * add the two new child branches to the active list */ while (nactive < N) { d = (double) nactive * -log(esl_rnd_UniformPositive(r)); bidx = esl_rnd_Roll(r, nactive); T->parent[node] = branchpapa[bidx]; if (branchside[bidx] == 0) { T->left[branchpapa[bidx]] = node; T->ld [branchpapa[bidx]] += d; } else { T->right[branchpapa[bidx]] = node; T->rd [branchpapa[bidx]] += d; } ESL_SWAP(branchpapa[bidx], branchpapa[nactive-1], int); ESL_SWAP(branchside[bidx], branchside[nactive-1], int); for (bidx = 0; bidx < nactive-1; bidx++) { if (branchside[bidx] == 0) T->ld[branchpapa[bidx]] += d; else T->rd[branchpapa[bidx]] += d; } /* delete the branch at nactive-1 that we just added to; * replace it with two new branches */ branchpapa[nactive-1] = node; branchside[nactive-1] = 0; branchpapa[nactive] = node; branchside[nactive] = 1; node++; nactive++; } /* Terminate by adding the N taxa to the N active branches. */ d = (double) N * -log(esl_rnd_UniformPositive(r)); for (bidx = 0; bidx < N; bidx++) { if (branchside[bidx] == 0) { T->left[branchpapa[bidx]] = -bidx; /* taxa indices stored as neg #'s */ T->ld [branchpapa[bidx]] += d; } else { T->right[branchpapa[bidx]] = -bidx; T->rd [branchpapa[bidx]] += d; } } *ret_T = T; free(branchpapa); free(branchside); return eslOK; ERROR: if (T != NULL) esl_tree_Destroy(T); if (branchpapa != NULL) free(branchpapa); if (branchside != NULL) free(branchside); *ret_T = NULL; return status; } /* Function: esl_tree_ToDistanceMatrix() * Synopsis: Obtain a pairwise distance matrix from a tree. * Incept: SRE, Fri Oct 6 13:50:37 2006 [Janelia] * * Purpose: Given tree <T>, calculate a pairwise distance matrix * and return it in <ret_D>. * * Note: Algorithm here is O(N^3). It can probably be improved. * There ought to be a more efficient recursion that * saves recalculating node-node distances inside the tree. * All we do here is a brute force, upwards O(N) LCA * search for each of the N^2 taxon pairs. * * Args: T - input tree * ret_D - RETURN: the new distance matrix * * Returns: <eslOK> on success, and <ret_D> points to the distance * matrix, which caller is responsible for free'ing with * <esl_dmatrix_Destroy()>. * * Throws: <eslEMEM> on allocation failure, in which case * <ret_D> is returned <NULL>. * * Xref: STL11/66. */ int esl_tree_ToDistanceMatrix(ESL_TREE *T, ESL_DMATRIX **ret_D) { ESL_DMATRIX *D = NULL; int i,j; /* a pair of taxa {0..N-1} */ int a,b; /* a pair of internal nodes {0..N-2} */ int p; /* a tmp parent index */ double d; /* ij distance */ int status; D = esl_dmatrix_Create(T->N, T->N); /* creates a NxN square symmetric matrix; really only need triangular */ if (D == NULL) { status = eslEMEM; goto ERROR; } if ((status = esl_tree_SetTaxaParents(T)) != eslOK) goto ERROR; for (i = 0; i < T->N; i++) { D->mx[i][i] = 0.; /* by definition */ for (j = i+1; j < T->N; j++) { a = T->taxaparent[i]; b = T->taxaparent[j]; d = (T->left[a] == -i) ? T->ld[a] : T->rd[a]; d += (T->left[b] == -j) ? T->ld[b] : T->rd[b]; while (a != b) /* a brute force LCA algorithm */ { if (a < b) ESL_SWAP(a, b, int); p = T->parent[a]; d += (T->left[p] == a) ? T->ld[p] : T->rd[p]; a = p; } D->mx[i][j] = D->mx[j][i] = d; } } *ret_D = D; return eslOK; ERROR: if (D != NULL) esl_dmatrix_Destroy(D); *ret_D = NULL; return status; } /***************************************************************** * Easel - a library of C functions for biological sequence analysis * Version h3.0; March 2010 * Copyright (C) 2010 Howard Hughes Medical Institute. * Other copyrights also apply. See the COPYRIGHT file for a full list. * * Easel is distributed under the Janelia Farm Software License, a BSD * license. See the LICENSE file for more details. *****************************************************************/
34.844955
119
0.539811
[ "object" ]
4f553ff5fd146b25b61eb4c0acf3f7caedc0590b
34,809
cpp
C++
src/sound/timidity/instrum_dls.cpp
raa-eruanna/ProjectPanther
7d703c162b4ede25faa3e99cacacb4fc79fb77da
[ "RSA-MD" ]
2
2018-01-18T21:30:20.000Z
2018-01-19T02:24:46.000Z
src/sound/timidity/instrum_dls.cpp
raa-eruanna/ProjectPanther
7d703c162b4ede25faa3e99cacacb4fc79fb77da
[ "RSA-MD" ]
null
null
null
src/sound/timidity/instrum_dls.cpp
raa-eruanna/ProjectPanther
7d703c162b4ede25faa3e99cacacb4fc79fb77da
[ "RSA-MD" ]
null
null
null
/* TiMidity -- Experimental MIDI to WAVE converter Copyright (C) 1995 Tuukka Toivonen <toivonen@clinet.fi> 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. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA instrum_dls.c */ #include <stdlib.h> #include <string.h> #include <math.h> #include "timidity.h" #include "doomdef.h" #include "m_swap.h" #define __Sound_SetError(x) namespace Timidity { /*-------------------------------------------------------------------------*/ /* * * * * * * * * * * * * * * * * load_riff.h * * * * * * * * * * * * * * */ /*-------------------------------------------------------------------------*/ struct RIFF_Chunk { RIFF_Chunk() { memset(this, 0, sizeof(*this)); } ~RIFF_Chunk() { // data is not freed here because it may be owned by a parent chunk if (child != NULL) { delete child; } if (next != NULL) { delete next; } } uint32_t magic; uint32_t length; uint32_t subtype; uint8_t *data; RIFF_Chunk *child; RIFF_Chunk *next; }; RIFF_Chunk *LoadRIFF(FILE *src); void FreeRIFF(RIFF_Chunk *chunk); void PrintRIFF(RIFF_Chunk *chunk, int level); /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ /*-------------------------------------------------------------------------*/ /* * * * * * * * * * * * * * * * * load_riff.c * * * * * * * * * * * * * * */ /*-------------------------------------------------------------------------*/ #define RIFF MAKE_ID('R','I','F','F') #define LIST MAKE_ID('L','I','S','T') static bool ChunkHasSubType(uint32_t magic) { return (magic == RIFF || magic == LIST); } static int ChunkHasSubChunks(uint32_t magic) { return (magic == RIFF || magic == LIST); } static void LoadSubChunks(RIFF_Chunk *chunk, uint8_t *data, uint32_t left) { uint8_t *subchunkData; uint32_t subchunkDataLen; while ( left > 8 ) { RIFF_Chunk *child = new RIFF_Chunk; RIFF_Chunk *next, *prev = NULL; for ( next = chunk->child; next; next = next->next ) { prev = next; } if ( prev ) { prev->next = child; } else { chunk->child = child; } child->magic = *(uint32_t *)data; data += 4; left -= 4; child->length = LittleLong(*(uint32_t *)data); data += 4; left -= 4; child->data = data; if ( child->length > left ) { child->length = left; } subchunkData = child->data; subchunkDataLen = child->length; if ( ChunkHasSubType(child->magic) && subchunkDataLen >= 4 ) { child->subtype = *(uint32_t *)subchunkData; subchunkData += 4; subchunkDataLen -= 4; } if ( ChunkHasSubChunks(child->magic) ) { LoadSubChunks(child, subchunkData, subchunkDataLen); } data += child->length + (child->length & 1); left -= child->length + (child->length & 1); } } RIFF_Chunk *LoadRIFF(FILE *src) { RIFF_Chunk *chunk; uint8_t *subchunkData; uint32_t subchunkDataLen; /* Allocate the chunk structure */ chunk = new RIFF_Chunk; /* Make sure the file is in RIFF format */ fread(&chunk->magic, 4, 1, src); fread(&chunk->length, 4, 1, src); chunk->length = LittleLong(chunk->length); if ( chunk->magic != RIFF ) { __Sound_SetError("Not a RIFF file"); delete chunk; return NULL; } chunk->data = (uint8_t *)malloc(chunk->length); if ( chunk->data == NULL ) { __Sound_SetError(ERR_OUT_OF_MEMORY); delete chunk; return NULL; } if ( fread(chunk->data, chunk->length, 1, src) != 1 ) { __Sound_SetError(ERR_IO_ERROR); FreeRIFF(chunk); return NULL; } subchunkData = chunk->data; subchunkDataLen = chunk->length; if ( ChunkHasSubType(chunk->magic) && subchunkDataLen >= 4 ) { chunk->subtype = *(uint32_t *)subchunkData; subchunkData += 4; subchunkDataLen -= 4; } if ( ChunkHasSubChunks(chunk->magic) ) { LoadSubChunks(chunk, subchunkData, subchunkDataLen); } return chunk; } void FreeRIFF(RIFF_Chunk *chunk) { free(chunk->data); delete chunk; } void PrintRIFF(RIFF_Chunk *chunk, int level) { static char prefix[128]; if ( level == sizeof(prefix)-1 ) { return; } if ( level > 0 ) { prefix[(level-1)*2] = ' '; prefix[(level-1)*2+1] = ' '; } prefix[level*2] = '\0'; printf("%sChunk: %c%c%c%c (%d bytes)", prefix, ((chunk->magic >> 0) & 0xFF), ((chunk->magic >> 8) & 0xFF), ((chunk->magic >> 16) & 0xFF), ((chunk->magic >> 24) & 0xFF), chunk->length); if ( chunk->subtype ) { printf(" subtype: %c%c%c%c", ((chunk->subtype >> 0) & 0xFF), ((chunk->subtype >> 8) & 0xFF), ((chunk->subtype >> 16) & 0xFF), ((chunk->subtype >> 24) & 0xFF)); } printf("\n"); if ( chunk->child ) { printf("%s{\n", prefix); PrintRIFF(chunk->child, level + 1); printf("%s}\n", prefix); } if ( chunk->next ) { PrintRIFF(chunk->next, level); } if ( level > 0 ) { prefix[(level-1)*2] = '\0'; } } #ifdef TEST_MAIN_RIFF main(int argc, char *argv[]) { int i; for ( i = 1; i < argc; ++i ) { RIFF_Chunk *chunk; SDL_RWops *src = SDL_RWFromFile(argv[i], "rb"); if ( !src ) { fprintf(stderr, "Couldn't open %s: %s", argv[i], SDL_GetError()); continue; } chunk = LoadRIFF(src); if ( chunk ) { PrintRIFF(chunk, 0); FreeRIFF(chunk); } else { fprintf(stderr, "Couldn't load %s: %s\n", argv[i], SDL_GetError()); } SDL_RWclose(src); } } #endif // TEST_MAIN /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ /*-------------------------------------------------------------------------*/ /* * * * * * * * * * * * * * * * * load_dls.h * * * * * * * * * * * * * * */ /*-------------------------------------------------------------------------*/ /* This code is based on the DLS spec version 1.1, available at: http://www.midi.org/about-midi/dls/dlsspec.shtml */ /* Some typedefs so the public dls headers don't need to be modified */ #define FAR typedef int16_t SHORT; typedef uint16_t USHORT; typedef int32_t LONG; typedef uint32_t ULONG; typedef uint32_t DWORD; #define mmioFOURCC MAKE_ID #define DEFINE_GUID(A, B, C, E, F, G, H, I, J, K, L, M) #include "dls1.h" #include "dls2.h" struct WaveFMT { uint16_t wFormatTag; uint16_t wChannels; uint32_t dwSamplesPerSec; uint32_t dwAvgBytesPerSec; uint16_t wBlockAlign; uint16_t wBitsPerSample; }; struct DLS_Wave { WaveFMT *format; uint8_t *data; uint32_t length; WSMPL *wsmp; WLOOP *wsmp_loop; }; struct DLS_Region { RGNHEADER *header; WAVELINK *wlnk; WSMPL *wsmp; WLOOP *wsmp_loop; CONNECTIONLIST *art; CONNECTION *artList; }; struct DLS_Instrument { const char *name; INSTHEADER *header; DLS_Region *regions; CONNECTIONLIST *art; CONNECTION *artList; }; struct DLS_Data { RIFF_Chunk *chunk; uint32_t cInstruments; DLS_Instrument *instruments; POOLTABLE *ptbl; POOLCUE *ptblList; DLS_Wave *waveList; const char *name; const char *artist; const char *copyright; const char *comments; }; DLS_Data *LoadDLS(FILE *src); void FreeDLS(DLS_Data *chunk); /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ /*-------------------------------------------------------------------------*/ /* * * * * * * * * * * * * * * * * load_dls.c * * * * * * * * * * * * * * */ /*-------------------------------------------------------------------------*/ #define FOURCC_LIST mmioFOURCC('L','I','S','T') #define FOURCC_FMT mmioFOURCC('f','m','t',' ') #define FOURCC_DATA mmioFOURCC('d','a','t','a') #define FOURCC_INFO mmioFOURCC('I','N','F','O') #define FOURCC_IARL mmioFOURCC('I','A','R','L') #define FOURCC_IART mmioFOURCC('I','A','R','T') #define FOURCC_ICMS mmioFOURCC('I','C','M','S') #define FOURCC_ICMT mmioFOURCC('I','C','M','T') #define FOURCC_ICOP mmioFOURCC('I','C','O','P') #define FOURCC_ICRD mmioFOURCC('I','C','R','D') #define FOURCC_IENG mmioFOURCC('I','E','N','G') #define FOURCC_IGNR mmioFOURCC('I','G','N','R') #define FOURCC_IKEY mmioFOURCC('I','K','E','Y') #define FOURCC_IMED mmioFOURCC('I','M','E','D') #define FOURCC_INAM mmioFOURCC('I','N','A','M') #define FOURCC_IPRD mmioFOURCC('I','P','R','D') #define FOURCC_ISBJ mmioFOURCC('I','S','B','J') #define FOURCC_ISFT mmioFOURCC('I','S','F','T') #define FOURCC_ISRC mmioFOURCC('I','S','R','C') #define FOURCC_ISRF mmioFOURCC('I','S','R','F') #define FOURCC_ITCH mmioFOURCC('I','T','C','H') static void FreeRegions(DLS_Instrument *instrument) { if ( instrument->regions ) { free(instrument->regions); } } static void AllocRegions(DLS_Instrument *instrument) { int datalen = (instrument->header->cRegions * sizeof(DLS_Region)); FreeRegions(instrument); instrument->regions = (DLS_Region *)malloc(datalen); if ( instrument->regions ) { memset(instrument->regions, 0, datalen); } } static void FreeInstruments(DLS_Data *data) { if ( data->instruments ) { uint32_t i; for ( i = 0; i < data->cInstruments; ++i ) { FreeRegions(&data->instruments[i]); } free(data->instruments); } } static void AllocInstruments(DLS_Data *data) { int datalen = (data->cInstruments * sizeof(DLS_Instrument)); FreeInstruments(data); data->instruments = (DLS_Instrument *)malloc(datalen); if ( data->instruments ) { memset(data->instruments, 0, datalen); } } static void FreeWaveList(DLS_Data *data) { if ( data->waveList ) { free(data->waveList); } } static void AllocWaveList(DLS_Data *data) { int datalen = (data->ptbl->cCues * sizeof(DLS_Wave)); FreeWaveList(data); data->waveList = (DLS_Wave *)malloc(datalen); if ( data->waveList ) { memset(data->waveList, 0, datalen); } } static void Parse_colh(DLS_Data *data, RIFF_Chunk *chunk) { data->cInstruments = LittleLong(*(uint32_t *)chunk->data); AllocInstruments(data); } static void Parse_insh(DLS_Data *data, RIFF_Chunk *chunk, DLS_Instrument *instrument) { INSTHEADER *header = (INSTHEADER *)chunk->data; header->cRegions = LittleLong(header->cRegions); header->Locale.ulBank = LittleLong(header->Locale.ulBank); header->Locale.ulInstrument = LittleLong(header->Locale.ulInstrument); instrument->header = header; AllocRegions(instrument); } static void Parse_rgnh(DLS_Data *data, RIFF_Chunk *chunk, DLS_Region *region) { RGNHEADER *header = (RGNHEADER *)chunk->data; header->RangeKey.usLow = LittleShort(header->RangeKey.usLow); header->RangeKey.usHigh = LittleShort(header->RangeKey.usHigh); header->RangeVelocity.usLow = LittleShort(header->RangeVelocity.usLow); header->RangeVelocity.usHigh = LittleShort(header->RangeVelocity.usHigh); header->fusOptions = LittleShort(header->fusOptions); header->usKeyGroup = LittleShort(header->usKeyGroup); region->header = header; } static void Parse_wlnk(DLS_Data *data, RIFF_Chunk *chunk, DLS_Region *region) { WAVELINK *wlnk = (WAVELINK *)chunk->data; wlnk->fusOptions = LittleShort(wlnk->fusOptions); wlnk->usPhaseGroup = LittleShort(wlnk->usPhaseGroup); wlnk->ulChannel = LittleLong((unsigned int)wlnk->ulChannel); wlnk->ulTableIndex = LittleLong((unsigned int)wlnk->ulTableIndex); region->wlnk = wlnk; } static void Parse_wsmp(DLS_Data *data, RIFF_Chunk *chunk, WSMPL **wsmp_ptr, WLOOP **wsmp_loop_ptr) { uint32_t i; WSMPL *wsmp = (WSMPL *)chunk->data; WLOOP *loop; wsmp->cbSize = LittleLong(wsmp->cbSize); wsmp->usUnityNote = LittleShort(wsmp->usUnityNote); wsmp->sFineTune = LittleShort(wsmp->sFineTune); wsmp->lAttenuation = LittleLong(wsmp->lAttenuation); wsmp->fulOptions = LittleLong(wsmp->fulOptions); wsmp->cSampleLoops = LittleLong(wsmp->cSampleLoops); loop = (WLOOP *)((uint8_t *)chunk->data + wsmp->cbSize); *wsmp_ptr = wsmp; *wsmp_loop_ptr = loop; for ( i = 0; i < wsmp->cSampleLoops; ++i ) { loop->cbSize = LittleLong(loop->cbSize); loop->ulType = LittleLong(loop->ulType); loop->ulStart = LittleLong(loop->ulStart); loop->ulLength = LittleLong(loop->ulLength); ++loop; } } static void Parse_art(DLS_Data *data, RIFF_Chunk *chunk, CONNECTIONLIST **art_ptr, CONNECTION **artList_ptr) { uint32_t i; CONNECTIONLIST *art = (CONNECTIONLIST *)chunk->data; CONNECTION *artList; art->cbSize = LittleLong(art->cbSize); art->cConnections = LittleLong(art->cConnections); artList = (CONNECTION *)((uint8_t *)chunk->data + art->cbSize); *art_ptr = art; *artList_ptr = artList; for ( i = 0; i < art->cConnections; ++i ) { artList->usSource = LittleShort(artList->usSource); artList->usControl = LittleShort(artList->usControl); artList->usDestination = LittleShort(artList->usDestination); artList->usTransform = LittleShort(artList->usTransform); artList->lScale = LittleLong(artList->lScale); ++artList; } } static void Parse_lart(DLS_Data *data, RIFF_Chunk *chunk, CONNECTIONLIST **conn_ptr, CONNECTION **connList_ptr) { /* FIXME: This only supports one set of connections */ for ( chunk = chunk->child; chunk; chunk = chunk->next ) { uint32_t magic = (chunk->magic == FOURCC_LIST) ? chunk->subtype : chunk->magic; switch(magic) { case FOURCC_ART1: case FOURCC_ART2: Parse_art(data, chunk, conn_ptr, connList_ptr); return; } } } static void Parse_rgn(DLS_Data *data, RIFF_Chunk *chunk, DLS_Region *region) { for ( chunk = chunk->child; chunk; chunk = chunk->next ) { uint32_t magic = (chunk->magic == FOURCC_LIST) ? chunk->subtype : chunk->magic; switch(magic) { case FOURCC_RGNH: Parse_rgnh(data, chunk, region); break; case FOURCC_WLNK: Parse_wlnk(data, chunk, region); break; case FOURCC_WSMP: Parse_wsmp(data, chunk, &region->wsmp, &region->wsmp_loop); break; case FOURCC_LART: case FOURCC_LAR2: Parse_lart(data, chunk, &region->art, &region->artList); break; } } } static void Parse_lrgn(DLS_Data *data, RIFF_Chunk *chunk, DLS_Instrument *instrument) { uint32_t region = 0; for ( chunk = chunk->child; chunk; chunk = chunk->next ) { uint32_t magic = (chunk->magic == FOURCC_LIST) ? chunk->subtype : chunk->magic; switch(magic) { case FOURCC_RGN: case FOURCC_RGN2: if ( region < instrument->header->cRegions ) { Parse_rgn(data, chunk, &instrument->regions[region++]); } break; } } } static void Parse_INFO_INS(DLS_Data *data, RIFF_Chunk *chunk, DLS_Instrument *instrument) { for ( chunk = chunk->child; chunk; chunk = chunk->next ) { uint32_t magic = (chunk->magic == FOURCC_LIST) ? chunk->subtype : chunk->magic; switch(magic) { case FOURCC_INAM: /* Name */ instrument->name = (const char *)chunk->data; break; } } } static void Parse_ins(DLS_Data *data, RIFF_Chunk *chunk, DLS_Instrument *instrument) { for ( chunk = chunk->child; chunk; chunk = chunk->next ) { uint32_t magic = (chunk->magic == FOURCC_LIST) ? chunk->subtype : chunk->magic; switch(magic) { case FOURCC_INSH: Parse_insh(data, chunk, instrument); break; case FOURCC_LRGN: Parse_lrgn(data, chunk, instrument); break; case FOURCC_LART: case FOURCC_LAR2: Parse_lart(data, chunk, &instrument->art, &instrument->artList); break; case FOURCC_INFO: Parse_INFO_INS(data, chunk, instrument); break; } } } static void Parse_lins(DLS_Data *data, RIFF_Chunk *chunk) { uint32_t instrument = 0; for ( chunk = chunk->child; chunk; chunk = chunk->next ) { uint32_t magic = (chunk->magic == FOURCC_LIST) ? chunk->subtype : chunk->magic; switch(magic) { case FOURCC_INS: if ( instrument < data->cInstruments ) { Parse_ins(data, chunk, &data->instruments[instrument++]); } break; } } } static void Parse_ptbl(DLS_Data *data, RIFF_Chunk *chunk) { uint32_t i; POOLTABLE *ptbl = (POOLTABLE *)chunk->data; ptbl->cbSize = LittleLong(ptbl->cbSize); ptbl->cCues = LittleLong(ptbl->cCues); data->ptbl = ptbl; data->ptblList = (POOLCUE *)((uint8_t *)chunk->data + ptbl->cbSize); for ( i = 0; i < ptbl->cCues; ++i ) { data->ptblList[i].ulOffset = LittleLong(data->ptblList[i].ulOffset); } AllocWaveList(data); } static void Parse_fmt(DLS_Data *data, RIFF_Chunk *chunk, DLS_Wave *wave) { WaveFMT *fmt = (WaveFMT *)chunk->data; fmt->wFormatTag = LittleShort(fmt->wFormatTag); fmt->wChannels = LittleShort(fmt->wChannels); fmt->dwSamplesPerSec = LittleLong(fmt->dwSamplesPerSec); fmt->dwAvgBytesPerSec = LittleLong(fmt->dwAvgBytesPerSec); fmt->wBlockAlign = LittleShort(fmt->wBlockAlign); fmt->wBitsPerSample = LittleShort(fmt->wBitsPerSample); wave->format = fmt; } static void Parse_data(DLS_Data *data, RIFF_Chunk *chunk, DLS_Wave *wave) { wave->data = chunk->data; wave->length = chunk->length; } static void Parse_wave(DLS_Data *data, RIFF_Chunk *chunk, DLS_Wave *wave) { for ( chunk = chunk->child; chunk; chunk = chunk->next ) { uint32_t magic = (chunk->magic == FOURCC_LIST) ? chunk->subtype : chunk->magic; switch(magic) { case FOURCC_FMT: Parse_fmt(data, chunk, wave); break; case FOURCC_DATA: Parse_data(data, chunk, wave); break; case FOURCC_WSMP: Parse_wsmp(data, chunk, &wave->wsmp, &wave->wsmp_loop); break; } } } static void Parse_wvpl(DLS_Data *data, RIFF_Chunk *chunk) { uint32_t wave = 0; for ( chunk = chunk->child; chunk; chunk = chunk->next ) { uint32_t magic = (chunk->magic == FOURCC_LIST) ? chunk->subtype : chunk->magic; switch(magic) { case FOURCC_wave: if ( wave < data->ptbl->cCues ) { Parse_wave(data, chunk, &data->waveList[wave++]); } break; } } } static void Parse_INFO_DLS(DLS_Data *data, RIFF_Chunk *chunk) { for ( chunk = chunk->child; chunk; chunk = chunk->next ) { uint32_t magic = (chunk->magic == FOURCC_LIST) ? chunk->subtype : chunk->magic; switch(magic) { case FOURCC_IARL: /* Archival Location */ break; case FOURCC_IART: /* Artist */ data->artist = (const char *)chunk->data; break; case FOURCC_ICMS: /* Commisioned */ break; case FOURCC_ICMT: /* Comments */ data->comments = (const char *)chunk->data; break; case FOURCC_ICOP: /* Copyright */ data->copyright = (const char *)chunk->data; break; case FOURCC_ICRD: /* Creation Date */ break; case FOURCC_IENG: /* Engineer */ break; case FOURCC_IGNR: /* Genre */ break; case FOURCC_IKEY: /* Keywords */ break; case FOURCC_IMED: /* Medium */ break; case FOURCC_INAM: /* Name */ data->name = (const char *)chunk->data; break; case FOURCC_IPRD: /* Product */ break; case FOURCC_ISBJ: /* Subject */ break; case FOURCC_ISFT: /* Software */ break; case FOURCC_ISRC: /* Source */ break; case FOURCC_ISRF: /* Source Form */ break; case FOURCC_ITCH: /* Technician */ break; } } } DLS_Data *LoadDLS(FILE *src) { RIFF_Chunk *chunk; DLS_Data *data = (DLS_Data *)malloc(sizeof(*data)); if ( !data ) { __Sound_SetError(ERR_OUT_OF_MEMORY); return NULL; } memset(data, 0, sizeof(*data)); data->chunk = LoadRIFF(src); if ( !data->chunk ) { FreeDLS(data); return NULL; } for ( chunk = data->chunk->child; chunk; chunk = chunk->next ) { uint32_t magic = (chunk->magic == FOURCC_LIST) ? chunk->subtype : chunk->magic; switch(magic) { case FOURCC_COLH: Parse_colh(data, chunk); break; case FOURCC_LINS: Parse_lins(data, chunk); break; case FOURCC_PTBL: Parse_ptbl(data, chunk); break; case FOURCC_WVPL: Parse_wvpl(data, chunk); break; case FOURCC_INFO: Parse_INFO_DLS(data, chunk); break; } } return data; } void FreeDLS(DLS_Data *data) { if ( data->chunk ) { FreeRIFF(data->chunk); } FreeInstruments(data); FreeWaveList(data); free(data); } static const char *SourceToString(USHORT usSource) { static char unknown[32]; switch(usSource) { case CONN_SRC_NONE: return "NONE"; case CONN_SRC_LFO: return "LFO"; case CONN_SRC_KEYONVELOCITY: return "KEYONVELOCITY"; case CONN_SRC_KEYNUMBER: return "KEYNUMBER"; case CONN_SRC_EG1: return "EG1"; case CONN_SRC_EG2: return "EG2"; case CONN_SRC_PITCHWHEEL: return "PITCHWHEEL"; case CONN_SRC_CC1: return "CC1"; case CONN_SRC_CC7: return "CC7"; case CONN_SRC_CC10: return "CC10"; case CONN_SRC_CC11: return "CC11"; case CONN_SRC_POLYPRESSURE: return "POLYPRESSURE"; case CONN_SRC_CHANNELPRESSURE: return "CHANNELPRESSURE"; case CONN_SRC_VIBRATO: return "VIBRATO"; case CONN_SRC_MONOPRESSURE: return "MONOPRESSURE"; case CONN_SRC_CC91: return "CC91"; case CONN_SRC_CC93: return "CC93"; default: mysnprintf(unknown, countof(unknown), "UNKNOWN (0x%04x)", usSource); return unknown; } } static const char *TransformToString(USHORT usTransform) { static char unknown[32]; switch (usTransform) { case CONN_TRN_NONE: return "NONE"; case CONN_TRN_CONCAVE: return "CONCAVE"; case CONN_TRN_CONVEX: return "CONVEX"; case CONN_TRN_SWITCH: return "SWITCH"; default: mysnprintf(unknown, countof(unknown), "UNKNOWN (0x%04x)", usTransform); return unknown; } } static const char *DestinationToString(USHORT usDestination) { static char unknown[32]; switch (usDestination) { case CONN_DST_NONE: return "NONE"; case CONN_DST_ATTENUATION: return "ATTENUATION"; case CONN_DST_PITCH: return "PITCH"; case CONN_DST_PAN: return "PAN"; case CONN_DST_LFO_FREQUENCY: return "LFO_FREQUENCY"; case CONN_DST_LFO_STARTDELAY: return "LFO_STARTDELAY"; case CONN_DST_EG1_ATTACKTIME: return "EG1_ATTACKTIME"; case CONN_DST_EG1_DECAYTIME: return "EG1_DECAYTIME"; case CONN_DST_EG1_RELEASETIME: return "EG1_RELEASETIME"; case CONN_DST_EG1_SUSTAINLEVEL: return "EG1_SUSTAINLEVEL"; case CONN_DST_EG2_ATTACKTIME: return "EG2_ATTACKTIME"; case CONN_DST_EG2_DECAYTIME: return "EG2_DECAYTIME"; case CONN_DST_EG2_RELEASETIME: return "EG2_RELEASETIME"; case CONN_DST_EG2_SUSTAINLEVEL: return "EG2_SUSTAINLEVEL"; case CONN_DST_KEYNUMBER: return "KEYNUMBER"; case CONN_DST_LEFT: return "LEFT"; case CONN_DST_RIGHT: return "RIGHT"; case CONN_DST_CENTER: return "CENTER"; case CONN_DST_LEFTREAR: return "LEFTREAR"; case CONN_DST_RIGHTREAR: return "RIGHTREAR"; case CONN_DST_LFE_CHANNEL: return "LFE_CHANNEL"; case CONN_DST_CHORUS: return "CHORUS"; case CONN_DST_REVERB: return "REVERB"; case CONN_DST_VIB_FREQUENCY: return "VIB_FREQUENCY"; case CONN_DST_VIB_STARTDELAY: return "VIB_STARTDELAY"; case CONN_DST_EG1_DELAYTIME: return "EG1_DELAYTIME"; case CONN_DST_EG1_HOLDTIME: return "EG1_HOLDTIME"; case CONN_DST_EG1_SHUTDOWNTIME: return "EG1_SHUTDOWNTIME"; case CONN_DST_EG2_DELAYTIME: return "EG2_DELAYTIME"; case CONN_DST_EG2_HOLDTIME: return "EG2_HOLDTIME"; case CONN_DST_FILTER_CUTOFF: return "FILTER_CUTOFF"; case CONN_DST_FILTER_Q: return "FILTER_Q"; default: mysnprintf(unknown, countof(unknown), "UNKNOWN (0x%04x)", usDestination); return unknown; } } static void PrintArt(const char *type, CONNECTIONLIST *art, CONNECTION *artList) { uint32_t i; printf("%s Connections:\n", type); for ( i = 0; i < art->cConnections; ++i ) { printf(" Source: %s, Control: %s, Destination: %s, Transform: %s, Scale: %d\n", SourceToString(artList[i].usSource), SourceToString(artList[i].usControl), DestinationToString(artList[i].usDestination), TransformToString(artList[i].usTransform), artList[i].lScale); } } static void PrintWave(DLS_Wave *wave, uint32_t index) { WaveFMT *format = wave->format; if ( format ) { printf(" Wave %u: Format: %hu, %hu channels, %u Hz, %hu bits (length = %u)\n", index, format->wFormatTag, format->wChannels, format->dwSamplesPerSec, format->wBitsPerSample, wave->length); } if ( wave->wsmp ) { uint32_t i; printf(" wsmp->usUnityNote = %hu\n", wave->wsmp->usUnityNote); printf(" wsmp->sFineTune = %hd\n", wave->wsmp->sFineTune); printf(" wsmp->lAttenuation = %d\n", wave->wsmp->lAttenuation); printf(" wsmp->fulOptions = 0x%8.8x\n", wave->wsmp->fulOptions); printf(" wsmp->cSampleLoops = %u\n", wave->wsmp->cSampleLoops); for ( i = 0; i < wave->wsmp->cSampleLoops; ++i ) { WLOOP *loop = &wave->wsmp_loop[i]; printf(" Loop %u:\n", i); printf(" ulStart = %u\n", loop->ulStart); printf(" ulLength = %u\n", loop->ulLength); } } } static void PrintRegion(DLS_Region *region, uint32_t index) { printf(" Region %u:\n", index); if ( region->header ) { printf(" RangeKey = { %hu - %hu }\n", region->header->RangeKey.usLow, region->header->RangeKey.usHigh); printf(" RangeVelocity = { %hu - %hu }\n", region->header->RangeVelocity.usLow, region->header->RangeVelocity.usHigh); printf(" fusOptions = 0x%4.4hx\n", region->header->fusOptions); printf(" usKeyGroup = %hu\n", region->header->usKeyGroup); } if ( region->wlnk ) { printf(" wlnk->fusOptions = 0x%4.4hx\n", region->wlnk->fusOptions); printf(" wlnk->usPhaseGroup = %hu\n", region->wlnk->usPhaseGroup); printf(" wlnk->ulChannel = %u\n", region->wlnk->ulChannel); printf(" wlnk->ulTableIndex = %u\n", region->wlnk->ulTableIndex); } if ( region->wsmp ) { uint32_t i; printf(" wsmp->usUnityNote = %hu\n", region->wsmp->usUnityNote); printf(" wsmp->sFineTune = %hd\n", region->wsmp->sFineTune); printf(" wsmp->lAttenuation = %d\n", region->wsmp->lAttenuation); printf(" wsmp->fulOptions = 0x%8.8x\n", region->wsmp->fulOptions); printf(" wsmp->cSampleLoops = %u\n", region->wsmp->cSampleLoops); for ( i = 0; i < region->wsmp->cSampleLoops; ++i ) { WLOOP *loop = &region->wsmp_loop[i]; printf(" Loop %u:\n", i); printf(" ulStart = %u\n", loop->ulStart); printf(" ulLength = %u\n", loop->ulLength); } } if ( region->art && region->art->cConnections > 0 ) { PrintArt("Region", region->art, region->artList); } } static void PrintInstrument(DLS_Instrument *instrument, uint32_t index) { printf("Instrument %u:\n", index); if ( instrument->name ) { printf(" Name: %s\n", instrument->name); } if ( instrument->header ) { uint32_t i; printf(" ulBank = 0x%8.8x\n", instrument->header->Locale.ulBank); printf(" ulInstrument = %u\n", instrument->header->Locale.ulInstrument); printf(" Regions: %u\n", instrument->header->cRegions); for ( i = 0; i < instrument->header->cRegions; ++i ) { PrintRegion(&instrument->regions[i], i); } } if ( instrument->art && instrument->art->cConnections > 0 ) { PrintArt("Instrument", instrument->art, instrument->artList); } }; void PrintDLS(DLS_Data *data) { printf("DLS Data:\n"); printf("cInstruments = %u\n", data->cInstruments); if ( data->instruments ) { uint32_t i; for ( i = 0; i < data->cInstruments; ++i ) { PrintInstrument(&data->instruments[i], i); } } if ( data->ptbl && data->ptbl->cCues > 0 ) { uint32_t i; printf("Cues: "); for ( i = 0; i < data->ptbl->cCues; ++i ) { if ( i > 0 ) { printf(", "); } printf("%u", data->ptblList[i].ulOffset); } printf("\n"); } if ( data->waveList && data->ptbl ) { uint32_t i; printf("Waves:\n"); for ( i = 0; i < data->ptbl->cCues; ++i ) { PrintWave(&data->waveList[i], i); } } if ( data->name ) { printf("Name: %s\n", data->name); } if ( data->artist ) { printf("Artist: %s\n", data->artist); } if ( data->copyright ) { printf("Copyright: %s\n", data->copyright); } if ( data->comments ) { printf("Comments: %s\n", data->comments); } } #ifdef TEST_MAIN_DLS } int main(int argc, char *argv[]) { int i; for ( i = 1; i < argc; ++i ) { Timidity::DLS_Data *data; FILE *src = fopen(argv[i], "rb"); if ( !src ) { fprintf(stderr, "Couldn't open %s: %s", argv[i], strerror(errno)); continue; } data = Timidity::LoadDLS(src); if ( data ) { Timidity::PrintRIFF(data->chunk, 0); Timidity::PrintDLS(data); Timidity::FreeDLS(data); } else { fprintf(stderr, "Couldn't load %s: %s\n", argv[i], strerror(errno)); } fclose(src); } return 0; } namespace Timidity { #endif // TEST_MAIN /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ /*-------------------------------------------------------------------------*/ /* * * * * * * * * * * * * * * * * instrum_dls.c * * * * * * * * * * * * * */ /*-------------------------------------------------------------------------*/ #ifndef TEST_MAIN_DLS DLS_Data *Timidity_LoadDLS(FILE *src) { return LoadDLS(src); } void Timidity_FreeDLS(DLS_Data *patches) { FreeDLS(patches); } /* convert timecents to sec */ static double to_msec(int timecent) { if (timecent == INT_MIN || timecent == 0) return 0.0; return 1000.0 * pow(2.0, (double)(timecent / 65536) / 1200.0); } /* convert decipercent to {0..1} */ static double to_normalized_percent(int decipercent) { return ((double)(decipercent / 65536)) / 1000.0; } /* convert from 8bit value to fractional offset (15.15) */ static int32_t to_offset(int offset) { return (int32_t)offset << (7+15); } /* calculate ramp rate in fractional unit; * diff = 8bit, time = msec */ static int32_t calc_rate(Renderer *song, int diff, int sample_rate, double msec) { double rate; if(msec < 6) msec = 6; if(diff == 0) diff = 255; diff <<= (7+15); rate = ((double)diff / song->rate) * song->control_ratio * 1000.0 / msec; return (int32_t)rate; } static int load_connection(ULONG cConnections, CONNECTION *artList, USHORT destination) { ULONG i; int value = 0; for (i = 0; i < cConnections; ++i) { CONNECTION *conn = &artList[i]; if(conn->usDestination == destination) { // The formula for the destination is: // usDestination = usDestination + usTransform(usSource * (usControl * lScale)) // Since we are only handling source/control of NONE and identity // transform, this simplifies to: usDestination = usDestination + lScale if (conn->usSource == CONN_SRC_NONE && conn->usControl == CONN_SRC_NONE && conn->usTransform == CONN_TRN_NONE) value += conn->lScale; } } return value; } static void load_region_dls(Renderer *song, Sample *sample, DLS_Instrument *ins, uint32_t index) { DLS_Region *rgn = &ins->regions[index]; DLS_Wave *wave = &song->patches->waveList[rgn->wlnk->ulTableIndex]; sample->type = INST_DLS; sample->self_nonexclusive = !!(rgn->header->fusOptions & F_RGN_OPTION_SELFNONEXCLUSIVE); sample->key_group = (int8_t)rgn->header->usKeyGroup; sample->low_freq = note_to_freq(rgn->header->RangeKey.usLow); sample->high_freq = note_to_freq(rgn->header->RangeKey.usHigh); sample->root_freq = note_to_freq(rgn->wsmp->usUnityNote + rgn->wsmp->sFineTune * .01f); sample->low_vel = (uint8_t)rgn->header->RangeVelocity.usLow; sample->high_vel = (uint8_t)rgn->header->RangeVelocity.usHigh; sample->modes = wave->format->wBitsPerSample == 8 ? PATCH_UNSIGNED : PATCH_16; sample->sample_rate = wave->format->dwSamplesPerSec; sample->data = NULL; sample->data_length = wave->length; convert_sample_data(sample, wave->data); if (rgn->wsmp->cSampleLoops) { sample->modes |= (PATCH_LOOPEN | PATCH_SUSTAIN/* | PATCH_NO_SRELEASE*/); sample->loop_start = rgn->wsmp_loop->ulStart / 2; sample->loop_end = sample->loop_start + (rgn->wsmp_loop->ulLength / 2); } sample->scale_factor = 1024; sample->scale_note = rgn->wsmp->usUnityNote; if (sample->modes & PATCH_SUSTAIN) { int value; int attack, hold, decay, release; int sustain; CONNECTIONLIST *art = NULL; CONNECTION *artList = NULL; if (ins->art && ins->art->cConnections > 0 && ins->artList) { art = ins->art; artList = ins->artList; } else { art = rgn->art; artList = rgn->artList; } attack = load_connection(art->cConnections, artList, CONN_DST_EG1_ATTACKTIME); hold = load_connection(art->cConnections, artList, CONN_DST_EG1_HOLDTIME); decay = load_connection(art->cConnections, artList, CONN_DST_EG1_DECAYTIME); release = load_connection(art->cConnections, artList, CONN_DST_EG1_RELEASETIME); sustain = load_connection(art->cConnections, artList, CONN_DST_EG1_SUSTAINLEVEL); value = load_connection(art->cConnections, artList, CONN_DST_PAN); sample->panning = (int)((0.5 + to_normalized_percent(value)) * 16383.f); /* printf("%d, Rate=%d LV=%d HV=%d Low=%d Hi=%d Root=%d Pan=%d Attack=%f Hold=%f Sustain=%d Decay=%f Release=%f\n", index, sample->sample_rate, rgn->header->RangeVelocity.usLow, rgn->header->RangeVelocity.usHigh, sample->low_freq, sample->high_freq, sample->root_freq, sample->panning, attack, hold, sustain, decay, release); */ sample->envelope.sf2.delay_vol = -32768; sample->envelope.sf2.attack_vol = (short)(attack >> 16); sample->envelope.sf2.hold_vol = (short)(hold >> 16); sample->envelope.sf2.decay_vol = (short)(decay >> 16); sample->envelope.sf2.release_vol = (short)(release >> 16); sample->envelope.sf2.sustain_vol = (short)(sustain >> 16); } sample->data_length <<= FRACTION_BITS; sample->loop_start <<= FRACTION_BITS; sample->loop_end <<= FRACTION_BITS; } Instrument *load_instrument_dls(Renderer *song, int drum, int bank, int instrument) { Instrument *inst; uint32_t i; DLS_Instrument *dls_ins = NULL; if (song->patches == NULL) { return NULL; } drum = drum ? 0x80000000 : 0; for (i = 0; i < song->patches->cInstruments; ++i) { dls_ins = &song->patches->instruments[i]; if ((dls_ins->header->Locale.ulBank & 0x80000000) == (ULONG)drum && ((dls_ins->header->Locale.ulBank >> 8) & 0xFF) == (ULONG)bank && dls_ins->header->Locale.ulInstrument == (ULONG)instrument) break; } if (i == song->patches->cInstruments && bank == 0) { for (i = 0; i < song->patches->cInstruments; ++i) { dls_ins = &song->patches->instruments[i]; if ((dls_ins->header->Locale.ulBank & 0x80000000) == (ULONG)drum && dls_ins->header->Locale.ulInstrument == (ULONG)instrument) break; } } if (i == song->patches->cInstruments) { // SNDDBG(("Couldn't find %s instrument %d in bank %d\n", drum ? "drum" : "melodic", instrument, bank)); return NULL; } inst = (Instrument *)safe_malloc(sizeof(Instrument)); inst->samples = dls_ins->header->cRegions; inst->sample = (Sample *)safe_malloc(inst->samples * sizeof(Sample)); memset(inst->sample, 0, inst->samples * sizeof(Sample)); /* printf("Found %s instrument %d in bank %d named %s with %d regions\n", drum ? "drum" : "melodic", instrument, bank, dls_ins->name, inst->samples); */ for (i = 0; i < dls_ins->header->cRegions; ++i) { load_region_dls(song, &inst->sample[i], dls_ins, i); } return inst; } #endif /* !TEST_MAIN_DLS */ }
28.071774
324
0.645465
[ "transform" ]
4f572863473110eb624237eb6b8be9ad8e13a0bc
2,638
hpp
C++
lib/primitive/src/serialization/amf3/Amf3Traits.hpp
tkeycoin/tkeycoin2
7fb88605b8874e16c01df1ee2d47f45094d5cf57
[ "MIT" ]
3
2020-01-24T04:45:14.000Z
2020-06-30T13:49:58.000Z
lib/primitive/src/serialization/amf3/Amf3Traits.hpp
Dikii27/tkeycoin2
7fb88605b8874e16c01df1ee2d47f45094d5cf57
[ "MIT" ]
1
2020-06-18T15:51:36.000Z
2020-06-20T17:25:45.000Z
lib/primitive/src/serialization/amf3/Amf3Traits.hpp
Dikii27/tkeycoin2
7fb88605b8874e16c01df1ee2d47f45094d5cf57
[ "MIT" ]
1
2020-10-20T06:50:13.000Z
2020-10-20T06:50:13.000Z
// Copyright (c) 2019 Tkeycoin Dao // Copyright (c) 2020 TKEY DMCC LLC & Tkeycoin Dao. All rights reserved. // Website: www.tkeycoin.com // // 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. // // Amf3Traits.hpp #pragma once #include <string> #include <set> #include <algorithm> #include <vector> class Amf3Traits final { public: std::string className; bool dynamic = false; bool externalizable = false; Amf3Traits() = default; // Default-constructor Amf3Traits(Amf3Traits&&) noexcept = delete; // Move-constructor Amf3Traits(const Amf3Traits&) = default; // Copy-constructor ~Amf3Traits() = default; // Destructor Amf3Traits& operator=(Amf3Traits&&) noexcept = delete; // Move-assignment Amf3Traits& operator=(const Amf3Traits&) = default; // Copy-assignment bool operator==(const Amf3Traits& other) const { return dynamic == other.dynamic && externalizable == other.externalizable && className == other.className && attributes == other.attributes; } bool operator!=(const Amf3Traits& other) const { return !(*this == other); } void addAttribute(std::string name) { if (!hasAttribute(name)) { attributes.push_back(name); } } bool hasAttribute(std::string name) const { auto it = std::find(attributes.begin(), attributes.end(), name); return (it != attributes.end()); } std::set<std::string> getUniqueAttributes() const { return std::set<std::string>(attributes.begin(), attributes.end()); } // Attribute names // Technically, this should be a set. However, since AMF does not actually // enforce the sealed property names to be unique, this needs to be a // vector to ensure we read the corresponding values, even if they are // later overwritten by another value for the same attribute name. // Additionally, since traits also can be sent by reference, we need to // actually store these duplicate names permanently, in case a later object // references a traits object with duplicate attribute names. // XXX: figure out whether this interferes with merging // {de,}serializationcontext into one object. std::vector<std::string> attributes; };
29.640449
76
0.719864
[ "object", "vector" ]
4f593918cdf9aa713b07a8f85faedf5310b5431f
2,392
hpp
C++
utils/camera-tool/includes/LensCalibration.hpp
TheGuardianWolf/Annotation-Tool
ba2b79269cfe8306aa49e93944e952b9f931ef99
[ "Artistic-2.0", "Apache-2.0", "CC0-1.0", "Unlicense" ]
null
null
null
utils/camera-tool/includes/LensCalibration.hpp
TheGuardianWolf/Annotation-Tool
ba2b79269cfe8306aa49e93944e952b9f931ef99
[ "Artistic-2.0", "Apache-2.0", "CC0-1.0", "Unlicense" ]
4
2019-01-08T19:57:57.000Z
2022-03-24T02:57:49.000Z
utils/camera-tool/includes/LensCalibration.hpp
TheGuardianWolf/Annotation-Tool
ba2b79269cfe8306aa49e93944e952b9f931ef99
[ "Artistic-2.0", "Apache-2.0", "CC0-1.0", "Unlicense" ]
1
2017-04-19T03:57:35.000Z
2017-04-19T03:57:35.000Z
/** * LensCalibration.hpp * Created by Jerry Fan, property of The University of Auckland. * Licenced under the Artistic Licence 2.0. * * This module is based off the example code provided by OpenCV to calibrate * and remove lens distortion based on a checkboard pattern. */ #ifndef LENSCALIBRATION_H #define LENSCALIBRATION_H #include <opencv2/core.hpp> class LensCalibration { private: const cv::Size boardSize; const unsigned int squareSize; // Millimeters const std::string pattern; const int flag; const int chessBoardFlags; bool calibrated; bool mapped; int frameCount; cv::Size imageSize; cv::Mat cameraMatrix; cv::Mat optimalCameraMatrix; cv::Mat distCoeffs; cv::Mat calibMap1; cv::Mat calibMap2; std::vector< std::vector<cv::Point2f> > imagePoints; bool runCalibration(); public: LensCalibration(); LensCalibration(std::string calibrationFile); LensCalibration(std::string calibrationFile, size_t calibFrames); /** * Check if calibration has been loaded. * @return Boolean. */ bool isCalibrated(); /** * Check if the calibration maps have been generated. * @return Boolean. */ bool isMapped(); /** * Perform calibration from a video sequence containing possible * checkerboard patterns in different positions. * @param filePath Video file. * @param calibFrames Valid frames to take. * @return Boolean indication of success. */ bool fromVideo(std::string filePath, size_t calibFrames); /** * Load calibration from existing calibration file into the object. * @param filePath Calibration file. * @return Boolean indication of success. */ bool fromFile(std::string filePath); /** * Stores the currently existing calibration to a file. * @param filePath Output calibration file (with valid extension). * @return Boolean indication of success. */ bool store(std::string filePath); /** * Create the calibration maps from current camera matrix and distortion * coefficients * @return Boolean indication of success. */ bool generateMaps(); bool onImage(std::string imagePath, cv::Mat& fixedImage); cv::Point2f onPoint(const cv::Point2f& point); }; #endif /* LENSCALIBRATION_H */
26.577778
77
0.668478
[ "object", "vector" ]
4f5a379df1dfd00cbb50f8f5255feb18694d47e3
362
cpp
C++
Leetcode/0940. Distinct Subsequences II/0940.cpp
Next-Gen-UI/Code-Dynamics
a9b9d5e3f27e870b3e030c75a1060d88292de01c
[ "MIT" ]
null
null
null
Leetcode/0940. Distinct Subsequences II/0940.cpp
Next-Gen-UI/Code-Dynamics
a9b9d5e3f27e870b3e030c75a1060d88292de01c
[ "MIT" ]
null
null
null
Leetcode/0940. Distinct Subsequences II/0940.cpp
Next-Gen-UI/Code-Dynamics
a9b9d5e3f27e870b3e030c75a1060d88292de01c
[ "MIT" ]
null
null
null
class Solution { public: int distinctSubseqII(string s) { constexpr int kMod = 1e9 + 7; // endsWith[i] := # of subseqs ends with 'a' + i vector<long> endsWith(26); for (const char c : s) endsWith[c - 'a'] = accumulate(begin(endsWith), end(endsWith), 1L) % kMod; return accumulate(begin(endsWith), end(endsWith), 0L) % kMod; } };
25.857143
80
0.616022
[ "vector" ]
4f5a51fe21fc1e395cb7f2300f7a58e78b3ccaff
17,537
cc
C++
waymo_open_dataset/metrics/detection_metrics.cc
reinforcementdriving/waymo-open-dataset
48665e7fc33eb412c4307d8ab6f92620eab9c95d
[ "Apache-2.0" ]
1,814
2019-08-20T18:30:38.000Z
2022-03-31T04:14:51.000Z
waymo_open_dataset/metrics/detection_metrics.cc
xuitex/waymo-open-dataset
1297cdcbcd103d4befb4b498e50a0c030053e6c0
[ "Apache-2.0" ]
418
2019-08-20T22:38:02.000Z
2022-03-31T07:51:15.000Z
waymo_open_dataset/metrics/detection_metrics.cc
xuitex/waymo-open-dataset
1297cdcbcd103d4befb4b498e50a0c030053e6c0
[ "Apache-2.0" ]
420
2019-08-21T10:59:06.000Z
2022-03-31T08:31:44.000Z
/* Copyright 2019 The Waymo Open Dataset 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 "waymo_open_dataset/metrics/detection_metrics.h" #include <algorithm> #include <iterator> #include <memory> #include <string> #include <utility> #include <glog/logging.h> #include "waymo_open_dataset/label.pb.h" #include "waymo_open_dataset/metrics/matcher.h" #include "waymo_open_dataset/metrics/metrics_utils.h" #include "waymo_open_dataset/protos/breakdown.pb.h" #include "waymo_open_dataset/protos/metrics.pb.h" namespace waymo { namespace open_dataset { namespace { // Computes a detection measurement (TP, FP, FN) from matching result at a given // difficulty level. // A ground truth without any prediction matched is not considered as an FN if // the ground truth has a detection difficulty level higher than the given one. // Note: pd_matches, gt_matches use indices to the *subsets* maintained by // matcher. DetectionMeasurement ComputeDetectionMeasurementFromMatchingResult( const Config& config, const Matcher& matcher, const std::vector<int>& pd_matches, const std::vector<int>& gt_matches, Label::DifficultyLevel difficulty_level, const Breakdown& breakdown) { int num_true_positives = 0; int num_false_positives = 0; int num_false_negatives = 0; float sum_heading_accuracy = 0.0; DetectionMeasurement measurement; DetectionMeasurement::Details* details = nullptr; if (config.include_details_in_measurements()) { details = measurement.add_details(); } auto is_in_breakdown = [&matcher, &breakdown](int gt_subset_id) { return internal::IsInBreakdown( matcher.ground_truths()[matcher.ground_truth_subset()[gt_subset_id]], breakdown); }; for (int i = 0, sz = pd_matches.size(); i < sz; ++i) { const int pd_index = matcher.prediction_subset()[i]; const std::string& pd_id = matcher.predictions()[pd_index].object().id(); // This is a true positive only if // 1) This prediction matches a ground truth. // 2) The matched ground truth is in the given breakdown. if (internal::IsTP(pd_matches, i) && (!internal::IsGroundTruthOnlyBreakdown(breakdown) || is_in_breakdown(pd_matches[i]))) { const int gt_index = matcher.ground_truth_subset()[pd_matches[i]]; const float heading_accuracy = internal::ComputeHeadingAccuracy(matcher, pd_index, gt_index); if (heading_accuracy <= config.min_heading_accuracy()) continue; ++num_true_positives; if (details != nullptr) { details->add_tp_pr_ids(pd_id); details->add_tp_gt_ids(matcher.ground_truths()[gt_index].object().id()); } sum_heading_accuracy += heading_accuracy; } // This is a false positive only if // 1) This prediction does not match to any ground truth. // 2) The prediction does not overlap with any other ground truth that is // not inside this breakdown. The threshold of deciding whether there is an // overlap is set to kOverlapIoUThreshold for now. if (internal::IsFP(matcher, pd_matches, i)) { bool is_fp = false; if (internal::IsGroundTruthOnlyBreakdown(breakdown)) { static constexpr double kOverlapIoUThreshold = 0.01; const int gt_subset_id = internal::FindGTWithLargestIoU( matcher, i, /*iou_threshold=*/kOverlapIoUThreshold); const bool overlap_with_gt_in_other_shard = gt_subset_id >= 0 && !is_in_breakdown(gt_subset_id); if (!overlap_with_gt_in_other_shard) { is_fp = true; } } else { is_fp = true; } if (is_fp) { ++num_false_positives; if (details != nullptr) { details->add_fp_ids(pd_id); } } } } for (int i = 0, sz = gt_matches.size(); i < sz; ++i) { // This is false negative only if // 1) This ground truth is not matched to any prediction. // 2) This ground truth is inside the given breakdown. if (internal::IsDetectionFN(matcher, gt_matches, i, difficulty_level) && (!internal::IsGroundTruthOnlyBreakdown(breakdown) || is_in_breakdown(i))) { ++num_false_negatives; if (details != nullptr) { const int gt_index = matcher.ground_truth_subset()[i]; details->add_fn_ids(matcher.ground_truths()[gt_index].object().id()); } } } measurement.set_num_tps(num_true_positives); measurement.set_num_fps(num_false_positives); measurement.set_num_fns(num_false_negatives); measurement.set_sum_ha(sum_heading_accuracy); if (details != nullptr && details->tp_gt_ids_size() != details->tp_pr_ids_size()) { LOG(FATAL) << "True positive sizes should be equal. pr size: " << details->tp_pr_ids_size() << ", gt size: " << details->tp_gt_ids_size(); } return measurement; } // Computes detection measurements for a single breakdown shard. // Returns a vector of detection measurements. Each element of that corresponds // to a difficulty level. The order of the vector is same as the difficulty // levels specified in the config. std::vector<DetectionMeasurements> ComputeDetectionMeasurementsPerBreakdownShard( const Config& config, const internal::BreakdownShardSubset& pd_subset, const internal::BreakdownShardSubset& gt_subset, Matcher* matcher) { CHECK(matcher != nullptr); std::vector<DetectionMeasurements> measurements; CHECK(!gt_subset.indices.empty()); matcher->SetGroundTruthSubset(gt_subset.indices[0]); const std::vector<Label::DifficultyLevel> difficulty_levels = internal::GetDifficultyLevels(config, pd_subset.breakdown_generator_id_index); measurements.resize(difficulty_levels.size()); for (int i = 0, sz = difficulty_levels.size(); i < sz; ++i) { auto* breakdown = measurements[i].mutable_breakdown(); breakdown->set_generator_id( config.breakdown_generator_ids(pd_subset.breakdown_generator_id_index)); breakdown->set_shard(pd_subset.breakdown_shard); breakdown->set_difficulty_level(difficulty_levels[i]); } // For each score cutoff in the config, filter predictions with score below // the cutoff and then do matching. Then computes detection measurements for // each difficulty level. for (int score_idx = 0, scores_sz = config.score_cutoffs_size(); score_idx < scores_sz; ++score_idx) { matcher->SetPredictionSubset(pd_subset.indices[score_idx]); std::vector<int> pd_matches; std::vector<int> gt_matches; matcher->Match(&pd_matches, &gt_matches); for (int dl_idx = 0, dl_sz = difficulty_levels.size(); dl_idx < dl_sz; ++dl_idx) { *measurements[dl_idx].add_measurements() = ComputeDetectionMeasurementFromMatchingResult( config, *matcher, pd_matches, gt_matches, difficulty_levels[dl_idx], measurements[dl_idx].breakdown()); measurements[dl_idx].mutable_measurements()->rbegin()->set_score_cutoff( config.score_cutoffs(score_idx)); } } return measurements; } // Merges two detection measurements. DetectionMeasurement MergeDetectionMeasurement(const DetectionMeasurement& m1, const DetectionMeasurement& m2) { if (!m1.has_score_cutoff()) return m2; if (!m2.has_score_cutoff()) return m1; CHECK_EQ(m1.score_cutoff(), m2.score_cutoff()); DetectionMeasurement m; #define ADD_FIELD(FIELD_NAME) \ m.set_##FIELD_NAME(m1.FIELD_NAME() + m2.FIELD_NAME()) ADD_FIELD(num_fps); ADD_FIELD(num_tps); ADD_FIELD(num_fns); ADD_FIELD(sum_ha); #undef ADD_FIELD // If we enables details population, appends it as a new frame. The new // frame's `details()` size should be 1. if (m1.details_size() == 1 || m2.details_size() == 1) { *m.mutable_details() = m1.details(); m.mutable_details()->MergeFrom(m2.details()); } m.set_score_cutoff(m1.score_cutoff()); return m; } // Merges new_m to m. void MergeDetectionMeasurements(const DetectionMeasurements& new_m, DetectionMeasurements* m) { CHECK(m != nullptr); if (m->measurements_size() == 0) { *m = new_m; return; } CHECK_EQ(m->measurements_size(), new_m.measurements_size()); CHECK_EQ(m->breakdown().generator_id(), new_m.breakdown().generator_id()); CHECK_EQ(m->breakdown().shard(), new_m.breakdown().shard()); CHECK_EQ(m->breakdown().difficulty_level(), new_m.breakdown().difficulty_level()); for (int i = 0, sz = m->measurements_size(); i < sz; ++i) { *m->mutable_measurements(i) = MergeDetectionMeasurement(m->measurements(i), new_m.measurements(i)); } } // Merges new_m to m element by element. void MergeDetectionMeasurementsVector( const std::vector<DetectionMeasurements>& new_m, std::vector<DetectionMeasurements>* m) { CHECK(m != nullptr); if (m->empty()) { *m = new_m; return; } CHECK_EQ(new_m.size(), m->size()); for (int i = 0, sz = m->size(); i < sz; ++i) { MergeDetectionMeasurements(new_m[i], &(*m)[i]); } } // Converts detection measurements to detection metrics. DetectionMetrics ToDetectionMetrics(const Config& config, DetectionMeasurements&& measurements, float desired_recall_delta) { DetectionMetrics metrics; *metrics.mutable_measurements() = measurements; const auto& m = metrics.measurements(); *metrics.mutable_breakdown() = m.breakdown(); for (const DetectionMeasurement& measurement : m.measurements()) { metrics.add_score_cutoffs(measurement.score_cutoff()); const int tp_fp_sum = measurement.num_tps() + measurement.num_fps(); if (tp_fp_sum <= 0) { metrics.add_precisions(0.0); metrics.add_precisions_ha_weighted(0.0); } else { const float precision = static_cast<float>(measurement.num_tps()) / tp_fp_sum; const float precision_ha = measurement.sum_ha() / tp_fp_sum; metrics.add_precisions(precision < config.min_precision() ? 0.0 : precision); metrics.add_precisions_ha_weighted( precision_ha < config.min_precision() ? 0.0 : precision_ha); } const int tp_fn_sum = measurement.num_tps() + measurement.num_fns(); if (tp_fn_sum <= 0) { metrics.add_recalls(0.0); metrics.add_recalls_ha_weighted(0.0); } else { metrics.add_recalls(static_cast<float>(measurement.num_tps()) / tp_fn_sum); // Use num_tps directly instead of sum_ha as none of the existing matcher // implementations takes heading accuracy into account. metrics.add_recalls_ha_weighted( static_cast<float>(measurement.num_tps()) / tp_fn_sum); } // If recall = 0.0, manually set precision = 1.0. if (*metrics.recalls().rbegin() == 0.0) { *metrics.mutable_precisions()->rbegin() = 1.0; } if (*metrics.recalls_ha_weighted().rbegin() == 0.0) { *metrics.mutable_precisions_ha_weighted()->rbegin() = 1.0; } } std::vector<float> precisions; std::vector<float> recalls; std::vector<float> precisions_ha_weighted; std::vector<float> recalls_ha_weighted; std::copy(metrics.precisions().begin(), metrics.precisions().end(), std::back_inserter(precisions)); std::copy(metrics.recalls().begin(), metrics.recalls().end(), std::back_inserter(recalls)); std::copy(metrics.precisions_ha_weighted().begin(), metrics.precisions_ha_weighted().end(), std::back_inserter(precisions_ha_weighted)); std::copy(metrics.recalls_ha_weighted().begin(), metrics.recalls_ha_weighted().end(), std::back_inserter(recalls_ha_weighted)); metrics.set_mean_average_precision(internal::ComputeMeanAveragePrecision( precisions, recalls, desired_recall_delta)); metrics.set_mean_average_precision_ha_weighted( internal::ComputeMeanAveragePrecision( precisions_ha_weighted, recalls_ha_weighted, desired_recall_delta)); return metrics; } } // namespace std::vector<DetectionMeasurements> ComputeDetectionMeasurements( const Config& config, const std::vector<Object>& pds, const std::vector<Object>& gts, ComputeIoUFunc custom_iou_func) { CHECK_GT(config.score_cutoffs_size(), 0) << "config.scores() must be populated: " << config.DebugString(); std::unique_ptr<Matcher> matcher = Matcher::Create(config); matcher->SetGroundTruths(gts); if (custom_iou_func != nullptr) { matcher->SetCustomIoUComputeFunc(custom_iou_func); } // Matcher stores a pointer to pds, so make a copy so pds lives the lifetime // of the matcher. auto pds_copy = pds; if (internal::HasVelocityBreakdown(config) && !pds.empty() && !pds[0].object().metadata().has_accel_x()) { pds_copy = internal::EstimateObjectSpeed(pds, gts); } matcher->SetPredictions(pds_copy); std::vector<DetectionMeasurements> measurements; const std::vector<internal::BreakdownShardSubset> pd_subsets = internal::BuildSubsets(config, matcher->predictions(), /*is_gt=*/false, /*is_detection=*/true); const std::vector<internal::BreakdownShardSubset> gt_subsets = internal::BuildSubsets(config, matcher->ground_truths(), /*is_gt=*/true, /*is_detection=*/true); CHECK_EQ(pd_subsets.size(), gt_subsets.size()); for (int i = 0, sz = pd_subsets.size(); i < sz; ++i) { const internal::BreakdownShardSubset& pd_subset = pd_subsets[i]; const internal::BreakdownShardSubset& gt_subset = gt_subsets[i]; // Computes detection measurements for each difficulty level for the // breakdown shard. std::vector<DetectionMeasurements> measurements_per_breadown_shard = ComputeDetectionMeasurementsPerBreakdownShard(config, pd_subset, gt_subset, matcher.get()); for (auto& m : measurements_per_breadown_shard) { measurements.emplace_back(std::move(m)); } } return measurements; } std::vector<DetectionMetrics> ComputeDetectionMetrics( const Config& config, const std::vector<std::vector<Object>>& pds, const std::vector<std::vector<Object>>& gts, ComputeIoUFunc custom_iou_func) { std::vector<DetectionMeasurements> measurements; CHECK_EQ(pds.size(), gts.size()); const int num_frames = pds.size(); const Config config_copy = config.score_cutoffs_size() > 0 ? config : EstimateScoreCutoffs(config, pds, gts); for (int i = 0; i < num_frames; ++i) { if (i == 0) { measurements = ComputeDetectionMeasurements(config_copy, pds[i], gts[i], custom_iou_func); } else { MergeDetectionMeasurementsVector( ComputeDetectionMeasurements(config_copy, pds[i], gts[i], custom_iou_func), &measurements); } } std::vector<DetectionMetrics> metrics; metrics.reserve(measurements.size()); for (auto& m : measurements) { metrics.emplace_back(ToDetectionMetrics(config, std::move(m), config.desired_recall_delta())); } return metrics; } std::vector<DetectionMetrics> ComputeDetectionMetrics( const Config& config, const std::vector<std::vector<DetectionMeasurements>>& measurements) { const int num_frames = measurements.size(); if (measurements.empty()) return {}; std::vector<DetectionMeasurements> measurements_merged = measurements[0]; for (int i = 1; i < num_frames; ++i) { MergeDetectionMeasurementsVector(measurements[i], &measurements_merged); } std::vector<DetectionMetrics> metrics; metrics.reserve(measurements_merged.size()); for (auto& m : measurements_merged) { metrics.emplace_back(ToDetectionMetrics(config, std::move(m), config.desired_recall_delta())); } return metrics; } Config EstimateScoreCutoffs(const Config& config, const std::vector<std::vector<Object>>& pds, const std::vector<std::vector<Object>>& gts) { CHECK_EQ(pds.size(), gts.size()); CHECK_EQ(config.score_cutoffs_size(), 0); std::vector<float> pd_scores; const int num_frames = pds.size(); Config config_copy(config); for (int frame_idx = 0; frame_idx < num_frames; ++frame_idx) { for (int pd_idx = 0, num_pds = pds[frame_idx].size(); pd_idx < num_pds; ++pd_idx) { pd_scores.push_back(pds[frame_idx][pd_idx].score()); } } std::sort(pd_scores.begin(), pd_scores.end()); std::vector<float> score_cutoffs = internal::DecideScoreCutoffs( pd_scores, config.num_desired_score_cutoffs()); for (auto s : score_cutoffs) { config_copy.add_score_cutoffs(s); } return config_copy; } } // namespace open_dataset } // namespace waymo
40.594907
80
0.675144
[ "object", "vector" ]
4f5b1473e6fbd14fea43d0cd2cf09bc69b00216a
18,126
cc
C++
src/sst/core/model/pymodel_comp.cc
AlecGrover/sst-core
3d5607f75f8912107246af8c38bc70c85e67915e
[ "BSD-3-Clause" ]
null
null
null
src/sst/core/model/pymodel_comp.cc
AlecGrover/sst-core
3d5607f75f8912107246af8c38bc70c85e67915e
[ "BSD-3-Clause" ]
null
null
null
src/sst/core/model/pymodel_comp.cc
AlecGrover/sst-core
3d5607f75f8912107246af8c38bc70c85e67915e
[ "BSD-3-Clause" ]
null
null
null
// -*- c++ -*- // Copyright 2009-2018 NTESS. Under the terms // of Contract DE-NA0003525 with NTESS, the U.S. // Government retains certain rights in this software. // // Copyright (c) 2009-2018, NTESS // All rights reserved. // // This file is part of the SST software package. For license // information, see the LICENSE file in the top level directory of the // distribution. #include "sst_config.h" #include <sst/core/warnmacros.h> DISABLE_WARN_DEPRECATED_REGISTER #include <Python.h> REENABLE_WARNING #include <string.h> #include <sstream> #include <sst/core/model/pymodel.h> #include <sst/core/model/pymodel_comp.h> #include <sst/core/model/pymodel_link.h> #include <sst/core/sst_types.h> #include <sst/core/simulation.h> #include <sst/core/element.h> #include <sst/core/component.h> #include <sst/core/subcomponent.h> #include <sst/core/configGraph.h> using namespace SST::Core; extern SST::Core::SSTPythonModelDefinition *gModel; extern "C" { ConfigComponent* ComponentHolder::getSubComp(const std::string &name, int slot_num) { for ( auto &sc : getComp()->subComponents ) { if ( sc.name == name && sc.slot_num == slot_num) return &sc; } return NULL; } ComponentId_t ComponentHolder::getID() { return getComp()->id; } const char* PyComponent::getName() const { return name; } ConfigComponent* PyComponent::getComp() { return &(gModel->getGraph()->getComponentMap()[id]); } PyComponent* PyComponent::getBaseObj() { return this; } int PyComponent::compare(ComponentHolder *other) { PyComponent *o = dynamic_cast<PyComponent*>(other); if ( o ) { return (id < o->id) ? -1 : (id > o->id) ? 1 : 0; } return 1; } const char* PySubComponent::getName() const { return name; } int PySubComponent::getSlot() const { return slot; } ConfigComponent* PySubComponent::getComp() { return parent->getSubComp(name,slot); } PyComponent* PySubComponent::getBaseObj() { return parent->getBaseObj(); } int PySubComponent::compare(ComponentHolder *other) { PySubComponent *o = dynamic_cast<PySubComponent*>(other); if ( o ) { int pCmp = parent->compare(o->parent); if ( pCmp == 0 ) /* Parents are equal */ pCmp = strcmp(name, o->name); return pCmp; } return -11; } static int compInit(ComponentPy_t *self, PyObject *args, PyObject *UNUSED(kwds)) { char *name, *type; ComponentId_t useID = UNSET_COMPONENT_ID; if ( !PyArg_ParseTuple(args, "ss|k", &name, &type, &useID) ) return -1; PyComponent *obj = new PyComponent(self); self->obj = obj; if ( useID == UNSET_COMPONENT_ID ) { obj->name = gModel->addNamePrefix(name); obj->id = gModel->addComponent(obj->name, type); gModel->getOutput()->verbose(CALL_INFO, 3, 0, "Creating component [%s] of type [%s]: id [%" PRIu64 "]\n", name, type, obj->id); } else { obj->name = name; obj->id = useID; } return 0; } static void compDealloc(ComponentPy_t *self) { if ( self->obj ) delete self->obj; self->ob_type->tp_free((PyObject*)self); } static PyObject* compAddParam(PyObject *self, PyObject *args) { char *param = NULL; PyObject *value = NULL; if ( !PyArg_ParseTuple(args, "sO", &param, &value) ) return NULL; ConfigComponent *c = getComp(self); if ( NULL == c ) return NULL; PyObject *vstr = PyObject_CallMethod(value, (char*)"__str__", NULL); c->addParameter(param, PyString_AsString(vstr), true); Py_XDECREF(vstr); return PyInt_FromLong(0); } static PyObject* compAddParams(PyObject *self, PyObject *args) { ConfigComponent *c = getComp(self); if ( NULL == c ) return NULL; if ( !PyDict_Check(args) ) { return NULL; } Py_ssize_t pos = 0; PyObject *key, *val; long count = 0; while ( PyDict_Next(args, &pos, &key, &val) ) { PyObject *kstr = PyObject_CallMethod(key, (char*)"__str__", NULL); PyObject *vstr = PyObject_CallMethod(val, (char*)"__str__", NULL); c->addParameter(PyString_AsString(kstr), PyString_AsString(vstr), true); Py_XDECREF(kstr); Py_XDECREF(vstr); count++; } return PyInt_FromLong(count); } static PyObject* compSetRank(PyObject *self, PyObject *args) { ConfigComponent *c = getComp(self); if ( NULL == c ) return NULL; PyErr_Clear(); unsigned long rank = (unsigned long)-1; unsigned long thread = (unsigned long)0; if ( !PyArg_ParseTuple(args, "k|k", &rank, &thread) ) { return NULL; } c->setRank(RankInfo(rank, thread)); return PyInt_FromLong(0); } static PyObject* compSetWeight(PyObject *self, PyObject *arg) { ConfigComponent *c = getComp(self); if ( NULL == c ) return NULL; PyErr_Clear(); double weight = PyFloat_AsDouble(arg); if ( PyErr_Occurred() ) { PyErr_Print(); exit(-1); } c->setWeight(weight); return PyInt_FromLong(0); } static PyObject* compAddLink(PyObject *self, PyObject *args) { ConfigComponent *c = getComp(self); ComponentId_t id = c->id; PyObject *plink = NULL; char *port = NULL, *lat = NULL; if ( !PyArg_ParseTuple(args, "O!s|s", &PyModel_LinkType, &plink, &port, &lat) ) { return NULL; } LinkPy_t* link = (LinkPy_t*)plink; if ( NULL == lat ) lat = link->latency; if ( NULL == lat ) return NULL; gModel->getOutput()->verbose(CALL_INFO, 4, 0, "Connecting component %" PRIu64 " to Link %s\n", id, link->name); gModel->addLink(id, link->name, port, lat, link->no_cut); return PyInt_FromLong(0); } static PyObject* compGetFullName(PyObject *self, PyObject *UNUSED(args)) { return PyString_FromString(getComp(self)->name.c_str()); } static int compCompare(PyObject *obj0, PyObject *obj1) { return ((ComponentPy_t*)obj0)->obj->compare(((ComponentPy_t*)obj1)->obj); } static PyObject* compSetSubComponent(PyObject *self, PyObject *args) { char *name = NULL, *type = NULL; int slot = 0; if ( !PyArg_ParseTuple(args, "ss|i", &name, &type, &slot) ) return NULL; ConfigComponent *c = getComp(self); if ( NULL == c ) return NULL; PyComponent *baseComp = ((ComponentPy_t*)self)->obj->getBaseObj(); ComponentId_t subC_id = SUBCOMPONENT_ID_CREATE(baseComp->id, ++(baseComp->subCompId)); if ( NULL != c->addSubComponent(subC_id, name, type, slot) ) { PyObject *argList = Py_BuildValue("Ossi", self, name, type, slot); PyObject *subObj = PyObject_CallObject((PyObject*)&PyModel_SubComponentType, argList); Py_DECREF(argList); return subObj; } char errMsg[1024] = {0}; snprintf(errMsg, sizeof(errMsg)-1, "Failed to create subcomponent %s on %s. Already attached a subcomponent at that slot name and number?\n", name, c->name.c_str()); PyErr_SetString(PyExc_RuntimeError, errMsg); return NULL; } static PyObject* compSetCoords(PyObject *self, PyObject *args) { std::vector<double> coords(3, 0.0); if ( !PyArg_ParseTuple(args, "d|dd", &coords[0], &coords[1], &coords[2]) ) { PyObject* list = NULL; if ( PyArg_ParseTuple(args, "O!", &PyList_Type, &list) && PyList_Size(list) > 0 ) { coords.clear(); for ( Py_ssize_t i = 0 ; i < PyList_Size(list) ; i++ ) { coords.push_back(PyFloat_AsDouble(PyList_GetItem(list, 0))); if ( PyErr_Occurred() ) goto error; } } else if ( PyArg_ParseTuple(args, "O!", &PyTuple_Type, &list) && PyTuple_Size(list) > 0 ) { coords.clear(); for ( Py_ssize_t i = 0 ; i < PyTuple_Size(list) ; i++ ) { coords.push_back(PyFloat_AsDouble(PyTuple_GetItem(list, 0))); if ( PyErr_Occurred() ) goto error; } } else { error: PyErr_SetString(PyExc_TypeError, "compSetCoords() expects arguments of 1-3 doubles, or a list/tuple of doubles"); return NULL; } } ConfigComponent *c = getComp(self); if ( NULL == c ) return NULL; c->setCoordinates(coords); return PyInt_FromLong(0); } static PyObject* compEnableAllStatistics(PyObject *self, PyObject *args) { int argOK = 0; PyObject* statParamDict = NULL; ConfigComponent *c = getComp(self); PyErr_Clear(); // Parse the Python Args and get optional Stat Params (as a Dictionary) argOK = PyArg_ParseTuple(args, "|O!", &PyDict_Type, &statParamDict); if (argOK) { c->enableStatistic(STATALLFLAG); // Generate and Add the Statistic Parameters for ( auto p : generateStatisticParameters(statParamDict) ) { c->addStatisticParameter(STATALLFLAG, p.first, p.second); } } else { // ParseTuple Failed, return NULL for error return NULL; } return PyInt_FromLong(0); } static PyObject* compEnableStatistics(PyObject *self, PyObject *args) { int argOK = 0; PyObject* statList = NULL; PyObject* statParamDict = NULL; Py_ssize_t numStats = 0; ConfigComponent *c = getComp(self); PyErr_Clear(); // Parse the Python Args and get A List Object and the optional Stat Params (as a Dictionary) argOK = PyArg_ParseTuple(args, "O!|O!", &PyList_Type, &statList, &PyDict_Type, &statParamDict); if (argOK) { // Generate the Statistic Parameters auto params = generateStatisticParameters(statParamDict); // Make sure we have a list if ( !PyList_Check(statList) ) { return NULL; } // Get the Number of Stats in the list, and enable them separately, // also set their parameters numStats = PyList_Size(statList); for (uint32_t x = 0; x < numStats; x++) { PyObject* pylistitem = PyList_GetItem(statList, x); PyObject* pyname = PyObject_CallMethod(pylistitem, (char*)"__str__", NULL); c->enableStatistic(PyString_AsString(pyname)); // Add the parameters for ( auto p : params ) { c->addStatisticParameter(PyString_AsString(pyname), p.first, p.second); } Py_XDECREF(pyname); } } else { // ParseTuple Failed, return NULL for error return NULL; } return PyInt_FromLong(0); } static PyMethodDef componentMethods[] = { { "addParam", compAddParam, METH_VARARGS, "Adds a parameter(name, value)"}, { "addParams", compAddParams, METH_O, "Adds Multiple Parameters from a dict"}, { "setRank", compSetRank, METH_VARARGS, "Sets which rank on which this component should sit"}, { "setWeight", compSetWeight, METH_O, "Sets the weight of the component"}, { "addLink", compAddLink, METH_VARARGS, "Connects this component to a Link"}, { "getFullName", compGetFullName, METH_NOARGS, "Returns the full name, after any prefix, of the component."}, { "enableAllStatistics", compEnableAllStatistics, METH_VARARGS, "Enable all Statistics in the component with optional parameters"}, { "enableStatistics", compEnableStatistics, METH_VARARGS, "Enables Multiple Statistics in the component with optional parameters"}, { "setSubComponent", compSetSubComponent, METH_VARARGS, "Bind a subcomponent to slot <name>, with type <type>"}, { "setCoordinates", compSetCoords, METH_VARARGS, "Set (X,Y,Z) coordinates of this component, for use with visualization"}, { NULL, NULL, 0, NULL } }; PyTypeObject PyModel_ComponentType = { PyObject_HEAD_INIT(NULL) 0, /* ob_size */ "sst.Component", /* tp_name */ sizeof(ComponentPy_t), /* tp_basicsize */ 0, /* tp_itemsize */ (destructor)compDealloc, /* tp_dealloc */ 0, /* tp_print */ 0, /* tp_getattr */ 0, /* tp_setattr */ compCompare, /* tp_compare */ 0, /* tp_repr */ 0, /* tp_as_number */ 0, /* tp_as_sequence */ 0, /* tp_as_mapping */ 0, /* tp_hash */ 0, /* tp_call */ 0, /* tp_str */ 0, /* tp_getattro */ 0, /* tp_setattro */ 0, /* tp_as_buffer */ Py_TPFLAGS_DEFAULT, /* tp_flags */ "SST Component", /* tp_doc */ 0, /* tp_traverse */ 0, /* tp_clear */ 0, /* tp_richcompare */ 0, /* tp_weaklistoffset */ 0, /* tp_iter */ 0, /* tp_iternext */ componentMethods, /* tp_methods */ 0, /* tp_members */ 0, /* tp_getset */ 0, /* tp_base */ 0, /* tp_dict */ 0, /* tp_descr_get */ 0, /* tp_descr_set */ 0, /* tp_dictoffset */ (initproc)compInit, /* tp_init */ 0, /* tp_alloc */ 0, /* tp_new */ 0, /* tp_free */ 0, /* tp_is_gc */ 0, /* tp_bases */ 0, /* tp_mro */ 0, /* tp_cache */ 0, /* tp_subclasses */ 0, /* tp_weaklist */ 0, /* tp_del */ 0, /* tp_version_tag */ }; static int subCompInit(ComponentPy_t *self, PyObject *args, PyObject *UNUSED(kwds)) { char *name, *type; int slot; PyObject *parent; if ( !PyArg_ParseTuple(args, "Ossi", &parent, &name, &type, &slot) ) return -1; PySubComponent *obj = new PySubComponent(self); obj->parent = ((ComponentPy_t*)parent)->obj; obj->name = strdup(name); obj->slot = slot; self->obj = obj; Py_INCREF(obj->parent->pobj); gModel->getOutput()->verbose(CALL_INFO, 3, 0, "Creating subcomponent [%s] of type [%s]]\n", name, type); return 0; } static void subCompDealloc(ComponentPy_t *self) { if ( self->obj ) { PySubComponent *obj = (PySubComponent*)self->obj; Py_XDECREF(obj->parent->pobj); delete self->obj; } self->ob_type->tp_free((PyObject*)self); } static PyMethodDef subComponentMethods[] = { { "addParam", compAddParam, METH_VARARGS, "Adds a parameter(name, value)"}, { "addParams", compAddParams, METH_O, "Adds Multiple Parameters from a dict"}, { "addLink", compAddLink, METH_VARARGS, "Connects this subComponent to a Link"}, { "enableAllStatistics", compEnableAllStatistics, METH_VARARGS, "Enable all Statistics in the component with optional parameters"}, { "enableStatistics", compEnableStatistics, METH_VARARGS, "Enables Multiple Statistics in the component with optional parameters"}, { "setSubComponent", compSetSubComponent, METH_VARARGS, "Bind a subcomponent to slot <name>, with type <type>"}, { "setCoordinates", compSetCoords, METH_VARARGS, "Set (X,Y,Z) coordinates of this component, for use with visualization"}, { NULL, NULL, 0, NULL } }; PyTypeObject PyModel_SubComponentType = { PyObject_HEAD_INIT(NULL) 0, /* ob_size */ "sst.SubComponent", /* tp_name */ sizeof(ComponentPy_t), /* tp_basicsize */ 0, /* tp_itemsize */ (destructor)subCompDealloc,/* tp_dealloc */ 0, /* tp_print */ 0, /* tp_getattr */ 0, /* tp_setattr */ compCompare, /* tp_compare */ 0, /* tp_repr */ 0, /* tp_as_number */ 0, /* tp_as_sequence */ 0, /* tp_as_mapping */ 0, /* tp_hash */ 0, /* tp_call */ 0, /* tp_str */ 0, /* tp_getattro */ 0, /* tp_setattro */ 0, /* tp_as_buffer */ Py_TPFLAGS_DEFAULT, /* tp_flags */ "SST SubComponent", /* tp_doc */ 0, /* tp_traverse */ 0, /* tp_clear */ 0, /* tp_richcompare */ 0, /* tp_weaklistoffset */ 0, /* tp_iter */ 0, /* tp_iternext */ subComponentMethods, /* tp_methods */ 0, /* tp_members */ 0, /* tp_getset */ 0, /* tp_base */ 0, /* tp_dict */ 0, /* tp_descr_get */ 0, /* tp_descr_set */ 0, /* tp_dictoffset */ (initproc)subCompInit, /* tp_init */ 0, /* tp_alloc */ 0, /* tp_new */ 0, /* tp_free */ 0, /* tp_is_gc */ 0, /* tp_bases */ 0, /* tp_mro */ 0, /* tp_cache */ 0, /* tp_subclasses */ 0, /* tp_weaklist */ 0, /* tp_del */ 0, /* tp_version_tag */ }; } /* extern C */
30.56661
170
0.54248
[ "object", "vector", "model" ]
4f5b3363a45f20b2629084e9420fccddd2ab69f8
474
cpp
C++
Dataset/Leetcode/train/62/453.cpp
kkcookies99/UAST
fff81885aa07901786141a71e5600a08d7cb4868
[ "MIT" ]
null
null
null
Dataset/Leetcode/train/62/453.cpp
kkcookies99/UAST
fff81885aa07901786141a71e5600a08d7cb4868
[ "MIT" ]
null
null
null
Dataset/Leetcode/train/62/453.cpp
kkcookies99/UAST
fff81885aa07901786141a71e5600a08d7cb4868
[ "MIT" ]
null
null
null
class Solution { public: int XXX(int m, int n) { //定义dp[j]为到达 【i,j】这个点的方法 vector<int> dp(n); dp[0] = 1; for(int i = 0;i<m;++i ){ for(int j = 0;j<n;++j){ if(j == 0){ dp[j] = dp[j]; }else if( i == 0 ){ dp[j] = dp[j-1]; }else{ dp[j] += dp[j-1]; } } } return dp[n-1]; } };
21.545455
37
0.280591
[ "vector" ]
4f5b4cba779905c2d01adb13976db8a1dc855ef1
8,468
cpp
C++
source/blender/freestyle/intern/view_map/SteerableViewMap.cpp
1-MillionParanoidTterabytes/Blender-2.79b-blackened
e8d767324e69015aa66850d13bee7db1dc7d084b
[ "Unlicense" ]
2
2018-06-18T01:50:25.000Z
2018-06-18T01:50:32.000Z
source/blender/freestyle/intern/view_map/SteerableViewMap.cpp
1-MillionParanoidTterabytes/Blender-2.79b-blackened
e8d767324e69015aa66850d13bee7db1dc7d084b
[ "Unlicense" ]
null
null
null
source/blender/freestyle/intern/view_map/SteerableViewMap.cpp
1-MillionParanoidTterabytes/Blender-2.79b-blackened
e8d767324e69015aa66850d13bee7db1dc7d084b
[ "Unlicense" ]
null
null
null
/* * ***** BEGIN GPL LICENSE BLOCK ***** * * 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; either version 2 * of the License, or (at your option) any later version. * * 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. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * * ***** END GPL LICENSE BLOCK ***** */ /** \file blender/freestyle/intern/view_map/SteerableViewMap.cpp * \ingroup freestyle * \brief Convenient access to the steerable ViewMap to which any element of the ViewMap belongs to. * \author Stephane Grabli * \date 01/07/2003 */ #include <sstream> #include "Silhouette.h" #include "SteerableViewMap.h" #include "../geometry/Geom.h" #include "../image/ImagePyramid.h" #include "../image/Image.h" #include "BKE_global.h" #include "BLI_math.h" extern "C" { #include "IMB_imbuf.h" #include "IMB_imbuf_types.h" } namespace Freestyle { using namespace Geometry; SteerableViewMap::SteerableViewMap(unsigned int nbOrientations) { _nbOrientations = nbOrientations; _bound = cos(M_PI / (float)_nbOrientations); for (unsigned int i = 0; i < _nbOrientations; ++i) { _directions.push_back(Vec2d(cos((float)i * M_PI / (float)_nbOrientations), sin((float)i * M_PI / (float)_nbOrientations))); } Build(); } void SteerableViewMap::Build() { _imagesPyramids = new ImagePyramid *[_nbOrientations + 1]; // one more map to store the complete visible VM memset((_imagesPyramids), 0, (_nbOrientations + 1) * sizeof(ImagePyramid *)); } SteerableViewMap::SteerableViewMap(const SteerableViewMap& iBrother) { _nbOrientations = iBrother._nbOrientations; unsigned int i; _bound = iBrother._bound; _directions = iBrother._directions; _mapping = iBrother._mapping; _imagesPyramids = new ImagePyramid *[_nbOrientations + 1]; // one more map to store the complete visible VM for (i = 0; i <= _nbOrientations; ++i) _imagesPyramids[i] = new GaussianPyramid(*(dynamic_cast<GaussianPyramid*>(iBrother._imagesPyramids[i]))); } SteerableViewMap::~SteerableViewMap() { Clear(); } void SteerableViewMap::Clear() { unsigned int i; if (_imagesPyramids) { for (i = 0; i <= _nbOrientations; ++i) { if (_imagesPyramids[i]) delete (_imagesPyramids)[i]; } delete[] _imagesPyramids; _imagesPyramids = 0; } if (!_mapping.empty()) { for (map<unsigned int, double*>::iterator m = _mapping.begin(), mend = _mapping.end(); m != mend; ++m) { delete[] (*m).second; } _mapping.clear(); } } void SteerableViewMap::Reset() { Clear(); Build(); } double SteerableViewMap::ComputeWeight(const Vec2d& dir, unsigned i) { double dotp = fabs(dir * _directions[i]); if (dotp < _bound) return 0.0; if (dotp > 1.0) dotp = 1.0; return cos((float)_nbOrientations / 2.0 * acos(dotp)); } double *SteerableViewMap::AddFEdge(FEdge *iFEdge) { unsigned i; unsigned id = iFEdge->getId().getFirst(); map<unsigned int, double *>::iterator o = _mapping.find(id); if (o != _mapping.end()) { return (*o).second; } double *res = new double[_nbOrientations]; for (i = 0; i < _nbOrientations; ++i) { res[i] = 0.0; } Vec3r o2d3 = iFEdge->orientation2d(); Vec2r o2d2(o2d3.x(), o2d3.y()); real norm = o2d2.norm(); if (norm < 1.0e-6) { return res; } o2d2 /= norm; for (i = 0; i < _nbOrientations; ++i) { res[i] = ComputeWeight(o2d2, i); } _mapping[id] = res; return res; } unsigned SteerableViewMap::getSVMNumber(const Vec2f& orient) { Vec2f dir(orient); //soc unsigned res = 0; real norm = dir.norm(); if (norm < 1.0e-6) { return _nbOrientations + 1; } dir /= norm; double maxw = 0.0f; unsigned winner = _nbOrientations + 1; for (unsigned int i = 0; i < _nbOrientations; ++i) { double w = ComputeWeight(dir, i); if (w > maxw) { maxw = w; winner = i; } } return winner; } unsigned SteerableViewMap::getSVMNumber(unsigned id) { map<unsigned int, double *>::iterator o = _mapping.find(id); if (o != _mapping.end()) { double *wvalues = (*o).second; double maxw = 0.0; unsigned winner = _nbOrientations + 1; for (unsigned i = 0; i < _nbOrientations; ++i) { double w = wvalues[i]; if (w > maxw) { maxw = w; winner = i; } } return winner; } return _nbOrientations + 1; } void SteerableViewMap::buildImagesPyramids(GrayImage **steerableBases, bool copy, unsigned iNbLevels, float iSigma) { for (unsigned int i = 0; i <= _nbOrientations; ++i) { ImagePyramid *svm = (_imagesPyramids)[i]; if (svm) delete svm; if (copy) svm = new GaussianPyramid(*(steerableBases[i]), iNbLevels, iSigma); else svm = new GaussianPyramid(steerableBases[i], iNbLevels, iSigma); _imagesPyramids[i] = svm; } } float SteerableViewMap::readSteerableViewMapPixel(unsigned iOrientation, int iLevel, int x, int y) { ImagePyramid *pyramid = _imagesPyramids[iOrientation]; if (!pyramid) { if (G.debug & G_DEBUG_FREESTYLE) { cout << "Warning: this steerable ViewMap level doesn't exist" << endl; } return 0.0f; } if ((x < 0) || (x >= pyramid->width()) || (y < 0) || (y >= pyramid->height())) return 0; //float v = pyramid->pixel(x, pyramid->height() - 1 - y, iLevel) * 255.0f; // We encode both the directionality and the lines counting on 8 bits (because of frame buffer). Thus, we allow // until 8 lines to pass through the same pixel, so that we can discretize the Pi/_nbOrientations angle into // 32 slices. Therefore, for example, in the vertical direction, a vertical line will have the value 32 on // each pixel it passes through. float v = pyramid->pixel(x, pyramid->height() - 1 - y, iLevel) / 32.0f; return v; } float SteerableViewMap::readCompleteViewMapPixel(int iLevel, int x, int y) { return readSteerableViewMapPixel(_nbOrientations, iLevel, x, y); } unsigned int SteerableViewMap::getNumberOfPyramidLevels() const { if (_imagesPyramids[0]) return _imagesPyramids[0]->getNumberOfLevels(); return 0; } void SteerableViewMap::saveSteerableViewMap() const { for (unsigned int i = 0; i <= _nbOrientations; ++i) { if (_imagesPyramids[i] == 0) { cerr << "SteerableViewMap warning: orientation " << i << " of steerable View Map whas not been computed yet" << endl; continue; } int ow = _imagesPyramids[i]->width(0); int oh = _imagesPyramids[i]->height(0); //soc QString base("SteerableViewMap"); string base("SteerableViewMap"); stringstream filename; for (int j = 0; j < _imagesPyramids[i]->getNumberOfLevels(); ++j) { //soc float coeff = 1.0f; // 1 / 255.0f; // 100 * 255; // * pow(2, j); //soc QImage qtmp(ow, oh, QImage::Format_RGB32); ImBuf *ibuf = IMB_allocImBuf(ow, oh, 32, IB_rect); int rowbytes = ow * 4; char *pix; for (int y = 0; y < oh; ++y) { //soc for (int x = 0; x < ow; ++x) { //soc int c = (int)(coeff * _imagesPyramids[i]->pixel(x, y, j)); if (c > 255) c = 255; //int c = (int)(_imagesPyramids[i]->pixel(x, y, j)); //soc qtmp.setPixel(x, y, qRgb(c, c, c)); pix = (char *)ibuf->rect + y * rowbytes + x * 4; pix[0] = pix[1] = pix[2] = c; } } //soc qtmp.save(base+QString::number(i)+"-"+QString::number(j)+".png", "PNG"); filename << base; filename << i << "-" << j << ".png"; ibuf->ftype = IMB_FTYPE_PNG; IMB_saveiff(ibuf, const_cast<char *>(filename.str().c_str()), 0); } #if 0 QString base("SteerableViewMap"); for (unsigned j = 0; j < _imagesPyramids[i]->getNumberOfLevels(); ++j) { GrayImage *img = _imagesPyramids[i]->getLevel(j); int ow = img->width(); int oh = img->height(); float coeff = 1.0f; // 100 * 255; // * pow(2, j); QImage qtmp(ow, oh, 32); for (unsigned int y = 0; y < oh; ++y) { for (unsigned int x = 0; x < ow; ++x) { int c = (int)(coeff * img->pixel(x, y)); if (c > 255) c = 255; //int c = (int)(_imagesPyramids[i]->pixel(x, y, j)); qtmp.setPixel(x, y, qRgb(c, c, c)); } } qtmp.save(base + QString::number(i) + "-" + QString::number(j) + ".png", "PNG"); } #endif } } } /* namespace Freestyle */
28.416107
115
0.652929
[ "geometry" ]
4f5bd4f69906871808260fad9653a3fe4534c1d3
34,010
cpp
C++
folly/test/FunctionTest.cpp
aloknnikhil/folly
f4fb4266c044a959f8f01bee88c2f502939f527f
[ "Apache-2.0" ]
1
2020-01-10T05:54:31.000Z
2020-01-10T05:54:31.000Z
folly/test/FunctionTest.cpp
aloknnikhil/folly
f4fb4266c044a959f8f01bee88c2f502939f527f
[ "Apache-2.0" ]
1
2021-05-26T00:37:20.000Z
2021-05-26T00:37:20.000Z
folly/test/FunctionTest.cpp
aloknnikhil/folly
f4fb4266c044a959f8f01bee88c2f502939f527f
[ "Apache-2.0" ]
1
2020-01-10T05:54:43.000Z
2020-01-10T05:54:43.000Z
/* * Copyright (c) Facebook, Inc. and its affiliates. * * 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 <array> #include <cstdarg> #include <folly/Function.h> #include <folly/Memory.h> #include <folly/portability/GTest.h> using folly::Function; using folly::FunctionRef; namespace { int func_int_int_add_25(int x) { return x + 25; } int func_int_int_add_111(int x) { return x + 111; } float floatMult(float a, float b) { return a * b; } template <class T, size_t S> struct Functor { std::array<T, S> data = {{0}}; // Two operator() with different argument types. // The InvokeReference tests use both T const& operator()(size_t index) const { return data[index]; } T operator()(size_t index, T const& value) { T oldvalue = data[index]; data[index] = value; return oldvalue; } }; template <typename Ret, typename... Args> void deduceArgs(Function<Ret(Args...)>) {} struct CallableButNotCopyable { CallableButNotCopyable() {} CallableButNotCopyable(CallableButNotCopyable const&) = delete; CallableButNotCopyable(CallableButNotCopyable&&) = delete; CallableButNotCopyable& operator=(CallableButNotCopyable const&) = delete; CallableButNotCopyable& operator=(CallableButNotCopyable&&) = delete; template <class... Args> void operator()(Args&&...) const {} }; } // namespace // TEST ===================================================================== // Test constructibility and non-constructibility for some tricky conversions static_assert( !std::is_assignable<Function<void()>, CallableButNotCopyable>::value, ""); static_assert( !std::is_constructible<Function<void()>, CallableButNotCopyable&>::value, ""); static_assert( !std::is_constructible<Function<void() const>, CallableButNotCopyable>:: value, ""); static_assert( !std::is_constructible<Function<void() const>, CallableButNotCopyable&>:: value, ""); static_assert( !std::is_assignable<Function<void()>, CallableButNotCopyable>::value, ""); static_assert( !std::is_assignable<Function<void()>, CallableButNotCopyable&>::value, ""); static_assert( !std::is_assignable<Function<void() const>, CallableButNotCopyable>::value, ""); static_assert( !std::is_assignable<Function<void() const>, CallableButNotCopyable&>::value, ""); static_assert( std::is_constructible<Function<int(int)>, Function<int(int) const>>::value, ""); static_assert( !std::is_constructible<Function<int(int) const>, Function<int(int)>>::value, ""); static_assert( std::is_constructible<Function<int(short)>, Function<short(int) const>>:: value, ""); static_assert( !std::is_constructible<Function<int(short) const>, Function<short(int)>>:: value, ""); static_assert( !std::is_constructible<Function<int(int)>, Function<int(int) const>&>:: value, ""); static_assert( !std::is_constructible<Function<int(int) const>, Function<int(int)>&>:: value, ""); static_assert( !std::is_constructible<Function<int(short)>, Function<short(int) const>&>:: value, ""); static_assert( !std::is_constructible<Function<int(short) const>, Function<short(int)>&>:: value, ""); static_assert( std::is_assignable<Function<int(int)>, Function<int(int) const>>::value, ""); static_assert( !std::is_assignable<Function<int(int) const>, Function<int(int)>>::value, ""); static_assert( std::is_assignable<Function<int(short)>, Function<short(int) const>>::value, ""); static_assert( !std::is_assignable<Function<int(short) const>, Function<short(int)>>:: value, ""); static_assert( !std::is_assignable<Function<int(int)>, Function<int(int) const>&>::value, ""); static_assert( !std::is_assignable<Function<int(int) const>, Function<int(int)>&>::value, ""); static_assert( !std::is_assignable<Function<int(short)>, Function<short(int) const>&>:: value, ""); static_assert( !std::is_assignable<Function<int(short) const>, Function<short(int)>&>:: value, ""); static_assert( std::is_nothrow_constructible< Function<int(int)>, Function<int(int) const>>::value, ""); static_assert( !std::is_nothrow_constructible< Function<int(short)>, Function<short(int) const>>::value, ""); static_assert( std::is_nothrow_assignable<Function<int(int)>, Function<int(int) const>>:: value, ""); static_assert( !std::is_nothrow_assignable< Function<int(short)>, Function<short(int) const>>::value, ""); static_assert( !std::is_constructible<Function<int const&()>, int (*)()>::value, ""); static_assert( !std::is_constructible<Function<int const&() const>, int (*)()>::value, ""); #if FOLLY_HAVE_NOEXCEPT_FUNCTION_TYPE static_assert( !std::is_constructible<Function<int const&() noexcept>, int (*)()>::value, ""); static_assert( !std::is_constructible<Function<int const&() const noexcept>, int (*)()>:: value, ""); #endif // TEST ===================================================================== // InvokeFunctor & InvokeReference TEST(Function, InvokeFunctor) { Functor<int, 100> func; static_assert( sizeof(func) > sizeof(Function<int(size_t)>), "sizeof(Function) is much larger than expected"); func(5, 123); Function<int(size_t) const> getter = std::move(func); // Function will allocate memory on the heap to store the functor object EXPECT_GT(getter.heapAllocatedMemory(), 0); EXPECT_EQ(123, getter(5)); } TEST(Function, InvokeReference) { Functor<int, 10> func; func(5, 123); // Have Functions for getter and setter, both referencing the same funtor Function<int(size_t) const> getter = std::ref(func); Function<int(size_t, int)> setter = std::ref(func); EXPECT_EQ(123, getter(5)); EXPECT_EQ(123, setter(5, 456)); EXPECT_EQ(456, setter(5, 567)); EXPECT_EQ(567, getter(5)); } // TEST ===================================================================== // Emptiness TEST(Function, Emptiness_T) { Function<int(int)> f; EXPECT_EQ(f, nullptr); EXPECT_EQ(nullptr, f); EXPECT_FALSE(f); EXPECT_THROW(f(98), std::bad_function_call); Function<int(int)> g([](int x) { return x + 1; }); EXPECT_NE(g, nullptr); EXPECT_NE(nullptr, g); // Explicitly convert to bool to work around // https://github.com/google/googletest/issues/429 EXPECT_TRUE(bool(g)); EXPECT_EQ(100, g(99)); Function<int(int)> h(&func_int_int_add_25); EXPECT_NE(h, nullptr); EXPECT_NE(nullptr, h); EXPECT_TRUE(bool(h)); EXPECT_EQ(125, h(100)); h = {}; EXPECT_EQ(h, nullptr); EXPECT_EQ(nullptr, h); EXPECT_FALSE(h); EXPECT_THROW(h(101), std::bad_function_call); Function<int(int)> i{Function<int(int)>{}}; EXPECT_EQ(i, nullptr); EXPECT_EQ(nullptr, i); EXPECT_FALSE(i); EXPECT_THROW(i(107), std::bad_function_call); struct CastableToBool { bool val; /* implicit */ CastableToBool(bool b) : val(b) {} explicit operator bool() { return val; } }; // models std::function struct NullptrTestableInSitu { int res; explicit NullptrTestableInSitu(std::nullptr_t) : res(1) {} explicit NullptrTestableInSitu(int i) : res(i) {} CastableToBool operator==(std::nullptr_t) const { return res % 3 != 1; } int operator()(int in) const { return res * in; } }; struct NullptrTestableOnHeap : NullptrTestableInSitu { unsigned char data[1024 - sizeof(NullptrTestableInSitu)]; using NullptrTestableInSitu::NullptrTestableInSitu; }; Function<int(int)> j(NullptrTestableInSitu(2)); EXPECT_EQ(j, nullptr); EXPECT_EQ(nullptr, j); EXPECT_FALSE(j); EXPECT_THROW(j(107), std::bad_function_call); Function<int(int)> k(NullptrTestableInSitu(4)); EXPECT_NE(k, nullptr); EXPECT_NE(nullptr, k); EXPECT_TRUE(k); EXPECT_EQ(428, k(107)); Function<int(int)> l(NullptrTestableOnHeap(2)); EXPECT_EQ(l, nullptr); EXPECT_EQ(nullptr, l); EXPECT_FALSE(l); EXPECT_THROW(l(107), std::bad_function_call); Function<int(int)> m(NullptrTestableOnHeap(4)); EXPECT_NE(m, nullptr); EXPECT_NE(nullptr, m); EXPECT_TRUE(m); EXPECT_EQ(428, m(107)); auto noopfun = [] {}; EXPECT_EQ(nullptr, FunctionRef<void()>(nullptr)); EXPECT_NE(nullptr, FunctionRef<void()>(noopfun)); EXPECT_EQ(FunctionRef<void()>(nullptr), nullptr); EXPECT_NE(FunctionRef<void()>(noopfun), nullptr); } // TEST ===================================================================== // Swap template <bool UseSwapMethod> void swap_test() { Function<int(int)> mf1(func_int_int_add_25); Function<int(int)> mf2(func_int_int_add_111); EXPECT_EQ(125, mf1(100)); EXPECT_EQ(211, mf2(100)); if (UseSwapMethod) { mf1.swap(mf2); } else { swap(mf1, mf2); } EXPECT_EQ(125, mf2(100)); EXPECT_EQ(211, mf1(100)); Function<int(int)> mf3(nullptr); EXPECT_EQ(mf3, nullptr); if (UseSwapMethod) { mf1.swap(mf3); } else { swap(mf1, mf3); } EXPECT_EQ(211, mf3(100)); EXPECT_EQ(nullptr, mf1); Function<int(int)> mf4([](int x) { return x + 222; }); EXPECT_EQ(322, mf4(100)); if (UseSwapMethod) { mf4.swap(mf3); } else { swap(mf4, mf3); } EXPECT_EQ(211, mf4(100)); EXPECT_EQ(322, mf3(100)); if (UseSwapMethod) { mf3.swap(mf1); } else { swap(mf3, mf1); } EXPECT_EQ(nullptr, mf3); EXPECT_EQ(322, mf1(100)); } TEST(Function, SwapMethod) { swap_test<true>(); } TEST(Function, SwapFunction) { swap_test<false>(); } // TEST ===================================================================== // Bind TEST(Function, Bind) { Function<float(float, float)> fnc = floatMult; auto task = std::bind(std::move(fnc), 2.f, 4.f); EXPECT_THROW(fnc(0, 0), std::bad_function_call); EXPECT_EQ(8, task()); auto task2(std::move(task)); EXPECT_THROW(task(), std::bad_function_call); EXPECT_EQ(8, task2()); } // TEST ===================================================================== // NonCopyableLambda TEST(Function, NonCopyableLambda) { auto unique_ptr_int = std::make_unique<int>(900); EXPECT_EQ(900, *unique_ptr_int); struct { char data[64]; } fooData = {{0}}; (void)fooData; // suppress gcc warning about fooData not being used auto functor = std::bind( [fooData](std::unique_ptr<int>& up) mutable { (void)fooData; return ++*up; }, std::move(unique_ptr_int)); EXPECT_EQ(901, functor()); Function<int(void)> func = std::move(functor); EXPECT_GT(func.heapAllocatedMemory(), 0); EXPECT_EQ(902, func()); } // TEST ===================================================================== // OverloadedFunctor TEST(Function, OverloadedFunctor) { struct OverloadedFunctor { // variant 1 int operator()(int x) { return 100 + 1 * x; } // variant 2 (const-overload of v1) int operator()(int x) const { return 100 + 2 * x; } // variant 3 int operator()(int x, int) { return 100 + 3 * x; } // variant 4 (const-overload of v3) int operator()(int x, int) const { return 100 + 4 * x; } // variant 5 (non-const, has no const-overload) int operator()(int x, char const*) { return 100 + 5 * x; } // variant 6 (const only) int operator()(int x, std::vector<int> const&) const { return 100 + 6 * x; } }; OverloadedFunctor of; Function<int(int)> variant1 = of; EXPECT_EQ(100 + 1 * 15, variant1(15)); Function<int(int) const> variant2 = of; EXPECT_EQ(100 + 2 * 16, variant2(16)); Function<int(int, int)> variant3 = of; EXPECT_EQ(100 + 3 * 17, variant3(17, 0)); Function<int(int, int) const> variant4 = of; EXPECT_EQ(100 + 4 * 18, variant4(18, 0)); Function<int(int, char const*)> variant5 = of; EXPECT_EQ(100 + 5 * 19, variant5(19, "foo")); Function<int(int, std::vector<int> const&)> variant6 = of; EXPECT_EQ(100 + 6 * 20, variant6(20, {})); EXPECT_EQ(100 + 6 * 20, variant6(20, {1, 2, 3})); Function<int(int, std::vector<int> const&) const> variant6const = of; EXPECT_EQ(100 + 6 * 21, variant6const(21, {})); // Cast const-functions to non-const and the other way around: if the functor // has both const and non-const operator()s for a given parameter signature, // constructing a Function must select one of them, depending on // whether the function type template parameter is const-qualified or not. // When the const-ness is later changed (by moving the // Function<R(Args...)const> into a Function<R(Args...)> or by // calling the folly::constCastFunction which moves it into a // Function<R(Args...)const>), the Function must still execute // the initially selected function. auto variant1_const = folly::constCastFunction(std::move(variant1)); EXPECT_THROW(variant1(0), std::bad_function_call); EXPECT_EQ(100 + 1 * 22, variant1_const(22)); Function<int(int)> variant2_nonconst = std::move(variant2); EXPECT_THROW(variant2(0), std::bad_function_call); EXPECT_EQ(100 + 2 * 23, variant2_nonconst(23)); auto variant3_const = folly::constCastFunction(std::move(variant3)); EXPECT_THROW(variant3(0, 0), std::bad_function_call); EXPECT_EQ(100 + 3 * 24, variant3_const(24, 0)); Function<int(int, int)> variant4_nonconst = std::move(variant4); EXPECT_THROW(variant4(0, 0), std::bad_function_call); EXPECT_EQ(100 + 4 * 25, variant4_nonconst(25, 0)); auto variant5_const = folly::constCastFunction(std::move(variant5)); EXPECT_THROW(variant5(0, ""), std::bad_function_call); EXPECT_EQ(100 + 5 * 26, variant5_const(26, "foo")); auto variant6_const = folly::constCastFunction(std::move(variant6)); EXPECT_THROW(variant6(0, {}), std::bad_function_call); EXPECT_EQ(100 + 6 * 27, variant6_const(27, {})); Function<int(int, std::vector<int> const&)> variant6const_nonconst = std::move(variant6const); EXPECT_THROW(variant6const(0, {}), std::bad_function_call); EXPECT_EQ(100 + 6 * 28, variant6const_nonconst(28, {})); } // TEST ===================================================================== // Lambda TEST(Function, Lambda) { // Non-mutable lambdas: can be stored in a non-const... Function<int(int)> func = [](int x) { return 1000 + x; }; EXPECT_EQ(1001, func(1)); // ...as well as in a const Function Function<int(int) const> func_const = [](int x) { return 2000 + x; }; EXPECT_EQ(2001, func_const(1)); // Mutable lambda: can only be stored in a const Function: int number = 3000; Function<int()> func_mutable = [number]() mutable { return ++number; }; EXPECT_EQ(3001, func_mutable()); EXPECT_EQ(3002, func_mutable()); // test after const-casting Function<int(int) const> func_made_const = folly::constCastFunction(std::move(func)); EXPECT_EQ(1002, func_made_const(2)); EXPECT_THROW(func(0), std::bad_function_call); Function<int(int)> func_const_made_nonconst = std::move(func_const); EXPECT_EQ(2002, func_const_made_nonconst(2)); EXPECT_THROW(func_const(0), std::bad_function_call); Function<int() const> func_mutable_made_const = folly::constCastFunction(std::move(func_mutable)); EXPECT_EQ(3003, func_mutable_made_const()); EXPECT_EQ(3004, func_mutable_made_const()); EXPECT_THROW(func_mutable(), std::bad_function_call); } // TEST ===================================================================== // DataMember & MemberFunction struct MemberFunc { int x; int getX() const { return x; } void setX(int xx) { x = xx; } }; TEST(Function, DataMember) { MemberFunc mf; MemberFunc const& cmf = mf; mf.x = 123; Function<int(MemberFunc const*)> data_getter1 = &MemberFunc::x; EXPECT_EQ(123, data_getter1(&cmf)); Function<int(MemberFunc*)> data_getter2 = &MemberFunc::x; EXPECT_EQ(123, data_getter2(&mf)); Function<int(MemberFunc const&)> data_getter3 = &MemberFunc::x; EXPECT_EQ(123, data_getter3(cmf)); Function<int(MemberFunc&)> data_getter4 = &MemberFunc::x; EXPECT_EQ(123, data_getter4(mf)); } TEST(Function, MemberFunction) { MemberFunc mf; MemberFunc const& cmf = mf; mf.x = 123; Function<int(MemberFunc const*)> getter1 = &MemberFunc::getX; EXPECT_EQ(123, getter1(&cmf)); Function<int(MemberFunc*)> getter2 = &MemberFunc::getX; EXPECT_EQ(123, getter2(&mf)); Function<int(MemberFunc const&)> getter3 = &MemberFunc::getX; EXPECT_EQ(123, getter3(cmf)); Function<int(MemberFunc&)> getter4 = &MemberFunc::getX; EXPECT_EQ(123, getter4(mf)); Function<void(MemberFunc*, int)> setter1 = &MemberFunc::setX; setter1(&mf, 234); EXPECT_EQ(234, mf.x); Function<void(MemberFunc&, int)> setter2 = &MemberFunc::setX; setter2(mf, 345); EXPECT_EQ(345, mf.x); } // TEST ===================================================================== // CaptureCopyMoveCount & ParameterCopyMoveCount class CopyMoveTracker { public: struct ConstructorTag {}; CopyMoveTracker() = delete; explicit CopyMoveTracker(ConstructorTag) : data_(std::make_shared<std::pair<size_t, size_t>>(0, 0)) {} CopyMoveTracker(CopyMoveTracker const& o) noexcept : data_(o.data_) { ++data_->first; } CopyMoveTracker& operator=(CopyMoveTracker const& o) noexcept { data_ = o.data_; ++data_->first; return *this; } CopyMoveTracker(CopyMoveTracker&& o) noexcept : data_(o.data_) { ++data_->second; } CopyMoveTracker& operator=(CopyMoveTracker&& o) noexcept { data_ = o.data_; ++data_->second; return *this; } size_t copyCount() const { return data_->first; } size_t moveCount() const { return data_->second; } size_t refCount() const { return data_.use_count(); } void resetCounters() { data_->first = data_->second = 0; } private: // copy, move std::shared_ptr<std::pair<size_t, size_t>> data_; }; TEST(Function, CaptureCopyMoveCount) { // This test checks that no unnecessary copies/moves are made. CopyMoveTracker cmt(CopyMoveTracker::ConstructorTag{}); EXPECT_EQ(0, cmt.copyCount()); EXPECT_EQ(0, cmt.moveCount()); EXPECT_EQ(1, cmt.refCount()); // Move into lambda, move lambda into Function auto lambda1 = [cmt = std::move(cmt)]() { return cmt.moveCount(); }; Function<size_t(void)> uf1 = std::move(lambda1); // Max copies: 0. Max copy+moves: 2. EXPECT_LE(cmt.moveCount() + cmt.copyCount(), 3); EXPECT_LE(cmt.copyCount(), 0); cmt.resetCounters(); // Move into lambda, copy lambda into Function auto lambda2 = [cmt = std::move(cmt)]() { return cmt.moveCount(); }; Function<size_t(void)> uf2 = lambda2; // Max copies: 1. Max copy+moves: 2. EXPECT_LE(cmt.moveCount() + cmt.copyCount(), 3); EXPECT_LE(cmt.copyCount(), 1); // Invoking Function must not make copies/moves of the callable cmt.resetCounters(); uf1(); uf2(); EXPECT_EQ(0, cmt.copyCount()); EXPECT_EQ(0, cmt.moveCount()); } TEST(Function, ParameterCopyMoveCount) { // This test checks that no unnecessary copies/moves are made. CopyMoveTracker cmt(CopyMoveTracker::ConstructorTag{}); EXPECT_EQ(0, cmt.copyCount()); EXPECT_EQ(0, cmt.moveCount()); EXPECT_EQ(1, cmt.refCount()); // pass by value Function<size_t(CopyMoveTracker)> uf1 = [](CopyMoveTracker c) { return c.moveCount(); }; cmt.resetCounters(); uf1(cmt); // Max copies: 1. Max copy+moves: 2. EXPECT_LE(cmt.moveCount() + cmt.copyCount(), 2); EXPECT_LE(cmt.copyCount(), 1); cmt.resetCounters(); uf1(std::move(cmt)); // Max copies: 1. Max copy+moves: 2. EXPECT_LE(cmt.moveCount() + cmt.copyCount(), 2); EXPECT_LE(cmt.copyCount(), 0); // pass by reference Function<size_t(CopyMoveTracker&)> uf2 = [](CopyMoveTracker& c) { return c.moveCount(); }; cmt.resetCounters(); uf2(cmt); // Max copies: 0. Max copy+moves: 0. EXPECT_LE(cmt.moveCount() + cmt.copyCount(), 0); EXPECT_LE(cmt.copyCount(), 0); // pass by const reference Function<size_t(CopyMoveTracker const&)> uf3 = [](CopyMoveTracker const& c) { return c.moveCount(); }; cmt.resetCounters(); uf3(cmt); // Max copies: 0. Max copy+moves: 0. EXPECT_LE(cmt.moveCount() + cmt.copyCount(), 0); EXPECT_LE(cmt.copyCount(), 0); // pass by rvalue reference Function<size_t(CopyMoveTracker &&)> uf4 = [](CopyMoveTracker&& c) { return c.moveCount(); }; cmt.resetCounters(); uf4(std::move(cmt)); // Max copies: 0. Max copy+moves: 0. EXPECT_LE(cmt.moveCount() + cmt.copyCount(), 0); EXPECT_LE(cmt.copyCount(), 0); } // TEST ===================================================================== // VariadicTemplate & VariadicArguments struct VariadicTemplateSum { int operator()() const { return 0; } template <class... Args> int operator()(int x, Args... args) const { return x + (*this)(args...); } }; TEST(Function, VariadicTemplate) { Function<int(int)> uf1 = VariadicTemplateSum(); Function<int(int, int)> uf2 = VariadicTemplateSum(); Function<int(int, int, int)> uf3 = VariadicTemplateSum(); EXPECT_EQ(66, uf1(66)); EXPECT_EQ(99, uf2(55, 44)); EXPECT_EQ(66, uf3(33, 22, 11)); } struct VariadicArgumentsSum { int operator()(int count, ...) const { int result = 0; va_list args; va_start(args, count); for (int i = 0; i < count; ++i) { result += va_arg(args, int); } va_end(args); return result; } }; TEST(Function, VariadicArguments) { Function<int(int)> uf1 = VariadicArgumentsSum(); Function<int(int, int)> uf2 = VariadicArgumentsSum(); Function<int(int, int, int)> uf3 = VariadicArgumentsSum(); EXPECT_EQ(0, uf1(0)); EXPECT_EQ(66, uf2(1, 66)); EXPECT_EQ(99, uf3(2, 55, 44)); } // TEST ===================================================================== // SafeCaptureByReference // A function can use Function const& as a parameter to signal that it // is safe to pass a lambda that captures local variables by reference. // It is safe because we know the function called can only invoke the // Function until it returns. It can't store a copy of the Function // (because it's not copyable), and it can't move the Function somewhere // else (because it gets only a const&). template <typename T> void for_each( T const& range, Function<void(typename T::value_type const&) const> const& func) { for (auto const& elem : range) { func(elem); } } TEST(Function, SafeCaptureByReference) { std::vector<int> const vec = {20, 30, 40, 2, 3, 4, 200, 300, 400}; int sum = 0; // for_each's second parameter is of type Function<...> const&. // Hence we know we can safely pass it a lambda that references local // variables. There is no way the reference to x will be stored anywhere. for_each(vec, [&sum](int x) { sum += x; }); EXPECT_EQ(999, sum); } // TEST ===================================================================== // IgnoreReturnValue TEST(Function, IgnoreReturnValue) { int x = 95; // Assign a lambda that return int to a folly::Function that returns void. Function<void()> f = [&]() -> int { return ++x; }; EXPECT_EQ(95, x); f(); EXPECT_EQ(96, x); Function<int()> g = [&]() -> int { return ++x; }; Function<void()> cg = std::move(g); EXPECT_EQ(96, x); cg(); EXPECT_EQ(97, x); } // TEST ===================================================================== // ReturnConvertible, ConvertReturnType TEST(Function, ReturnConvertible) { struct CBase { int x; }; struct CDerived : CBase {}; Function<double()> f1 = []() -> int { return 5; }; EXPECT_EQ(5.0, f1()); Function<int()> f2 = []() -> double { return 5.2; }; EXPECT_EQ(5, f2()); CDerived derived; derived.x = 55; Function<CBase const&()> f3 = [&]() -> CDerived const& { return derived; }; EXPECT_EQ(55, f3().x); Function<CBase const&()> f4 = [&]() -> CDerived& { return derived; }; EXPECT_EQ(55, f4().x); Function<CBase&()> f5 = [&]() -> CDerived& { return derived; }; EXPECT_EQ(55, f5().x); Function<CBase const*()> f6 = [&]() -> CDerived const* { return &derived; }; EXPECT_EQ(f6()->x, 55); Function<CBase const*()> f7 = [&]() -> CDerived* { return &derived; }; EXPECT_EQ(55, f7()->x); Function<CBase*()> f8 = [&]() -> CDerived* { return &derived; }; EXPECT_EQ(55, f8()->x); Function<CBase()> f9 = [&]() -> CDerived { auto d = derived; d.x = 66; return d; }; EXPECT_EQ(66, f9().x); } TEST(Function, ConvertReturnType) { struct CBase { int x; }; struct CDerived : CBase {}; Function<int()> f1 = []() -> int { return 5; }; Function<double()> cf1 = std::move(f1); EXPECT_EQ(5.0, cf1()); Function<int()> ccf1 = std::move(cf1); EXPECT_EQ(5, ccf1()); Function<double()> f2 = []() -> double { return 5.2; }; Function<int()> cf2 = std::move(f2); EXPECT_EQ(5, cf2()); Function<double()> ccf2 = std::move(cf2); EXPECT_EQ(5.0, ccf2()); CDerived derived; derived.x = 55; Function<CDerived const&()> f3 = [&]() -> CDerived const& { return derived; }; Function<CBase const&()> cf3 = std::move(f3); EXPECT_EQ(55, cf3().x); Function<CDerived&()> f4 = [&]() -> CDerived& { return derived; }; Function<CBase const&()> cf4 = std::move(f4); EXPECT_EQ(55, cf4().x); Function<CDerived&()> f5 = [&]() -> CDerived& { return derived; }; Function<CBase&()> cf5 = std::move(f5); EXPECT_EQ(55, cf5().x); Function<CDerived const*()> f6 = [&]() -> CDerived const* { return &derived; }; Function<CBase const*()> cf6 = std::move(f6); EXPECT_EQ(55, cf6()->x); Function<CDerived const*()> f7 = [&]() -> CDerived* { return &derived; }; Function<CBase const*()> cf7 = std::move(f7); EXPECT_EQ(55, cf7()->x); Function<CDerived*()> f8 = [&]() -> CDerived* { return &derived; }; Function<CBase*()> cf8 = std::move(f8); EXPECT_EQ(55, cf8()->x); Function<CDerived()> f9 = [&]() -> CDerived { auto d = derived; d.x = 66; return d; }; Function<CBase()> cf9 = std::move(f9); EXPECT_EQ(66, cf9().x); } // TEST ===================================================================== // asStdFunction_* TEST(Function, asStdFunction_void) { int i = 0; folly::Function<void()> f = [&] { ++i; }; auto sf = std::move(f).asStdFunction(); static_assert( std::is_same<decltype(sf), std::function<void()>>::value, "std::function has wrong type"); sf(); EXPECT_EQ(1, i); } TEST(Function, asStdFunction_void_const) { int i = 0; folly::Function<void() const> f = [&] { ++i; }; auto sf = std::move(f).asStdFunction(); static_assert( std::is_same<decltype(sf), std::function<void()>>::value, "std::function has wrong type"); sf(); EXPECT_EQ(1, i); } TEST(Function, asStdFunction_return) { int i = 0; folly::Function<int()> f = [&] { ++i; return 42; }; auto sf = std::move(f).asStdFunction(); static_assert( std::is_same<decltype(sf), std::function<int()>>::value, "std::function has wrong type"); EXPECT_EQ(42, sf()); EXPECT_EQ(1, i); } TEST(Function, asStdFunction_return_const) { int i = 0; folly::Function<int() const> f = [&] { ++i; return 42; }; auto sf = std::move(f).asStdFunction(); static_assert( std::is_same<decltype(sf), std::function<int()>>::value, "std::function has wrong type"); EXPECT_EQ(42, sf()); EXPECT_EQ(1, i); } TEST(Function, asStdFunction_args) { int i = 0; folly::Function<void(int, int)> f = [&](int x, int y) { ++i; return x + y; }; auto sf = std::move(f).asStdFunction(); static_assert( std::is_same<decltype(sf), std::function<void(int, int)>>::value, "std::function has wrong type"); sf(42, 42); EXPECT_EQ(1, i); } TEST(Function, asStdFunction_args_const) { int i = 0; folly::Function<void(int, int) const> f = [&](int x, int y) { ++i; return x + y; }; auto sf = std::move(f).asStdFunction(); static_assert( std::is_same<decltype(sf), std::function<void(int, int)>>::value, "std::function has wrong type"); sf(42, 42); EXPECT_EQ(1, i); } // TEST ===================================================================== // asSharedProxy_* TEST(Function, asSharedProxy_void) { int i = 0; folly::Function<void()> f = [&i] { ++i; }; auto sp = std::move(f).asSharedProxy(); auto spcopy = sp; sp(); EXPECT_EQ(1, i); spcopy(); EXPECT_EQ(2, i); } TEST(Function, asSharedProxy_void_const) { int i = 0; folly::Function<void() const> f = [&i] { ++i; }; auto sp = std::move(f).asSharedProxy(); auto spcopy = sp; sp(); EXPECT_EQ(1, i); spcopy(); EXPECT_EQ(2, i); } TEST(Function, asSharedProxy_return) { folly::Function<int()> f = [i = 0]() mutable { ++i; return i; }; auto sp = std::move(f).asSharedProxy(); auto spcopy = sp; EXPECT_EQ(1, sp()); EXPECT_EQ(2, spcopy()); } TEST(Function, asSharedProxy_return_const) { int i = 0; folly::Function<int() const> f = [&i] { ++i; return i; }; auto sp = std::move(f).asSharedProxy(); auto spcopy = sp; EXPECT_EQ(1, sp()); EXPECT_EQ(2, spcopy()); } TEST(Function, asSharedProxy_args) { int i = 0; folly::Function<int(int, int)> f = [&](int x, int y) mutable { ++i; return x + y * 2; }; auto sp = std::move(f).asSharedProxy(); auto spcopy = sp; EXPECT_EQ(120, sp(100, 10)); EXPECT_EQ(1, i); EXPECT_EQ(120, spcopy(100, 10)); EXPECT_EQ(2, i); } TEST(Function, asSharedProxy_args_const) { int i = 0; folly::Function<int(int, int) const> f = [&i](int x, int y) { ++i; return x * 100 + y * 10 + i; }; auto sp = std::move(f).asSharedProxy(); auto spcopy = sp; EXPECT_EQ(561, sp(5, 6)); EXPECT_EQ(562, spcopy(5, 6)); } TEST(Function, NoAllocatedMemoryAfterMove) { Functor<int, 100> foo; Function<int(size_t)> func = foo; EXPECT_GT(func.heapAllocatedMemory(), 0); Function<int(size_t)> func2 = std::move(func); EXPECT_GT(func2.heapAllocatedMemory(), 0); EXPECT_EQ(func.heapAllocatedMemory(), 0); } TEST(Function, ConstCastEmbedded) { int x = 0; auto functor = [&x]() { ++x; }; Function<void() const> func(functor); EXPECT_EQ(func.heapAllocatedMemory(), 0); Function<void()> func2(std::move(func)); EXPECT_EQ(func2.heapAllocatedMemory(), 0); } TEST(Function, EmptyAfterConstCast) { Function<int(size_t)> func; EXPECT_FALSE(func); Function<int(size_t) const> func2 = constCastFunction(std::move(func)); EXPECT_FALSE(func2); } TEST(Function, SelfStdSwap) { Function<int()> f = [] { return 42; }; f.swap(f); EXPECT_TRUE(bool(f)); EXPECT_EQ(42, f()); std::swap(f, f); EXPECT_TRUE(bool(f)); EXPECT_EQ(42, f()); folly::swap(f, f); EXPECT_TRUE(bool(f)); EXPECT_EQ(42, f()); } TEST(Function, SelfMove) { Function<int()> f = [] { return 42; }; Function<int()>& g = f; f = std::move(g); // shouldn't crash! (void)bool(f); // valid but unspecified state f = [] { return 43; }; EXPECT_TRUE(bool(f)); EXPECT_EQ(43, f()); } TEST(Function, SelfMove2) { int alive{0}; struct arg { int* ptr_; explicit arg(int* ptr) noexcept : ptr_(ptr) { ++*ptr_; } arg(arg&& o) noexcept : ptr_(o.ptr_) { ++*ptr_; } arg& operator=(arg&&) = delete; ~arg() { --*ptr_; } }; EXPECT_EQ(0, alive); Function<int()> f = [myarg = arg{&alive}] { return 42; }; EXPECT_EQ(1, alive); Function<int()>& g = f; f = std::move(g); EXPECT_FALSE(bool(f)) << "self-assign is self-destruct"; EXPECT_EQ(0, alive) << "self-asign is self-destruct"; f = [] { return 43; }; EXPECT_EQ(0, alive) << "sanity check against double-destruction"; EXPECT_TRUE(bool(f)); EXPECT_EQ(43, f()); } TEST(Function, DeducableArguments) { deduceArgs(Function<void()>{[] {}}); deduceArgs(Function<void(int, float)>{[](int, float) {}}); deduceArgs(Function<int(int, float)>{[](int i, float) { return i; }}); } TEST(Function, CtorWithCopy) { struct X { X() {} X(X const&) noexcept(true) {} X& operator=(X const&) = default; }; struct Y { Y() {} Y(Y const&) noexcept(false) {} Y(Y&&) noexcept(true) {} Y& operator=(Y&&) = default; Y& operator=(Y const&) = default; }; auto lx = [x = X()] {}; auto ly = [y = Y()] {}; EXPECT_TRUE(noexcept(Function<void()>(lx))); EXPECT_FALSE(noexcept(Function<void()>(ly))); } TEST(Function, Bug_T23346238) { const Function<void()> nullfun; } TEST(Function, MaxAlignCallable) { using A = folly::aligned_storage_for_t<folly::max_align_t>; auto f = [a = A()] { return reinterpret_cast<uintptr_t>(&a) % alignof(A); }; EXPECT_EQ(alignof(A), alignof(decltype(f))) << "sanity"; EXPECT_EQ(0, f()) << "sanity"; EXPECT_EQ(0, Function<size_t()>(f)()); } TEST(Function, AllocatedSize) { Function<void(int)> defaultConstructed; EXPECT_EQ(defaultConstructed.heapAllocatedMemory(), 0U) << "Default constructed Function should have zero allocations"; // On any platform this has to allocate heap storage, because the captures are // larger than the inline size of the Function object: constexpr size_t kCaptureBytes = sizeof(Function<void(int)>) + 1; Function<void(int)> fromLambda{ [x = std::array<char, kCaptureBytes>()](int) { (void)x; }}; // I can't assert much about the size because it's permitted to vary from // platform to platform or as optimization levels change, but we can be sure // that the lambda must be at least as large as its captures EXPECT_GE(fromLambda.heapAllocatedMemory(), kCaptureBytes) << "Lambda-derived Function's allocated size is smaller than the " "lambda's capture size"; }
27.650407
80
0.624258
[ "object", "vector" ]
4f5d222042e2d5b960d504496c210240599aed9b
6,058
cpp
C++
3rdParty/iresearch/core/utils/locale_utils.cpp
0xflotus/arangodb
1de6a7aff9183920cb8d2241c9c226b30bcf4d05
[ "Apache-2.0" ]
1
2019-08-11T04:06:49.000Z
2019-08-11T04:06:49.000Z
3rdParty/iresearch/core/utils/locale_utils.cpp
0xflotus/arangodb
1de6a7aff9183920cb8d2241c9c226b30bcf4d05
[ "Apache-2.0" ]
null
null
null
3rdParty/iresearch/core/utils/locale_utils.cpp
0xflotus/arangodb
1de6a7aff9183920cb8d2241c9c226b30bcf4d05
[ "Apache-2.0" ]
1
2021-07-12T06:29:34.000Z
2021-07-12T06:29:34.000Z
//////////////////////////////////////////////////////////////////////////////// /// DISCLAIMER /// /// Copyright 2016 by EMC Corporation, All Rights Reserved /// /// Licensed under the Apache License, Version 2.0 (the "License"); /// you may not use this file except in compliance with the License. /// You may obtain a copy of the License at /// /// http://www.apache.org/licenses/LICENSE-2.0 /// /// Unless required by applicable law or agreed to in writing, software /// distributed under the License is distributed on an "AS IS" BASIS, /// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. /// See the License for the specific language governing permissions and /// limitations under the License. /// /// Copyright holder is EMC Corporation /// /// @author Andrey Abramov /// @author Vasiliy Nabatchikov //////////////////////////////////////////////////////////////////////////////// #if defined (__GNUC__) #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wdeprecated-declarations" #endif #include <boost/locale/generator.hpp> #if defined (__GNUC__) #pragma GCC diagnostic pop #endif #include <boost/locale/info.hpp> #if defined (__GNUC__) #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wdeprecated-declarations" #endif #include <boost/locale/util.hpp> #if defined (__GNUC__) #pragma GCC diagnostic pop #endif #include "locale_utils.hpp" NS_LOCAL std::locale generate_locale(std::string const& sName) { // valgrind reports invalid reads for locale_genrator if declared inside function boost::locale::generator locale_genrator; // stateful object, cannot be static return locale_genrator.generate(sName); } NS_END NS_ROOT NS_BEGIN( locale_utils ) std::string country(std::locale const& locale) { try { // try extracting 'info' facet from existing locale return std::use_facet<boost::locale::info>(locale).country(); } catch (...) { // use Boost to parse the locale name and create a facet auto locale_info = boost::locale::util::create_info(locale, locale.name()); auto& info_facet = std::use_facet<boost::locale::info>(locale_info); return info_facet.country(); } } std::string encoding(std::locale const& locale){ try { // try extracting 'info' facet from existing locale return std::use_facet<boost::locale::info>(locale).encoding(); } catch (...) { // use Boost to parse the locale name and create a facet auto locale_info = boost::locale::util::create_info(locale, locale.name()); auto& info_facet = std::use_facet<boost::locale::info>(locale_info); return info_facet.encoding(); } } std::string language(std::locale const& locale){ try { // try extracting 'info' facet from existing locale return std::use_facet<boost::locale::info>(locale).language(); } catch (...) { // use Boost to parse the locale name and create a facet auto locale_info = boost::locale::util::create_info(locale, locale.name()); auto& info_facet = std::use_facet<boost::locale::info>(locale_info); return info_facet.language(); } } std::locale locale(char const* czName, bool bForceUTF8 /*= false*/) { if (!czName) { return bForceUTF8 ? locale(std::locale::classic().name(), true) : std::locale::classic() ; } const std::string sName(czName); return locale(sName, bForceUTF8); } std::locale locale(std::string const& sName, bool bForceUTF8 /*= false*/) { if (!bForceUTF8) { return generate_locale(sName); } // ensure boost::locale::info facet exists for 'sName' since it is used below auto locale = generate_locale(sName); auto locale_info = boost::locale::util::create_info(locale, sName); auto& info_facet = std::use_facet<boost::locale::info>(locale_info); if (info_facet.utf8()) { return locale; } return iresearch::locale_utils::locale( info_facet.language(), info_facet.country(), "UTF-8", info_facet.variant() ); } std::locale locale(std::string const& sLanguage, std::string const& sCountry, std::string const& sEncoding, std::string const& sVariant /*= ""*/) { bool bValid = sLanguage.find('_') == std::string::npos && sCountry.find('_') == std::string::npos && sEncoding.find('_') == std::string::npos && sVariant.find('_') == std::string::npos && sLanguage.find('.') == std::string::npos && sCountry.find('.') == std::string::npos && sEncoding.find('.') == std::string::npos && sVariant.find('.') == std::string::npos && sLanguage.find('@') == std::string::npos && sCountry.find('@') == std::string::npos && sEncoding.find('@') == std::string::npos && sVariant.find('@') == std::string::npos; std::string sName = sLanguage;// sLanguage.empty() && sCountry.empty() && (!sEncoding.empty() || !sVariant.empty()) ? "C" : sLanguage; if (!bValid || !sCountry.empty()) { sName.append(1, '_').append(sCountry); } if (!bValid || !sEncoding.empty()) { sName.append(1, '.').append(sEncoding); } if (!bValid || !sVariant.empty()) { sName.append(1, '@').append(sVariant); } return iresearch::locale_utils::locale(sName); } std::string name(std::locale const& locale) { try { return std::use_facet<boost::locale::info>(locale).name(); } catch (...) { return locale.name(); // fall back to default value if failed to get facet } } bool utf8(std::locale const& locale) { try { // try extracting 'info' facet from existing locale return std::use_facet<boost::locale::info>(locale).utf8(); } catch (...) { // use Boost to parse the locale name and create a facet auto locale_info = boost::locale::util::create_info(locale, locale.name()); auto& info_facet = std::use_facet<boost::locale::info>(locale_info); return info_facet.utf8(); } } NS_END NS_END // ----------------------------------------------------------------------------- // --SECTION-- END-OF-FILE // -----------------------------------------------------------------------------
31.884211
188
0.630406
[ "object" ]
4f64518cc9bc34eca21f012bc2188d8b7b765c74
7,157
cpp
C++
Cpp/Control/FeedforwardController.cpp
mass2010chromium/Klampt
4a50ac10daf636e4f2d7acb635db2292fc2c72b6
[ "BSD-3-Clause" ]
null
null
null
Cpp/Control/FeedforwardController.cpp
mass2010chromium/Klampt
4a50ac10daf636e4f2d7acb635db2292fc2c72b6
[ "BSD-3-Clause" ]
null
null
null
Cpp/Control/FeedforwardController.cpp
mass2010chromium/Klampt
4a50ac10daf636e4f2d7acb635db2292fc2c72b6
[ "BSD-3-Clause" ]
null
null
null
#include "FeedforwardController.h" #include "Sensing/JointSensors.h" //#include "Modeling/ParabolicRamp.h" #include <KrisLibrary/robotics/NewtonEuler.h> #include <string> #include <sstream> using namespace Klampt; FeedforwardController::FeedforwardController(RobotModel& _robot,shared_ptr<RobotController> _base) :RobotController(_robot),base(_base),stateEstimator(NULL),enableGravityCompensation(true), enableFeedforwardAcceleration(true),gravity(0,0,-9.8) { if(base) Assert(&robot == &base->robot); ZeroForces(); } void FeedforwardController::Update(Real dt) { if(!base) return; base->sensors = sensors; base->command = command; base->Update(dt); if(!enableGravityCompensation && !enableFeedforwardAcceleration) { //cout<<"FF disabled"<<endl; return; } if(stateEstimator) { stateEstimator->ReadSensors(*sensors); stateEstimator->UpdateModel(); } else { if(!sensors->GetTypedSensor<JointPositionSensor>()) { printf("FeedforwardController: No joint positions, FF disabled\n"); enableGravityCompensation = enableFeedforwardAcceleration = false; return; } Config& q = sensors->GetTypedSensor<JointPositionSensor>()->q; if(q.n != robot.q.n) { printf("FeedforwardController: joint encoders don't provide full state information, FF disabled\n"); enableGravityCompensation = enableFeedforwardAcceleration = false; return; } robot.UpdateConfig(q); if(!sensors->GetTypedSensor<JointVelocitySensor>()) robot.dq.setZero(); else { Vector& dq = sensors->GetTypedSensor<JointVelocitySensor>()->dq; if(dq.n != robot.dq.n) robot.dq.setZero(); else robot.dq = dq; } } Vector torques; SolveTorques(torques,dt); //cout<<"Estimated config "<<robot.q<<endl; //cout<<"FF Torques: "<<torques<<endl; for(size_t i=0;i<command->actuators.size();i++) { if(robot.drivers[i].type == RobotModelDriver::Normal) { command->actuators[i].torque = torques(robot.drivers[i].linkIndices[0]); } else { Vector J; robot.GetDriverJacobian(i,J); Real scale = 1.0/J.normSquared(); command->actuators[i].torque=0; for(int j=0;j<J.n;j++) command->actuators[i].torque += J(j)*torques(j)*scale; } } if(stateEstimator) { stateEstimator->ReadCommand(*command); stateEstimator->Advance(dt); } RobotController::Update(dt); } void FeedforwardController::Reset() { ZeroForces(); if(base) { base->command = command; base->Reset(); command = base->command; } if(stateEstimator) stateEstimator->Reset(); RobotController::Reset(); } bool FeedforwardController::ReadState(File& f) { if(!RobotController::ReadState(f)) { printf("FeedforwardController::RobotController couldn't read state\n"); return false; } if(base && !base->ReadState(f)) { printf("FeedforwardController::Couldn't read base state\n"); return false; } if(!ReadFile(f,gravity)) { printf("FeedforwardController::Couldn't read gravity\n"); return false; } for(size_t i=0;i<wrenches.size();i++) { if(!ReadFile(f,wrenches[i].f)) { printf("FeedforwardController::Couldn't read wrench %d\n",i); return false; } if(!ReadFile(f,wrenches[i].m)) { printf("FeedforwardController::Couldn't read wrench %d\n",i); return false; } } return true; } bool FeedforwardController::WriteState(File& f) const { if(!RobotController::WriteState(f)) return false; if(base && !base->WriteState(f)) return false; if(!WriteFile(f,gravity)) return false; for(size_t i=0;i<wrenches.size();i++) { if(!WriteFile(f,wrenches[i].f)) return false; if(!WriteFile(f,wrenches[i].m)) return false; } return true; } map<string,string> FeedforwardController::Settings() const { map<string,string> res = base->Settings(); FILL_CONTROLLER_SETTING(res,enableGravityCompensation); FILL_CONTROLLER_SETTING(res,enableFeedforwardAcceleration); FILL_CONTROLLER_SETTING(res,gravity); return res; } bool FeedforwardController::GetSetting(const string& name,string& str) const { if(base->GetSetting(name,str)) return true; READ_CONTROLLER_SETTING(enableGravityCompensation) READ_CONTROLLER_SETTING(enableFeedforwardAcceleration) READ_CONTROLLER_SETTING(gravity) return false; } bool FeedforwardController::SetSetting(const string& name,const string& str) { if(base->SetSetting(name,str)) return true; WRITE_CONTROLLER_SETTING(enableGravityCompensation) WRITE_CONTROLLER_SETTING(enableFeedforwardAcceleration) WRITE_CONTROLLER_SETTING(gravity) return false; } vector<string> FeedforwardController::Commands() const { vector<string> res=base->Commands(); res.push_back("add_ext_force"); res.push_back("zero_ext_forces"); return res; } bool FeedforwardController::SendCommand(const string& name,const string& str) { if(base->SendCommand(name,str)) return true; if(name == "zero_ext_forces") { ZeroForces(); return true; } else if(name == "add_ext_force") { int link; Vector3 f; Vector3 worldpt; stringstream ss(str); ss>>link>>f>>worldpt; if(!ss) return false; AddForce(link,f,worldpt); return true; } return false; } void FeedforwardController::SolveTorques(Vector& torques,Real dt) { //assumes robot is updated from sensing NewtonEulerSolver ne(robot); if(enableGravityCompensation) ne.SetGravityWrenches(gravity); for(size_t i=0;i<wrenches.size();i++) { ne.externalWrenches[i].f += wrenches[i].f; ne.externalWrenches[i].m += wrenches[i].m; //cout<<"Total wrench "<<i<<": "<<ne.externalWrenches[i].m<<", "<<ne.externalWrenches[i].f<<endl; } if(enableFeedforwardAcceleration) { Assert(dt > 0); Vector ddq(robot.links.size(),Zero); for(size_t i=0;i<command->actuators.size();i++) { if(robot.drivers[i].type == RobotModelDriver::Normal) { int link=robot.drivers[i].linkIndices[0]; Assert(link >= 0 && link < (int)robot.links.size()); //finite difference version ddq(link) = (command->actuators[i].dqdes-robot.dq(link))/dt; //Hacky PD-like version //Real kP=1.0,kD=10.0; //ddq(link) = kP*(command->actuators[i].qdes-robot.q(link))+kD*(command->actuators[i].dqdes-robot.dq(link)); /* ParabolicRamp1D ramp; ramp.x0 = robot.q(link); ramp.x1 = command->actuators[i].qdes; ramp.dx0 = robot.dq(link); ramp.dx1 = command->actuators[i].dqdes; if(ramp.SolveMinTime(robot.accMax(link),robot.velMax(link))) ddq(link) = ramp.a1; //ddq(link) = 0; */ } else { //TODO: other types of drivers? } } ne.CalcTorques(ddq,torques); //cout<<"Desired accel: "<<ddq<<endl; //cout<<"FF torques: "<<torques<<endl; } else ne.CalcResidualTorques(torques); } void FeedforwardController::ZeroForces() { wrenches.resize(robot.links.size()); Wrench zero; zero.f.setZero(); zero.m.setZero(); fill(wrenches.begin(),wrenches.end(),zero); } void FeedforwardController::AddForce(int link,const Vector3& f,const Vector3& worldpt) { wrenches[link].f += f; wrenches[link].m += cross(f,worldpt-robot.links[link].T_World*robot.links[link].com); }
28.513944
109
0.686601
[ "vector" ]
4f6646694c2de578f73e6b7e331a7c534518506f
2,674
cpp
C++
libnd4j/include/ops/declarable/impl/DeclarableReductionOp.cpp
bpossolo/deeplearning4j
722d5a052af17f19dcd42ef923b9a5b63ab2cbee
[ "Apache-2.0" ]
13,006
2015-02-13T18:35:31.000Z
2022-03-18T12:11:44.000Z
libnd4j/include/ops/declarable/impl/DeclarableReductionOp.cpp
bpossolo/deeplearning4j
722d5a052af17f19dcd42ef923b9a5b63ab2cbee
[ "Apache-2.0" ]
5,319
2015-02-13T08:21:46.000Z
2019-06-12T14:56:50.000Z
libnd4j/include/ops/declarable/impl/DeclarableReductionOp.cpp
bpossolo/deeplearning4j
722d5a052af17f19dcd42ef923b9a5b63ab2cbee
[ "Apache-2.0" ]
4,719
2015-02-13T22:48:55.000Z
2022-03-22T07:25:36.000Z
/******************************************************************************* * Copyright (c) 2015-2018 Skymind, Inc. * * This program and the accompanying materials are made available under the * terms of the Apache License, Version 2.0 which is available at * https://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. * * SPDX-License-Identifier: Apache-2.0 ******************************************************************************/ // // Created by raver119 on 07.10.2017. // #include <ops/declarable/DeclarableReductionOp.h> #include <ops/declarable/DeclarableOp.h> #include <helpers/TAD.h> #include <helpers/ShapeUtils.h> #include <helpers/ConstantTadHelper.h> #include <array/DataTypeUtils.h> namespace sd { namespace ops { DeclarableReductionOp::DeclarableReductionOp(int numInputs, int numOutputs, const char *opName, bool allowsInplace, int tArgs, int iArgs) : sd::ops::DeclarableOp(numInputs, numOutputs, opName, allowsInplace, tArgs, iArgs) { // } sd::ShapeList* DeclarableReductionOp::calculateOutputShape(sd::ShapeList* inputShape, sd::graph::Context& block) { // int numDims = INT_ARG(0); std::vector<int> dims; if (inputShape->size() > 1) { // the second argument is axis auto axis = INPUT_VARIABLE(1); for (int e = 0; e < axis->lengthOf(); e++) dims.push_back(axis->e<int>(e)); } else if (block.getIArguments()->size()) for (int e = 0; e < block.getIArguments()->size(); e++) dims.push_back(INT_ARG(e)); else if (block.getAxis()->size()) { dims = *block.getAxis(); //.push_back(axis->e<int>(e)); } if (dims.size() > 1) std::sort(dims.begin(), dims.end()); // special case - output is scalar if (dims.size() == 0 || (dims.size() == 1 && dims.at(0) == sd::DataTypeUtils::max<int>())) { auto newShape = ConstantShapeHelper::getInstance()->scalarShapeInfo(block.dataType()); return SHAPELIST(newShape); } auto newShape = ShapeUtils::evalReduceShapeInfo('c', dims, inputShape->at(0), false, false, block.getWorkspace()); return SHAPELIST(newShape); } } }
41.78125
231
0.575916
[ "vector" ]
4f684c723fca3383d6985b7df8601b85af150486
6,503
cpp
C++
lolCompiler/ASTWriter.cpp
NeutralNoise/lol_script
632b6a56c9caa3d44e93e2006cedec5d6730e3e2
[ "MIT" ]
null
null
null
lolCompiler/ASTWriter.cpp
NeutralNoise/lol_script
632b6a56c9caa3d44e93e2006cedec5d6730e3e2
[ "MIT" ]
null
null
null
lolCompiler/ASTWriter.cpp
NeutralNoise/lol_script
632b6a56c9caa3d44e93e2006cedec5d6730e3e2
[ "MIT" ]
null
null
null
#include "ASTWriter.h" #include "ASTNode.h" #include "../Common/cpuEnums.h" #include "AST.h" bool CheckVeriableIsReal(ASTNode * perent, unsigned int *nodePos, unsigned int *identPos) { //Find the memory position of the identifer well check to make sure its real. ASTNode * node = perent->GetPerent(); unsigned int identpos = 0, nodep = 0; bool foundSelf = false; //Its the first. while (1) { if (node == nullptr) { //we have reached the top. //TODO Error there is no identifer with this name break; } std::vector<ASTNode*> n = node->GetNodes(); for (size_t t = 0; t < n.size(); t++) { //We don't wanna go past here because its the same one as this one. so just go up to the next level. if (perent == n[t]) { foundSelf = true; break; } if (n[t]->GetType() == ASTNodeType::AST_Variable_Declaration) { for (size_t r = 0; r < n[t]->GetNodes().size(); r++) { ASTNode* in = n[t]->GetNodes()[r]; if (in->GetType() == ASTNodeType::AST_Variable_Identifier) { //For when we have more then 1 veriable decleared. for (size_t g = 0; g < perent->GetNodes().size(); g++) { if (in->GetLiteral() == perent->GetNodes()[g]->GetLiteral()) { *nodePos = t; *identPos = r; return true; } } } } } } node = node->GetPerent(); } return foundSelf; } unsigned int WriteReturn(std::ofstream &stream, ASTNode * perent) { //OP code + reg + data/ident + hlt code const unsigned int size = sizeof(char) + sizeof(char) + sizeof(int); // +sizeof(char); //OP code + reg + valtype + data/ident const unsigned int identsize = sizeof(char) + sizeof(char) + sizeof(char) + sizeof(int); char * op = nullptr; //new char[size]; if (perent->GetNodes().size()) { std::vector<ASTNode*> nodes = perent->GetNodes(); for (size_t i = 0; i < nodes.size(); i++) { //TODO allow so we can call functions and do other things in return statements. if (nodes[i]->GetType() == ASTNodeType::AST_Literal) { op = new char[size]; *op = CPU_OP_CODE::MOVE_CON_TO_REG; *(op + 1) = (char)CPU_REG_NUM::RA_NUM; //Check if we have a interger literal. if (nodes[i]->GetToken().GetType() == TokenType::INTEGER_LITERAL) { char * pend; *(long*)(op + 2) = strtol(nodes[i]->GetToken().GetToken().c_str(), &pend, 10); WriteBytes(stream, (unsigned char*)op, size); return size; } else if (nodes[i]->GetToken().GetType() == TokenType::CHAR_LITERAL) { } else { //TODO error unknown literal. } return size; } else if (nodes[i]->GetType() == ASTNodeType::AST_Identifier) { //Find the memory position of the identifer well check to make sure its real. ASTNode * node = nodes[i]->GetPerent(); unsigned int identpos = 0, nodep = 0; bool foundIdent = false; while (1) { if (node == nullptr) { //we have reached the top. //TODO Error Error there is no identifer with this name break; } std::vector<ASTNode*> n = node->GetNodes(); for (size_t t = 0; t < n.size(); t++) { //We don't wanna go past here because its the same one as this one. so just go up to the next level. if (nodes[i] == n[t]) { break; } if (n[t]->GetType() == ASTNodeType::AST_Variable_Declaration) { for (size_t r = 0; r < n[t]->GetNodes().size(); r++) { ASTNode* in = n[t]->GetNodes()[r]; if (in->GetType() == ASTNodeType::AST_Variable_Identifier) { if (in->GetLiteral() == nodes[i]->GetLiteral()) { foundIdent = true; nodep = t; identpos = r; break; } } } if (foundIdent) { break; } } } if (foundIdent) { break; } node = node->GetPerent(); } if (foundIdent) { //TODO these need to be improved to allow ptrs and shit like that. op = new char[identsize]; *op = CPU_OP_CODE::MOVE_MEM_TO_REG; *(long*)(op + 1) = htonl(node->GetNodes()[nodep]->GetFilePosition()); *(op + 5) = (char)VAL_TYPE::VAL; *(op + 6) = (char)CPU_REG_NUM::RA_NUM; //*(long*)(op + 3) = node->GetNodes()[nodep]->GetNodes()[identpos]->GetFilePosition(); WriteBytes(stream, (unsigned char*)op, identsize); return identsize; } } else { //Unknown return type. //TODO error message of unknown return type. } } } else { } return 0; } unsigned int WriteVeriable(std::ofstream &stream, ASTNode * perent) { unsigned int np; unsigned int ip; if (CheckVeriableIsReal(perent, &np, &ip)) { perent->SetFilePosition(stream.tellp()); for (size_t i = 0; i < perent->GetNodes().size(); i++) { for (size_t r = 0; r < perent->GetNodes()[i]->GetNodes().size(); r++) { ASTNode * t = perent->GetNodes()[i]->GetNodes()[r]; if (t->GetType() == ASTNodeType::AST_Literal) { uint32_t literalS = htonl(atoi(t->GetLiteral().c_str())); WriteBytes(stream, (unsigned char *)&literalS, sizeof(int)); return sizeof(int); } } } } return 0; } unsigned int WriteReturnVariable(std::ofstream &stream, ASTNode * perent, ASTNode * node) { //TODO this should be done else where size_t size = sizeof(char) + sizeof(char) + sizeof(char) + sizeof(int); unsigned char * op = nullptr; ASTNode* tempNode = perent; while (tempNode != nullptr) { for (size_t dsds = 0; dsds < tempNode->GetNodes().size(); dsds++){ if (tempNode->GetNodes()[dsds]->GetType() == ASTNodeType::AST_Variable_Declaration) { for (size_t vid = 0; vid < tempNode->GetNodes()[dsds]->GetNodes().size(); vid++) { ASTNode * stdfsafs = tempNode->GetNodes()[vid]; for (size_t dsa = 0; dsa < stdfsafs->GetNodes().size(); dsa++) { if (stdfsafs->GetNodes()[dsa]->GetType() == ASTNodeType::AST_Variable_Identifier) { if (stdfsafs->GetNodes()[dsa]->GetLiteral() == node->GetLiteral()) { // std::cout << "Using Variable: " << stdfsafs->GetNodes()[dsa]->GetLiteral() << "\n"; std::cout << "At Position: " << stdfsafs->GetFilePosition() << "\n"; op = new unsigned char[size]; *op = CPU_OP_CODE::MOVE_MEM_TO_REG; *(int*)(op + 1) = stdfsafs->GetFilePosition(); *(op + 5) = VAL_TYPE::VAL; *(op + 6) = CPU_REG_NUM::RA_NUM; WriteBytes(stream, (unsigned char*)op, size); //TODO Jump to where this function was called from. return size; } } } } } } tempNode = tempNode->GetPerent(); } return 0; }
32.678392
106
0.590958
[ "vector" ]
4f68f36ff36c42befcfc7906801a0899e960b289
7,348
cpp
C++
llvm/lib/Target/TargetRecip.cpp
zard49/kokkos-clang
c519a032853e6507075de1807c5730b8239ab936
[ "Unlicense" ]
4
2019-04-18T03:54:09.000Z
2021-03-22T02:27:31.000Z
llvm/lib/Target/TargetRecip.cpp
losalamos/kokkos-clang
d68d9c63cea3dbaad33454e4ebc9df829bca24fe
[ "Unlicense" ]
null
null
null
llvm/lib/Target/TargetRecip.cpp
losalamos/kokkos-clang
d68d9c63cea3dbaad33454e4ebc9df829bca24fe
[ "Unlicense" ]
2
2019-11-16T19:03:05.000Z
2020-03-19T08:32:37.000Z
//===-------------------------- TargetRecip.cpp ---------------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This class is used to customize machine-specific reciprocal estimate code // generation in a target-independent way. // If a target does not support operations in this specification, then code // generation will default to using supported operations. // //===----------------------------------------------------------------------===// #include "llvm/ADT/StringRef.h" #include "llvm/ADT/STLExtras.h" #include "llvm/Support/ErrorHandling.h" #include "llvm/Target/TargetRecip.h" #include <map> using namespace llvm; // These are the names of the individual reciprocal operations. These are // the key strings for queries and command-line inputs. // In addition, the command-line interface recognizes the global parameters // "all", "none", and "default". static const char *RecipOps[] = { "divd", "divf", "vec-divd", "vec-divf", "sqrtd", "sqrtf", "vec-sqrtd", "vec-sqrtf", }; // The uninitialized state is needed for the enabled settings and refinement // steps because custom settings may arrive via the command-line before target // defaults are set. TargetRecip::TargetRecip() { unsigned NumStrings = llvm::array_lengthof(RecipOps); for (unsigned i = 0; i < NumStrings; ++i) RecipMap.insert(std::make_pair(RecipOps[i], RecipParams())); } static bool parseRefinementStep(StringRef In, size_t &Position, uint8_t &Value) { const char RefStepToken = ':'; Position = In.find(RefStepToken); if (Position == StringRef::npos) return false; StringRef RefStepString = In.substr(Position + 1); // Allow exactly one numeric character for the additional refinement // step parameter. if (RefStepString.size() == 1) { char RefStepChar = RefStepString[0]; if (RefStepChar >= '0' && RefStepChar <= '9') { Value = RefStepChar - '0'; return true; } } report_fatal_error("Invalid refinement step for -recip."); } bool TargetRecip::parseGlobalParams(const std::string &Arg) { StringRef ArgSub = Arg; // Look for an optional setting of the number of refinement steps needed // for this type of reciprocal operation. size_t RefPos; uint8_t RefSteps; StringRef RefStepString; if (parseRefinementStep(ArgSub, RefPos, RefSteps)) { // Split the string for further processing. RefStepString = ArgSub.substr(RefPos + 1); ArgSub = ArgSub.substr(0, RefPos); } bool Enable; bool UseDefaults; if (ArgSub == "all") { UseDefaults = false; Enable = true; } else if (ArgSub == "none") { UseDefaults = false; Enable = false; } else if (ArgSub == "default") { UseDefaults = true; } else { // Any other string is invalid or an individual setting. return false; } // All enable values will be initialized to target defaults if 'default' was // specified. if (!UseDefaults) for (auto &KV : RecipMap) KV.second.Enabled = Enable; // Custom refinement count was specified with all, none, or default. if (!RefStepString.empty()) for (auto &KV : RecipMap) KV.second.RefinementSteps = RefSteps; return true; } void TargetRecip::parseIndividualParams(const std::vector<std::string> &Args) { static const char DisabledPrefix = '!'; unsigned NumArgs = Args.size(); for (unsigned i = 0; i != NumArgs; ++i) { StringRef Val = Args[i]; bool IsDisabled = Val[0] == DisabledPrefix; // Ignore the disablement token for string matching. if (IsDisabled) Val = Val.substr(1); size_t RefPos; uint8_t RefSteps; StringRef RefStepString; if (parseRefinementStep(Val, RefPos, RefSteps)) { // Split the string for further processing. RefStepString = Val.substr(RefPos + 1); Val = Val.substr(0, RefPos); } RecipIter Iter = RecipMap.find(Val); if (Iter == RecipMap.end()) { // Try again specifying float suffix. Iter = RecipMap.find(Val.str() + 'f'); if (Iter == RecipMap.end()) { Iter = RecipMap.find(Val.str() + 'd'); assert(Iter == RecipMap.end() && "Float entry missing from map"); report_fatal_error("Invalid option for -recip."); } // The option was specified without a float or double suffix. if (RecipMap[Val.str() + 'd'].Enabled != Uninitialized) { // Make sure that the double entry was not already specified. // The float entry will be checked below. report_fatal_error("Duplicate option for -recip."); } } if (Iter->second.Enabled != Uninitialized) report_fatal_error("Duplicate option for -recip."); // Mark the matched option as found. Do not allow duplicate specifiers. Iter->second.Enabled = !IsDisabled; if (!RefStepString.empty()) Iter->second.RefinementSteps = RefSteps; // If the precision was not specified, the double entry is also initialized. if (Val.back() != 'f' && Val.back() != 'd') { RecipMap[Val.str() + 'd'].Enabled = !IsDisabled; if (!RefStepString.empty()) RecipMap[Val.str() + 'd'].RefinementSteps = RefSteps; } } } TargetRecip::TargetRecip(const std::vector<std::string> &Args) : TargetRecip() { unsigned NumArgs = Args.size(); // Check if "all", "default", or "none" was specified. if (NumArgs == 1 && parseGlobalParams(Args[0])) return; parseIndividualParams(Args); } bool TargetRecip::isEnabled(StringRef Key) const { ConstRecipIter Iter = RecipMap.find(Key); assert(Iter != RecipMap.end() && "Unknown name for reciprocal map"); assert(Iter->second.Enabled != Uninitialized && "Enablement setting was not initialized"); return Iter->second.Enabled; } unsigned TargetRecip::getRefinementSteps(StringRef Key) const { ConstRecipIter Iter = RecipMap.find(Key); assert(Iter != RecipMap.end() && "Unknown name for reciprocal map"); assert(Iter->second.RefinementSteps != Uninitialized && "Refinement step setting was not initialized"); return Iter->second.RefinementSteps; } /// Custom settings (previously initialized values) override target defaults. void TargetRecip::setDefaults(StringRef Key, bool Enable, unsigned RefSteps) { if (Key == "all") { for (auto &KV : RecipMap) { RecipParams &RP = KV.second; if (RP.Enabled == Uninitialized) RP.Enabled = Enable; if (RP.RefinementSteps == Uninitialized) RP.RefinementSteps = RefSteps; } } else { RecipParams &RP = RecipMap[Key]; if (RP.Enabled == Uninitialized) RP.Enabled = Enable; if (RP.RefinementSteps == Uninitialized) RP.RefinementSteps = RefSteps; } } bool TargetRecip::operator==(const TargetRecip &Other) const { for (const auto &KV : RecipMap) { StringRef Op = KV.first; const RecipParams &RP = KV.second; const RecipParams &OtherRP = Other.RecipMap.find(Op)->second; if (RP.RefinementSteps != OtherRP.RefinementSteps) return false; if (RP.Enabled != OtherRP.Enabled) return false; } return true; }
32.513274
80
0.641943
[ "vector" ]
4f6d2e75e4bd2fb088a08f8b0956b801a5e2570d
7,622
cpp
C++
RobWork/src/rw/graspplanning/Contour2DInfoMap.cpp
ZLW07/RobWork
e713881f809d866b9a0749eeb15f6763e64044b3
[ "Apache-2.0" ]
1
2021-12-29T14:16:27.000Z
2021-12-29T14:16:27.000Z
RobWork/src/rw/graspplanning/Contour2DInfoMap.cpp
ZLW07/RobWork
e713881f809d866b9a0749eeb15f6763e64044b3
[ "Apache-2.0" ]
null
null
null
RobWork/src/rw/graspplanning/Contour2DInfoMap.cpp
ZLW07/RobWork
e713881f809d866b9a0749eeb15f6763e64044b3
[ "Apache-2.0" ]
null
null
null
/******************************************************************************** * Copyright 2009 The Robotics Group, The Maersk Mc-Kinney Moller Institute, * Faculty of Engineering, University of Southern Denmark * * 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 "Contour2DInfoMap.hpp" #include <rw/core/macros.hpp> #include <rw/geometry/Contour2D.hpp> #include <rw/math/Constants.hpp> #include <rw/math/Math.hpp> #include <rw/math/Vector2D.hpp> #include <cstdio> using namespace rw::math; using namespace rw::graspplanning; using namespace rw::geometry; using namespace rw::sensor; #define PIXEL_STEP_SIZE 8 //#define RW_DEBUGS(str) #define RW_DEBUGS(str) std::cout << str << std::endl namespace { double clampAngle (double angle) { while (angle < 0) angle += 2 * Pi; while (angle > 2 * Pi) angle -= 2 * Pi; return angle; } /** * @brief */ struct MovingAverage { public: MovingAverage (int len) : _len (len), _cb (_len, 0.0), _sum (0.0), _idx (0) {} void addSample (double sample) { _sum -= _cb[_idx]; _sum += sample; _cb[_idx] = sample; _idx++; if (_idx == _len) _idx = 0; } double getAverage () { return _sum / _len; } private: const int _len; std::vector< double > _cb; double _sum; int _idx; }; } // namespace Contour2DInfoMap::Contour2DInfoMap (int res) : _res (res), _resStep (2 * Pi / res), _resStepInv (1.0 / _resStep) {} void Contour2DInfoMap::reset (const Contour2D& contour) { const int contourSize = (int) contour.size (); int _avgFilterLen = 8; if (contourSize < 2 * _avgFilterLen) RW_THROW ("Contour is too small"); RW_DEBUGS ("--- Resetting INFO map"); RW_DEBUGS ("- contour size: " << contourSize); _avgCurvature = 0; _minCurvature = 1000; _maxCurvature = 0; _contour = &contour; _normalToContactsMap.clear (); _normalToContactsMap.resize (_res + 1); _contacts.clear (); _contacts.resize (contourSize); // create the moving average filters MovingAverage curvAvg1 (_avgFilterLen), curvAvg2 (_avgFilterLen); // initialize the average filters for (int idx = contourSize - _avgFilterLen; idx < contourSize + _avgFilterLen; idx++) { int sampleIdx = idx; if (idx >= contourSize) sampleIdx = idx - contourSize; double curvature = Contour2D::getCurvature (sampleIdx, PIXEL_STEP_SIZE, contour); RW_DEBUGS ("pre Curvature: " << curvature); curvAvg1.addSample (fabs (curvature)); if (idx >= 0) curvAvg2.addSample (curvAvg1.getAverage ()); } // main loop for (int idx = 0; idx < contourSize; idx++) { // calculate normal and curvature info // const Vector2D<> normal = Contour2DUtil::calcNormal(idx, PIXEL_STEP_SIZE, contour); const double curvature = Contour2D::getCurvature (idx, PIXEL_STEP_SIZE, contour); // update the average filter values int sampleIdx = idx + _avgFilterLen; if (sampleIdx >= contourSize) sampleIdx = sampleIdx - contourSize; double sampleCurv = Contour2D::getCurvature (sampleIdx, PIXEL_STEP_SIZE, contour); curvAvg1.addSample (fabs (sampleCurv)); curvAvg2.addSample (curvAvg1.getAverage ()); // now insert the calculated values into the contact struct Contact2D& c = _contacts[idx]; c.p = contour.points ()[idx].P (); // c.n = normal; c.n = contour.points ()[idx].N (); c.curvature = curvature; c.avgCurvature = Math::sqr (curvAvg2.getAverage ()); if (_minCurvature > c.avgCurvature) _minCurvature = c.avgCurvature; if (_maxCurvature < c.avgCurvature) _maxCurvature = c.avgCurvature; _avgCurvature += c.avgCurvature; // use angle of the normal relative to x-axis to compute index double nAngle = clampAngle (angle (Vector2D<> (1, 0), c.n)); RW_DEBUGS ("Angle : " << angle (Vector2D<> (1, 0), c.n)); RW_DEBUGS ("ClampedAngle: " << nAngle); /* double nAngle = atan2(c.n(1),c.n(0)); if(nAngle<0) nAngle +=2*Pi; */ unsigned int nAngleIdx = (unsigned int) std::floor (nAngle * _resStepInv + 0.5); RW_DEBUGS ("insert: " << nAngleIdx << " angle: " << nAngle); if (nAngleIdx >= _normalToContactsMap.size ()) { RW_WARN ("Index out of range: " << nAngleIdx << "<" << _normalToContactsMap.size ()); nAngleIdx = (unsigned int) (_normalToContactsMap.size () - 1); } _normalToContactsMap[nAngleIdx].push_back (&c); } _avgCurvature /= contourSize; std::cout << "- Average Object Curvature: " << _avgCurvature << std::endl; std::cout << "- Max Object Curvature: " << _maxCurvature << std::endl; std::cout << "- Min Object Curvature: " << _minCurvature << std::endl; } Contour2DInfoMap::ContactPtrList Contour2DInfoMap::getCNormals (double nAngle, double margin, double thres) { int startIdx = (int) std::floor (clampAngle (nAngle - margin) * _resStepInv + 0.5); int stopIdx = (int) std::floor (clampAngle (nAngle + margin) * _resStepInv + 0.5); ContactPtrList list; if (startIdx > stopIdx) { for (; startIdx < _res; startIdx++) { for (Contact2D* cPtr : _normalToContactsMap[startIdx]) { if (cPtr->avgCurvature < thres) list.push_back (cPtr); } } startIdx = 0; } for (; startIdx <= stopIdx; startIdx++) { for (Contact2D* cPtr : _normalToContactsMap[startIdx]) { if (cPtr->avgCurvature < thres) list.push_back (cPtr); } } return list; } void Contour2DInfoMap::printToFile (const std::string& file) { FILE* cfile = fopen (file.c_str (), "w"); if (cfile == NULL) { perror ("Can't create img_file_name"); return; } for (size_t i = 0; i < _contacts.size (); i++) { rw::sensor::Contact2D& c = _contacts[i]; double theta = _resStep * i; ContactPtrList& list = _normalToContactsMap[0]; if (list.size () == 0) fprintf (cfile, "%f %f %f %f %f %f -0.1\n", theta * rw::math::Rad2Deg, c.p (0), c.p (1), c.p (2), c.curvature, c.avgCurvature); else fprintf (cfile, "%f %f %f %f %f %f %f\n", theta * rw::math::Rad2Deg, c.p (0), c.p (1), c.p (2), c.curvature, c.avgCurvature, list[0]->avgCurvature); } fclose (cfile); printf ("wrote: img_file_name\n"); }
33.429825
97
0.56455
[ "geometry", "object", "vector" ]
4f6deed3c70466e1dfb424cb733180c04e8b152c
36,104
cpp
C++
src/threepp/renderers/GLRenderer.cpp
lardratboy/threepp
18cd3e6b5966f7d10d4f627ac75088316300b7c8
[ "MIT" ]
null
null
null
src/threepp/renderers/GLRenderer.cpp
lardratboy/threepp
18cd3e6b5966f7d10d4f627ac75088316300b7c8
[ "MIT" ]
null
null
null
src/threepp/renderers/GLRenderer.cpp
lardratboy/threepp
18cd3e6b5966f7d10d4f627ac75088316300b7c8
[ "MIT" ]
null
null
null
#include "threepp/renderers/GLRenderer.hpp" #include "threepp/objects/Group.hpp" #include "threepp/objects/LOD.hpp" #include "threepp/objects/Line.hpp" #include "threepp/objects/LineLoop.hpp" #include "threepp/objects/LineSegments.hpp" using namespace threepp; GLRenderer::GLRenderer(Canvas &canvas, const GLRenderer::Parameters &parameters) : canvas_(canvas), _size(canvas.getSize()), _viewport(0, 0, _size.width, _size.height), _scissor(0, 0, _size.width, _size.height), state(canvas), background(state, parameters.premultipliedAlpha), bufferRenderer(new gl::GLBufferRenderer(info)), indexedBufferRenderer(new gl::GLIndexedBufferRenderer(info)), clipping(properties), bindingStates(attributes), geometries(attributes, info, bindingStates), textures(state, properties, info), objects(geometries, attributes, info), renderLists(properties), shadowMap(objects), materials(properties), programCache(bindingStates, clipping), onMaterialDispose(*this) { info.programs = &programCache.programs; } int GLRenderer::getTargetPixelRatio() const { return _pixelRatio; } WindowSize GLRenderer::getSize() const { return _size; } void GLRenderer::setSize(WindowSize size) { _size = size; int canvasWidth = _size.width * _pixelRatio; int canvasHeight = _size.height * _pixelRatio; canvas_.setSize({canvasWidth, canvasHeight}); this->setViewport(0, 0, size.width, size.height); } void GLRenderer::getDrawingBufferSize(Vector2 &target) const { target.set((float) (_size.width * _pixelRatio), (float) (_size.height * _pixelRatio)).floor(); } void GLRenderer::setDrawingBufferSize(int width, int height, int pixelRatio) { _size.width = width; _size.height = height; _pixelRatio = pixelRatio; canvas_.setSize({width * pixelRatio, height * pixelRatio}); this->setViewport(0, 0, width, height); } void GLRenderer::getCurrentViewport(Vector4 &target) const { target.copy(_currentViewport); } void GLRenderer::getViewport(Vector4 &target) const { target.copy(_viewport); } void GLRenderer::setViewport(const Vector4 &v) { _viewport.copy(v); state.viewport(_currentViewport.copy(_viewport).multiplyScalar((float) _pixelRatio).floor()); } void GLRenderer::setViewport(int x, int y, int width, int height) { _viewport.set((float) x, (float) y, (float) width, (float) height); state.viewport(_currentViewport.copy(_viewport).multiplyScalar((float) _pixelRatio).floor()); } void GLRenderer::getScissor(Vector4 &target) { target.copy(_scissor); } void GLRenderer::setScissor(const Vector4 &v) { _scissor.copy(v); state.scissor(_currentScissor.copy(_scissor).multiplyScalar((float) _pixelRatio).floor()); } void GLRenderer::setScissor(int x, int y, int width, int height) { _scissor.set((float) x, (float) y, (float) width, (float) height); state.scissor(_currentScissor.copy(_scissor).multiplyScalar((float) _pixelRatio).floor()); } bool GLRenderer::getScissorTest() const { return _scissorTest; } void GLRenderer::setScissorTest(bool boolean) { _scissorTest = boolean; state.setScissorTest(_scissorTest); } void GLRenderer::getClearColor(Color &target) const { target.copy(background.getClearColor()); } void GLRenderer::setClearColor(const Color &color, float alpha) { background.setClearColor(color, alpha); } float GLRenderer::getClearAlpha() const { return background.getClearAlpha(); } void GLRenderer::setClearAlpha(float clearAlpha) { background.setClearAlpha(clearAlpha); } void GLRenderer::clear(bool color, bool depth, bool stencil) { GLbitfield bits = 0; if (color) bits |= GL_COLOR_BUFFER_BIT; if (depth) bits |= GL_DEPTH_BUFFER_BIT; if (stencil) bits |= GL_STENCIL_BUFFER_BIT; glClear(bits); } void GLRenderer::clearColor() { clear(true, false, false); } void GLRenderer::clearDepth() { clear(false, true, false); } void GLRenderer::clearStencil() { clear(false, false, true); } void GLRenderer::dispose() { renderLists.dispose(); renderStates.dispose(); properties.dispose(); // cubemaps.dispose(); objects.dispose(); bindingStates.dispose(); } void GLRenderer::deallocateMaterial(Material &material) { releaseMaterialProgramReferences(material); properties.materialProperties.remove(material.uuid); } void GLRenderer::releaseMaterialProgramReferences(Material &material) { auto &programs = properties.materialProperties.get(material.uuid).programs; if (!programs.empty()) { for (auto &[key, program] : programs) { programCache.releaseProgram(program); } } } void GLRenderer::renderBufferDirect( const std::shared_ptr<Camera> &camera, const std::shared_ptr<Scene> &scene, const std::shared_ptr<BufferGeometry> &geometry, const std::shared_ptr<Material> &material, const std::shared_ptr<Object3D> &object, std::optional<GeometryGroup> group) { if (scene == nullptr) { throw std::runtime_error("TODO"); //scene = &_emptyScene; // renderBufferDirect second parameter used to be fog (could be nullptr) } bool isMesh = instanceof <Mesh>(object.get()); const auto frontFaceCW = (isMesh && object->matrixWorld->determinant() < 0); auto program = setProgram(camera, scene, material, object); state.setMaterial(material.get(), frontFaceCW); // auto index = geometry->getIndex(); const auto &position = geometry->getAttribute<float>("position"); // if (index == nullptr) { if (!geometry->hasAttribute("position") || position->count() == 0) return; } else if (index->count() == 0) { return; } // int rangeFactor = 1; auto wireframeMaterial = dynamic_cast<MaterialWithWireframe *>(material.get()); bool isWireframeMaterial = wireframeMaterial != nullptr; if (isWireframeMaterial && wireframeMaterial->wireframe) { index = geometries.getWireframeAttribute(*geometry); rangeFactor = 2; } bindingStates.setup(object.get(), material.get(), program, geometry.get(), index); gl::BufferRenderer *renderer = bufferRenderer.get(); if (index != nullptr) { const auto &attribute = attributes.get(index); renderer = indexedBufferRenderer.get(); indexedBufferRenderer->setIndex(attribute); } // const auto dataCount = (index != nullptr) ? index->count() : position->count(); const auto rangeStart = geometry->drawRange.start * rangeFactor; const auto rangeCount = geometry->drawRange.count * rangeFactor; const auto groupStart = group ? group->start * rangeFactor : 0; const auto groupCount = group ? group->count * rangeFactor : std::numeric_limits<int>::max(); const auto drawStart = std::max(rangeStart, groupStart); const auto drawEnd = std::min(dataCount, std::min(rangeStart + rangeCount, groupStart + groupCount)) - 1; const auto drawCount = std::max(0, drawEnd - drawStart + 1); if (drawCount == 0) return; // if (isMesh) { if (isWireframeMaterial && wireframeMaterial->wireframe) { state.setLineWidth(wireframeMaterial->wireframeLinewidth * (float) getTargetPixelRatio()); renderer->setMode(GL_LINES); } else { renderer->setMode(GL_TRIANGLES); } } else if (instanceof <Line>(object.get())) { float lineWidth = 1; if (isWireframeMaterial) { lineWidth = wireframeMaterial->wireframeLinewidth; } state.setLineWidth(lineWidth * getTargetPixelRatio()); if (instanceof <LineSegments>(object.get())) { renderer->setMode(GL_LINES); } else if (instanceof <LineLoop>(object.get())) { renderer->setMode(GL_LINE_LOOP); } else { renderer->setMode(GL_LINE_STRIP); } } else if (instanceof <Points>(object.get())) { renderer->setMode(GL_POINTS); } else if (false /*object.isSprite*/) { renderer->setMode(GL_TRIANGLES); } if (instanceof <InstancedMesh>(object.get())) { auto instancedMesh = dynamic_cast<InstancedMesh *>(object.get()); renderer->renderInstances(drawStart, drawCount, instancedMesh->count); } else if (instanceof <InstancedBufferGeometry>(geometry.get())) { auto g = dynamic_cast<InstancedBufferGeometry *>(geometry.get()); const auto instanceCount = std::min(g->instanceCount, g->_maxInstanceCount); renderer->renderInstances(drawStart, drawCount, instanceCount); } else { renderer->render(drawStart, drawCount); } } void GLRenderer::render(const std::shared_ptr<Scene> &scene, const std::shared_ptr<Camera> &camera) { // update scene graph if (scene->autoUpdate) scene->updateMatrixWorld(); // update camera matrices and frustum if (camera->parent == nullptr) camera->updateMatrixWorld(); // // if ( scene.isScene === true ) scene.onBeforeRender( _this, scene, camera, _currentRenderTarget ); currentRenderState = renderStates.get(scene.get(), (int) renderStateStack.size()); currentRenderState->init(); renderStateStack.emplace_back(currentRenderState); _projScreenMatrix.multiplyMatrices(camera->projectionMatrix, camera->matrixWorldInverse); _frustum.setFromProjectionMatrix(_projScreenMatrix); _localClippingEnabled = this->localClippingEnabled; _clippingEnabled = clipping.init(this->clippingPlanes, _localClippingEnabled, camera); currentRenderList = renderLists.get(scene.get(), (int) renderListStack.size()); currentRenderList->init(); renderListStack.emplace_back(currentRenderList); projectObject(scene, camera, 0, sortObjects); currentRenderList->finish(); if (sortObjects) { currentRenderList->sort(); } // if (_clippingEnabled) clipping.beginShadows(); auto &shadowsArray = currentRenderState->getShadowsArray(); shadowMap.render(*this, shadowsArray, scene.get(), camera.get()); currentRenderState->setupLights(); currentRenderState->setupLightsView(camera.get()); if (_clippingEnabled) clipping.endShadows(); // if (this->info.autoReset) this->info.reset(); // background.render(*this, scene.get()); // render scene auto &opaqueObjects = currentRenderList->opaque; auto &transmissiveObjects = currentRenderList->transmissive; auto &transparentObjects = currentRenderList->transparent; // if (!opaqueObjects.empty()) renderObjects(opaqueObjects, scene, camera); if (!transmissiveObjects.empty()) renderTransmissiveObjects(opaqueObjects, transmissiveObjects, scene, camera); if (!transparentObjects.empty()) renderObjects(transparentObjects, scene, camera); // if (_currentRenderTarget) { // Generate mipmap if we're using any kind of mipmap filtering textures.updateRenderTargetMipmap(_currentRenderTarget); } // // if ( scene.isScene === true ) scene.onAfterRender( _this, scene, camera ); // Ensure depth buffer writing is enabled so it can be cleared on next render state.depthBuffer.setTest(true); state.depthBuffer.setMask(true); state.colorBuffer.setMask(true); // state.setPolygonOffset(false); // finish _currentMaterialId = -1; _currentCamera = nullptr; renderStateStack.pop_back(); if (!renderStateStack.empty()) { currentRenderState = renderStateStack[renderStateStack.size() - 1]; } else { currentRenderState = nullptr; } renderListStack.pop_back(); if (!renderListStack.empty()) { currentRenderList = renderListStack[renderListStack.size() - 1]; } else { currentRenderList = nullptr; } } void GLRenderer::projectObject(const std::shared_ptr<Object3D> &object, const std::shared_ptr<Camera> &camera, int groupOrder, bool sortObjects) { if (!object->visible) return; bool visible = object->layers.test(camera->layers); if (visible) { if (instanceof <Group>(object.get())) { groupOrder = object->renderOrder; } else if (instanceof <LOD>(object.get())) { auto lod = dynamic_cast<LOD *>(object.get()); if (lod->autoUpdate) lod->update(camera.get()); } else if (instanceof <Light>(object.get())) { auto light = dynamic_cast<Light *>(object.get()); currentRenderState->pushLight(light); if (light->castShadow) { currentRenderState->pushShadow(light); } // } else if ( object.isSprite ) { // // if ( ! object.frustumCulled || _frustum.intersectsSprite( object ) ) { // // if ( sortObjects ) { // // _vector3.setFromMatrixPosition( object.matrixWorld ) // .applyMatrix4( _projScreenMatrix ); // // } // // const geometry = objects.update( object ); // const material = object.material; // // if ( material.visible ) { // // currentRenderList.push( object, geometry, material, groupOrder, _vector3.z, null ); // // } // // } // // } else if ( object.isImmediateRenderObject ) { // // if ( sortObjects ) { // // _vector3.setFromMatrixPosition( object.matrixWorld ) // .applyMatrix4( _projScreenMatrix ); // // } // // currentRenderList.push( object, null, object.material, groupOrder, _vector3.z, null ); } else if (instanceof <Mesh>(object.get()) || instanceof <Line>(object.get()) || instanceof <Points>(object.get())) { if (!object->frustumCulled || _frustum.intersectsObject(*object)) { if (sortObjects) { _vector3.setFromMatrixPosition(*object->matrixWorld) .applyMatrix4(_projScreenMatrix); } auto geometry = objects.update(object); auto material = object->material(); if (false /*Array.isArray( material )*/) { // const groups = geometry.groups; // // for ( let i = 0, l = groups.length; i < l; i ++ ) { // // const group = groups[ i ]; // const groupMaterial = material[ group.materialIndex ]; // // if ( groupMaterial && groupMaterial.visible ) { // // currentRenderList.push( object, geometry, groupMaterial, groupOrder, _vector3.z, group ); // // } // // } } else if (material->visible) { currentRenderList->push(object, geometry, material, groupOrder, _vector3.z, std::nullopt); } } } } for (const auto &child : object->children) { projectObject(child, camera, groupOrder, sortObjects); } } void GLRenderer::renderTransmissiveObjects( std::vector<std::shared_ptr<gl::RenderItem>> &opaqueObjects, std::vector<std::shared_ptr<gl::RenderItem>> &transmissiveObjects, const std::shared_ptr<Scene> &scene, const std::shared_ptr<Camera> &camera) { //TODO } void GLRenderer::renderObjects( std::vector<std::shared_ptr<gl::RenderItem>> &renderList, const std::shared_ptr<Scene> &scene, const std::shared_ptr<Camera> &camera) { auto overrideMaterial = scene->overrideMaterial; for (const auto &renderItem : renderList) { auto object = renderItem->object; auto geometry = renderItem->geometry; auto material = overrideMaterial == nullptr ? renderItem->material : overrideMaterial; auto group = renderItem->group; if (false /*camera.isArrayCamera*/) { // const cameras = camera.cameras; // // for ( let j = 0, jl = cameras.length; j < jl; j ++ ) { // // const camera2 = cameras[ j ]; // // if ( object.layers.test( camera2.layers ) ) { // // state.viewport( _currentViewport.copy( camera2.viewport ) ); // // currentRenderState.setupLightsView( camera2 ); // // renderObject( object, scene, camera2, geometry, material, group ); // // } // // } } else { renderObject(object, scene, camera, geometry, material, group); } } } void GLRenderer::renderObject( const std::shared_ptr<Object3D> &object, const std::shared_ptr<Scene> &scene, const std::shared_ptr<Camera> &camera, const std::shared_ptr<BufferGeometry> &geometry, const std::shared_ptr<Material> &material, std::optional<GeometryGroup> group) { if (object->onBeforeRender) { object->onBeforeRender.value()((void *) this, scene, camera, geometry, material, group); } object->modelViewMatrix.multiplyMatrices(camera->matrixWorldInverse, *object->matrixWorld); object->normalMatrix.getNormalMatrix(object->modelViewMatrix); if (false /*object.isImmediateRenderObject*/) { // const program = setProgram( camera, scene, material, object ); // // state.setMaterial( material ); // // bindingStates.reset(); // // renderObjectImmediate( object, program ); } else { renderBufferDirect(camera, scene, geometry, material, object, group); } if (object->onAfterRender) { object->onAfterRender.value()(this, scene, camera, geometry, material, group); } } std::shared_ptr<gl::GLProgram> GLRenderer::getProgram( const std::shared_ptr<Material> &material, const std::shared_ptr<Scene> &scene, const std::shared_ptr<Object3D> &object) { // bool isScene = instanceof <Scene>(scene); // // if (!isScene) scene = &_emptyScene;// scene could be a Mesh, Line, Points, ... auto &materialProperties = properties.materialProperties.get(material->uuid); auto &lights = currentRenderState->getLights(); auto &shadowsArray = currentRenderState->getShadowsArray(); auto lightsStateVersion = lights.state.version; auto parameters = programCache.getParameters(*this, material.get(), lights.state, (int) shadowsArray.size(), scene, object); auto programCacheKey = programCache.getProgramCacheKey(*this, parameters); auto &programs = materialProperties.programs; // always update environment and fog - changing these trigger an getProgram call, but it's possible that the program doesn't change materialProperties.environment = instanceof <MeshStandardMaterial>(material.get()) ? scene->environment : nullptr; materialProperties.fog = scene->fog; // materialProperties.envMap = cubemaps.get( material.envMap || materialProperties.environment ); if (programs.empty()) { // new material material->addEventListener("dispose", &onMaterialDispose); } std::shared_ptr<gl::GLProgram> program = nullptr; if (programs.count(programCacheKey)) { program = programs.at(programCacheKey); if (materialProperties.currentProgram == program && materialProperties.lightsStateVersion == lightsStateVersion) { updateCommonMaterialProperties(material, parameters); return program; } } else { parameters.uniforms = programCache.getUniforms(material); // material.onBuild( parameters, this ); // material.onBeforeCompile( parameters, this ); program = programCache.acquireProgram(*this, parameters, programCacheKey); programs[programCacheKey] = program; materialProperties.uniforms = parameters.uniforms; } auto &uniforms = materialProperties.uniforms; if (! instanceof <ShaderMaterial>(material.get()) && ! instanceof <RawShaderMaterial>(material.get()) || material->clipping) { uniforms->operator[]("clippingPlanes") = clipping.uniform; } updateCommonMaterialProperties(material, parameters); // store the light setup it was created for materialProperties.needsLights = materialNeedsLights(material); materialProperties.lightsStateVersion = lightsStateVersion; if (materialProperties.needsLights) { // wire up the material to this renderer's lighting state uniforms->operator[]("ambientLightColor").setValue(lights.state.ambient); uniforms->operator[]("lightProbe").setValue(lights.state.probe); uniforms->operator[]("directionalLights").setValue(lights.state.directional); uniforms->operator[]("directionalLightShadows").setValue(lights.state.directionalShadow); uniforms->operator[]("spotLights").setValue(lights.state.spot); uniforms->operator[]("spotLightShadows").setValue(lights.state.spotShadow); uniforms->operator[]("rectAreaLights").setValue(lights.state.rectArea); // uniforms->operator[]("ltc_1").setValue(lights.state.rectAreaLTC1); // uniforms->operator[]("ltc_2").setValue(lights.state.rectAreaLTC2); uniforms->operator[]("pointLights").setValue(lights.state.point); uniforms->operator[]("pointLightShadows").setValue(lights.state.pointShadow); uniforms->operator[]("hemisphereLights").setValue(lights.state.hemi); uniforms->operator[]("directionalShadowMap").setValue(lights.state.directionalShadowMap); uniforms->operator[]("directionalShadowMatrix").setValue(lights.state.directionalShadowMatrix); uniforms->operator[]("spotShadowMap").setValue(lights.state.spotShadowMap); uniforms->operator[]("spotShadowMatrix").setValue(lights.state.spotShadowMatrix); uniforms->operator[]("pointShadowMap").setValue(lights.state.pointShadowMap); uniforms->operator[]("pointShadowMatrix").setValue(lights.state.pointShadowMatrix); } auto progUniforms = program->getUniforms(); auto uniformsList = gl::GLUniforms::seqWithValue(progUniforms->seq, uniforms); materialProperties.currentProgram = program; materialProperties.uniformsList = uniformsList; return materialProperties.currentProgram; } void GLRenderer::updateCommonMaterialProperties(const std::shared_ptr<Material> &material, gl::ProgramParameters &parameters) { auto &materialProperties = properties.materialProperties.get(material->uuid); materialProperties.outputEncoding = parameters.outputEncoding; materialProperties.instancing = parameters.instancing; materialProperties.numClippingPlanes = parameters.numClippingPlanes; materialProperties.numIntersection = parameters.numClipIntersection; materialProperties.vertexAlphas = parameters.vertexAlphas; } std::shared_ptr<gl::GLProgram> GLRenderer::setProgram( const std::shared_ptr<Camera> &camera, const std::shared_ptr<Scene> &scene, const std::shared_ptr<Material> &material, const std::shared_ptr<Object3D> &object) { // bool isScene = instanceof <Scene>(scene); // if (!isScene) scene = _emptyScene;// scene could be a Mesh, Line, Points, ... // bool isMeshBasicMaterial = instanceof <MeshBasicMaterial>(material.get()); bool isMeshLambertMaterial = instanceof <MeshLambertMaterial>(material.get()); bool isMeshToonMaterial = instanceof <MeshToonMaterial>(material.get()); bool isMeshPhongMaterial = instanceof <MeshPhongMaterial>(material.get()); bool isMeshStandardMaterial = instanceof <MeshStandardMaterial>(material.get()); bool isShadowMaterial = instanceof <ShadowMaterial>(material.get()); bool isShaderMaterial = instanceof <ShaderMaterial>(material.get()); bool isEnvMap = instanceof <MaterialWithEnvMap>(material.get()) && dynamic_cast<MaterialWithEnvMap *>(material.get())->envMap; textures.resetTextureUnits(); auto fog = scene->fog; auto environment = isMeshStandardMaterial ? scene->environment : nullptr; int encoding = (_currentRenderTarget == nullptr) ? outputEncoding : _currentRenderTarget->texture->encoding; // const envMap = cubemaps.get(material.envMap || environment); bool vertexAlphas = material->vertexColors && object->geometry() && object->geometry()->hasAttribute("color") && object->geometry()->getAttribute<float>("color")->itemSize() == 4; auto &materialProperties = properties.materialProperties.get(material->uuid); auto &lights = currentRenderState->getLights(); if (_clippingEnabled) { if (_localClippingEnabled || camera != _currentCamera) { bool useCache = camera == _currentCamera && material->id == _currentMaterialId; // we might want to call this function with some ClippingGroup // object instead of the material, once it becomes feasible // (#8465, #8379) clipping.setState(material, camera, useCache); } } // bool needsProgramChange = false; bool isInstancedMesh = instanceof <InstancedMesh>(object.get()); if (material->version == materialProperties.version) { if (materialProperties.needsLights && (materialProperties.lightsStateVersion != lights.state.version)) { needsProgramChange = true; } else if (materialProperties.outputEncoding != encoding) { needsProgramChange = true; } else if (isInstancedMesh && !materialProperties.instancing) { needsProgramChange = true; } else if (!isInstancedMesh && materialProperties.instancing) { needsProgramChange = true; } else if (false /*materialProperties.envMap != envMap*/) { needsProgramChange = true; } else if (fog && material->fog && materialProperties.fog && !(fog.value() == materialProperties.fog.value())) { needsProgramChange = true; } else if (materialProperties.numClippingPlanes && (materialProperties.numClippingPlanes.value() != clipping.numPlanes || materialProperties.numIntersection != clipping.numIntersection)) { needsProgramChange = true; } else if (materialProperties.vertexAlphas != vertexAlphas) { needsProgramChange = true; } } else { needsProgramChange = true; materialProperties.version = material->version; } // auto program = materialProperties.currentProgram; if (needsProgramChange) { program = getProgram(material, scene, object); } bool refreshProgram = false; bool refreshMaterial = false; bool refreshLights = false; auto p_uniforms = program->getUniforms(); auto &m_uniforms = materialProperties.uniforms; if (state.useProgram(program->program)) { refreshProgram = true; refreshMaterial = true; refreshLights = true; } if (material->id != _currentMaterialId) { _currentMaterialId = material->id; refreshMaterial = true; } if (refreshProgram || _currentCamera != camera) { p_uniforms->setValue("projectionMatrix", camera->projectionMatrix); if (gl::GLCapabilities::instance().logarithmicDepthBuffer) { p_uniforms->setValue("logDepthBufFC", 2.f / (std::log(camera->far + 1.f) / math::LN2)); } if (_currentCamera != camera) { _currentCamera = camera; // lighting uniforms depend on the camera so enforce an update // now, in case this material supports lights - or later, when // the next material that does gets activated: refreshMaterial = true;// set to true on material change refreshLights = true; // remains set until update done } // load material specific uniforms // (shader material also gets them for the sake of genericity) if (isShaderMaterial || isMeshPhongMaterial || isMeshToonMaterial || isMeshStandardMaterial || isEnvMap) { if (p_uniforms->map.count("cameraPosition")) { auto &uCamPos = p_uniforms->map["cameraPosition"]; _vector3.setFromMatrixPosition(*camera->matrixWorld); uCamPos->setValue(_vector3); } } if (isMeshPhongMaterial || isMeshToonMaterial || isMeshLambertMaterial || isMeshBasicMaterial || isMeshStandardMaterial || isShaderMaterial) { p_uniforms->setValue("isOrthographic", instanceof <OrthographicCamera>(camera.get())); } if (isMeshPhongMaterial || isMeshToonMaterial || isMeshLambertMaterial || isMeshBasicMaterial || isMeshStandardMaterial || isShaderMaterial || isShadowMaterial) { p_uniforms->setValue("viewMatrix", camera->matrixWorldInverse); } } if (refreshMaterial || materialProperties.receiveShadow != object->receiveShadow) { materialProperties.receiveShadow = object->receiveShadow; p_uniforms->setValue("receiveShadow", object->receiveShadow); } if (refreshMaterial) { p_uniforms->setValue("toneMappingExposure", toneMappingExposure); if (materialProperties.needsLights) { // the current material requires lighting info // note: all lighting uniforms are always set correctly // they simply reference the renderer's state for their // values // // use the current material's .needsUpdate flags to set // the GL state when required markUniformsLightsNeedsUpdate(m_uniforms, refreshLights); } // refresh uniforms common to several materials if (fog && material->fog) { materials.refreshFogUniforms(m_uniforms, *fog); } materials.refreshMaterialUniforms(m_uniforms, material.get(), _pixelRatio, _size.height /*, _transmissionRenderTarget*/); gl::GLUniforms::upload(materialProperties.uniformsList, m_uniforms, &textures); } if (isShaderMaterial) { auto m = dynamic_cast<ShaderMaterial *>(material.get()); if (m->uniformsNeedUpdate) { gl::GLUniforms::upload(materialProperties.uniformsList, m_uniforms, &textures); m->uniformsNeedUpdate = false; } } if (false /*material.isSpriteMaterial*/) { // TODO // p_uniforms->setValue("center", object->center); } // common matrices p_uniforms->setValue("modelViewMatrix", object->modelViewMatrix); p_uniforms->setValue("normalMatrix", object->normalMatrix); p_uniforms->setValue("modelMatrix", *object->matrixWorld); return program; } void GLRenderer::markUniformsLightsNeedsUpdate(std::shared_ptr<UniformMap> &uniforms, bool value) { uniforms->operator[]("ambientLightColor").needsUpdate = value; uniforms->operator[]("lightProbe").needsUpdate = value; uniforms->operator[]("directionalLights").needsUpdate = value; uniforms->operator[]("directionalLightShadows").needsUpdate = value; uniforms->operator[]("pointLights").needsUpdate = value; uniforms->operator[]("pointLightShadows").needsUpdate = value; uniforms->operator[]("spotLights").needsUpdate = value; uniforms->operator[]("spotLightShadows").needsUpdate = value; uniforms->operator[]("rectAreaLights").needsUpdate = value; uniforms->operator[]("hemisphereLights").needsUpdate = value; } bool GLRenderer::materialNeedsLights(const std::shared_ptr<Material> &material) { bool isMeshLambertMaterial = instanceof <MeshLambertMaterial>(material.get()); bool isMeshToonMaterial = instanceof <MeshToonMaterial>(material.get()); bool isMeshPhongMaterial = instanceof <MeshPhongMaterial>(material.get()); bool isMeshStandardMaterial = instanceof <MeshStandardMaterial>(material.get()); bool isShadowMaterial = instanceof <ShadowMaterial>(material.get()); bool isShaderMaterial = instanceof <ShaderMaterial>(material.get()); bool lights = false; if (instanceof <MaterialWithLights>(material.get())) { lights = dynamic_cast<MaterialWithLights *>(material.get())->lights; } return isMeshLambertMaterial || isMeshToonMaterial || isMeshPhongMaterial || isMeshStandardMaterial || isShadowMaterial || (isShaderMaterial && lights); } void GLRenderer::setRenderTarget(const std::shared_ptr<GLRenderTarget> &renderTarget, int activeCubeFace, int activeMipmapLevel) { _currentRenderTarget = renderTarget; _currentActiveCubeFace = activeCubeFace; _currentActiveMipmapLevel = activeMipmapLevel; if (renderTarget && !properties.renderTargetProperties.get(renderTarget->uuid).glFramebuffer) { textures.setupRenderTarget(renderTarget); } unsigned int framebuffer = 0; if (renderTarget) { const auto &texture = renderTarget->texture; framebuffer = *properties.renderTargetProperties.get(renderTarget->uuid).glFramebuffer; _currentViewport.copy(renderTarget->viewport); _currentScissor.copy(renderTarget->scissor); _currentScissorTest = renderTarget->scissorTest; } else { _currentViewport.copy(_viewport).multiplyScalar(static_cast<float>(_pixelRatio)).floor(); _currentScissor.copy(_scissor).multiplyScalar(static_cast<float>(_pixelRatio)).floor(); _currentScissorTest = _scissorTest; } const bool framebufferBound = state.bindFramebuffer(GL_FRAMEBUFFER, framebuffer) && framebuffer; if (framebufferBound && gl::GLCapabilities::instance().drawBuffers) { bool needsUpdate = false; if (renderTarget) { if (_currentDrawBuffers.size() != 1 || _currentDrawBuffers[0] != GL_COLOR_ATTACHMENT0) { _currentDrawBuffers[0] = GL_COLOR_ATTACHMENT0; _currentDrawBuffers.resize(1); needsUpdate = true; } } else { if (_currentDrawBuffers.size() != 1 || _currentDrawBuffers[0] != GL_BACK) { _currentDrawBuffers.clear(); _currentDrawBuffers.emplace_back(GL_BACK); needsUpdate = true; } } if (needsUpdate) { glDrawBuffers((int) _currentDrawBuffers.size(), _currentDrawBuffers.data()); } } state.viewport(_currentViewport); state.scissor(_currentScissor); state.setScissorTest(_currentScissorTest.value_or(false)); } GLRenderer::OnMaterialDispose::OnMaterialDispose(GLRenderer &scope) : scope_(scope) {} void GLRenderer::OnMaterialDispose::onEvent(Event &event) { auto material = static_cast<Material *>(event.target); material->removeEventListener("dispose", this); scope_.deallocateMaterial(*material); }
32.120996
146
0.639929
[ "mesh", "geometry", "render", "object", "vector" ]
4f70e063ec3b7ad98bf0dc7eb0f00db4351ba576
17,508
cpp
C++
src/libutil/filesystem_test.cpp
hobbes1069/oiio
662278827211715563f6ff10d549307b4aca1d84
[ "BSD-3-Clause" ]
3
2018-03-09T15:45:40.000Z
2019-03-22T16:25:55.000Z
src/libutil/filesystem_test.cpp
hobbes1069/oiio
662278827211715563f6ff10d549307b4aca1d84
[ "BSD-3-Clause" ]
null
null
null
src/libutil/filesystem_test.cpp
hobbes1069/oiio
662278827211715563f6ff10d549307b4aca1d84
[ "BSD-3-Clause" ]
null
null
null
/* Copyright 2011 Larry Gritz and the other authors and contributors. All Rights Reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the software's owners nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. (This is the Modified BSD License) */ #include <sstream> #include <fstream> #include <OpenImageIO/platform.h> #include <OpenImageIO/imageio.h> #include <OpenImageIO/filesystem.h> #include <OpenImageIO/unittest.h> #ifndef _WIN32 # include <sys/stat.h> #endif using namespace OIIO; // This will be run via testsuite/unit_filesystem, from the // build/ARCH/src/libOpenImageIO directory. Two levels up will be // build/ARCH. void test_filename_decomposition () { std::string test ("/directoryA/directory/filename.ext"); std::cout << "Testing filename, extension, parent_path\n"; OIIO_CHECK_EQUAL (Filesystem::filename(test), "filename.ext"); OIIO_CHECK_EQUAL (Filesystem::extension(test), ".ext"); OIIO_CHECK_EQUAL (Filesystem::extension("/directory/filename"), ""); OIIO_CHECK_EQUAL (Filesystem::extension("/directory/filename."), "."); OIIO_CHECK_EQUAL (Filesystem::parent_path(test), "/directoryA/directory"); std::cout << "Testing path_is_absolute\n"; OIIO_CHECK_EQUAL (Filesystem::path_is_absolute ("/foo/bar"), true); OIIO_CHECK_EQUAL (Filesystem::path_is_absolute ("foo/bar"), false); OIIO_CHECK_EQUAL (Filesystem::path_is_absolute ("../foo/bar"), false); std::cout << "Testing replace_extension\n"; OIIO_CHECK_EQUAL (Filesystem::replace_extension(test,"foo"), "/directoryA/directory/filename.foo"); } void test_filename_searchpath_find () { #if _WIN32 # define DIRSEP "\\" #else # define DIRSEP "/" #endif #define PATHSEP ":" std::string pathlist (".." DIRSEP ".." PATHSEP ".." DIRSEP ".." DIRSEP "cpack" PATHSEP "foo/bar/baz"); std::cout << "Testing searchpath_split\n"; std::vector<std::string> dirs; Filesystem::searchpath_split (pathlist, dirs); OIIO_CHECK_EQUAL (dirs.size(), 3); OIIO_CHECK_EQUAL (dirs[0], ".." DIRSEP ".."); OIIO_CHECK_EQUAL (dirs[1], ".." DIRSEP ".." DIRSEP "cpack"); OIIO_CHECK_EQUAL (dirs[2], "foo/bar/baz"); std::cout << "Testing searchpath_find\n"; // non-recursive search success OIIO_CHECK_EQUAL (Filesystem::searchpath_find ("License.txt", dirs, false, false), ".." DIRSEP ".." DIRSEP "cpack" DIRSEP "License.txt"); // non-recursive search failure (file is in a subdirectory) OIIO_CHECK_EQUAL (Filesystem::searchpath_find ("oiioversion.h", dirs, false, false), ""); // recursive search success (file is in a subdirectory) OIIO_CHECK_EQUAL (Filesystem::searchpath_find ("oiioversion.h", dirs, false, true), ".." DIRSEP ".." DIRSEP "include" DIRSEP "OpenImageIO" DIRSEP "oiioversion.h"); } inline std::string my_read_text_file (string_view filename) { std::string err; std::string contents; bool ok = Filesystem::read_text_file (filename, contents); OIIO_CHECK_ASSERT (ok); return contents; } static void test_file_status () { // Make test file, test Filesystem::fopen in the process. FILE *file = Filesystem::fopen ("testfile", "w"); OIIO_CHECK_ASSERT (file != NULL); const char testtext[] = "test\nfoo\nbar\n"; fputs (testtext, file); fclose (file); std::cout << "Testing file_size:\n"; OIIO_CHECK_EQUAL (Filesystem::file_size("testfile"), 13); std::cout << "Testing read_text_file\n"; OIIO_CHECK_EQUAL (my_read_text_file("testfile"), testtext); std::cout << "Testing read_bytes:\n"; char buf[3]; size_t nread = Filesystem::read_bytes ("testfile", buf, 3, 5); OIIO_CHECK_EQUAL (nread, 3); OIIO_CHECK_EQUAL (buf[0], 'f'); OIIO_CHECK_EQUAL (buf[1], 'o'); OIIO_CHECK_EQUAL (buf[2], 'o'); std::cout << "Testing create_directory\n"; Filesystem::create_directory ("testdir"); std::cout << "Testing exists\n"; OIIO_CHECK_ASSERT (Filesystem::exists("testfile")); OIIO_CHECK_ASSERT (Filesystem::exists("testdir")); OIIO_CHECK_ASSERT (! Filesystem::exists("noexist")); std::cout << "Testing is_directory, is_regular\n"; OIIO_CHECK_ASSERT (Filesystem::is_regular("testfile")); OIIO_CHECK_ASSERT (! Filesystem::is_directory("testfile")); OIIO_CHECK_ASSERT (! Filesystem::is_regular("testdir")); OIIO_CHECK_ASSERT (Filesystem::is_directory("testdir")); OIIO_CHECK_ASSERT (! Filesystem::is_regular("noexist")); OIIO_CHECK_ASSERT (! Filesystem::is_directory("noexist")); std::cout << "Testing copy, rename, remove\n"; OIIO_CHECK_ASSERT (! Filesystem::exists("testfile2")); OIIO_CHECK_ASSERT (! Filesystem::exists("testfile3")); Filesystem::copy ("testfile", "testfile2"); OIIO_CHECK_ASSERT (Filesystem::exists("testfile2")); OIIO_CHECK_EQUAL (my_read_text_file("testfile2"), testtext); Filesystem::rename ("testfile2", "testfile3"); OIIO_CHECK_ASSERT (! Filesystem::exists("testfile2")); OIIO_CHECK_ASSERT (Filesystem::exists("testfile3")); OIIO_CHECK_EQUAL (my_read_text_file("testfile3"), testtext); Filesystem::remove ("testfile"); Filesystem::remove ("testfile3"); Filesystem::remove ("testdir"); OIIO_CHECK_ASSERT (! Filesystem::exists("testfile")); OIIO_CHECK_ASSERT (! Filesystem::exists("testfile2")); OIIO_CHECK_ASSERT (! Filesystem::exists("testfile3")); OIIO_CHECK_ASSERT (! Filesystem::exists("testdir")); } static void test_seq (const char *str, const char *expected) { std::vector<int> sequence; Filesystem::enumerate_sequence (str, sequence); std::stringstream joined; for (size_t i = 0; i < sequence.size(); ++i) { if (i) joined << " "; joined << sequence[i]; } std::cout << " \"" << str << "\" -> " << joined.str() << "\n"; OIIO_CHECK_EQUAL (joined.str(), std::string(expected)); } static void test_file_seq (const char *pattern, const char *override, const std::string &expected) { std::vector<int> numbers; std::vector<std::string> names; std::string normalized_pattern; std::string frame_range; Filesystem::parse_pattern(pattern, 0, normalized_pattern, frame_range); if (override && strlen(override) > 0) frame_range = override; Filesystem::enumerate_sequence(frame_range.c_str(), numbers); Filesystem::enumerate_file_sequence (normalized_pattern, numbers, names); std::string joined = Strutil::join(names, " "); std::cout << " " << pattern; if (override) std::cout << " + " << override; std::cout << " -> " << joined << "\n"; OIIO_CHECK_EQUAL (joined, expected); } static void test_file_seq_with_view (const char *pattern, const char *override, const char *view, const std::string &expected) { std::vector<int> numbers; std::vector<string_view> views; std::vector<std::string> names; std::string normalized_pattern; std::string frame_range; Filesystem::parse_pattern(pattern, 0, normalized_pattern, frame_range); if (override && strlen(override) > 0) frame_range = override; Filesystem::enumerate_sequence(frame_range.c_str(), numbers); if (view) { for (size_t i = 0, e = numbers.size(); i < e; ++i) views.emplace_back(view); } Filesystem::enumerate_file_sequence (normalized_pattern, numbers, views, names); std::string joined = Strutil::join(names, " "); std::cout << " " << pattern; if (override) std::cout << " + " << override; std::cout << " -> " << joined << "\n"; OIIO_CHECK_EQUAL (joined, expected); } static void test_scan_file_seq (const char *pattern, const std::string &expected) { std::vector<int> numbers; std::vector<std::string> names; std::string normalized_pattern; std::string frame_range; Filesystem::parse_pattern(pattern, 0, normalized_pattern, frame_range); Filesystem::scan_for_matching_filenames (normalized_pattern, numbers, names); std::string joined = Strutil::join(names, " "); std::cout << " " << pattern; std::cout << " -> " << joined << "\n"; OIIO_CHECK_EQUAL (joined, expected); // Check that we don't crash from exceptions generated by strangely // formed patterns. const char *weird = "{'cpu_model': 'Intel(R) Xeon(R) CPU E5-2630 @ 2.30GHz'}"; Filesystem::parse_pattern (weird, 0, normalized_pattern, frame_range); Filesystem::scan_for_matching_filenames (normalized_pattern, numbers, names); OIIO_CHECK_EQUAL (names.size(), 0); // If we didn't crash above, we're ok! } static void test_scan_file_seq_with_views (const char *pattern, const char **views_, const std::string &expected) { std::vector<int> frame_numbers; std::vector<string_view> frame_views; std::vector<std::string> frame_names; std::string normalized_pattern; std::string frame_range; std::vector<string_view> views; for (size_t i = 0; views_[i]; ++i) views.emplace_back(views_[i]); Filesystem::parse_pattern(pattern, 0, normalized_pattern, frame_range); Filesystem::scan_for_matching_filenames (normalized_pattern, views, frame_numbers, frame_views, frame_names); std::string joined = Strutil::join(frame_names, " "); std::cout << " " << pattern; std::cout << " -> " << joined << "\n"; OIIO_CHECK_EQUAL (joined, expected); } void test_frame_sequences () { std::cout << "Testing frame number sequences:\n"; test_seq ("3", "3"); test_seq ("1-5", "1 2 3 4 5"); test_seq ("5-1", "5 4 3 2 1"); test_seq ("1-3,6,10-12", "1 2 3 6 10 11 12"); test_seq ("1-5x2", "1 3 5"); test_seq ("1-5y2", "2 4"); std::cout << "\n"; test_file_seq ("foo.1-5#.exr", NULL, "foo.0001.exr foo.0002.exr foo.0003.exr foo.0004.exr foo.0005.exr"); test_file_seq ("foo.5-1#.exr", NULL, "foo.0005.exr foo.0004.exr foo.0003.exr foo.0002.exr foo.0001.exr"); test_file_seq ("foo.1-3,6,10-12#.exr", NULL, "foo.0001.exr foo.0002.exr foo.0003.exr foo.0006.exr foo.0010.exr foo.0011.exr foo.0012.exr"); test_file_seq ("foo.1-5x2#.exr", NULL, "foo.0001.exr foo.0003.exr foo.0005.exr"); test_file_seq ("foo.1-5y2#.exr", NULL, "foo.0002.exr foo.0004.exr"); test_file_seq ("foo.#.exr", "1-5", "foo.0001.exr foo.0002.exr foo.0003.exr foo.0004.exr foo.0005.exr"); test_file_seq ("foo.#.exr", "1-5x2", "foo.0001.exr foo.0003.exr foo.0005.exr"); test_file_seq ("foo.1-3@@.exr", NULL, "foo.01.exr foo.02.exr foo.03.exr"); test_file_seq ("foo.1-3@#.exr", NULL, "foo.00001.exr foo.00002.exr foo.00003.exr"); test_file_seq ("foo.1-5%04d.exr", NULL, "foo.0001.exr foo.0002.exr foo.0003.exr foo.0004.exr foo.0005.exr"); test_file_seq ("foo.%04d.exr", "1-5", "foo.0001.exr foo.0002.exr foo.0003.exr foo.0004.exr foo.0005.exr"); test_file_seq ("foo.%4d.exr", "1-5", "foo. 1.exr foo. 2.exr foo. 3.exr foo. 4.exr foo. 5.exr"); test_file_seq ("foo.%d.exr", "1-5", "foo.1.exr foo.2.exr foo.3.exr foo.4.exr foo.5.exr"); const char *views1[] = { "left", "right", "foo", "", NULL }; for (auto view : views1) { test_file_seq_with_view ("foo.1-5#.exr", NULL, view, "foo.0001.exr foo.0002.exr foo.0003.exr foo.0004.exr foo.0005.exr"); test_file_seq_with_view ("foo.5-1#.exr", NULL, view, "foo.0005.exr foo.0004.exr foo.0003.exr foo.0002.exr foo.0001.exr"); test_file_seq_with_view ("foo.1-3,6,10-12#.exr", NULL, view, "foo.0001.exr foo.0002.exr foo.0003.exr foo.0006.exr foo.0010.exr foo.0011.exr foo.0012.exr"); test_file_seq_with_view ("foo.1-5x2#.exr", NULL, view, "foo.0001.exr foo.0003.exr foo.0005.exr"); test_file_seq_with_view ("foo.1-5y2#.exr", NULL, view, "foo.0002.exr foo.0004.exr"); test_file_seq_with_view ("foo.#.exr", "1-5", view, "foo.0001.exr foo.0002.exr foo.0003.exr foo.0004.exr foo.0005.exr"); test_file_seq_with_view ("foo.#.exr", "1-5x2", view, "foo.0001.exr foo.0003.exr foo.0005.exr"); test_file_seq_with_view ("foo.1-3@@.exr", NULL, view, "foo.01.exr foo.02.exr foo.03.exr"); test_file_seq_with_view ("foo.1-3@#.exr", NULL, view, "foo.00001.exr foo.00002.exr foo.00003.exr"); test_file_seq_with_view ("foo.1-5%04d.exr", NULL, view, "foo.0001.exr foo.0002.exr foo.0003.exr foo.0004.exr foo.0005.exr"); test_file_seq_with_view ("foo.%04d.exr", "1-5", view, "foo.0001.exr foo.0002.exr foo.0003.exr foo.0004.exr foo.0005.exr"); test_file_seq_with_view ("foo.%4d.exr", "1-5", view, "foo. 1.exr foo. 2.exr foo. 3.exr foo. 4.exr foo. 5.exr"); test_file_seq_with_view ("foo.%d.exr", "1-5", view, "foo.1.exr foo.2.exr foo.3.exr foo.4.exr foo.5.exr"); } // test_file_seq_with_view ("%V.%04d", NULL, NULL, ""); // test_file_seq_with_view ("%v", NULL, NULL, ""); // test_file_seq_with_view ("%V", NULL, "", ""); // test_file_seq_with_view ("%v", NULL, "", ""); // test_file_seq_with_view ("%V", NULL, "left", "left"); // test_file_seq_with_view ("%V", NULL, "right", "right"); // test_file_seq_with_view ("%v", NULL, "left", "l"); // test_file_seq_with_view ("%v", NULL, "right", "r"); test_file_seq_with_view ("foo_%V.1-2#.exr", NULL, "left", "foo_left.0001.exr foo_left.0002.exr"); test_file_seq_with_view ("%V/foo_%V.1-2#.exr", NULL, "left", "left/foo_left.0001.exr left/foo_left.0002.exr"); test_file_seq_with_view ("%v/foo_%V.1-2#.exr", NULL, "left", "l/foo_left.0001.exr l/foo_left.0002.exr"); test_file_seq_with_view ("%V/foo_%v.1-2#.exr", NULL, "left", "left/foo_l.0001.exr left/foo_l.0002.exr"); test_file_seq_with_view ("%v/foo_%v.1-2#.exr", NULL, "left", "l/foo_l.0001.exr l/foo_l.0002.exr"); std::cout << "\n"; } void create_test_file(const string_view& fn) { std::ofstream f(fn.c_str()); f.close(); } void test_scan_sequences () { std::cout << "Testing frame sequence scanning:\n"; std::vector< std::string > filenames; for (size_t i = 1; i <= 5; i++) { std::string fn = Strutil::format ("foo.%04d.exr", i); filenames.push_back (fn); create_test_file(fn); } #ifdef _WIN32 test_scan_file_seq ("foo.#.exr", ".\\foo.0001.exr .\\foo.0002.exr .\\foo.0003.exr .\\foo.0004.exr .\\foo.0005.exr"); #else test_scan_file_seq ("foo.#.exr", "./foo.0001.exr ./foo.0002.exr ./foo.0003.exr ./foo.0004.exr ./foo.0005.exr"); #endif filenames.clear(); Filesystem::create_directory ("left"); Filesystem::create_directory ("left/l"); for (size_t i = 1; i <= 5; i++) { std::string fn = Strutil::format ("left/l/foo_left_l.%04d.exr", i); filenames.push_back (fn); create_test_file(fn); } const char *views[] = { "left", NULL }; #ifdef _WIN32 test_scan_file_seq_with_views ("%V/%v/foo_%V_%v.#.exr", views, "left\\l\\foo_left_l.0001.exr left\\l\\foo_left_l.0002.exr left\\l\\foo_left_l.0003.exr left\\l\\foo_left_l.0004.exr left\\l\\foo_left_l.0005.exr"); #else test_scan_file_seq_with_views ("%V/%v/foo_%V_%v.#.exr", views, "left/l/foo_left_l.0001.exr left/l/foo_left_l.0002.exr left/l/foo_left_l.0003.exr left/l/foo_left_l.0004.exr left/l/foo_left_l.0005.exr"); #endif filenames.clear(); Filesystem::create_directory ("right"); Filesystem::create_directory ("right/r"); std::string fn; fn = "left/l/foo_left_l"; filenames.push_back(fn); create_test_file(fn); fn = "right/r/foo_right_r"; filenames.push_back(fn); create_test_file(fn); const char *views2[] = { "left", "right", NULL }; #ifdef _WIN32 test_scan_file_seq_with_views ("%V/%v/foo_%V_%v", views2, "left\\l\\foo_left_l right\\r\\foo_right_r"); #else test_scan_file_seq_with_views ("%V/%v/foo_%V_%v", views2, "left/l/foo_left_l right/r/foo_right_r"); #endif } int main (int argc, char *argv[]) { test_filename_decomposition (); test_filename_searchpath_find (); test_file_status (); test_frame_sequences (); test_scan_sequences (); return unit_test_failures; }
38.649007
215
0.662668
[ "vector" ]
4f710cc7b6bd80333029c25a371bab3c5a7de42d
2,114
cc
C++
source/domainvariables/dv_dvisc_const.cc
BYUignite/ODT
7c320c776e50f4da5faf9e8e67161b6fa2737c24
[ "MIT" ]
6
2020-11-13T00:34:37.000Z
2022-02-16T19:06:39.000Z
source/domainvariables/dv_dvisc_const.cc
ElsevierSoftwareX/SOFTX-D-20-00063
291d6ff9ae5813aed3135dc22525c9f0fc99282a
[ "MIT" ]
null
null
null
source/domainvariables/dv_dvisc_const.cc
ElsevierSoftwareX/SOFTX-D-20-00063
291d6ff9ae5813aed3135dc22525c9f0fc99282a
[ "MIT" ]
5
2020-10-17T15:20:51.000Z
2021-09-04T13:27:54.000Z
/** * @file dv_dvisc_const.cc * @brief Source file for class dv_dvisc_const */ #include "dv_dvisc_const.h" #include "domain.h" //////////////////////////////////////////////////////////////////////////////// /*! dv_dvisc_const constructor function * * @param p_domn \input set domain pointer with. * @param p_phi \input set vector pointer with. */ dv_dvisc_const::dv_dvisc_const(domain *line, const string s, const bool Lt, const bool Lo) { domn = line; var_name = s; L_transported = Lt; L_output = Lo; d = vector<double>(domn->ngrd, domn->pram->kvisc0 * domn->pram->rho0); if(Lt){ *domn->io->ostrm << endl << "ERROR, you set dvisc to be transported. Resetting L_transported to false" << endl; L_transported = false; } } //////////////////////////////////////////////////////////////////////////////// /*! merger2cells function * * Function presumes that the variable being merged is a quantity per unit mass. * Merging conservatively: (rho*phi*dx)_merged = (rho*phi*dx)_1 + (rho*phi*dx)_2 * Then solve for phi_merged. * * @param imrg \input merge cells imrg and imrg+1 * @param imrg \input merge cells imrg and imrg+1 * @param m1 \input mass in cell imrg * @param m2 \input mass in cell imrg * @param LconstVolume \input (for posf, default is false) */ void dv_dvisc_const::merge2cells(const int imrg, const double m1, const double m2, const bool LconstVolume) { d.erase(d.begin() + imrg+1); } //////////////////////////////////////////////////////////////////////////////// /*! dv_dvisc_const setVar function * @param ipt \input optional point to compute at */ void dv_dvisc_const::setVar(const int ipt){ if(ipt != -1) { cout << endl << "ERROR in setVar: ipt must be -1" << endl; exit(0); } d.resize(domn->ngrd, domn->pram->kvisc0 * domn->pram->rho0); }
29.774648
119
0.51088
[ "vector" ]
4f742b93f03c1b475526bf4683ec86ec63721cc8
26,858
cc
C++
net/udp/udp_socket_win.cc
justremotephone/android_external_chromium_org
246856e61da7acf5494076c74198f2aea894a721
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
2
2020-01-25T10:18:18.000Z
2021-01-23T15:29:56.000Z
net/udp/udp_socket_win.cc
justremotephone/android_external_chromium_org
246856e61da7acf5494076c74198f2aea894a721
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
1
2018-02-10T21:00:08.000Z
2018-03-20T05:09:50.000Z
net/udp/udp_socket_win.cc
justremotephone/android_external_chromium_org
246856e61da7acf5494076c74198f2aea894a721
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
1
2020-11-04T07:24:13.000Z
2020-11-04T07:24:13.000Z
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "net/udp/udp_socket_win.h" #include <mstcpip.h> #include "base/callback.h" #include "base/logging.h" #include "base/message_loop/message_loop.h" #include "base/metrics/histogram.h" #include "base/metrics/sparse_histogram.h" #include "base/metrics/stats_counters.h" #include "base/rand_util.h" #include "net/base/io_buffer.h" #include "net/base/ip_endpoint.h" #include "net/base/net_errors.h" #include "net/base/net_log.h" #include "net/base/net_util.h" #include "net/base/winsock_init.h" #include "net/base/winsock_util.h" #include "net/socket/socket_descriptor.h" #include "net/udp/udp_net_log_parameters.h" namespace { const int kBindRetries = 10; const int kPortStart = 1024; const int kPortEnd = 65535; } // namespace namespace net { // This class encapsulates all the state that has to be preserved as long as // there is a network IO operation in progress. If the owner UDPSocketWin // is destroyed while an operation is in progress, the Core is detached and it // lives until the operation completes and the OS doesn't reference any resource // declared on this class anymore. class UDPSocketWin::Core : public base::RefCounted<Core> { public: explicit Core(UDPSocketWin* socket); // Start watching for the end of a read or write operation. void WatchForRead(); void WatchForWrite(); // The UDPSocketWin is going away. void Detach() { socket_ = NULL; } // The separate OVERLAPPED variables for asynchronous operation. OVERLAPPED read_overlapped_; OVERLAPPED write_overlapped_; // The buffers used in Read() and Write(). scoped_refptr<IOBuffer> read_iobuffer_; scoped_refptr<IOBuffer> write_iobuffer_; // The address storage passed to WSARecvFrom(). SockaddrStorage recv_addr_storage_; private: friend class base::RefCounted<Core>; class ReadDelegate : public base::win::ObjectWatcher::Delegate { public: explicit ReadDelegate(Core* core) : core_(core) {} virtual ~ReadDelegate() {} // base::ObjectWatcher::Delegate methods: virtual void OnObjectSignaled(HANDLE object); private: Core* const core_; }; class WriteDelegate : public base::win::ObjectWatcher::Delegate { public: explicit WriteDelegate(Core* core) : core_(core) {} virtual ~WriteDelegate() {} // base::ObjectWatcher::Delegate methods: virtual void OnObjectSignaled(HANDLE object); private: Core* const core_; }; ~Core(); // The socket that created this object. UDPSocketWin* socket_; // |reader_| handles the signals from |read_watcher_|. ReadDelegate reader_; // |writer_| handles the signals from |write_watcher_|. WriteDelegate writer_; // |read_watcher_| watches for events from Read(). base::win::ObjectWatcher read_watcher_; // |write_watcher_| watches for events from Write(); base::win::ObjectWatcher write_watcher_; DISALLOW_COPY_AND_ASSIGN(Core); }; UDPSocketWin::Core::Core(UDPSocketWin* socket) : socket_(socket), reader_(this), writer_(this) { memset(&read_overlapped_, 0, sizeof(read_overlapped_)); memset(&write_overlapped_, 0, sizeof(write_overlapped_)); read_overlapped_.hEvent = WSACreateEvent(); write_overlapped_.hEvent = WSACreateEvent(); } UDPSocketWin::Core::~Core() { // Make sure the message loop is not watching this object anymore. read_watcher_.StopWatching(); write_watcher_.StopWatching(); WSACloseEvent(read_overlapped_.hEvent); memset(&read_overlapped_, 0xaf, sizeof(read_overlapped_)); WSACloseEvent(write_overlapped_.hEvent); memset(&write_overlapped_, 0xaf, sizeof(write_overlapped_)); } void UDPSocketWin::Core::WatchForRead() { // We grab an extra reference because there is an IO operation in progress. // Balanced in ReadDelegate::OnObjectSignaled(). AddRef(); read_watcher_.StartWatching(read_overlapped_.hEvent, &reader_); } void UDPSocketWin::Core::WatchForWrite() { // We grab an extra reference because there is an IO operation in progress. // Balanced in WriteDelegate::OnObjectSignaled(). AddRef(); write_watcher_.StartWatching(write_overlapped_.hEvent, &writer_); } void UDPSocketWin::Core::ReadDelegate::OnObjectSignaled(HANDLE object) { DCHECK_EQ(object, core_->read_overlapped_.hEvent); if (core_->socket_) core_->socket_->DidCompleteRead(); core_->Release(); } void UDPSocketWin::Core::WriteDelegate::OnObjectSignaled(HANDLE object) { DCHECK_EQ(object, core_->write_overlapped_.hEvent); if (core_->socket_) core_->socket_->DidCompleteWrite(); core_->Release(); } //----------------------------------------------------------------------------- UDPSocketWin::UDPSocketWin(DatagramSocket::BindType bind_type, const RandIntCallback& rand_int_cb, net::NetLog* net_log, const net::NetLog::Source& source) : socket_(INVALID_SOCKET), addr_family_(0), socket_options_(SOCKET_OPTION_MULTICAST_LOOP), multicast_interface_(0), multicast_time_to_live_(1), bind_type_(bind_type), rand_int_cb_(rand_int_cb), recv_from_address_(NULL), net_log_(BoundNetLog::Make(net_log, NetLog::SOURCE_UDP_SOCKET)) { EnsureWinsockInit(); net_log_.BeginEvent(NetLog::TYPE_SOCKET_ALIVE, source.ToEventParametersCallback()); if (bind_type == DatagramSocket::RANDOM_BIND) DCHECK(!rand_int_cb.is_null()); } UDPSocketWin::~UDPSocketWin() { Close(); net_log_.EndEvent(NetLog::TYPE_SOCKET_ALIVE); } void UDPSocketWin::Close() { DCHECK(CalledOnValidThread()); if (!is_connected()) return; // Zero out any pending read/write callback state. read_callback_.Reset(); recv_from_address_ = NULL; write_callback_.Reset(); base::TimeTicks start_time = base::TimeTicks::Now(); closesocket(socket_); UMA_HISTOGRAM_TIMES("Net.UDPSocketWinClose", base::TimeTicks::Now() - start_time); socket_ = INVALID_SOCKET; addr_family_ = 0; core_->Detach(); core_ = NULL; } int UDPSocketWin::GetPeerAddress(IPEndPoint* address) const { DCHECK(CalledOnValidThread()); DCHECK(address); if (!is_connected()) return ERR_SOCKET_NOT_CONNECTED; // TODO(szym): Simplify. http://crbug.com/126152 if (!remote_address_.get()) { SockaddrStorage storage; if (getpeername(socket_, storage.addr, &storage.addr_len)) return MapSystemError(WSAGetLastError()); scoped_ptr<IPEndPoint> address(new IPEndPoint()); if (!address->FromSockAddr(storage.addr, storage.addr_len)) return ERR_ADDRESS_INVALID; remote_address_.reset(address.release()); } *address = *remote_address_; return OK; } int UDPSocketWin::GetLocalAddress(IPEndPoint* address) const { DCHECK(CalledOnValidThread()); DCHECK(address); if (!is_connected()) return ERR_SOCKET_NOT_CONNECTED; // TODO(szym): Simplify. http://crbug.com/126152 if (!local_address_.get()) { SockaddrStorage storage; if (getsockname(socket_, storage.addr, &storage.addr_len)) return MapSystemError(WSAGetLastError()); scoped_ptr<IPEndPoint> address(new IPEndPoint()); if (!address->FromSockAddr(storage.addr, storage.addr_len)) return ERR_ADDRESS_INVALID; local_address_.reset(address.release()); net_log_.AddEvent(NetLog::TYPE_UDP_LOCAL_ADDRESS, CreateNetLogUDPConnectCallback(local_address_.get())); } *address = *local_address_; return OK; } int UDPSocketWin::Read(IOBuffer* buf, int buf_len, const CompletionCallback& callback) { return RecvFrom(buf, buf_len, NULL, callback); } int UDPSocketWin::RecvFrom(IOBuffer* buf, int buf_len, IPEndPoint* address, const CompletionCallback& callback) { DCHECK(CalledOnValidThread()); DCHECK_NE(INVALID_SOCKET, socket_); DCHECK(read_callback_.is_null()); DCHECK(!recv_from_address_); DCHECK(!callback.is_null()); // Synchronous operation not supported. DCHECK_GT(buf_len, 0); int nread = InternalRecvFrom(buf, buf_len, address); if (nread != ERR_IO_PENDING) return nread; read_callback_ = callback; recv_from_address_ = address; return ERR_IO_PENDING; } int UDPSocketWin::Write(IOBuffer* buf, int buf_len, const CompletionCallback& callback) { return SendToOrWrite(buf, buf_len, NULL, callback); } int UDPSocketWin::SendTo(IOBuffer* buf, int buf_len, const IPEndPoint& address, const CompletionCallback& callback) { return SendToOrWrite(buf, buf_len, &address, callback); } int UDPSocketWin::SendToOrWrite(IOBuffer* buf, int buf_len, const IPEndPoint* address, const CompletionCallback& callback) { DCHECK(CalledOnValidThread()); DCHECK_NE(INVALID_SOCKET, socket_); DCHECK(write_callback_.is_null()); DCHECK(!callback.is_null()); // Synchronous operation not supported. DCHECK_GT(buf_len, 0); DCHECK(!send_to_address_.get()); int nwrite = InternalSendTo(buf, buf_len, address); if (nwrite != ERR_IO_PENDING) return nwrite; if (address) send_to_address_.reset(new IPEndPoint(*address)); write_callback_ = callback; return ERR_IO_PENDING; } int UDPSocketWin::Connect(const IPEndPoint& address) { net_log_.BeginEvent(NetLog::TYPE_UDP_CONNECT, CreateNetLogUDPConnectCallback(&address)); int rv = InternalConnect(address); if (rv != OK) Close(); net_log_.EndEventWithNetErrorCode(NetLog::TYPE_UDP_CONNECT, rv); return rv; } int UDPSocketWin::InternalConnect(const IPEndPoint& address) { DCHECK(!is_connected()); DCHECK(!remote_address_.get()); int addr_family = address.GetSockAddrFamily(); int rv = CreateSocket(addr_family); if (rv < 0) return rv; if (bind_type_ == DatagramSocket::RANDOM_BIND) { // Construct IPAddressNumber of appropriate size (IPv4 or IPv6) of 0s, // representing INADDR_ANY or in6addr_any. size_t addr_size = addr_family == AF_INET ? kIPv4AddressSize : kIPv6AddressSize; IPAddressNumber addr_any(addr_size); rv = RandomBind(addr_any); } // else connect() does the DatagramSocket::DEFAULT_BIND if (rv < 0) { UMA_HISTOGRAM_SPARSE_SLOWLY("Net.UdpSocketRandomBindErrorCode", -rv); Close(); return rv; } SockaddrStorage storage; if (!address.ToSockAddr(storage.addr, &storage.addr_len)) return ERR_ADDRESS_INVALID; rv = connect(socket_, storage.addr, storage.addr_len); if (rv < 0) { // Close() may change the last error. Map it beforehand. int result = MapSystemError(WSAGetLastError()); Close(); return result; } remote_address_.reset(new IPEndPoint(address)); return rv; } int UDPSocketWin::Bind(const IPEndPoint& address) { DCHECK(!is_connected()); int rv = CreateSocket(address.GetSockAddrFamily()); if (rv < 0) return rv; rv = SetSocketOptions(); if (rv < 0) { Close(); return rv; } rv = DoBind(address); if (rv < 0) { Close(); return rv; } local_address_.reset(); return rv; } int UDPSocketWin::CreateSocket(int addr_family) { addr_family_ = addr_family; socket_ = CreatePlatformSocket(addr_family_, SOCK_DGRAM, IPPROTO_UDP); if (socket_ == INVALID_SOCKET) return MapSystemError(WSAGetLastError()); core_ = new Core(this); return OK; } int UDPSocketWin::SetReceiveBufferSize(int32 size) { DCHECK(CalledOnValidThread()); int rv = setsockopt(socket_, SOL_SOCKET, SO_RCVBUF, reinterpret_cast<const char*>(&size), sizeof(size)); if (rv != 0) return MapSystemError(WSAGetLastError()); // According to documentation, setsockopt may succeed, but we need to check // the results via getsockopt to be sure it works on Windows. int32 actual_size = 0; int option_size = sizeof(actual_size); rv = getsockopt(socket_, SOL_SOCKET, SO_RCVBUF, reinterpret_cast<char*>(&actual_size), &option_size); if (rv != 0) return MapSystemError(WSAGetLastError()); if (actual_size >= size) return OK; UMA_HISTOGRAM_CUSTOM_COUNTS("Net.SocketUnchangeableReceiveBuffer", actual_size, 1000, 1000000, 50); return ERR_SOCKET_RECEIVE_BUFFER_SIZE_UNCHANGEABLE; } int UDPSocketWin::SetSendBufferSize(int32 size) { DCHECK(CalledOnValidThread()); int rv = setsockopt(socket_, SOL_SOCKET, SO_SNDBUF, reinterpret_cast<const char*>(&size), sizeof(size)); if (rv != 0) return MapSystemError(WSAGetLastError()); // According to documentation, setsockopt may succeed, but we need to check // the results via getsockopt to be sure it works on Windows. int32 actual_size = 0; int option_size = sizeof(actual_size); rv = getsockopt(socket_, SOL_SOCKET, SO_SNDBUF, reinterpret_cast<char*>(&actual_size), &option_size); if (rv != 0) return MapSystemError(WSAGetLastError()); if (actual_size >= size) return OK; UMA_HISTOGRAM_CUSTOM_COUNTS("Net.SocketUnchangeableSendBuffer", actual_size, 1000, 1000000, 50); return ERR_SOCKET_SEND_BUFFER_SIZE_UNCHANGEABLE; } void UDPSocketWin::AllowAddressReuse() { DCHECK(CalledOnValidThread()); DCHECK(!is_connected()); socket_options_ |= SOCKET_OPTION_REUSE_ADDRESS; } void UDPSocketWin::AllowBroadcast() { DCHECK(CalledOnValidThread()); DCHECK(!is_connected()); socket_options_ |= SOCKET_OPTION_BROADCAST; } void UDPSocketWin::DoReadCallback(int rv) { DCHECK_NE(rv, ERR_IO_PENDING); DCHECK(!read_callback_.is_null()); // since Run may result in Read being called, clear read_callback_ up front. CompletionCallback c = read_callback_; read_callback_.Reset(); c.Run(rv); } void UDPSocketWin::DoWriteCallback(int rv) { DCHECK_NE(rv, ERR_IO_PENDING); DCHECK(!write_callback_.is_null()); // since Run may result in Write being called, clear write_callback_ up front. CompletionCallback c = write_callback_; write_callback_.Reset(); c.Run(rv); } void UDPSocketWin::DidCompleteRead() { DWORD num_bytes, flags; BOOL ok = WSAGetOverlappedResult(socket_, &core_->read_overlapped_, &num_bytes, FALSE, &flags); WSAResetEvent(core_->read_overlapped_.hEvent); int result = ok ? num_bytes : MapSystemError(WSAGetLastError()); // Convert address. if (recv_from_address_ && result >= 0) { if (!ReceiveAddressToIPEndpoint(recv_from_address_)) result = ERR_ADDRESS_INVALID; } LogRead(result, core_->read_iobuffer_->data()); core_->read_iobuffer_ = NULL; recv_from_address_ = NULL; DoReadCallback(result); } void UDPSocketWin::LogRead(int result, const char* bytes) const { if (result < 0) { net_log_.AddEventWithNetErrorCode(NetLog::TYPE_UDP_RECEIVE_ERROR, result); return; } if (net_log_.IsLogging()) { // Get address for logging, if |address| is NULL. IPEndPoint address; bool is_address_valid = ReceiveAddressToIPEndpoint(&address); net_log_.AddEvent( NetLog::TYPE_UDP_BYTES_RECEIVED, CreateNetLogUDPDataTranferCallback( result, bytes, is_address_valid ? &address : NULL)); } base::StatsCounter read_bytes("udp.read_bytes"); read_bytes.Add(result); } void UDPSocketWin::DidCompleteWrite() { DWORD num_bytes, flags; BOOL ok = WSAGetOverlappedResult(socket_, &core_->write_overlapped_, &num_bytes, FALSE, &flags); WSAResetEvent(core_->write_overlapped_.hEvent); int result = ok ? num_bytes : MapSystemError(WSAGetLastError()); LogWrite(result, core_->write_iobuffer_->data(), send_to_address_.get()); send_to_address_.reset(); core_->write_iobuffer_ = NULL; DoWriteCallback(result); } void UDPSocketWin::LogWrite(int result, const char* bytes, const IPEndPoint* address) const { if (result < 0) { net_log_.AddEventWithNetErrorCode(NetLog::TYPE_UDP_SEND_ERROR, result); return; } if (net_log_.IsLogging()) { net_log_.AddEvent( NetLog::TYPE_UDP_BYTES_SENT, CreateNetLogUDPDataTranferCallback(result, bytes, address)); } base::StatsCounter write_bytes("udp.write_bytes"); write_bytes.Add(result); } int UDPSocketWin::InternalRecvFrom(IOBuffer* buf, int buf_len, IPEndPoint* address) { DCHECK(!core_->read_iobuffer_); SockaddrStorage& storage = core_->recv_addr_storage_; storage.addr_len = sizeof(storage.addr_storage); WSABUF read_buffer; read_buffer.buf = buf->data(); read_buffer.len = buf_len; DWORD flags = 0; DWORD num; CHECK_NE(INVALID_SOCKET, socket_); AssertEventNotSignaled(core_->read_overlapped_.hEvent); int rv = WSARecvFrom(socket_, &read_buffer, 1, &num, &flags, storage.addr, &storage.addr_len, &core_->read_overlapped_, NULL); if (rv == 0) { if (ResetEventIfSignaled(core_->read_overlapped_.hEvent)) { int result = num; // Convert address. if (address && result >= 0) { if (!ReceiveAddressToIPEndpoint(address)) result = ERR_ADDRESS_INVALID; } LogRead(result, buf->data()); return result; } } else { int os_error = WSAGetLastError(); if (os_error != WSA_IO_PENDING) { int result = MapSystemError(os_error); LogRead(result, NULL); return result; } } core_->WatchForRead(); core_->read_iobuffer_ = buf; return ERR_IO_PENDING; } int UDPSocketWin::InternalSendTo(IOBuffer* buf, int buf_len, const IPEndPoint* address) { DCHECK(!core_->write_iobuffer_); SockaddrStorage storage; struct sockaddr* addr = storage.addr; // Convert address. if (!address) { addr = NULL; storage.addr_len = 0; } else { if (!address->ToSockAddr(addr, &storage.addr_len)) { int result = ERR_ADDRESS_INVALID; LogWrite(result, NULL, NULL); return result; } } WSABUF write_buffer; write_buffer.buf = buf->data(); write_buffer.len = buf_len; DWORD flags = 0; DWORD num; AssertEventNotSignaled(core_->write_overlapped_.hEvent); int rv = WSASendTo(socket_, &write_buffer, 1, &num, flags, addr, storage.addr_len, &core_->write_overlapped_, NULL); if (rv == 0) { if (ResetEventIfSignaled(core_->write_overlapped_.hEvent)) { int result = num; LogWrite(result, buf->data(), address); return result; } } else { int os_error = WSAGetLastError(); if (os_error != WSA_IO_PENDING) { int result = MapSystemError(os_error); LogWrite(result, NULL, NULL); return result; } } core_->WatchForWrite(); core_->write_iobuffer_ = buf; return ERR_IO_PENDING; } int UDPSocketWin::SetSocketOptions() { BOOL true_value = 1; if (socket_options_ & SOCKET_OPTION_REUSE_ADDRESS) { int rv = setsockopt(socket_, SOL_SOCKET, SO_REUSEADDR, reinterpret_cast<const char*>(&true_value), sizeof(true_value)); if (rv < 0) return MapSystemError(WSAGetLastError()); } if (socket_options_ & SOCKET_OPTION_BROADCAST) { int rv = setsockopt(socket_, SOL_SOCKET, SO_BROADCAST, reinterpret_cast<const char*>(&true_value), sizeof(true_value)); if (rv < 0) return MapSystemError(WSAGetLastError()); } if (!(socket_options_ & SOCKET_OPTION_MULTICAST_LOOP)) { DWORD loop = 0; int protocol_level = addr_family_ == AF_INET ? IPPROTO_IP : IPPROTO_IPV6; int option = addr_family_ == AF_INET ? IP_MULTICAST_LOOP: IPV6_MULTICAST_LOOP; int rv = setsockopt(socket_, protocol_level, option, reinterpret_cast<const char*>(&loop), sizeof(loop)); if (rv < 0) return MapSystemError(WSAGetLastError()); } if (multicast_time_to_live_ != 1) { DWORD hops = multicast_time_to_live_; int protocol_level = addr_family_ == AF_INET ? IPPROTO_IP : IPPROTO_IPV6; int option = addr_family_ == AF_INET ? IP_MULTICAST_TTL: IPV6_MULTICAST_HOPS; int rv = setsockopt(socket_, protocol_level, option, reinterpret_cast<const char*>(&hops), sizeof(hops)); if (rv < 0) return MapSystemError(WSAGetLastError()); } if (multicast_interface_ != 0) { switch (addr_family_) { case AF_INET: { in_addr address; address.s_addr = htonl(multicast_interface_); int rv = setsockopt(socket_, IPPROTO_IP, IP_MULTICAST_IF, reinterpret_cast<const char*>(&address), sizeof(address)); if (rv) return MapSystemError(WSAGetLastError()); break; } case AF_INET6: { uint32 interface_index = multicast_interface_; int rv = setsockopt(socket_, IPPROTO_IPV6, IPV6_MULTICAST_IF, reinterpret_cast<const char*>(&interface_index), sizeof(interface_index)); if (rv) return MapSystemError(WSAGetLastError()); break; } default: NOTREACHED() << "Invalid address family"; return ERR_ADDRESS_INVALID; } } return OK; } int UDPSocketWin::DoBind(const IPEndPoint& address) { SockaddrStorage storage; if (!address.ToSockAddr(storage.addr, &storage.addr_len)) return ERR_ADDRESS_INVALID; int rv = bind(socket_, storage.addr, storage.addr_len); if (rv == 0) return OK; int last_error = WSAGetLastError(); UMA_HISTOGRAM_SPARSE_SLOWLY("Net.UdpSocketBindErrorFromWinOS", last_error); // Map some codes that are special to bind() separately. // * WSAEACCES: If a port is already bound to a socket, WSAEACCES may be // returned instead of WSAEADDRINUSE, depending on whether the socket // option SO_REUSEADDR or SO_EXCLUSIVEADDRUSE is set and whether the // conflicting socket is owned by a different user account. See the MSDN // page "Using SO_REUSEADDR and SO_EXCLUSIVEADDRUSE" for the gory details. if (last_error == WSAEACCES || last_error == WSAEADDRNOTAVAIL) return ERR_ADDRESS_IN_USE; return MapSystemError(last_error); } int UDPSocketWin::RandomBind(const IPAddressNumber& address) { DCHECK(bind_type_ == DatagramSocket::RANDOM_BIND && !rand_int_cb_.is_null()); for (int i = 0; i < kBindRetries; ++i) { int rv = DoBind(IPEndPoint(address, rand_int_cb_.Run(kPortStart, kPortEnd))); if (rv == OK || rv != ERR_ADDRESS_IN_USE) return rv; } return DoBind(IPEndPoint(address, 0)); } bool UDPSocketWin::ReceiveAddressToIPEndpoint(IPEndPoint* address) const { SockaddrStorage& storage = core_->recv_addr_storage_; return address->FromSockAddr(storage.addr, storage.addr_len); } int UDPSocketWin::JoinGroup( const IPAddressNumber& group_address) const { DCHECK(CalledOnValidThread()); if (!is_connected()) return ERR_SOCKET_NOT_CONNECTED; switch (group_address.size()) { case kIPv4AddressSize: { if (addr_family_ != AF_INET) return ERR_ADDRESS_INVALID; ip_mreq mreq; mreq.imr_interface.s_addr = htonl(multicast_interface_); memcpy(&mreq.imr_multiaddr, &group_address[0], kIPv4AddressSize); int rv = setsockopt(socket_, IPPROTO_IP, IP_ADD_MEMBERSHIP, reinterpret_cast<const char*>(&mreq), sizeof(mreq)); if (rv) return MapSystemError(WSAGetLastError()); return OK; } case kIPv6AddressSize: { if (addr_family_ != AF_INET6) return ERR_ADDRESS_INVALID; ipv6_mreq mreq; mreq.ipv6mr_interface = multicast_interface_; memcpy(&mreq.ipv6mr_multiaddr, &group_address[0], kIPv6AddressSize); int rv = setsockopt(socket_, IPPROTO_IPV6, IPV6_ADD_MEMBERSHIP, reinterpret_cast<const char*>(&mreq), sizeof(mreq)); if (rv) return MapSystemError(WSAGetLastError()); return OK; } default: NOTREACHED() << "Invalid address family"; return ERR_ADDRESS_INVALID; } } int UDPSocketWin::LeaveGroup( const IPAddressNumber& group_address) const { DCHECK(CalledOnValidThread()); if (!is_connected()) return ERR_SOCKET_NOT_CONNECTED; switch (group_address.size()) { case kIPv4AddressSize: { if (addr_family_ != AF_INET) return ERR_ADDRESS_INVALID; ip_mreq mreq; mreq.imr_interface.s_addr = htonl(multicast_interface_); memcpy(&mreq.imr_multiaddr, &group_address[0], kIPv4AddressSize); int rv = setsockopt(socket_, IPPROTO_IP, IP_DROP_MEMBERSHIP, reinterpret_cast<const char*>(&mreq), sizeof(mreq)); if (rv) return MapSystemError(WSAGetLastError()); return OK; } case kIPv6AddressSize: { if (addr_family_ != AF_INET6) return ERR_ADDRESS_INVALID; ipv6_mreq mreq; mreq.ipv6mr_interface = multicast_interface_; memcpy(&mreq.ipv6mr_multiaddr, &group_address[0], kIPv6AddressSize); int rv = setsockopt(socket_, IPPROTO_IPV6, IP_DROP_MEMBERSHIP, reinterpret_cast<const char*>(&mreq), sizeof(mreq)); if (rv) return MapSystemError(WSAGetLastError()); return OK; } default: NOTREACHED() << "Invalid address family"; return ERR_ADDRESS_INVALID; } } int UDPSocketWin::SetMulticastInterface(uint32 interface_index) { DCHECK(CalledOnValidThread()); if (is_connected()) return ERR_SOCKET_IS_CONNECTED; multicast_interface_ = interface_index; return OK; } int UDPSocketWin::SetMulticastTimeToLive(int time_to_live) { DCHECK(CalledOnValidThread()); if (is_connected()) return ERR_SOCKET_IS_CONNECTED; if (time_to_live < 0 || time_to_live > 255) return ERR_INVALID_ARGUMENT; multicast_time_to_live_ = time_to_live; return OK; } int UDPSocketWin::SetMulticastLoopbackMode(bool loopback) { DCHECK(CalledOnValidThread()); if (is_connected()) return ERR_SOCKET_IS_CONNECTED; if (loopback) socket_options_ |= SOCKET_OPTION_MULTICAST_LOOP; else socket_options_ &= ~SOCKET_OPTION_MULTICAST_LOOP; return OK; } // TODO(hubbe): Implement differentiated services for windows. // Note: setsockopt(IP_TOS) does not work on windows XP and later. int UDPSocketWin::SetDiffServCodePoint(DiffServCodePoint dscp) { return ERR_NOT_IMPLEMENTED; } void UDPSocketWin::DetachFromThread() { base::NonThreadSafe::DetachFromThread(); } } // namespace net
31.784615
80
0.681473
[ "object" ]
4f770e326244e5fa5b7c8c1c2dbede2e1e31e2f6
4,915
hh
C++
src/include/macho.hh
lethalbit/Slice-N-Splice
5e3f7917756e087c8732360d7344268c4fa266a6
[ "BSD-3-Clause" ]
5
2019-01-16T15:51:38.000Z
2021-03-06T16:11:14.000Z
src/include/macho.hh
lethalbit/Slice-N-Splice
5e3f7917756e087c8732360d7344268c4fa266a6
[ "BSD-3-Clause" ]
7
2019-02-07T07:47:31.000Z
2020-05-29T13:34:14.000Z
src/include/macho.hh
lethalbit/Slice-N-Splice
5e3f7917756e087c8732360d7344268c4fa266a6
[ "BSD-3-Clause" ]
1
2020-05-29T12:08:16.000Z
2020-05-29T12:08:16.000Z
/* macho.hh - Mach-O structures and utilities */ #pragma once #if !defined(__SNS_MACHO_HH__) #define __SNS_MACHO_HH__ #include <cstdint> #include <cstring> #include <memory> #include <vector> #include <iostream> #include <mmap_t.hh> #include <fd_t.hh> #include <utility.hh> #if defined(CXXFS_EXP) #include <experimental/filesystem> namespace fs = std::experimental::filesystem; #else #include <filesystem> namespace fs = std::filesystem; #endif /* Basic types used to composite the larger types */ /* Mach-O CPU Type */ enum class mach_cpu_t : uint32_t { Any = 0xFFFFFFFFU, None = 0x00000000U, Vax = 0x00000001U, MC680X0 = 0x00000006U, x86 = 0x00000007U, x86_64 = (mach_cpu_t::x86 | 0x01000000U), MIPS = 0x00000008U, MC98000 = 0x0000000AU, HPPA = 0x0000000BU, ARM = 0x0000000CU, ARM64 = (mach_cpu_t::ARM | 0x01000000U), MC88000 = 0x0000000DU, SPARC = 0x0000000EU, I860 = 0x0000000FU, ALPHA = 0x00000010U, PowerPC = 0x00000012U, PowerPC64 = (mach_cpu_t::PowerPC | 0x01000000U) }; extern const std::array<const enum_pair_t<mach_cpu_t>, 17> mach_cpu_s; extern std::ostream& operator<<(std::ostream& out, const mach_cpu_t& mcpu); /* Mach-O CPU Sub-type */ enum class mach_cpu_sub_t : uint32_t { Multiple = 0xFFFFFFFFU, LSB = 0x00000000U, MSB = 0x00000001U, }; extern const std::array<const enum_pair_t<mach_cpu_sub_t>, 3> mach_cpu_sub_s; extern std::ostream& operator<<(std::ostream& out, const mach_cpu_sub_t& mcpusub); /* Mach-O CPU Sub-type */ enum class mach_filetype_t : uint32_t { None = 0x00000000U, Object = 0x00000001U, Execute = 0x00000002U, FVMLib = 0x00000003U, Core = 0x00000004U, Preload = 0x00000005U, Dylib = 0x00000006U, Dylinker = 0x00000007U, Bundle = 0x00000008U, DylibStub = 0x00000009U, DSym = 0x0000000AU, KEXTBundle = 0x0000000BU, }; extern const std::array<const enum_pair_t<mach_filetype_t>, 17> mach_filetype_s; extern std::ostream& operator<<(std::ostream& out, const mach_filetype_t& mftype); enum class mach_flags_t : uint32_t { None = 0x00000000U, NoUndefs = 0x00000001U, IncrLink = 0x00000002U, DyndLink = 0x00000004U, BinDataLoad = 0x00000008U, PreBound = 0x00000010U, SplitSegs = 0x00000020U, LazyInit = 0x00000040U, TwoLevel = 0x00000080U, ForceFlat = 0x00000100U, NoMultiDefs = 0x00000200U, NoFixePreBinding = 0x00000400U, Prebindable = 0x00000800U, AllModsBound = 0x00001000U, SubsectionsViaSyms = 0x00002000U, Canonical = 0x00004000U, WeakDefines = 0x00008000U, BindsToWeak = 0x00010000U, AllowStackExecution = 0x00020000U, RootSafe = 0x00040000U, SetUIDSafe = 0x00080000U, NoReexportedDylibs = 0x00100000U, PIE = 0x00200000U, DeadStrippableDylib = 0x00400000U, HasTLVDescriptions = 0x00800000U, NoHeapExecution = 0x01000000U, AppExtensionSafe = 0x02000000U, }; template<> struct EnableBitmask<mach_flags_t>{ static constexpr bool enabled = true; }; extern const std::array<const enum_pair_t<mach_flags_t>, 27> mach_flags_s; extern std::ostream& operator<<(std::ostream& out, const mach_flags_t& mflag); /* Mach-O Structure definitions */ /* Mach-O Magic */ struct mach_magic_t final { private: uint8_t _magic1; uint8_t _magic2; uint8_t _magic3; uint8_t _magic4; public: constexpr mach_magic_t() noexcept : _magic1{}, _magic2{}, _magic3{}, _magic4{} { /* NOP */ } [[nodiscard]] bool is_valid() const noexcept { return (_magic1 == 0xFEU && _magic2 == 0xEDU && _magic3 == 0xFAU && _magic4 == 0xCEU); } void set() noexcept { _magic1 = 0xFEU; _magic2 = 0xEDU; _magic3 = 0xFAU; _magic4 = 0xCEU; } [[nodiscard]] std::array<uint8_t, 4> get() const noexcept { return { _magic1, _magic2, _magic3, _magic4 }; } }; /* 32-Bit Mach-O header */ struct mach32_header_t final { private: mach_magic_t _magic; /* Should always be 0xFEEDFACE */ mach_cpu_t _cpu; /* CPU Type */ mach_cpu_sub_t _subcpu; /* Sub CPU Type */ uint32_t _filetype; /* Type of binary file this is */ uint32_t _ncmds; /* Number of load commands */ uint32_t _cmd_size; /* The size of each load command */ mach_flags_t _flags; /* Various flags */ public: constexpr mach32_header_t() noexcept : _magic{}, _cpu{}, _subcpu{}, _filetype{}, _ncmds{}, _cmd_size{}, _flags{} { /* NOP */ } constexpr mach32_header_t( mach_magic_t magic, mach_cpu_t cpu, mach_cpu_sub_t subcpu, uint32_t filetype, uint32_t ncmds, uint32_t cmd_size, mach_flags_t flags) noexcept : _magic{magic}, _cpu{cpu}, _subcpu{subcpu}, _filetype{filetype}, _ncmds{ncmds}, _cmd_size{cmd_size}, _flags{flags} { /* NOP */ } // void magic() }; #endif /* __SNS_MACHO_HH__ */
27.458101
82
0.67589
[ "object", "vector" ]
4f78017e30b4129073b270493592c34591996740
2,704
cpp
C++
src/mongo/db/pipeline/accumulator_avg.cpp
morsvolia/mongo
8cbe89efab77d70ac653d20b693cffe15a47acea
[ "Apache-2.0" ]
324
2015-01-01T14:56:10.000Z
2022-03-08T04:52:37.000Z
src/mongo/db/pipeline/accumulator_avg.cpp
morsvolia/mongo
8cbe89efab77d70ac653d20b693cffe15a47acea
[ "Apache-2.0" ]
38
2015-01-31T03:57:16.000Z
2019-04-21T03:30:53.000Z
src/mongo/db/pipeline/accumulator_avg.cpp
morsvolia/mongo
8cbe89efab77d70ac653d20b693cffe15a47acea
[ "Apache-2.0" ]
60
2015-01-14T14:19:41.000Z
2021-02-10T21:54:12.000Z
/** * Copyright (c) 2011 10gen Inc. * Copyright (C) 2013 Tokutek Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License, version 3, * as published by the Free Software Foundation. * * 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 Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "pch.h" #include "accumulator.h" #include "db/pipeline/document.h" #include "db/pipeline/expression_context.h" #include "db/pipeline/value.h" namespace mongo { const char AccumulatorAvg::subTotalName[] = "subTotal"; const char AccumulatorAvg::countName[] = "count"; Value AccumulatorAvg::evaluate(const Document& pDocument) const { if (!pCtx->getDoingMerge()) { Super::evaluate(pDocument); } else { /* If we're in the router, we expect an object that contains both a subtotal and a count. This is what getValue() produced below. */ Value shardOut = vpOperand[0]->evaluate(pDocument); verify(shardOut.getType() == Object); Value subTotal = shardOut[subTotalName]; verify(!subTotal.missing()); doubleTotal += subTotal.getDouble(); Value subCount = shardOut[countName]; verify(!subCount.missing()); count += subCount.getLong(); } return Value(); } intrusive_ptr<Accumulator> AccumulatorAvg::create( const intrusive_ptr<ExpressionContext> &pCtx) { intrusive_ptr<AccumulatorAvg> pA(new AccumulatorAvg(pCtx)); return pA; } Value AccumulatorAvg::getValue() const { if (!pCtx->getInShard()) { double avg = 0; if (count) avg = doubleTotal / static_cast<double>(count); return Value::createDouble(avg); } MutableDocument out; out.addField(subTotalName, Value::createDouble(doubleTotal)); out.addField(countName, Value::createLong(count)); return Value::createDocument(out.freeze()); } AccumulatorAvg::AccumulatorAvg( const intrusive_ptr<ExpressionContext> &pTheCtx): AccumulatorSum(), pCtx(pTheCtx) { } const char *AccumulatorAvg::getOpName() const { return "$avg"; } }
31.08046
76
0.62574
[ "object" ]
4f79507b0008e33837c369a09a808be2f98e60a7
1,729
cxx
C++
src/Cxx/GeometricObjects/Line.cxx
cvandijck/VTKExamples
b6bb89414522afc1467be8a1f0089a37d0c16883
[ "Apache-2.0" ]
309
2017-05-21T09:07:19.000Z
2022-03-15T09:18:55.000Z
src/Cxx/GeometricObjects/Line.cxx
yijianmingliu/VTKExamples
dc8aac47c4384f9a2de9facbdd1ab3249f62ec99
[ "Apache-2.0" ]
379
2017-05-21T09:06:43.000Z
2021-03-29T20:30:50.000Z
src/Cxx/GeometricObjects/Line.cxx
yijianmingliu/VTKExamples
dc8aac47c4384f9a2de9facbdd1ab3249f62ec99
[ "Apache-2.0" ]
170
2017-05-17T14:47:41.000Z
2022-03-31T13:16:26.000Z
#include <vtkActor.h> #include <vtkLineSource.h> #include <vtkNamedColors.h> #include <vtkPolyData.h> #include <vtkPolyDataMapper.h> #include <vtkProperty.h> #include <vtkRenderer.h> #include <vtkRenderWindow.h> #include <vtkRenderWindowInteractor.h> #include <vtkSmartPointer.h> int main(int, char *[]) { // Create two points, P0 and P1 double p0[3] = {1.0, 0.0, 0.0}; double p1[3] = {0.0, 1.0, 0.0}; vtkSmartPointer<vtkLineSource> lineSource = vtkSmartPointer<vtkLineSource>::New(); lineSource->SetPoint1(p0); lineSource->SetPoint2(p1); // Visualize vtkSmartPointer<vtkNamedColors> colors = vtkSmartPointer<vtkNamedColors>::New(); vtkSmartPointer<vtkPolyDataMapper> mapper = vtkSmartPointer<vtkPolyDataMapper>::New(); mapper->SetInputConnection(lineSource->GetOutputPort()); vtkSmartPointer<vtkActor> actor = vtkSmartPointer<vtkActor>::New(); actor->SetMapper(mapper); actor->GetProperty()->SetLineWidth(4); actor->GetProperty()->SetColor(colors->GetColor3d("Peacock").GetData()); vtkSmartPointer<vtkRenderer> renderer = vtkSmartPointer<vtkRenderer>::New(); vtkSmartPointer<vtkRenderWindow> renderWindow = vtkSmartPointer<vtkRenderWindow>::New(); renderWindow->AddRenderer(renderer); renderWindow->SetWindowName("Line"); vtkSmartPointer<vtkRenderWindowInteractor> renderWindowInteractor = vtkSmartPointer<vtkRenderWindowInteractor>::New(); renderWindowInteractor->SetRenderWindow(renderWindow); renderer->SetBackground(colors->GetColor3d("Silver").GetData()); renderer->AddActor(actor); renderWindow->Render(); renderWindowInteractor->Start(); return EXIT_SUCCESS; }
32.018519
99
0.714864
[ "render" ]
4f79ef02732e6245be694907075d8b6abca4b88c
3,833
cpp
C++
src/NGSIv2/NGSIv2Params.cpp
eProsima/FIROS2
b7ef9ed449a9f1179ebedf0e9bb2492740f9b1ed
[ "Apache-2.0" ]
7
2018-06-01T14:31:18.000Z
2021-05-09T16:31:58.000Z
src/DynNGSIv2/NGSIv2Params.cpp
eProsima/FIROS2
b7ef9ed449a9f1179ebedf0e9bb2492740f9b1ed
[ "Apache-2.0" ]
12
2018-06-01T01:35:13.000Z
2021-08-17T12:38:27.000Z
src/DynNGSIv2/NGSIv2Params.cpp
eProsima/FIROS2
b7ef9ed449a9f1179ebedf0e9bb2492740f9b1ed
[ "Apache-2.0" ]
4
2018-04-17T17:46:21.000Z
2020-03-25T03:43:31.000Z
#include "NGSIv2Params.h" static const std::string s_sHost("host"); static const std::string s_sPort("port"); static const std::string s_sId("id"); static const std::string s_sType("type"); static const std::string s_sAttrs("attrs"); static const std::string s_sExpression("expression"); static const std::string s_sNotifs("notifs"); static const std::string s_sListenerHost("listener_host"); static const std::string s_sListenerPort("listener_port"); static const std::string s_sListenerBufferSize("listener_buffer_size"); static const std::string s_sExpiration("expiration"); static const std::string s_sThrottling("throttling"); static const std::string s_sDescription("description"); static const std::string s_sRetries("http_retries"); static const std::string s_sRetryWait("retry_wait"); static const std::string s_sHttpTimeout("http_timeout"); NGSIv2Params::NGSIv2Params() : name("") , host("") , port(0) , retries(0) , retryWait_ms(1000) , httpTimeout(0) { } bool NGSIv2Params::LoadConfig(const std::vector<std::pair<std::string, std::string>> *config) { for (auto pair : *config) { try { if (pair.first.compare(s_sHost) == 0) { host = pair.second; } else if (pair.first.compare(s_sPort) == 0) { port = std::stoi(pair.second); } else if (pair.first.compare(s_sHttpTimeout) == 0) { httpTimeout = std::stoi(pair.second); } else if (pair.first.compare(s_sRetries) == 0) { retries = std::stoi(pair.second); } else if (pair.first.compare(s_sRetryWait) == 0) { retryWait_ms = std::stoi(pair.second); } } catch (...) { return false; } } return true; } NGSIv2SubscriptionParams::NGSIv2SubscriptionParams() : idPattern("") , type("") , attrs("") , expression("") , notif("") , expiration("") , throttling(0) , description("") , host("") , port(0) , buffer_size(0) { } bool NGSIv2SubscriptionParams::LoadConfig(const std::vector<std::pair<std::string, std::string>> *config) { for (auto pair : *config) { try { if (pair.first.compare(s_sId) == 0) { idPattern = pair.second; } else if (pair.first.compare(s_sType) == 0) { type = pair.second; } else if (pair.first.compare(s_sAttrs) == 0) { attrs = pair.second; } else if (pair.first.compare(s_sExpression) == 0) { expression = pair.second; } else if (pair.first.compare(s_sNotifs) == 0) { notif = pair.second; } else if (pair.first.compare(s_sListenerHost) == 0) { host = pair.second; } else if (pair.first.compare(s_sListenerPort) == 0) { port = std::stoi(pair.second); } else if (pair.first.compare(s_sExpiration) == 0) { expiration = pair.second; } else if (pair.first.compare(s_sThrottling) == 0) { throttling = std::stoi(pair.second); } else if (pair.first.compare(s_sDescription) == 0) { description = pair.second; } else if (pair.first.compare(s_sListenerBufferSize) == 0) { buffer_size = std::stoi(pair.second); } } catch (...) { return false; } } return true; }
27.378571
105
0.52048
[ "vector" ]
4f7c22ce839f5b4834915d61086d4479c6dc0e7c
26,368
cpp
C++
src/idaplugin/code_viewer.cpp
GregoryMorse/retdec-idaplugin
72d04ef2b4855cfa8861876985b5adb8d9a68521
[ "MIT" ]
null
null
null
src/idaplugin/code_viewer.cpp
GregoryMorse/retdec-idaplugin
72d04ef2b4855cfa8861876985b5adb8d9a68521
[ "MIT" ]
null
null
null
src/idaplugin/code_viewer.cpp
GregoryMorse/retdec-idaplugin
72d04ef2b4855cfa8861876985b5adb8d9a68521
[ "MIT" ]
null
null
null
/** * @file idaplugin/code_viewer.cpp * @brief Module contains classes/methods dealing with decompiled code * visualization. * @copyright (c) 2017 Avast Software, licensed under the MIT license */ #include <regex> #include "code_viewer.h" #include "config_generator.h" #include "idaplugin.h" namespace idaplugin { extern RdGlobalInfo decompInfo; ea_t globalAddress = 0; // //============================================================================== // /** * @brief Get tagged line on current position. * @param v Control. * @param mouse Current for mouse pointer? * @param[out] line Current line. * @param x This is horizontal position in line string *WITHOUT* tags. * @param y This is vertical position (line number) in viewer. * @param rx This is horizontal position in line string *WITH* tags. * @return False if OK, true otherwise. */ static bool get_current_line_with_tags( TWidget* v, bool mouse, std::string& line, int& x, int& y, unsigned& rx) { if (get_custom_viewer_place(v, mouse, &x, &y) == nullptr) { return true; } line = get_custom_viewer_curline(v, mouse); rx = x; for (unsigned i = 0; i <= rx && i<line.size(); ++i) { unsigned char c = line[i]; if (c == COLOR_ON || c == COLOR_OFF) { rx += 2; // {ON,OFF} + COLOR = 1 + 1 = 2 ++i; } if (c == COLOR_ESC || c == COLOR_INV) { rx += 1; } } return false; } /** * @brief Get line without tags on current position. * @param v Control. * @param mouse Current for mouse pointer? * @param[out] line Current line. * @param x This is horizontal position in line string *WITHOUT* tags. * @param y This is vertical position (line number) in viewer. * @return False if OK, true otherwise. */ bool get_current_line_without_tags( TWidget* v, bool mouse, std::string &line, int& x, int& y) { unsigned rx_unused; if (get_current_line_with_tags(v, mouse, line, x, y, rx_unused)) { return true; } qstring buf; tag_remove(&buf, line.c_str()); if (x >= static_cast<int>(buf.length())) { return true; } line = buf.c_str(); return false; } /** * @brief Get current word * @param v Control * @param mouse bool mouse (current for mouse pointer?) * @param[out] word result * @param[out] color resulted word color * @return False if OK, true otherwise. */ static bool get_current_word( TWidget* v, bool mouse, std::string& word, int& color) { // Use SDK function to get highlighted ID. // qstring buf; if (!get_highlight(&buf, v, nullptr)) { return true; } int x, y; unsigned rx; std::string taggedLine; if (get_current_line_with_tags(v, mouse, taggedLine, x, y, rx)) { return true; } int prevColor = -1; int nextColor = -1; auto onColor = taggedLine.find_last_of(COLOR_ON, rx); if (onColor != std::string::npos && onColor > 0 && taggedLine[onColor-1] == COLOR_ON) { prevColor = taggedLine[onColor]; } else if (onColor != std::string::npos && (onColor+1) < taggedLine.length()) { prevColor = taggedLine[onColor+1]; } auto offColor = taggedLine.find_first_of(COLOR_OFF, rx); if (offColor != std::string::npos && (offColor+1) < taggedLine.length()) { nextColor = taggedLine[offColor+1]; } if (prevColor == -1 || prevColor != nextColor) { return false; } word = buf.c_str(); color = nextColor; return false; } bool isWordGlobal(const std::string& word, int color) { return color == COLOR_DEFAULT && decompInfo.configDB.globals.getObjectByNameOrRealName(word) != nullptr; } const retdec::config::Object* getWordGlobal(const std::string& word, int color) { return !word.empty() && color == COLOR_DEFAULT ? decompInfo.configDB.globals.getObjectByNameOrRealName(word) : nullptr; } bool isWordFunction(const std::string& word, int color) { return color == COLOR_DEFAULT && decompInfo.configDB.functions.hasFunction(word); } bool isWordIdentifier(const std::string& word, int color) { return color == COLOR_DREF; } const retdec::config::Function* getWordFunction( const std::string& word, int color) { return !word.empty() && color == COLOR_DEFAULT ? decompInfo.configDB.functions.getFunctionByName(word) : nullptr; } func_t* getIdaFunction(const std::string& word, int color) { if (word.empty()) { return nullptr; } if (!isWordFunction(word, color)) { return nullptr; } auto* cfgFnc = decompInfo.configDB.functions.getFunctionByName(word); if (cfgFnc == nullptr) { return nullptr; } return get_func(cfgFnc->getStart()); } bool isCurrentFunction(func_t* fnc) { return decompInfo.navigationActual != decompInfo.navigationList.end() && fnc == *decompInfo.navigationActual; } func_t* getCurrentFunction() { return decompInfo.navigationActual != decompInfo.navigationList.end() ? *decompInfo.navigationActual : nullptr; } bool isWordCurrentParameter(const std::string& word, int color) { if (!isWordIdentifier(word, color)) { return false; } auto* idaCurrentFnc = getCurrentFunction(); if (idaCurrentFnc == nullptr) { return false; } qstring name; get_func_name(&name, idaCurrentFnc->start_ea); auto* ccFnc = decompInfo.configDB.functions.getFunctionByName(name.c_str()); if (ccFnc == nullptr) { return false; } for (auto& p : ccFnc->parameters) { auto realName = p.getRealName(); if ((!realName.empty() && realName == word) || p.getName() == word) { return true; } } return false; } // //============================================================================== // /** * Decompile or just show function. * @param cv Current custom control. * @param calledFnc Called function name. * @param force If function to decompile/show is the same as current function, * decompile/show it again only if this is set to @c true. * @param forceDec Force new decompilation. */ void decompileFunction( TWidget* cv, const std::string& calledFnc, bool force = false, bool forceDec = false) { auto* globVar = decompInfo.configDB.globals.getObjectByNameOrRealName( calledFnc); if (globVar && globVar->getStorage().isMemory()) { INFO_MSG("Global variable -> jump to ASM.\n"); jumpto( globVar->getStorage().getAddress() ); return; } auto* cfgFnc = decompInfo.configDB.functions.getFunctionByName(calledFnc); if (!cfgFnc) { INFO_MSG("Unknown function to decompile \"" << calledFnc << "\" -> do nothing.\n"); return; } if (cfgFnc->isUserDefined()) { for (unsigned i = 0; i < get_func_qty(); ++i) { func_t *fnc = getn_func(i); if (fnc->start_ea != cfgFnc->getStart()) { continue; } if (!force && isCurrentFunction(fnc)) { INFO_MSG("The current function is not decompiled/shown again.\n"); return; } // Decompile found function. // runSelectiveDecompilation(fnc, forceDec); return; } } // Such function exists in config file, but not in IDA functions. // This is import/export or something similar -> jump to IDA disasm view. // INFO_MSG("Not a user-defined function -> jump to ASM.\n"); jumpto( cfgFnc->getStart() ); } // //============================================================================== // bool idaapi moveToPrevious() { DBG_MSG("\t ESC : ["); for (auto& fnc : decompInfo.navigationList) { DBG_MSG(" " << std::hex << fnc->start_ea); } DBG_MSG(" ] (# " << std::dec << decompInfo.navigationList.size() << ") : from " << std::hex << (*decompInfo.navigationActual)->start_ea << " => BACK\n"); if (decompInfo.navigationList.size() <= 1) { return false; } if (decompInfo.navigationActual != decompInfo.navigationList.begin()) { decompInfo.navigationActual--; DBG_MSG("\t\t=> " << std::hex << (*decompInfo.navigationActual)->start_ea << "\n"); auto fit = decompInfo.fnc2code.find(*decompInfo.navigationActual); if (fit == decompInfo.fnc2code.end()) { return false; } decompInfo.decompiledFunction = fit->first; qthread_create(showDecompiledCode, static_cast<void*>(&decompInfo)); } else { DBG_MSG("\t\t=> FIRST : cannot move to the previous\n"); } return false; } struct move_backward_ah_t : public action_handler_t { static const char* actionName; static const char* actionLabel; static const char* actionHotkey; virtual int idaapi activate(action_activation_ctx_t*) { moveToPrevious(); return false; } virtual action_state_t idaapi update(action_update_ctx_t*) { return AST_ENABLE_ALWAYS; } }; const char* move_backward_ah_t::actionName = "retdec:ActionMoveBackward"; const char* move_backward_ah_t::actionLabel = "Move backward"; const char* move_backward_ah_t::actionHotkey = "ESC"; static move_backward_ah_t move_backward_ah; static const action_desc_t move_backward_ah_desc = ACTION_DESC_LITERAL( move_backward_ah_t::actionName, move_backward_ah_t::actionLabel, &move_backward_ah, nullptr, move_backward_ah_t::actionHotkey, -1); // //============================================================================== // bool idaapi moveToNext() { DBG_MSG("\t CTRL + F : ["); for (auto& fnc : decompInfo.navigationList) { DBG_MSG(" " << std::hex << fnc->start_ea); } DBG_MSG(" ] (#" << std::dec << decompInfo.navigationList.size() << ") : from " << std::hex << (*decompInfo.navigationActual)->start_ea << " => FORWARD\n"); if (decompInfo.navigationList.size() <= 1) { return false; } auto last = decompInfo.navigationList.end(); last--; if (decompInfo.navigationActual != last) { decompInfo.navigationActual++; DBG_MSG("\t\t=> " << std::hex << (*decompInfo.navigationActual)->start_ea << "\n"); auto fit = decompInfo.fnc2code.find(*decompInfo.navigationActual); if (fit != decompInfo.fnc2code.end()) { decompInfo.decompiledFunction = fit->first; qthread_create(showDecompiledCode, static_cast<void*>(&decompInfo)); return false; } } else { DBG_MSG("\t\t=> LAST : cannot move to the next\n"); } return false; } struct move_forward_ah_t : public action_handler_t { static const char* actionName; static const char* actionLabel; static const char* actionHotkey; virtual int idaapi activate(action_activation_ctx_t*) { moveToNext(); return false; } virtual action_state_t idaapi update(action_update_ctx_t*) { return AST_ENABLE_ALWAYS; } }; const char* move_forward_ah_t::actionName = "retdec:ActionMoveForward"; const char* move_forward_ah_t::actionLabel = "Move forward"; const char* move_forward_ah_t::actionHotkey = "Ctrl+F"; static move_forward_ah_t move_forward_ah; static const action_desc_t move_forward_ah_desc = ACTION_DESC_LITERAL( move_forward_ah_t::actionName, move_forward_ah_t::actionLabel, &move_forward_ah, nullptr, move_forward_ah_t::actionHotkey, -1); // //============================================================================== // bool idaapi insertCurrentFunctionComment() { auto* fnc = getCurrentFunction(); if (fnc == nullptr) { return false; } qstring qCmt; get_func_cmt(&qCmt, fnc, false); qstring buff; if (ask_text( &buff, MAXSTR, qCmt.c_str(), "Please enter function comment (max %d characters)", MAXSTR)) { set_func_cmt(fnc, buff.c_str(), false); decompInfo.decompiledFunction = fnc; qthread_create(showDecompiledCode, static_cast<void*>(&decompInfo)); } return false; } struct change_fnc_comment_ah_t : public action_handler_t { static const char* actionName; static const char* actionLabel; static const char* actionHotkey; virtual int idaapi activate(action_activation_ctx_t*) { insertCurrentFunctionComment(); return false; } virtual action_state_t idaapi update(action_update_ctx_t*) { return AST_ENABLE_ALWAYS; } }; const char* change_fnc_comment_ah_t::actionName = "retdec:ActionChangeFncComment"; const char* change_fnc_comment_ah_t::actionLabel = "Edit func comment"; const char* change_fnc_comment_ah_t::actionHotkey = ";"; static change_fnc_comment_ah_t change_fnc_comment_ah; static const action_desc_t change_fnc_comment_ah_desc = ACTION_DESC_LITERAL( change_fnc_comment_ah_t::actionName, change_fnc_comment_ah_t::actionLabel, &change_fnc_comment_ah, nullptr, change_fnc_comment_ah_t::actionHotkey, -1); // //============================================================================== // bool idaapi changeFunctionGlobalName(TWidget* cv) { std::string word; int color = -1; if (get_current_word(cv, false, word, color)) { return false; } std::string askString; ea_t address; const retdec::config::Function* fnc = nullptr; const retdec::config::Object* gv = nullptr; if ((fnc = getWordFunction(word, color))) { askString = "Please enter function name"; address = fnc->getStart(); } else if ((gv = getWordGlobal(word, color))) { askString = "Please enter global variable name"; address = gv->getStorage().getAddress(); } else { return false; } qstring qNewName = word.c_str(); if (!ask_str(&qNewName, HIST_IDENT, "%s", askString.c_str()) || qNewName.empty()) { return false; } std::string newName = qNewName.c_str(); if (newName == word) { return false; } auto fit = decompInfo.fnc2code.find(*decompInfo.navigationActual); if (fit == decompInfo.fnc2code.end()) { return false; } std::regex e(std::string(SCOLOR_ON) + "." + newName + SCOLOR_OFF + "."); if (decompInfo.configDB.globals.getObjectByNameOrRealName(newName) != nullptr || decompInfo.configDB.functions.hasFunction(newName) || std::regex_search(fit->second.code, e)) { WARNING_GUI("Name \"" << newName << "\" is not unique\n"); return false; } if (set_name(address, newName.c_str()) == false) { return false; } std::string oldName = std::string(SCOLOR_ON) + SCOLOR_DEFAULT + word + SCOLOR_OFF + SCOLOR_DEFAULT; std::string replace = std::string(SCOLOR_ON) + SCOLOR_DEFAULT + newName + SCOLOR_OFF + SCOLOR_DEFAULT; for (auto& fncItem : decompInfo.fnc2code) { auto& code = fncItem.second.code; std::string::size_type n = 0; while (( n = code.find(oldName, n)) != std::string::npos) { code.replace(n, oldName.size(), replace); n += replace.size(); } } // TODO: just setting a new name to function/global would be faster. // ConfigGenerator jg(decompInfo); decompInfo.dbFile = jg.generate(); decompInfo.decompiledFunction = fit->first; qthread_create(showDecompiledCode, static_cast<void*>(&decompInfo)); return false; } struct change_fnc_global_name_ah_t : public action_handler_t { TWidget* view = nullptr; static const char* actionName; static const char* actionLabel; static const char* actionHotkey; virtual int idaapi activate(action_activation_ctx_t*) { changeFunctionGlobalName(view); return false; } virtual action_state_t idaapi update(action_update_ctx_t*) { return AST_ENABLE_ALWAYS; } void setView(TWidget* v) { view = v; } }; const char* change_fnc_global_name_ah_t::actionName = "retdec:ActionChangeFncGlobName"; const char* change_fnc_global_name_ah_t::actionLabel = "Rename"; const char* change_fnc_global_name_ah_t::actionHotkey = "N"; static change_fnc_global_name_ah_t change_fnc_global_name_ah; static const action_desc_t change_fnc_global_name_ah_desc = ACTION_DESC_LITERAL( change_fnc_global_name_ah_t::actionName, change_fnc_global_name_ah_t::actionLabel, &change_fnc_global_name_ah, nullptr, change_fnc_global_name_ah_t::actionHotkey, -1); // //============================================================================== // bool idaapi openXrefsWindow(func_t* fnc) { open_xrefs_window(fnc->start_ea); return false; } struct open_xrefs_ah_t : public action_handler_t { func_t* fnc = nullptr; static const char* actionName; static const char* actionLabel; static const char* actionHotkey; virtual int idaapi activate(action_activation_ctx_t*) { openXrefsWindow(fnc); return false; } virtual action_state_t idaapi update(action_update_ctx_t*) { return AST_ENABLE_ALWAYS; } void setFunction(func_t* f) { fnc = f; } }; const char* open_xrefs_ah_t::actionName = "retdec:ActionOpenXrefs"; const char* open_xrefs_ah_t::actionLabel = "Open xrefs window"; const char* open_xrefs_ah_t::actionHotkey = "X"; static open_xrefs_ah_t open_xrefs_ah; static const action_desc_t open_xrefs_ah_desc = ACTION_DESC_LITERAL( open_xrefs_ah_t::actionName, open_xrefs_ah_t::actionLabel, &open_xrefs_ah, nullptr, open_xrefs_ah_t::actionHotkey, -1); // //============================================================================== // bool idaapi openCallsWindow(func_t* fnc) { open_calls_window(fnc->start_ea); return false; } struct open_calls_ah_t : public action_handler_t { func_t* fnc = nullptr; static const char* actionName; static const char* actionLabel; static const char* actionHotkey; virtual int idaapi activate(action_activation_ctx_t*) { openCallsWindow(fnc); return false; } virtual action_state_t idaapi update(action_update_ctx_t*) { return AST_ENABLE_ALWAYS; } void setFunction(func_t* f) { fnc = f; } }; const char* open_calls_ah_t::actionName = "retdec:ActionOpenCalls"; const char* open_calls_ah_t::actionLabel = "Open calls window"; const char* open_calls_ah_t::actionHotkey = "C"; static open_calls_ah_t open_calls_ah; static const action_desc_t open_calls_ah_desc = ACTION_DESC_LITERAL( open_calls_ah_t::actionName, open_calls_ah_t::actionLabel, &open_calls_ah, nullptr, open_calls_ah_t::actionHotkey, -1); // //============================================================================== // bool idaapi changeTypeDeclaration(TWidget* cv) { std::string word; int color = -1; if (get_current_word(cv, false, word, color)) { return false; } auto* idaFnc = getIdaFunction(word, color); auto* cFnc = getWordFunction(word, color); auto* cGv = getWordGlobal(word, color); ea_t addr = 0; if (cFnc && idaFnc && isCurrentFunction(idaFnc) && cFnc->getName() != "main") { addr = cFnc->getStart(); } else if (cGv && cGv->getStorage().isMemory()) { WARNING_MSG("Setting type for global variable is not supported at the moment.\n"); return false; } else { return false; } qstring buf; int flags = PRTYPE_1LINE | PRTYPE_SEMI; if (print_type(&buf, addr, flags)) { std::string askString = "Please enter type declaration:"; qstring qNewDeclr = buf; if (!ask_str(&qNewDeclr, HIST_IDENT, "%s", askString.c_str()) || qNewDeclr.empty()) { return false; } if (apply_cdecl(nullptr, addr, qNewDeclr.c_str())) { decompileFunction(cv, word, true, true); } else { WARNING_MSG("Cannot change declaration to: " << qNewDeclr.c_str() << "\n"); } } else { WARNING_MSG("Cannot change declaration for: " << cFnc->getName() << "\n"); } return false; } struct change_fnc_type_ah_t : public action_handler_t { TWidget* view = nullptr; static const char* actionName; static const char* actionLabel; static const char* actionHotkey; virtual int idaapi activate(action_activation_ctx_t*) { changeTypeDeclaration(view); return false; } virtual action_state_t idaapi update(action_update_ctx_t*) { return AST_ENABLE_ALWAYS; } void setView(TWidget* v) { view = v; } }; const char* change_fnc_type_ah_t::actionName = "retdec:ActionChangeFncType"; const char* change_fnc_type_ah_t::actionLabel = "Change type declaration"; const char* change_fnc_type_ah_t::actionHotkey = "Y"; static change_fnc_type_ah_t change_fnc_type_ah; static const action_desc_t change_fnc_type_ah_desc = ACTION_DESC_LITERAL( change_fnc_type_ah_t::actionName, change_fnc_type_ah_t::actionLabel, &change_fnc_type_ah, nullptr, change_fnc_type_ah_t::actionHotkey, -1); // //============================================================================== // /** * Jump to specified address in IDA's disassembly. * @param ud Address to jump to. */ bool idaapi jumpToASM(ea_t ea) { jumpto(ea); return false; } struct jump_to_asm_ah_t : public action_handler_t { ea_t addr; static const char* actionName; static const char* actionLabel; static const char* actionHotkey; virtual int idaapi activate(action_activation_ctx_t*) { jumpToASM(addr); return false; } virtual action_state_t idaapi update(action_update_ctx_t*) { return AST_ENABLE_ALWAYS; } void setAddress(ea_t a) { addr = a; } }; const char* jump_to_asm_ah_t::actionName = "retdec:ActionJumpToAsm"; const char* jump_to_asm_ah_t::actionLabel = "Jump to ASM"; const char* jump_to_asm_ah_t::actionHotkey = "A"; static jump_to_asm_ah_t jump_to_asm_ah; static const action_desc_t jump_to_asm_ah_desc = ACTION_DESC_LITERAL( jump_to_asm_ah_t::actionName, jump_to_asm_ah_t::actionLabel, &jump_to_asm_ah, nullptr, jump_to_asm_ah_t::actionHotkey, -1); // //============================================================================== // /** * Callback for keybord action in custom viewer. */ bool idaapi ct_keyboard(TWidget* cv, int key, int shift, void* ud) { // ESC : move to the previous saved position. // if (key == 27 && shift == 0) { return moveToPrevious(); } // CTRL + F : move to the next saved position. // 70 = 'F' // else if (key == 70 && shift == 4) { return moveToNext(); } // Get word, function, global, ... // std::string word; int color = -1; if (get_current_word(cv, false, word, color)) { return false; } auto* idaFnc = getIdaFunction(word, color); const retdec::config::Function* cFnc = getWordFunction(word, color); const retdec::config::Object* cGv = getWordGlobal(word, color); // 45 = INSERT // 186 = ';' // if ((key == 45 && shift == 0) || (key == 186 && shift == 0)) { return insertCurrentFunctionComment(); } // 78 = N // else if (key == 78 && shift == 0) { if (decompInfo.navigationActual == decompInfo.navigationList.end()) { return false; } if (cFnc || cGv) { return changeFunctionGlobalName(cv); } else { if (isWordCurrentParameter(word, color)) { // TODO } return false; } } // 88 = X // else if (key == 88 && shift == 0) { if (idaFnc == nullptr) { return false; } openXrefsWindow(idaFnc); } // 67 = C // else if (key == 67 && shift == 0) { if (idaFnc == nullptr) { return false; } openCallsWindow(idaFnc); } // 89 = Y // else if (key == 89 && shift == 0) { return changeTypeDeclaration(cv); } // 65 = A // else if (key == 65 && shift == 0) { ea_t addr = 0; if (idaFnc) { addr = idaFnc->start_ea; } else if (cGv) { addr = cGv->getStorage().getAddress(); } else { return false; } jumpToASM(addr); } return false; } // //============================================================================== // ssize_t idaapi ui_callback(void* ud, int notification_code, va_list va) { RdGlobalInfo* di = static_cast<RdGlobalInfo*>(ud); switch (notification_code) { // called when IDA is preparing a context menu for a view // Here dynamic context-depending user menu items can be added. case ui_populating_widget_popup: { TWidget* view = va_arg(va, TWidget*); if (view != di->custViewer && view != di->codeViewer) { return false; } std::string word; int color = -1; if (get_current_word(view, false, word, color)) { // fail -> nothing } auto* idaFnc = getIdaFunction(word, color); const retdec::config::Function* cFnc = getWordFunction(word, color); const retdec::config::Object* cGv = getWordGlobal(word, color); TPopupMenu* p = va_arg(va, TPopupMenu*); // Function context. // if (idaFnc && cFnc) { attach_action_to_popup(view, p, "-"); jump_to_asm_ah.setAddress(idaFnc->start_ea); attach_action_to_popup(view, p, jump_to_asm_ah_t::actionName); change_fnc_global_name_ah.setView(view); attach_action_to_popup(view, p, change_fnc_global_name_ah_t::actionName); if (isCurrentFunction(idaFnc)) { change_fnc_type_ah.setView(view); attach_action_to_popup(view, p, change_fnc_type_ah_t::actionName); } open_xrefs_ah.setFunction(idaFnc); attach_action_to_popup(view, p, open_xrefs_ah_t::actionName); open_calls_ah.setFunction(idaFnc); attach_action_to_popup(view, p, open_calls_ah_t::actionName); } // Global var context. // else if (cGv) { globalAddress = cGv->getStorage().getAddress(); attach_action_to_popup(view, p, "-"); jump_to_asm_ah.setAddress(globalAddress); attach_action_to_popup(view, p, jump_to_asm_ah_t::actionName); change_fnc_global_name_ah.setView(view); attach_action_to_popup(view, p, change_fnc_global_name_ah_t::actionName); } // Common for all contexts. // attach_action_to_popup(view, p, "-"); attach_action_to_popup(view, p, change_fnc_comment_ah_t::actionName); attach_action_to_popup(view, p, move_backward_ah_t::actionName); attach_action_to_popup(view, p, move_forward_ah_t::actionName); attach_action_to_popup(view, p, "-"); break; } } return false; } void registerPermanentActions() { register_action(jump_to_asm_ah_desc); register_action(change_fnc_global_name_ah_desc); register_action(open_xrefs_ah_desc); register_action(open_calls_ah_desc); register_action(change_fnc_type_ah_desc); register_action(change_fnc_comment_ah_desc); register_action(move_forward_ah_desc); register_action(move_backward_ah_desc); } // //============================================================================== // /** * Callback for double click in custom viewer. */ bool idaapi ct_double(TWidget* cv, int shift, void* ud) { std::string word; int color = -1; if (get_current_word(cv, false, word, color)) { return false; } if (color == COLOR_DEFAULT || color == COLOR_IMPNAME) { decompileFunction(cv, word); return false; } return false; } // //============================================================================== // void idaapi ct_close(TWidget* cv, void* ud) { RdGlobalInfo* di = static_cast<RdGlobalInfo*>(ud); di->custViewer = nullptr; di->codeViewer = nullptr; } // //============================================================================== // /** * Use @c ShowOutput structure to show decompiled code from thread. */ int idaapi showDecompiledCode(void *ud) { RdGlobalInfo *di = static_cast<RdGlobalInfo*>(ud); ShowOutput show(di); execute_sync(show, MFF_FAST); return 0; } } // namespace idaplugin
22.195286
88
0.664593
[ "object" ]
4f7d7fef27ba15e74ac3686a7bb565553a3b42bc
16,090
cpp
C++
protobuf/protoc_echo_plugin/CppFormatter.cpp
philips-software/embeddedinfralib
f3fea435041d965124e5ccb780dddcefb47fdc0c
[ "Unlicense" ]
54
2019-04-02T14:42:54.000Z
2022-03-20T23:02:19.000Z
protobuf/protoc_echo_plugin/CppFormatter.cpp
gabrielfrasantos/embeddedinfralib
55bcde34a2c46d92ef07370e364173b7a03a5f8d
[ "Unlicense" ]
32
2019-03-26T06:57:29.000Z
2022-03-25T00:04:44.000Z
protobuf/protoc_echo_plugin/CppFormatter.cpp
philips-software/embeddedinfralib
f3fea435041d965124e5ccb780dddcefb47fdc0c
[ "Unlicense" ]
20
2019-03-25T15:49:49.000Z
2022-03-20T23:02:22.000Z
#include "protobuf/protoc_echo_plugin/CppFormatter.hpp" #include <functional> namespace application { template<class C> void ForEach(const C& elements, std::function<void(const typename C::value_type&)> each, std::function<void()> between) { if (!elements.empty()) { each(elements.front()); for (auto element = std::next(elements.begin()); element != elements.end(); ++element) { between(); each(*element); } } } template<class C> C Filter(const C& elements, std::function<bool(const typename C::value_type&)> filter) { C result; for (auto& element : elements) if (filter(element)) result.push_back(element); return result; } Entity::Entity(bool hasHeaderCode, bool hasSourceCode) : hasHeaderCode(hasHeaderCode) , hasSourceCode(hasSourceCode) {} bool Entity::HasHeaderCode() const { return hasHeaderCode; } bool Entity::HasSourceCode() const { return hasSourceCode; } Entities::Entities(bool insertNewlineBetweenEntities, bool hasSourceCode) : Entity(true, hasSourceCode) , insertNewlineBetweenEntities(insertNewlineBetweenEntities) {} void Entities::Add(std::shared_ptr<Entity>&& newEntity) { entities.push_back(std::move(newEntity)); } void Entities::PrintHeader(google::protobuf::io::Printer& printer) const { if (insertNewlineBetweenEntities) ForEach(Filter(entities, [](const std::shared_ptr<Entity>& entity) { return entity->HasHeaderCode(); }), [&printer](const std::shared_ptr<Entity>& entity) { entity->PrintHeader(printer); }, [&printer]() { printer.Print("\n"); }); else for (auto& entity : entities) entity->PrintHeader(printer); } void Entities::PrintSource(google::protobuf::io::Printer& printer, const std::string& scope) const { ForEach(Filter(entities, [](const std::shared_ptr<Entity>& entity) { return entity->HasSourceCode(); }), [&printer, &scope](const std::shared_ptr<Entity>& entity) { entity->PrintSource(printer, scope); }, [&printer]() { printer.Print("\n"); }); } bool Entities::EntitiesHaveHeaderCode() const { for (auto& entity : entities) if (entity->HasHeaderCode()) return true; return false; } bool Entities::EntitiesHaveSourceCode() const { for (auto& entity : entities) if (entity->HasSourceCode()) return true; return false; } Class::Class(const std::string& name) : Entities(true) , name(name) {} void Class::Parent(const std::string& parentName) { parents.push_back(parentName); } void Class::PrintHeader(google::protobuf::io::Printer& printer) const { printer.Print(R"(class $name$ )", "name", name); if (!parents.empty()) printer.Print(" : $parents$\n", "parents", Parents()); printer.Print("{\n"); printer.Indent(); Entities::PrintHeader(printer); printer.Outdent(); printer.Print(R"(}; )"); } void Class::PrintSource(google::protobuf::io::Printer& printer, const std::string& scope) const { Entities::PrintSource(printer, scope + name + "::"); } std::string Class::Parents() const { std::string res; ForEach(parents, [&res](const std::string& parent) { res += parent; }, [&res]() { res += "\n , "; }); return res; } Access::Access(const std::string& level) : Entities(false) , level(level) {} void Access::PrintHeader(google::protobuf::io::Printer& printer) const { printer.Outdent(); printer.Print("$level$:\n", "level", level); printer.Indent(); Entities::PrintHeader(printer); } bool Access::HasSourceCode() const { return EntitiesHaveSourceCode(); } Namespace::Namespace(const std::string& name) : Entities(true) , name(name) {} void Namespace::PrintHeader(google::protobuf::io::Printer& printer) const { printer.Print("namespace $name$\n{\n", "name", name); printer.Indent(); Entities::PrintHeader(printer); printer.Outdent(); printer.Print("}\n"); } void Namespace::PrintSource(google::protobuf::io::Printer& printer, const std::string& scope) const { printer.Print("namespace $name$\n{\n", "name", name); printer.Indent(); Entities::PrintSource(printer, scope); printer.Outdent(); printer.Print("}\n"); } bool Namespace::HasHeaderCode() const { return EntitiesHaveHeaderCode(); } bool Namespace::HasSourceCode() const { return EntitiesHaveSourceCode(); } const uint32_t Function::fConst; const uint32_t Function::fVirtual; const uint32_t Function::fAbstract; const uint32_t Function::fOverride; Function::Function(const std::string& name, const std::string& body, const std::string& result, uint32_t flags) : name(name) , body(body) , result(result) , flags(flags) {} void Function::Parameter(const std::string& parameter) { parameters.push_back(parameter); } void Function::PrintHeader(google::protobuf::io::Printer& printer) const { printer.Print("$virtual$$result$ $name$($parameters$)$const$$override$$abstract$;\n" , "result", result , "name", name , "parameters", Parameters() , "const", (flags & fConst) != 0 ? " const" : "" , "virtual", (flags & fVirtual) != 0 ? "virtual " : "" , "abstract", (flags & fAbstract) != 0 ? " = 0" : "" , "override", (flags & fOverride) != 0 ? " override" : ""); } void Function::PrintSource(google::protobuf::io::Printer& printer, const std::string& scope) const { printer.Print("$result$ $scope$$name$($parameters$)$const$\n" , "result", result , "scope", scope , "name", name , "parameters", Parameters() , "const", (flags & fConst) != 0 ? " const" : ""); if (body.empty()) printer.Print("{}\n"); else { printer.Print("{\n"); printer.Indent(); printer.Print(body.c_str()); printer.Outdent(); printer.Print("}\n"); } } std::string Function::Parameters() const { std::string res; ForEach(parameters, [&res](const std::string& parameter) { res += parameter; }, [&res]() { res += ", "; }); return res; } const uint32_t Constructor::cDefault; const uint32_t Constructor::cDelete; Constructor::Constructor(const std::string& name, const std::string& body, uint32_t flags) : name(name) , body(body) , flags(flags) {} void Constructor::Parameter(const std::string& parameter) { parameters.push_back(parameter); } void Constructor::Initializer(const std::string& initializer) { initializers.push_back(initializer); } void Constructor::PrintHeader(google::protobuf::io::Printer& printer) const { printer.Print("$name$($parameters$)$default$$delete$;\n" , "name", name , "parameters", Parameters() , "default", (flags & cDefault) != 0 ? " = default" : "" , "delete", (flags & cDelete) != 0 ? " = delete" : ""); } void Constructor::PrintSource(google::protobuf::io::Printer& printer, const std::string& scope) const { if ((flags & cDefault) == 0 && (flags & cDelete) == 0) { printer.Print(R"($scope$$name$($parameters$) )" , "scope", scope , "name", name , "parameters", Parameters()); printer.Indent(); PrintInitializers(printer); printer.Outdent(); if (body.empty()) printer.Print("{}\n"); else { printer.Print("{\n"); printer.Indent(); printer.Print(body.c_str()); printer.Outdent(); printer.Print("}\n"); } }; } bool Constructor::HasSourceCode() const { return flags == 0; } std::string Constructor::Parameters() const { std::string result; ForEach(parameters, [&result](const std::string& parameter) { result += parameter; }, [&result]() { result += ", "; }); return result; } void Constructor::PrintInitializers(google::protobuf::io::Printer& printer) const { std::string separator = ": "; for (auto& initializer : initializers) { printer.Print("$separator$$initializer$\n", "separator", separator, "initializer", initializer); separator = ", "; } } DataMember::DataMember(const std::string& name, const std::string& type, const std::string& initializer) : Entity(true, false) , name(name) , type(type) , initializer(initializer) {} void DataMember::PrintHeader(google::protobuf::io::Printer& printer) const { if (initializer.empty()) printer.Print("$type$ $name$;\n", "type", type, "name", name); else printer.Print("$type$ $name$ = $initializer$;\n", "type", type, "name", name, "initializer", initializer); } void DataMember::PrintSource(google::protobuf::io::Printer& printer, const std::string& scope) const {} StaticDataMember::StaticDataMember(const std::string& name, const std::string& type, const std::string& initializer) : Entity(true, true) , name(name) , type(type) , initializer(initializer) {} void StaticDataMember::PrintHeader(google::protobuf::io::Printer& printer) const { printer.Print("static $type$ $name$;\n", "type", type, "name", name); } void StaticDataMember::PrintSource(google::protobuf::io::Printer& printer, const std::string& scope) const { printer.Print("$type$ $scope$$name$ = $initializer$;\n", "type", type, "scope", scope, "name", name, "initializer", initializer); } Using::Using(const std::string& name, const std::string& definition) : Entity(true, false) , name(name) , definition(definition) {} void Using::PrintHeader(google::protobuf::io::Printer& printer) const { printer.Print("using $name$ = $definition$;\n", "name", name, "definition", definition); } void Using::PrintSource(google::protobuf::io::Printer& printer, const std::string& scope) const {} void UsingTemplate::PrintHeader(google::protobuf::io::Printer& printer) const { printer.Print("template<$parameters$>\n", "parameters", Parameters()); Using::PrintHeader(printer); } void UsingTemplate::PrintSource(google::protobuf::io::Printer& printer, const std::string& scope) const {} void UsingTemplate::TemplateParameter(const std::string& parameter) { parameters.push_back(parameter); } std::string UsingTemplate::Parameters() const { std::string result; for (auto& parameter : parameters) { if (!result.empty()) result.append(", "); result.append(parameter); } return result; } IncludesByHeader::IncludesByHeader() : Entity(true, false) {} void IncludesByHeader::Path(const std::string& path) { paths.push_back(path); } void IncludesByHeader::PrintHeader(google::protobuf::io::Printer& printer) const { for (auto& path : paths) printer.Print(R"(#include "$path$" )", "path", path); } void IncludesByHeader::PrintSource(google::protobuf::io::Printer& printer, const std::string& scope) const {} IncludesBySource::IncludesBySource() : Entity(false, true) {} void IncludesBySource::Path(const std::string& path) { paths.push_back(path); } void IncludesBySource::PrintHeader(google::protobuf::io::Printer& printer) const {} void IncludesBySource::PrintSource(google::protobuf::io::Printer& printer, const std::string& scope) const { for (auto& path : paths) printer.Print(R"(#include "$path$" )", "path", path); } ClassForwardDeclaration::ClassForwardDeclaration(const std::string& name) : Entity(true, false) , name(name) {} void ClassForwardDeclaration::PrintHeader(google::protobuf::io::Printer& printer) const { printer.Print("class $name$;\n", "name", name); } void ClassForwardDeclaration::PrintSource(google::protobuf::io::Printer& printer, const std::string& scope) const {} StructTemplateForwardDeclaration::StructTemplateForwardDeclaration(const std::string& name) : Entity(true, false) , name(name) {} void StructTemplateForwardDeclaration::PrintHeader(google::protobuf::io::Printer& printer) const { printer.Print("template<$parameters$>\n", "parameters", Parameters()); printer.Print("struct $name$;\n", "name", name); } void StructTemplateForwardDeclaration::PrintSource(google::protobuf::io::Printer& printer, const std::string& scope) const {} void StructTemplateForwardDeclaration::TemplateParameter(const std::string& parameter) { parameters.push_back(parameter); } std::string StructTemplateForwardDeclaration::Parameters() const { std::string result; for (auto& parameter : parameters) { if (!result.empty()) result.append(", "); result.append(parameter); } return result; } StructTemplateSpecialization::StructTemplateSpecialization(const std::string& name) : Entities(false, false) , name(name) {} void StructTemplateSpecialization::PrintHeader(google::protobuf::io::Printer& printer) const { printer.Print("template<>\n"); printer.Print("struct $name$<$specializations$> {\n", "name", name, "specializations", Specializations()); printer.Indent(); Entities::PrintHeader(printer); printer.Outdent(); printer.Print("};\n"); } void StructTemplateSpecialization::PrintSource(google::protobuf::io::Printer& printer, const std::string& scope) const {} void StructTemplateSpecialization::TemplateSpecialization(const std::string& parameter) { specializations.push_back(parameter); } std::string StructTemplateSpecialization::Specializations() const { std::string result; for (auto& specialization : specializations) { if (!result.empty()) result.append(", "); result.append(specialization); } return result; } EnumDeclaration::EnumDeclaration(const std::string& name, const std::vector<std::pair<std::string, int>>& members) : Entity(true, false) , name(name) , members(members) {} void EnumDeclaration::PrintHeader(google::protobuf::io::Printer& printer) const { printer.Print("enum class $name$\n{\n", "name", name); printer.Indent(); for (auto& member : members) { printer.Print("$name$ = $initializer$", "name", member.first, "initializer", std::to_string(member.second)); if (&member != &members.back()) printer.Print(","); printer.Print("\n"); } printer.Outdent(); printer.Print("};\n", "name", name); } void EnumDeclaration::PrintSource(google::protobuf::io::Printer& printer, const std::string& scope) const {} }
29.686347
252
0.583654
[ "vector" ]
4f7d9be179a4e7e1ed14d7b113ccad873641043d
114,617
hpp
C++
redfish-core/lib/systems.hpp
murali-srinivasan/bmcweb
7f0d05a6fed797ec8de8b79e8677afb11139e315
[ "Apache-2.0" ]
null
null
null
redfish-core/lib/systems.hpp
murali-srinivasan/bmcweb
7f0d05a6fed797ec8de8b79e8677afb11139e315
[ "Apache-2.0" ]
null
null
null
redfish-core/lib/systems.hpp
murali-srinivasan/bmcweb
7f0d05a6fed797ec8de8b79e8677afb11139e315
[ "Apache-2.0" ]
null
null
null
/* // Copyright (c) 2018 Intel Corporation // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. */ #pragma once #include "led.hpp" #include "pcie.hpp" #include "redfish_util.hpp" #ifdef BMCWEB_ENABLE_IBM_LAMP_TEST #include "oem/ibm/lamp_test.hpp" #endif #include <app.hpp> #include <boost/container/flat_map.hpp> #include <registries/privilege_registry.hpp> #include <utils/fw_utils.hpp> #include <utils/json_utils.hpp> #include <variant> namespace redfish { /** * @brief Updates the Functional State of DIMMs * * @param[in] aResp Shared pointer for completing asynchronous calls * @param[in] dimmState Dimm's Functional state, true/false * * @return None. */ inline void updateDimmProperties(const std::shared_ptr<bmcweb::AsyncResp>& aResp, const std::variant<bool>& dimmState) { const bool* isDimmFunctional = std::get_if<bool>(&dimmState); if (isDimmFunctional == nullptr) { messages::internalError(aResp->res); return; } BMCWEB_LOG_DEBUG << "Dimm Functional: " << *isDimmFunctional; // Set it as Enabled if at least one DIMM is functional // Update STATE only if previous State was DISABLED and current Dimm is // ENABLED. nlohmann::json& prevMemSummary = aResp->res.jsonValue["MemorySummary"]["Status"]["State"]; if (prevMemSummary == "Disabled") { if (*isDimmFunctional == true) { aResp->res.jsonValue["MemorySummary"]["Status"]["State"] = "Enabled"; } } } /* * @brief Update "ProcessorSummary" "Count" based on Cpu PresenceState * * @param[in] aResp Shared pointer for completing asynchronous calls * @param[in] cpuPresenceState CPU present or not * * @return None. */ inline void modifyCpuPresenceState(const std::shared_ptr<bmcweb::AsyncResp>& aResp, const std::variant<bool>& cpuPresenceState) { const bool* isCpuPresent = std::get_if<bool>(&cpuPresenceState); if (isCpuPresent == nullptr) { messages::internalError(aResp->res); return; } BMCWEB_LOG_DEBUG << "Cpu Present: " << *isCpuPresent; if (*isCpuPresent == true) { nlohmann::json& procCount = aResp->res.jsonValue["ProcessorSummary"]["Count"]; auto procCountPtr = procCount.get_ptr<nlohmann::json::number_integer_t*>(); if (procCountPtr != nullptr) { // shouldn't be possible to be nullptr *procCountPtr += 1; } } } /* * @brief Update "ProcessorSummary" "Status" "State" based on * CPU Functional State * * @param[in] aResp Shared pointer for completing asynchronous calls * @param[in] cpuFunctionalState is CPU functional true/false * * @return None. */ inline void modifyCpuFunctionalState(const std::shared_ptr<bmcweb::AsyncResp>& aResp, const std::variant<bool>& cpuFunctionalState) { const bool* isCpuFunctional = std::get_if<bool>(&cpuFunctionalState); if (isCpuFunctional == nullptr) { messages::internalError(aResp->res); return; } BMCWEB_LOG_DEBUG << "Cpu Functional: " << *isCpuFunctional; nlohmann::json& prevProcState = aResp->res.jsonValue["ProcessorSummary"]["Status"]["State"]; // Set it as Enabled if at least one CPU is functional // Update STATE only if previous State was Non_Functional and current CPU is // Functional. if (prevProcState == "Disabled") { if (*isCpuFunctional == true) { aResp->res.jsonValue["ProcessorSummary"]["Status"]["State"] = "Enabled"; } } } /* * @brief Get "ProcessorSummary" Properties * * @param[in] aResp Shared pointer for completing asynchronous calls * @param[in] service dbus service for Cpu Information * @param[in] path dbus path for Cpu * @param[in] properties from dbus Inventory.Item.Cpu interface * * @return None. */ inline void getProcessorProperties( const std::shared_ptr<bmcweb::AsyncResp>& aResp, const std::string& service, const std::string& path, const std::vector<std::pair< std::string, std::variant<std::string, uint64_t, uint32_t, uint16_t>>>& properties) { BMCWEB_LOG_DEBUG << "Got " << properties.size() << " Cpu properties."; auto getCpuPresenceState = [aResp](const boost::system::error_code ec3, const std::variant<bool>& cpuPresenceCheck) { if (ec3) { BMCWEB_LOG_ERROR << "DBUS response error " << ec3; return; } modifyCpuPresenceState(aResp, cpuPresenceCheck); }; auto getCpuFunctionalState = [aResp](const boost::system::error_code ec3, const std::variant<bool>& cpuFunctionalCheck) { if (ec3) { BMCWEB_LOG_ERROR << "DBUS response error " << ec3; return; } modifyCpuFunctionalState(aResp, cpuFunctionalCheck); }; // Get the Presence of CPU crow::connections::systemBus->async_method_call( std::move(getCpuPresenceState), service, path, "org.freedesktop.DBus.Properties", "Get", "xyz.openbmc_project.Inventory.Item", "Present"); // Get the Functional State crow::connections::systemBus->async_method_call( std::move(getCpuFunctionalState), service, path, "org.freedesktop.DBus.Properties", "Get", "xyz.openbmc_project.State.Decorator.OperationalStatus", "Functional"); for (const auto& property : properties) { if (property.first == "Family") { // Get the CPU Model const std::string* modelStr = std::get_if<std::string>(&property.second); if (!modelStr) { messages::internalError(aResp->res); return; } nlohmann::json& prevModel = aResp->res.jsonValue["ProcessorSummary"]["Model"]; std::string* prevModelPtr = prevModel.get_ptr<std::string*>(); // If CPU Models are different, use the first entry in // alphabetical order // If Model has never been set // before, set it to *modelStr if (prevModelPtr == nullptr) { prevModel = *modelStr; } // If Model has been set before, only change if new Model is // higher in alphabetical order else { if (*modelStr < *prevModelPtr) { prevModel = *modelStr; } } } if (property.first == "CoreCount") { // Get CPU CoreCount and add it to the total const uint16_t* coreCountVal = std::get_if<uint16_t>(&property.second); if (!coreCountVal) { messages::internalError(aResp->res); return; } nlohmann::json& coreCount = aResp->res.jsonValue["ProcessorSummary"]["CoreCount"]; int64_t* coreCountPtr = coreCount.get_ptr<int64_t*>(); if (coreCountPtr == nullptr) { coreCount = *coreCountVal; } else { *coreCountPtr += *coreCountVal; } } } } /* * @brief Get ProcessorSummary fields * * @param[in] aResp Shared pointer for completing asynchronous calls * @param[in] service dbus service for Cpu Information * @param[in] path dbus path for Cpu * * @return None. */ inline void getProcessorSummary(const std::shared_ptr<bmcweb::AsyncResp>& aResp, const std::string& service, const std::string& path) { crow::connections::systemBus->async_method_call( [aResp, service, path](const boost::system::error_code ec2, const std::vector<std::pair< std::string, std::variant<std::string, uint64_t, uint32_t, uint16_t>>>& properties) { if (ec2) { BMCWEB_LOG_ERROR << "DBUS response error " << ec2; messages::internalError(aResp->res); return; } getProcessorProperties(aResp, service, path, properties); }, service, path, "org.freedesktop.DBus.Properties", "GetAll", "xyz.openbmc_project.Inventory.Item.Cpu"); } /* * @brief Retrieves computer system properties over dbus * * @param[in] aResp Shared pointer for completing asynchronous calls * * @return None. */ inline void getComputerSystem(const std::shared_ptr<bmcweb::AsyncResp>& aResp) { BMCWEB_LOG_DEBUG << "Get available system components."; crow::connections::systemBus->async_method_call( [aResp]( const boost::system::error_code ec, const std::vector<std::pair< std::string, std::vector<std::pair<std::string, std::vector<std::string>>>>>& subtree) { if (ec) { BMCWEB_LOG_DEBUG << "DBUS response error"; messages::internalError(aResp->res); return; } // Iterate over all retrieved ObjectPaths. for (const std::pair<std::string, std::vector<std::pair< std::string, std::vector<std::string>>>>& object : subtree) { const std::string& path = object.first; BMCWEB_LOG_DEBUG << "Got path: " << path; const std::vector< std::pair<std::string, std::vector<std::string>>>& connectionNames = object.second; if (connectionNames.size() < 1) { continue; } // This is not system, so check if it's cpu, dimm, UUID or // BiosVer for (const auto& connection : connectionNames) { for (const auto& interfaceName : connection.second) { if (interfaceName == "xyz.openbmc_project.Inventory.Item.Dimm") { BMCWEB_LOG_DEBUG << "Found Dimm, now get its properties."; crow::connections::systemBus->async_method_call( [aResp, service{connection.first}, path](const boost::system::error_code ec2, const std::vector< std::pair<std::string, VariantType>>& properties) { if (ec2) { BMCWEB_LOG_ERROR << "DBUS response error " << ec2; messages::internalError(aResp->res); return; } BMCWEB_LOG_DEBUG << "Got " << properties.size() << " Dimm properties."; if (properties.size() > 0) { for (const std::pair<std::string, VariantType>& property : properties) { if (property.first != "MemorySizeInKB") { continue; } const uint32_t* value = std::get_if<uint32_t>( &property.second); if (value == nullptr) { BMCWEB_LOG_DEBUG << "Find incorrect type of " "MemorySize"; continue; } nlohmann::json& totalMemory = aResp->res .jsonValue["MemorySummar" "y"] ["TotalSystemMe" "moryGiB"]; uint64_t* preValue = totalMemory .get_ptr<uint64_t*>(); if (preValue == nullptr) { continue; } aResp->res .jsonValue["MemorySummary"] ["TotalSystemMemoryGi" "B"] = *value / (1024 * 1024) + *preValue; aResp->res .jsonValue["MemorySummary"] ["Status"]["State"] = "Enabled"; } } else { auto getDimmProperties = [aResp]( const boost::system::error_code ec3, const std::variant<bool>& dimmState) { if (ec3) { BMCWEB_LOG_ERROR << "DBUS response " "error " << ec3; return; } updateDimmProperties(aResp, dimmState); }; crow::connections::systemBus ->async_method_call( std::move(getDimmProperties), service, path, "org.freedesktop.DBus." "Properties", "Get", "xyz.openbmc_project.State." "Decorator.OperationalStatus", "Functional"); } }, connection.first, path, "org.freedesktop.DBus.Properties", "GetAll", "xyz.openbmc_project.Inventory.Item.Dimm"); } else if (interfaceName == "xyz.openbmc_project.Inventory.Item.Cpu") { BMCWEB_LOG_DEBUG << "Found Cpu, now get its properties."; getProcessorSummary(aResp, connection.first, path); } else if (interfaceName == "xyz.openbmc_project.Common.UUID") { BMCWEB_LOG_DEBUG << "Found UUID, now get its properties."; crow::connections::systemBus->async_method_call( [aResp]( const boost::system::error_code ec3, const std::vector< std::pair<std::string, VariantType>>& properties) { if (ec3) { BMCWEB_LOG_DEBUG << "DBUS response error " << ec3; messages::internalError(aResp->res); return; } BMCWEB_LOG_DEBUG << "Got " << properties.size() << " UUID properties."; for (const std::pair<std::string, VariantType>& property : properties) { if (property.first == "UUID") { const std::string* value = std::get_if<std::string>( &property.second); if (value != nullptr) { std::string valueStr = *value; if (valueStr.size() == 32) { valueStr.insert(8, 1, '-'); valueStr.insert(13, 1, '-'); valueStr.insert(18, 1, '-'); valueStr.insert(23, 1, '-'); } BMCWEB_LOG_DEBUG << "UUID = " << valueStr; aResp->res.jsonValue["UUID"] = valueStr; } } } }, connection.first, path, "org.freedesktop.DBus.Properties", "GetAll", "xyz.openbmc_project.Common.UUID"); } else if (interfaceName == "xyz.openbmc_project.Inventory.Item.System") { crow::connections::systemBus->async_method_call( [aResp]( const boost::system::error_code ec2, const std::vector< std::pair<std::string, VariantType>>& propertiesList) { if (ec2) { // doesn't have to include this // interface return; } BMCWEB_LOG_DEBUG << "Got " << propertiesList.size() << " properties for system"; for (const std::pair<std::string, VariantType>& property : propertiesList) { const std::string& propertyName = property.first; if ((propertyName == "PartNumber") || (propertyName == "SerialNumber") || (propertyName == "Manufacturer") || (propertyName == "Model") || (propertyName == "SubModel")) { const std::string* value = std::get_if<std::string>( &property.second); if (value != nullptr) { aResp->res .jsonValue[propertyName] = *value; } } } // Grab the bios version fw_util::populateFirmwareInformation( aResp, fw_util::biosPurpose, "BiosVersion", false); }, connection.first, path, "org.freedesktop.DBus.Properties", "GetAll", "xyz.openbmc_project.Inventory.Decorator." "Asset"); crow::connections::systemBus->async_method_call( [aResp]( const boost::system::error_code ec2, const std::variant<std::string>& property) { if (ec2) { // doesn't have to include this // interface return; } const std::string* value = std::get_if<std::string>(&property); if (value != nullptr) { aResp->res.jsonValue["AssetTag"] = *value; } }, connection.first, path, "org.freedesktop.DBus.Properties", "Get", "xyz.openbmc_project.Inventory.Decorator." "AssetTag", "AssetTag"); } } } } }, "xyz.openbmc_project.ObjectMapper", "/xyz/openbmc_project/object_mapper", "xyz.openbmc_project.ObjectMapper", "GetSubTree", "/xyz/openbmc_project/inventory", int32_t(0), std::array<const char*, 5>{ "xyz.openbmc_project.Inventory.Decorator.Asset", "xyz.openbmc_project.Inventory.Item.Cpu", "xyz.openbmc_project.Inventory.Item.Dimm", "xyz.openbmc_project.Inventory.Item.System", "xyz.openbmc_project.Common.UUID", }); } /** * @brief Retrieves host state properties over dbus * * @param[in] aResp Shared pointer for completing asynchronous calls. * * @return None. */ inline void getHostState(const std::shared_ptr<bmcweb::AsyncResp>& aResp) { BMCWEB_LOG_DEBUG << "Get host information."; crow::connections::systemBus->async_method_call( [aResp](const boost::system::error_code ec, const std::variant<std::string>& hostState) { if (ec) { if (ec == boost::system::errc::host_unreachable) { // Service not available, no error, just don't return // host state info BMCWEB_LOG_DEBUG << "Service not available " << ec; return; } BMCWEB_LOG_ERROR << "DBUS response error " << ec; messages::internalError(aResp->res); return; } const std::string* s = std::get_if<std::string>(&hostState); BMCWEB_LOG_DEBUG << "Host state: " << *s; if (s != nullptr) { // Verify Host State if (*s == "xyz.openbmc_project.State.Host.HostState.Running") { aResp->res.jsonValue["PowerState"] = "On"; aResp->res.jsonValue["Status"]["State"] = "Enabled"; } else if (*s == "xyz.openbmc_project.State.Host.HostState." "Quiesced") { aResp->res.jsonValue["PowerState"] = "On"; aResp->res.jsonValue["Status"]["State"] = "Quiesced"; } else if (*s == "xyz.openbmc_project.State.Host.HostState." "DiagnosticMode") { aResp->res.jsonValue["PowerState"] = "On"; aResp->res.jsonValue["Status"]["State"] = "InTest"; } else if (*s == "xyz.openbmc_project.State.Host.HostState." "TransitioningToRunning") { aResp->res.jsonValue["PowerState"] = "PoweringOn"; aResp->res.jsonValue["Status"]["State"] = "Starting"; } else if (*s == "xyz.openbmc_project.State.Host.HostState." "TransitioningToOff") { aResp->res.jsonValue["PowerState"] = "PoweringOff"; aResp->res.jsonValue["Status"]["State"] = "Disabled"; } else { aResp->res.jsonValue["PowerState"] = "Off"; aResp->res.jsonValue["Status"]["State"] = "Disabled"; } } }, "xyz.openbmc_project.State.Host", "/xyz/openbmc_project/state/host0", "org.freedesktop.DBus.Properties", "Get", "xyz.openbmc_project.State.Host", "CurrentHostState"); } /** * @brief Translates boot type DBUS property value to redfish. * * @param[in] dbusType The boot type in DBUS speak. * * @return Returns as a string, the boot type in Redfish terms. If translation * cannot be done, returns an empty string. */ inline std::string dbusToRfBootType(const std::string& dbusType) { if (dbusType == "xyz.openbmc_project.Control.Boot.Type.Types.Legacy") { return "Legacy"; } if (dbusType == "xyz.openbmc_project.Control.Boot.Type.Types.EFI") { return "UEFI"; } return ""; } /** * @brief Retrieves boot progress of the system * * @param[in] aResp Shared pointer for generating response message. * * @return None. */ inline void getBootProgress(const std::shared_ptr<bmcweb::AsyncResp>& aResp) { crow::connections::systemBus->async_method_call( [aResp](const boost::system::error_code ec, const std::variant<std::string>& bootProgress) { if (ec) { // BootProgress is an optional object so just do nothing if // not found return; } const std::string* bootProgressStr = std::get_if<std::string>(&bootProgress); if (!bootProgressStr) { // Interface implemented but property not found, return error // for that messages::internalError(aResp->res); return; } BMCWEB_LOG_DEBUG << "Boot Progress: " << *bootProgressStr; // Now convert the D-Bus BootProgress to the appropriate Redfish // enum std::string rfBpLastState = "None"; if (*bootProgressStr == "xyz.openbmc_project.State.Boot.Progress." "ProgressStages.Unspecified") { rfBpLastState = "None"; } else if (*bootProgressStr == "xyz.openbmc_project.State.Boot.Progress.ProgressStages." "PrimaryProcInit") { rfBpLastState = "PrimaryProcessorInitializationStarted"; } else if (*bootProgressStr == "xyz.openbmc_project.State.Boot.Progress.ProgressStages." "BusInit") { rfBpLastState = "BusInitializationStarted"; } else if (*bootProgressStr == "xyz.openbmc_project.State.Boot.Progress.ProgressStages." "MemoryInit") { rfBpLastState = "MemoryInitializationStarted"; } else if (*bootProgressStr == "xyz.openbmc_project.State.Boot.Progress.ProgressStages." "SecondaryProcInit") { rfBpLastState = "SecondaryProcessorInitializationStarted"; } else if (*bootProgressStr == "xyz.openbmc_project.State.Boot.Progress.ProgressStages." "PCIInit") { rfBpLastState = "PCIResourceConfigStarted"; } else if (*bootProgressStr == "xyz.openbmc_project.State.Boot.Progress.ProgressStages." "SystemSetup") { rfBpLastState = "SetupEntered"; } else if (*bootProgressStr == "xyz.openbmc_project.State.Boot.Progress.ProgressStages." "SystemInitComplete") { rfBpLastState = "SystemHardwareInitializationComplete"; } else if (*bootProgressStr == "xyz.openbmc_project.State.Boot.Progress.ProgressStages." "OSStart") { rfBpLastState = "OSBootStarted"; } else if (*bootProgressStr == "xyz.openbmc_project.State.Boot.Progress.ProgressStages." "OSRunning") { rfBpLastState = "OSRunning"; } else { BMCWEB_LOG_DEBUG << "Unsupported D-Bus BootProgress " << *bootProgressStr; // Just return the default } aResp->res.jsonValue["BootProgress"]["LastState"] = rfBpLastState; }, "xyz.openbmc_project.State.Host", "/xyz/openbmc_project/state/host0", "org.freedesktop.DBus.Properties", "Get", "xyz.openbmc_project.State.Boot.Progress", "BootProgress"); } /** * @brief Retrieves the Last Reset Time * * "Reset" is an overloaded term in Redfish, "Reset" includes power on * and power off. Even though this is the "system" Redfish object look at the * chassis D-Bus interface for the LastStateChangeTime since this has the * last power operation time. * * @param[in] aResp Shared pointer for generating response message. * * @return None. */ inline void getLastResetTime(const std::shared_ptr<bmcweb::AsyncResp>& aResp) { BMCWEB_LOG_DEBUG << "Getting System Last Reset Time"; crow::connections::systemBus->async_method_call( [aResp](const boost::system::error_code ec, std::variant<uint64_t>& lastResetTime) { if (ec) { BMCWEB_LOG_DEBUG << "D-BUS response error " << ec; return; } const uint64_t* lastResetTimePtr = std::get_if<uint64_t>(&lastResetTime); if (!lastResetTimePtr) { messages::internalError(aResp->res); return; } // LastStateChangeTime is epoch time, in milliseconds // https://github.com/openbmc/phosphor-dbus-interfaces/blob/33e8e1dd64da53a66e888d33dc82001305cd0bf9/xyz/openbmc_project/State/Chassis.interface.yaml#L19 time_t lastResetTimeStamp = static_cast<time_t>(*lastResetTimePtr / 1000); // Convert to ISO 8601 standard aResp->res.jsonValue["LastResetTime"] = crow::utility::getDateTime(lastResetTimeStamp); }, "xyz.openbmc_project.State.Chassis", "/xyz/openbmc_project/state/chassis0", "org.freedesktop.DBus.Properties", "Get", "xyz.openbmc_project.State.Chassis", "LastStateChangeTime"); } /** * @brief Retrieves Automatic Retry properties. Known on D-Bus as AutoReboot. * * @param[in] aResp Shared pointer for generating response message. * * @return None. */ inline void getAutomaticRetry(const std::shared_ptr<bmcweb::AsyncResp>& aResp) { BMCWEB_LOG_DEBUG << "Get Automatic Retry policy"; crow::connections::systemBus->async_method_call( [aResp](const boost::system::error_code ec, std::variant<bool>& autoRebootEnabled) { if (ec) { BMCWEB_LOG_DEBUG << "D-BUS response error " << ec; return; } const bool* autoRebootEnabledPtr = std::get_if<bool>(&autoRebootEnabled); if (!autoRebootEnabledPtr) { messages::internalError(aResp->res); return; } BMCWEB_LOG_DEBUG << "Auto Reboot: " << *autoRebootEnabledPtr; if (*autoRebootEnabledPtr == true) { aResp->res.jsonValue["Boot"]["AutomaticRetryConfig"] = "RetryAttempts"; // If AutomaticRetry (AutoReboot) is enabled see how many // attempts are left crow::connections::systemBus->async_method_call( [aResp](const boost::system::error_code ec2, std::variant<uint32_t>& autoRebootAttemptsLeft) { if (ec2) { BMCWEB_LOG_DEBUG << "D-BUS response error " << ec2; return; } const uint32_t* autoRebootAttemptsLeftPtr = std::get_if<uint32_t>(&autoRebootAttemptsLeft); if (!autoRebootAttemptsLeftPtr) { messages::internalError(aResp->res); return; } BMCWEB_LOG_DEBUG << "Auto Reboot Attempts Left: " << *autoRebootAttemptsLeftPtr; aResp->res .jsonValue["Boot"] ["RemainingAutomaticRetryAttempts"] = *autoRebootAttemptsLeftPtr; }, "xyz.openbmc_project.State.Host", "/xyz/openbmc_project/state/host0", "org.freedesktop.DBus.Properties", "Get", "xyz.openbmc_project.Control.Boot.RebootAttempts", "AttemptsLeft"); } else { aResp->res.jsonValue["Boot"]["AutomaticRetryConfig"] = "Disabled"; } // Not on D-Bus. Hardcoded here: // https://github.com/openbmc/phosphor-state-manager/blob/1dbbef42675e94fb1f78edb87d6b11380260535a/meson_options.txt#L71 aResp->res.jsonValue["Boot"]["AutomaticRetryAttempts"] = 3; // "AutomaticRetryConfig" can be 3 values, Disabled, RetryAlways, // and RetryAttempts. OpenBMC only supports Disabled and // RetryAttempts. aResp->res.jsonValue["Boot"]["AutomaticRetryConfig@Redfish." "AllowableValues"] = {"Disabled", "RetryAttempts"}; }, "xyz.openbmc_project.Settings", "/xyz/openbmc_project/control/host0/auto_reboot", "org.freedesktop.DBus.Properties", "Get", "xyz.openbmc_project.Control.Boot.RebootPolicy", "AutoReboot"); } /** * @brief Retrieves power restore policy over DBUS. * * @param[in] aResp Shared pointer for generating response message. * * @return None. */ inline void getPowerRestorePolicy(const std::shared_ptr<bmcweb::AsyncResp>& aResp) { BMCWEB_LOG_DEBUG << "Get power restore policy"; crow::connections::systemBus->async_method_call( [aResp](const boost::system::error_code ec, std::variant<std::string>& policy) { if (ec) { BMCWEB_LOG_DEBUG << "DBUS response error " << ec; return; } const boost::container::flat_map<std::string, std::string> policyMaps = { {"xyz.openbmc_project.Control.Power.RestorePolicy.Policy." "AlwaysOn", "AlwaysOn"}, {"xyz.openbmc_project.Control.Power.RestorePolicy.Policy." "AlwaysOff", "AlwaysOff"}, {"xyz.openbmc_project.Control.Power.RestorePolicy.Policy." "Restore", "LastState"}}; const std::string* policyPtr = std::get_if<std::string>(&policy); if (!policyPtr) { messages::internalError(aResp->res); return; } auto policyMapsIt = policyMaps.find(*policyPtr); if (policyMapsIt == policyMaps.end()) { messages::internalError(aResp->res); return; } aResp->res.jsonValue["PowerRestorePolicy"] = policyMapsIt->second; }, "xyz.openbmc_project.Settings", "/xyz/openbmc_project/control/host0/power_restore_policy", "org.freedesktop.DBus.Properties", "Get", "xyz.openbmc_project.Control.Power.RestorePolicy", "PowerRestorePolicy"); } /** * @brief Stop Boot On Fault over DBUS. * * @param[in] aResp Shared pointer for generating response message. * * @return None. */ inline void getStopBootOnFault(const std::shared_ptr<bmcweb::AsyncResp>& aResp) { BMCWEB_LOG_DEBUG << "Get Stop Boot On Fault"; // Get Stop Boot On Fault object path: crow::connections::systemBus->async_method_call( [aResp]( const boost::system::error_code ec, const std::vector<std::pair< std::string, std::vector<std::pair<std::string, std::vector<std::string>>>>>& subtree) { if (ec) { messages::internalError(aResp->res); return; } if (subtree.size() == 0) { return; } if (subtree.size() > 1) { // More then one StopBootOnFault object is not supported and is // an error BMCWEB_LOG_DEBUG << "Found more than 1 system D-Bus " "StopBootOnFault objects: " << subtree.size(); messages::internalError(aResp->res); return; } if (subtree[0].first.empty() || subtree[0].second.size() != 1) { BMCWEB_LOG_DEBUG << "StopBootOnFault mapper error!"; messages::internalError(aResp->res); return; } const std::string& path = subtree[0].first; const std::string& service = subtree[0].second.begin()->first; if (service.empty()) { BMCWEB_LOG_DEBUG << "StopBootOnFault service mapper error!"; messages::internalError(aResp->res); return; } // Valid Stop Boot On Fault object found, now read the current value crow::connections::systemBus->async_method_call( [aResp](const boost::system::error_code ec, std::variant<bool>& quiesceOnHwError) { if (ec) { BMCWEB_LOG_DEBUG << "DBUS response error on StopBootOnFault Get : " << ec; messages::internalError(aResp->res); return; } const bool* quiesceOnHwErrorPtr = std::get_if<bool>(&quiesceOnHwError); if (!quiesceOnHwErrorPtr) { messages::internalError(aResp->res); return; } BMCWEB_LOG_DEBUG << "Stop Boot On Fault: " << *quiesceOnHwErrorPtr; if (*quiesceOnHwErrorPtr == true) { aResp->res.jsonValue["Boot"]["StopBootOnFault"] = "AnyFault"; } else { aResp->res.jsonValue["Boot"]["StopBootOnFault"] = "Never"; } }, service, path, "org.freedesktop.DBus.Properties", "Get", "xyz.openbmc_project.Logging.Settings", "QuiesceOnHwError"); }, "xyz.openbmc_project.ObjectMapper", "/xyz/openbmc_project/object_mapper", "xyz.openbmc_project.ObjectMapper", "GetSubTree", "/", 0, std::array<const char*, 1>{"xyz.openbmc_project.Logging.Settings"}); } /** * @brief Get TrustedModuleRequiredToBoot property. Determines whether or not * TPM is required for booting the host. * * @param[in] aResp Shared pointer for generating response message. * * @return None. */ inline void getTrustedModuleRequiredToBoot( const std::shared_ptr<bmcweb::AsyncResp>& aResp) { BMCWEB_LOG_DEBUG << "Get TPM required to boot."; crow::connections::systemBus->async_method_call( [aResp]( const boost::system::error_code ec, std::vector<std::pair< std::string, std::vector<std::pair<std::string, std::vector<std::string>>>>>& subtree) { if (ec) { BMCWEB_LOG_DEBUG << "DBUS response error on TPM.Policy GetSubTree" << ec; // This is an optional D-Bus object so just return if // error occurs return; } if (subtree.size() == 0) { // As noted above, this is an optional interface so just return // if there is no instance found return; } /* When there is more than one TPMEnable object... */ if (subtree.size() > 1) { BMCWEB_LOG_DEBUG << "DBUS response has more than 1 TPM Enable object:" << subtree.size(); // Throw an internal Error and return messages::internalError(aResp->res); return; } // Make sure the Dbus response map has a service and objectPath // field if (subtree[0].first.empty() || subtree[0].second.size() != 1) { BMCWEB_LOG_DEBUG << "TPM.Policy mapper error!"; messages::internalError(aResp->res); return; } const std::string& path = subtree[0].first; const std::string& serv = subtree[0].second.begin()->first; // Valid TPM Enable object found, now reading the current value crow::connections::systemBus->async_method_call( [aResp](const boost::system::error_code ec, std::variant<bool>& tpmRequired) { if (ec) { BMCWEB_LOG_DEBUG << "D-BUS response error on TPM.Policy Get" << ec; messages::internalError(aResp->res); return; } const bool* tpmRequiredVal = std::get_if<bool>(&tpmRequired); if (!tpmRequiredVal) { messages::internalError(aResp->res); return; } if (*tpmRequiredVal == true) { aResp->res .jsonValue["Boot"]["TrustedModuleRequiredToBoot"] = "Required"; } else { aResp->res .jsonValue["Boot"]["TrustedModuleRequiredToBoot"] = "Disabled"; } }, serv, path, "org.freedesktop.DBus.Properties", "Get", "xyz.openbmc_project.Control.TPM.Policy", "TPMEnable"); }, "xyz.openbmc_project.ObjectMapper", "/xyz/openbmc_project/object_mapper", "xyz.openbmc_project.ObjectMapper", "GetSubTree", "/", int32_t(0), std::array<const char*, 1>{"xyz.openbmc_project.Control.TPM.Policy"}); } /** * @brief Set TrustedModuleRequiredToBoot property. Determines whether or not * TPM is required for booting the host. * * @param[in] aResp Shared pointer for generating response message. * @param[in] tpmRequired Value to set TPM Required To Boot property to. * * @return None. */ inline void setTrustedModuleRequiredToBoot( const std::shared_ptr<bmcweb::AsyncResp>& aResp, const bool tpmRequired) { BMCWEB_LOG_DEBUG << "Set TrustedModuleRequiredToBoot."; crow::connections::systemBus->async_method_call( [aResp, tpmRequired]( const boost::system::error_code ec, std::vector<std::pair< std::string, std::vector<std::pair<std::string, std::vector<std::string>>>>>& subtree) { if (ec) { BMCWEB_LOG_DEBUG << "DBUS response error on TPM.Policy GetSubTree" << ec; messages::internalError(aResp->res); return; } if (subtree.size() == 0) { messages::propertyValueNotInList(aResp->res, "ComputerSystem", "TrustedModuleRequiredToBoot"); return; } /* When there is more than one TPMEnable object... */ if (subtree.size() > 1) { BMCWEB_LOG_DEBUG << "DBUS response has more than 1 TPM Enable object:" << subtree.size(); // Throw an internal Error and return messages::internalError(aResp->res); return; } // Make sure the Dbus response map has a service and objectPath // field if (subtree[0].first.empty() || subtree[0].second.size() != 1) { BMCWEB_LOG_DEBUG << "TPM.Policy mapper error!"; messages::internalError(aResp->res); return; } const std::string& path = subtree[0].first; const std::string& serv = subtree[0].second.begin()->first; if (serv.empty()) { BMCWEB_LOG_DEBUG << "TPM.Policy service mapper error!"; messages::internalError(aResp->res); return; } // Valid TPM Enable object found, now setting the value crow::connections::systemBus->async_method_call( [aResp](const boost::system::error_code ec) { if (ec) { BMCWEB_LOG_DEBUG << "DBUS response error: Set " "TrustedModuleRequiredToBoot" << ec; messages::internalError(aResp->res); return; } BMCWEB_LOG_DEBUG << "Set TrustedModuleRequiredToBoot done."; }, serv, path, "org.freedesktop.DBus.Properties", "Set", "xyz.openbmc_project.Control.TPM.Policy", "TPMEnable", std::variant<bool>(tpmRequired)); }, "xyz.openbmc_project.ObjectMapper", "/xyz/openbmc_project/object_mapper", "xyz.openbmc_project.ObjectMapper", "GetSubTree", "/", int32_t(0), std::array<const char*, 1>{"xyz.openbmc_project.Control.TPM.Policy"}); } /** * @brief Sets AssetTag * * @param[in] aResp Shared pointer for generating response message. * @param[in] assetTag "AssetTag" from request. * * @return None. */ inline void setAssetTag(const std::shared_ptr<bmcweb::AsyncResp>& aResp, const std::string& assetTag) { crow::connections::systemBus->async_method_call( [aResp, assetTag]( const boost::system::error_code ec, const std::vector<std::pair< std::string, std::vector<std::pair<std::string, std::vector<std::string>>>>>& subtree) { if (ec) { BMCWEB_LOG_DEBUG << "D-Bus response error on GetSubTree " << ec; messages::internalError(aResp->res); return; } if (subtree.size() == 0) { BMCWEB_LOG_DEBUG << "Can't find system D-Bus object!"; messages::internalError(aResp->res); return; } // Assume only 1 system D-Bus object // Throw an error if there is more than 1 if (subtree.size() > 1) { BMCWEB_LOG_DEBUG << "Found more than 1 system D-Bus object!"; messages::internalError(aResp->res); return; } if (subtree[0].first.empty() || subtree[0].second.size() != 1) { BMCWEB_LOG_DEBUG << "Asset Tag Set mapper error!"; messages::internalError(aResp->res); return; } const std::string& path = subtree[0].first; const std::string& service = subtree[0].second.begin()->first; if (service.empty()) { BMCWEB_LOG_DEBUG << "Asset Tag Set service mapper error!"; messages::internalError(aResp->res); return; } crow::connections::systemBus->async_method_call( [aResp](const boost::system::error_code ec2) { if (ec2) { BMCWEB_LOG_DEBUG << "D-Bus response error on AssetTag Set " << ec2; messages::internalError(aResp->res); return; } }, service, path, "org.freedesktop.DBus.Properties", "Set", "xyz.openbmc_project.Inventory.Decorator.AssetTag", "AssetTag", std::variant<std::string>(assetTag)); }, "xyz.openbmc_project.ObjectMapper", "/xyz/openbmc_project/object_mapper", "xyz.openbmc_project.ObjectMapper", "GetSubTree", "/xyz/openbmc_project/inventory", int32_t(0), std::array<const char*, 1>{ "xyz.openbmc_project.Inventory.Item.System"}); } /** * @brief Validate the specified stopBootOnFault is valid and return the * stopBootOnFault name associated with that string * * @param[in] aResp Shared pointer for generating response message. * @param[in] stopBootOnFaultString String representing the desired * stopBootOnFault * * @return stopBootOnFault value or empty if incoming value is not valid */ inline std::optional<bool> validstopBootOnFault(const std::string& stopBootOnFaultString) { std::optional<bool> validstopBootEnabled; if (stopBootOnFaultString == "AnyFault") { return true; } if (stopBootOnFaultString == "Never") { return false; } return std::nullopt; } /** * @brief Sets stopBootOnFault * * @param[in] aResp Shared pointer for generating response message. * @param[in] stopBootOnFault "StopBootOnFault" from request. * * @return None. */ inline void setStopBootOnFault(const std::shared_ptr<bmcweb::AsyncResp>& aResp, const std::string& stopBootOnFault) { BMCWEB_LOG_DEBUG << "Set Stop Boot On Fault."; std::optional<bool> stopBootEnabled = validstopBootOnFault(stopBootOnFault); if (!stopBootEnabled) { return; } bool autoStopBootEnabled = *stopBootEnabled; crow::connections::systemBus->async_method_call( [aResp, autoStopBootEnabled]( const boost::system::error_code ec, const std::vector<std::pair< std::string, std::vector<std::pair<std::string, std::vector<std::string>>>>>& subtree) { if (ec) { BMCWEB_LOG_DEBUG << "DBUS response error on StopBootOnFault GetSubTree " << ec; messages::internalError(aResp->res); return; } if (subtree.size() == 0) { messages::propertyValueNotInList(aResp->res, "ComputerSystem", "StopBootOnFault"); return; } if (subtree.size() > 1) { // More then one StopBootOnFault object is not supported and is // an error BMCWEB_LOG_DEBUG << "Found more than 1 system D-Bus " "StopBootOnFault objects: " << subtree.size(); messages::internalError(aResp->res); return; } if (subtree[0].first.empty() || subtree[0].second.size() != 1) { BMCWEB_LOG_DEBUG << "StopBootOnFault mapper error!"; messages::internalError(aResp->res); return; } const std::string& path = subtree[0].first; const std::string& service = subtree[0].second.begin()->first; if (service.empty()) { BMCWEB_LOG_DEBUG << "StopBootOnFault service mapper error!"; messages::internalError(aResp->res); return; } crow::connections::systemBus->async_method_call( [aResp](const boost::system::error_code ec) { if (ec) { messages::internalError(aResp->res); return; } }, service, path, "org.freedesktop.DBus.Properties", "Set", "xyz.openbmc_project.Logging.Settings", "QuiesceOnHwError", std::variant<bool>(autoStopBootEnabled)); }, "xyz.openbmc_project.ObjectMapper", "/xyz/openbmc_project/object_mapper", "xyz.openbmc_project.ObjectMapper", "GetSubTree", "/", 0, std::array<const char*, 1>{"xyz.openbmc_project.Logging.Settings"}); } /** * @brief Sets automaticRetry (Auto Reboot) * * @param[in] aResp Shared pointer for generating response message. * @param[in] automaticRetryConfig "AutomaticRetryConfig" from request. * * @return None. */ inline void setAutomaticRetry(const std::shared_ptr<bmcweb::AsyncResp>& aResp, const std::string& automaticRetryConfig) { BMCWEB_LOG_DEBUG << "Set Automatic Retry."; // OpenBMC only supports "Disabled" and "RetryAttempts". bool autoRebootEnabled; if (automaticRetryConfig == "Disabled") { autoRebootEnabled = false; } else if (automaticRetryConfig == "RetryAttempts") { autoRebootEnabled = true; } else { BMCWEB_LOG_DEBUG << "Invalid property value for " "AutomaticRetryConfig: " << automaticRetryConfig; messages::propertyValueNotInList(aResp->res, automaticRetryConfig, "AutomaticRetryConfig"); return; } crow::connections::systemBus->async_method_call( [aResp](const boost::system::error_code ec) { if (ec) { messages::internalError(aResp->res); return; } }, "xyz.openbmc_project.Settings", "/xyz/openbmc_project/control/host0/auto_reboot", "org.freedesktop.DBus.Properties", "Set", "xyz.openbmc_project.Control.Boot.RebootPolicy", "AutoReboot", std::variant<bool>(autoRebootEnabled)); } /** * @brief Sets power restore policy properties. * * @param[in] aResp Shared pointer for generating response message. * @param[in] policy power restore policy properties from request. * * @return None. */ inline void setPowerRestorePolicy(const std::shared_ptr<bmcweb::AsyncResp>& aResp, const std::string& policy) { BMCWEB_LOG_DEBUG << "Set power restore policy."; const boost::container::flat_map<std::string, std::string> policyMaps = { {"AlwaysOn", "xyz.openbmc_project.Control.Power.RestorePolicy.Policy." "AlwaysOn"}, {"AlwaysOff", "xyz.openbmc_project.Control.Power.RestorePolicy.Policy." "AlwaysOff"}, {"LastState", "xyz.openbmc_project.Control.Power.RestorePolicy.Policy." "Restore"}}; std::string powerRestorPolicy; auto policyMapsIt = policyMaps.find(policy); if (policyMapsIt == policyMaps.end()) { messages::propertyValueNotInList(aResp->res, policy, "PowerRestorePolicy"); return; } powerRestorPolicy = policyMapsIt->second; crow::connections::systemBus->async_method_call( [aResp](const boost::system::error_code ec) { if (ec) { messages::internalError(aResp->res); return; } }, "xyz.openbmc_project.Settings", "/xyz/openbmc_project/control/host0/power_restore_policy", "org.freedesktop.DBus.Properties", "Set", "xyz.openbmc_project.Control.Power.RestorePolicy", "PowerRestorePolicy", std::variant<std::string>(powerRestorPolicy)); } #ifdef BMCWEB_ENABLE_REDFISH_PROVISIONING_FEATURE /** * @brief Retrieves provisioning status * * @param[in] aResp Shared pointer for completing asynchronous calls. * * @return None. */ inline void getProvisioningStatus(std::shared_ptr<bmcweb::AsyncResp> aResp) { BMCWEB_LOG_DEBUG << "Get OEM information."; crow::connections::systemBus->async_method_call( [aResp](const boost::system::error_code ec, const std::vector<std::pair<std::string, VariantType>>& propertiesList) { nlohmann::json& oemPFR = aResp->res.jsonValue["Oem"]["OpenBmc"]["FirmwareProvisioning"]; aResp->res.jsonValue["Oem"]["OpenBmc"]["@odata.type"] = "#OemComputerSystem.OpenBmc"; oemPFR["@odata.type"] = "#OemComputerSystem.FirmwareProvisioning"; if (ec) { BMCWEB_LOG_DEBUG << "DBUS response error " << ec; // not an error, don't have to have the interface oemPFR["ProvisioningStatus"] = "NotProvisioned"; return; } const bool* provState = nullptr; const bool* lockState = nullptr; for (const std::pair<std::string, VariantType>& property : propertiesList) { if (property.first == "UfmProvisioned") { provState = std::get_if<bool>(&property.second); } else if (property.first == "UfmLocked") { lockState = std::get_if<bool>(&property.second); } } if ((provState == nullptr) || (lockState == nullptr)) { BMCWEB_LOG_DEBUG << "Unable to get PFR attributes."; messages::internalError(aResp->res); return; } if (*provState == true) { if (*lockState == true) { oemPFR["ProvisioningStatus"] = "ProvisionedAndLocked"; } else { oemPFR["ProvisioningStatus"] = "ProvisionedButNotLocked"; } } else { oemPFR["ProvisioningStatus"] = "NotProvisioned"; } }, "xyz.openbmc_project.PFR.Manager", "/xyz/openbmc_project/pfr", "org.freedesktop.DBus.Properties", "GetAll", "xyz.openbmc_project.PFR.Attributes"); } #endif /** * @brief Translate the PowerMode to a response message. * * @param[in] aResp Shared pointer for generating response message. * @param[in] modeValue PowerMode value to be translated * * @return None. */ inline void translatePowerMode(const std::shared_ptr<bmcweb::AsyncResp>& aResp, const std::string& modeValue) { std::string modeString; if (modeValue == "xyz.openbmc_project.Control.Power.Mode." "PowerMode.Static") { aResp->res.jsonValue["PowerMode"] = "Static"; } else if (modeValue == "xyz.openbmc_project.Control.Power.Mode." "PowerMode.MaximumPerformance") { aResp->res.jsonValue["PowerMode"] = "MaximumPerformance"; } else if (modeValue == "xyz.openbmc_project.Control.Power.Mode." "PowerMode.PowerSaving") { aResp->res.jsonValue["PowerMode"] = "PowerSaving"; } else if (modeValue == "xyz.openbmc_project.Control.Power.Mode." "PowerMode.OEM") { aResp->res.jsonValue["PowerMode"] = "OEM"; } else { // Any other values would be invalid BMCWEB_LOG_DEBUG << "PowerMode value was not valid: " << modeValue; messages::internalError(aResp->res); } } /** * @brief Retrieves system power mode * * @param[in] aResp Shared pointer for generating response message. * * @return None. */ inline void getPowerMode(const std::shared_ptr<bmcweb::AsyncResp>& aResp) { BMCWEB_LOG_DEBUG << "Get power mode."; // Get Power Mode object path: crow::connections::systemBus->async_method_call( [aResp]( const boost::system::error_code ec, const std::vector<std::pair< std::string, std::vector<std::pair<std::string, std::vector<std::string>>>>>& subtree) { if (ec) { BMCWEB_LOG_DEBUG << "DBUS response error on Power.Mode GetSubTree " << ec; // This is an optional D-Bus object so just return if // error occurs return; } if (subtree.empty()) { // As noted above, this is an optional interface so just return // if there is no instance found return; } if (subtree.size() > 1) { // More then one PowerMode object is not supported and is an // error BMCWEB_LOG_DEBUG << "Found more than 1 system D-Bus Power.Mode objects: " << subtree.size(); messages::internalError(aResp->res); return; } if ((subtree[0].first.empty()) || (subtree[0].second.size() != 1)) { BMCWEB_LOG_DEBUG << "Power.Mode mapper error!"; messages::internalError(aResp->res); return; } const std::string& path = subtree[0].first; const std::string& service = subtree[0].second.begin()->first; if (service.empty()) { BMCWEB_LOG_DEBUG << "Power.Mode service mapper error!"; messages::internalError(aResp->res); return; } // Valid Power Mode object found, now read the current value crow::connections::systemBus->async_method_call( [aResp](const boost::system::error_code ec, const std::variant<std::string>& pmode) { if (ec) { BMCWEB_LOG_DEBUG << "DBUS response error on PowerMode Get: " << ec; messages::internalError(aResp->res); return; } const std::string* s = std::get_if<std::string>(&pmode); if (s == nullptr) { BMCWEB_LOG_DEBUG << "Unable to get PowerMode value"; messages::internalError(aResp->res); return; } aResp->res.jsonValue["PowerMode@Redfish.AllowableValues"] = {"Static", "MaximumPerformance", "PowerSaving"}; BMCWEB_LOG_DEBUG << "Current power mode: " << *s; translatePowerMode(aResp, *s); }, service, path, "org.freedesktop.DBus.Properties", "Get", "xyz.openbmc_project.Control.Power.Mode", "PowerMode"); }, "xyz.openbmc_project.ObjectMapper", "/xyz/openbmc_project/object_mapper", "xyz.openbmc_project.ObjectMapper", "GetSubTree", "/", int32_t(0), std::array<const char*, 1>{"xyz.openbmc_project.Control.Power.Mode"}); } /** * @brief Validate the specified mode is valid and return the PowerMode * name associated with that string * * @param[in] aResp Shared pointer for generating response message. * @param[in] modeString String representing the desired PowerMode * * @return PowerMode value or empty string if mode is not valid */ inline std::string validatePowerMode(const std::shared_ptr<bmcweb::AsyncResp>& aResp, const std::string& modeString) { std::string mode; if (modeString == "Static") { mode = "xyz.openbmc_project.Control.Power.Mode.PowerMode.Static"; } else if (modeString == "MaximumPerformance") { mode = "xyz.openbmc_project.Control.Power.Mode.PowerMode." "MaximumPerformance"; } else if (modeString == "PowerSaving") { mode = "xyz.openbmc_project.Control.Power.Mode.PowerMode.PowerSaving"; } else { messages::propertyValueNotInList(aResp->res, modeString, "PowerMode"); } return mode; } /** * @brief Sets system power mode. * * @param[in] aResp Shared pointer for generating response message. * @param[in] pmode System power mode from request. * * @return None. */ inline void setPowerMode(const std::shared_ptr<bmcweb::AsyncResp>& aResp, const std::string& pmode) { BMCWEB_LOG_DEBUG << "Set power mode."; std::string powerMode = validatePowerMode(aResp, pmode); if (powerMode.empty()) { return; } // Get Power Mode object path: crow::connections::systemBus->async_method_call( [aResp, powerMode]( const boost::system::error_code ec, const std::vector<std::pair< std::string, std::vector<std::pair<std::string, std::vector<std::string>>>>>& subtree) { if (ec) { BMCWEB_LOG_DEBUG << "DBUS response error on Power.Mode GetSubTree " << ec; // This is an optional D-Bus object, but user attempted to patch messages::internalError(aResp->res); return; } if (subtree.empty()) { // This is an optional D-Bus object, but user attempted to patch messages::resourceNotFound(aResp->res, "ComputerSystem", "PowerMode"); return; } if (subtree.size() > 1) { // More then one PowerMode object is not supported and is an // error BMCWEB_LOG_DEBUG << "Found more than 1 system D-Bus Power.Mode objects: " << subtree.size(); messages::internalError(aResp->res); return; } if ((subtree[0].first.empty()) || (subtree[0].second.size() != 1)) { BMCWEB_LOG_DEBUG << "Power.Mode mapper error!"; messages::internalError(aResp->res); return; } const std::string& path = subtree[0].first; const std::string& service = subtree[0].second.begin()->first; if (service.empty()) { BMCWEB_LOG_DEBUG << "Power.Mode service mapper error!"; messages::internalError(aResp->res); return; } BMCWEB_LOG_DEBUG << "Setting power mode(" << powerMode << ") -> " << path; // Set the Power Mode property crow::connections::systemBus->async_method_call( [aResp](const boost::system::error_code ec) { if (ec) { messages::internalError(aResp->res); return; } }, service, path, "org.freedesktop.DBus.Properties", "Set", "xyz.openbmc_project.Control.Power.Mode", "PowerMode", std::variant<std::string>(powerMode)); }, "xyz.openbmc_project.ObjectMapper", "/xyz/openbmc_project/object_mapper", "xyz.openbmc_project.ObjectMapper", "GetSubTree", "/", int32_t(0), std::array<const char*, 1>{"xyz.openbmc_project.Control.Power.Mode"}); } /** * @brief Translates watchdog timeout action DBUS property value to redfish. * * @param[in] dbusAction The watchdog timeout action in D-BUS. * * @return Returns as a string, the timeout action in Redfish terms. If * translation cannot be done, returns an empty string. */ inline std::string dbusToRfWatchdogAction(const std::string& dbusAction) { if (dbusAction == "xyz.openbmc_project.State.Watchdog.Action.None") { return "None"; } if (dbusAction == "xyz.openbmc_project.State.Watchdog.Action.HardReset") { return "ResetSystem"; } if (dbusAction == "xyz.openbmc_project.State.Watchdog.Action.PowerOff") { return "PowerDown"; } if (dbusAction == "xyz.openbmc_project.State.Watchdog.Action.PowerCycle") { return "PowerCycle"; } return ""; } /** *@brief Translates timeout action from Redfish to DBUS property value. * *@param[in] rfAction The timeout action in Redfish. * *@return Returns as a string, the time_out action as expected by DBUS. *If translation cannot be done, returns an empty string. */ inline std::string rfToDbusWDTTimeOutAct(const std::string& rfAction) { if (rfAction == "None") { return "xyz.openbmc_project.State.Watchdog.Action.None"; } if (rfAction == "PowerCycle") { return "xyz.openbmc_project.State.Watchdog.Action.PowerCycle"; } if (rfAction == "PowerDown") { return "xyz.openbmc_project.State.Watchdog.Action.PowerOff"; } if (rfAction == "ResetSystem") { return "xyz.openbmc_project.State.Watchdog.Action.HardReset"; } return ""; } /** * @brief Retrieves host watchdog timer properties over DBUS * * @param[in] aResp Shared pointer for completing asynchronous calls. * * @return None. */ inline void getHostWatchdogTimer(const std::shared_ptr<bmcweb::AsyncResp>& aResp) { BMCWEB_LOG_DEBUG << "Get host watchodg"; crow::connections::systemBus->async_method_call( [aResp](const boost::system::error_code ec, PropertiesType& properties) { if (ec) { // watchdog service is stopped BMCWEB_LOG_DEBUG << "DBUS response error " << ec; return; } BMCWEB_LOG_DEBUG << "Got " << properties.size() << " wdt prop."; nlohmann::json& hostWatchdogTimer = aResp->res.jsonValue["HostWatchdogTimer"]; // watchdog service is running/enabled hostWatchdogTimer["Status"]["State"] = "Enabled"; for (const auto& property : properties) { BMCWEB_LOG_DEBUG << "prop=" << property.first; if (property.first == "Enabled") { const bool* state = std::get_if<bool>(&property.second); if (!state) { messages::internalError(aResp->res); return; } hostWatchdogTimer["FunctionEnabled"] = *state; } else if (property.first == "ExpireAction") { const std::string* s = std::get_if<std::string>(&property.second); if (!s) { messages::internalError(aResp->res); return; } std::string action = dbusToRfWatchdogAction(*s); if (action.empty()) { messages::internalError(aResp->res); return; } hostWatchdogTimer["TimeoutAction"] = action; } } }, "xyz.openbmc_project.Watchdog", "/xyz/openbmc_project/watchdog/host0", "org.freedesktop.DBus.Properties", "GetAll", "xyz.openbmc_project.State.Watchdog"); } /** * @brief Sets Host WatchDog Timer properties. * * @param[in] aResp Shared pointer for generating response message. * @param[in] wdtEnable The WDTimer Enable value (true/false) from incoming * RF request. * @param[in] wdtTimeOutAction The WDT Timeout action, from incoming RF request. * * @return None. */ inline void setWDTProperties(const std::shared_ptr<bmcweb::AsyncResp>& aResp, const std::optional<bool> wdtEnable, const std::optional<std::string>& wdtTimeOutAction) { BMCWEB_LOG_DEBUG << "Set host watchdog"; if (wdtTimeOutAction) { std::string wdtTimeOutActStr = rfToDbusWDTTimeOutAct(*wdtTimeOutAction); // check if TimeOut Action is Valid if (wdtTimeOutActStr.empty()) { BMCWEB_LOG_DEBUG << "Unsupported value for TimeoutAction: " << *wdtTimeOutAction; messages::propertyValueNotInList(aResp->res, *wdtTimeOutAction, "TimeoutAction"); return; } crow::connections::systemBus->async_method_call( [aResp](const boost::system::error_code ec) { if (ec) { BMCWEB_LOG_DEBUG << "DBUS response error " << ec; messages::internalError(aResp->res); return; } }, "xyz.openbmc_project.Watchdog", "/xyz/openbmc_project/watchdog/host0", "org.freedesktop.DBus.Properties", "Set", "xyz.openbmc_project.State.Watchdog", "ExpireAction", std::variant<std::string>(wdtTimeOutActStr)); } if (wdtEnable) { crow::connections::systemBus->async_method_call( [aResp](const boost::system::error_code ec) { if (ec) { BMCWEB_LOG_DEBUG << "DBUS response error " << ec; messages::internalError(aResp->res); return; } }, "xyz.openbmc_project.Watchdog", "/xyz/openbmc_project/watchdog/host0", "org.freedesktop.DBus.Properties", "Set", "xyz.openbmc_project.State.Watchdog", "Enabled", std::variant<bool>(*wdtEnable)); } } using ipsPropertiesType = std::vector<std::pair<std::string, dbus::utility::DbusVariantType>>; /** * @brief Parse the Idle Power Saver properties into json * * @param[in] aResp Shared pointer for completing asynchronous calls. * @param[in] properties IPS property data from DBus. * * @return true if successful */ bool parseIpsProperties(const std::shared_ptr<bmcweb::AsyncResp>& aResp, ipsPropertiesType& properties) { for (const auto& property : properties) { if (property.first == "Enabled") { const bool* state = std::get_if<bool>(&property.second); if (!state) { return false; } aResp->res.jsonValue["IdlePowerSaver"][property.first] = *state; } else if (property.first == "EnterUtilizationPercent") { const uint8_t* util = std::get_if<uint8_t>(&property.second); if (!util) { return false; } aResp->res.jsonValue["IdlePowerSaver"][property.first] = *util; } else if (property.first == "EnterDwellTime") { // Convert Dbus time from milliseconds to seconds const uint64_t* timeMilliseconds = std::get_if<uint64_t>(&property.second); if (!timeMilliseconds) { return false; } const std::chrono::duration<uint64_t, std::milli> ms( *timeMilliseconds); aResp->res.jsonValue["IdlePowerSaver"]["EnterDwellTimeSeconds"] = std::chrono::duration_cast<std::chrono::duration<uint64_t>>(ms) .count(); } else if (property.first == "ExitUtilizationPercent") { const uint8_t* util = std::get_if<uint8_t>(&property.second); if (!util) { return false; } aResp->res.jsonValue["IdlePowerSaver"][property.first] = *util; } else if (property.first == "ExitDwellTime") { // Convert Dbus time from milliseconds to seconds const uint64_t* timeMilliseconds = std::get_if<uint64_t>(&property.second); if (!timeMilliseconds) { return false; } const std::chrono::duration<uint64_t, std::milli> ms( *timeMilliseconds); aResp->res.jsonValue["IdlePowerSaver"]["ExitDwellTimeSeconds"] = std::chrono::duration_cast<std::chrono::duration<uint64_t>>(ms) .count(); } else { BMCWEB_LOG_WARNING << "Unexpected IdlePowerSaver property: " << property.first; } } return true; } /** * @brief Retrieves host watchdog timer properties over DBUS * * @param[in] aResp Shared pointer for completing asynchronous calls. * * @return None. */ inline void getIdlePowerSaver(const std::shared_ptr<bmcweb::AsyncResp>& aResp) { BMCWEB_LOG_DEBUG << "Get idle power saver parameters"; // Get IdlePowerSaver object path: crow::connections::systemBus->async_method_call( [aResp]( const boost::system::error_code ec, const std::vector<std::pair< std::string, std::vector<std::pair<std::string, std::vector<std::string>>>>>& subtree) { if (ec) { BMCWEB_LOG_DEBUG << "DBUS response error on Power.IdlePowerSaver GetSubTree " << ec; messages::internalError(aResp->res); return; } if (subtree.empty()) { // This is an optional interface so just return // if there is no instance found BMCWEB_LOG_DEBUG << "No instances found"; return; } if (subtree.size() > 1) { // More then one PowerIdlePowerSaver object is not supported and // is an error BMCWEB_LOG_DEBUG << "Found more than 1 system D-Bus " "Power.IdlePowerSaver objects: " << subtree.size(); messages::internalError(aResp->res); return; } if ((subtree[0].first.empty()) || (subtree[0].second.size() != 1)) { BMCWEB_LOG_DEBUG << "Power.IdlePowerSaver mapper error!"; messages::internalError(aResp->res); return; } const std::string& path = subtree[0].first; const std::string& service = subtree[0].second.begin()->first; if (service.empty()) { BMCWEB_LOG_DEBUG << "Power.IdlePowerSaver service mapper error!"; messages::internalError(aResp->res); return; } // Valid IdlePowerSaver object found, now read the current values crow::connections::systemBus->async_method_call( [aResp](const boost::system::error_code ec, ipsPropertiesType& properties) { if (ec) { BMCWEB_LOG_ERROR << "DBUS response error on IdlePowerSaver GetAll: " << ec; messages::internalError(aResp->res); return; } if (parseIpsProperties(aResp, properties) == false) { messages::internalError(aResp->res); return; } }, service, path, "org.freedesktop.DBus.Properties", "GetAll", "xyz.openbmc_project.Control.Power.IdlePowerSaver"); }, "xyz.openbmc_project.ObjectMapper", "/xyz/openbmc_project/object_mapper", "xyz.openbmc_project.ObjectMapper", "GetSubTree", "/", int32_t(0), std::array<const char*, 1>{ "xyz.openbmc_project.Control.Power.IdlePowerSaver"}); BMCWEB_LOG_DEBUG << "EXIT: Get idle power saver parameters"; } /** * @brief Sets Idle Power Saver properties. * * @param[in] aResp Shared pointer for generating response message. * @param[in] ipsEnable The IPS Enable value (true/false) from incoming * RF request. * @param[in] ipsEnterUtil The utilization limit to enter idle state. * @param[in] ipsEnterTime The time the utilization must be below ipsEnterUtil * before entering idle state. * @param[in] ipsExitUtil The utilization limit when exiting idle state. * @param[in] ipsExitTime The time the utilization must be above ipsExutUtil * before exiting idle state * * @return None. */ inline void setIdlePowerSaver(const std::shared_ptr<bmcweb::AsyncResp>& aResp, const std::optional<bool> ipsEnable, const std::optional<uint8_t> ipsEnterUtil, const std::optional<uint64_t> ipsEnterTime, const std::optional<uint8_t> ipsExitUtil, const std::optional<uint64_t> ipsExitTime) { BMCWEB_LOG_DEBUG << "Set idle power saver properties"; // Get IdlePowerSaver object path: crow::connections::systemBus->async_method_call( [aResp, ipsEnable, ipsEnterUtil, ipsEnterTime, ipsExitUtil, ipsExitTime]( const boost::system::error_code ec, const std::vector<std::pair< std::string, std::vector<std::pair<std::string, std::vector<std::string>>>>>& subtree) { if (ec) { BMCWEB_LOG_DEBUG << "DBUS response error on Power.IdlePowerSaver GetSubTree " << ec; messages::internalError(aResp->res); return; } if (subtree.empty()) { // This is an optional D-Bus object, but user attempted to patch messages::resourceNotFound(aResp->res, "ComputerSystem", "IdlePowerSaver"); return; } if (subtree.size() > 1) { // More then one PowerIdlePowerSaver object is not supported and // is an error BMCWEB_LOG_DEBUG << "Found more than 1 system D-Bus " "Power.IdlePowerSaver objects: " << subtree.size(); messages::internalError(aResp->res); return; } if ((subtree[0].first.empty()) || (subtree[0].second.size() != 1)) { BMCWEB_LOG_DEBUG << "Power.IdlePowerSaver mapper error!"; messages::internalError(aResp->res); return; } const std::string& path = subtree[0].first; const std::string& service = subtree[0].second.begin()->first; if (service.empty()) { BMCWEB_LOG_DEBUG << "Power.IdlePowerSaver service mapper error!"; messages::internalError(aResp->res); return; } // Valid Power IdlePowerSaver object found, now set any values that // need to be updated if (ipsEnable) { crow::connections::systemBus->async_method_call( [aResp](const boost::system::error_code ec) { if (ec) { BMCWEB_LOG_DEBUG << "DBUS response error " << ec; messages::internalError(aResp->res); return; } }, service, path, "org.freedesktop.DBus.Properties", "Set", "xyz.openbmc_project.Control.Power.IdlePowerSaver", "Enabled", std::variant<bool>(*ipsEnable)); } if (ipsEnterUtil) { crow::connections::systemBus->async_method_call( [aResp](const boost::system::error_code ec) { if (ec) { BMCWEB_LOG_DEBUG << "DBUS response error " << ec; messages::internalError(aResp->res); return; } }, service, path, "org.freedesktop.DBus.Properties", "Set", "xyz.openbmc_project.Control.Power.IdlePowerSaver", "EnterUtilizationPercent", std::variant<uint8_t>(*ipsEnterUtil)); } if (ipsEnterTime) { // Convert from seconds into milliseconds for DBus const uint64_t timeMilliseconds = *ipsEnterTime * 1000; crow::connections::systemBus->async_method_call( [aResp](const boost::system::error_code ec) { if (ec) { BMCWEB_LOG_DEBUG << "DBUS response error " << ec; messages::internalError(aResp->res); return; } }, service, path, "org.freedesktop.DBus.Properties", "Set", "xyz.openbmc_project.Control.Power.IdlePowerSaver", "EnterDwellTime", std::variant<uint64_t>(timeMilliseconds)); } if (ipsExitUtil) { crow::connections::systemBus->async_method_call( [aResp](const boost::system::error_code ec) { if (ec) { BMCWEB_LOG_DEBUG << "DBUS response error " << ec; messages::internalError(aResp->res); return; } }, service, path, "org.freedesktop.DBus.Properties", "Set", "xyz.openbmc_project.Control.Power.IdlePowerSaver", "ExitUtilizationPercent", std::variant<uint8_t>(*ipsExitUtil)); } if (ipsExitTime) { // Convert from seconds into milliseconds for DBus const uint64_t timeMilliseconds = *ipsExitTime * 1000; crow::connections::systemBus->async_method_call( [aResp](const boost::system::error_code ec) { if (ec) { BMCWEB_LOG_DEBUG << "DBUS response error " << ec; messages::internalError(aResp->res); return; } }, service, path, "org.freedesktop.DBus.Properties", "Set", "xyz.openbmc_project.Control.Power.IdlePowerSaver", "ExitDwellTime", std::variant<uint64_t>(timeMilliseconds)); } }, "xyz.openbmc_project.ObjectMapper", "/xyz/openbmc_project/object_mapper", "xyz.openbmc_project.ObjectMapper", "GetSubTree", "/", int32_t(0), std::array<const char*, 1>{ "xyz.openbmc_project.Control.Power.IdlePowerSaver"}); BMCWEB_LOG_DEBUG << "EXIT: Set idle power saver parameters"; } /** * SystemsCollection derived class for delivering ComputerSystems Collection * Schema */ inline void requestRoutesSystemsCollection(App& app) { BMCWEB_ROUTE(app, "/redfish/v1/Systems/") .privileges(redfish::privileges::getComputerSystemCollection) .methods(boost::beast::http::verb::get)( [](const crow::Request& /*req*/, const std::shared_ptr<bmcweb::AsyncResp>& asyncResp) { asyncResp->res.jsonValue["@odata.type"] = "#ComputerSystemCollection.ComputerSystemCollection"; asyncResp->res.jsonValue["@odata.id"] = "/redfish/v1/Systems"; asyncResp->res.jsonValue["Name"] = "Computer System Collection"; crow::connections::systemBus->async_method_call( [asyncResp](const boost::system::error_code ec, const std::variant<std::string>& /*hostName*/) { nlohmann::json& ifaceArray = asyncResp->res.jsonValue["Members"]; ifaceArray = nlohmann::json::array(); auto& count = asyncResp->res.jsonValue["Members@odata.count"]; ifaceArray.push_back( {{"@odata.id", "/redfish/v1/Systems/system"}}); count = ifaceArray.size(); if (!ec) { BMCWEB_LOG_DEBUG << "Hypervisor is available"; ifaceArray.push_back( {{"@odata.id", "/redfish/v1/Systems/hypervisor"}}); count = ifaceArray.size(); } }, "xyz.openbmc_project.Network.Hypervisor", "/xyz/openbmc_project/network/hypervisor/config", "org.freedesktop.DBus.Properties", "Get", "xyz.openbmc_project.Network.SystemConfiguration", "HostName"); }); } /** * Function transceives data with dbus directly. */ inline void doNMI(const std::shared_ptr<bmcweb::AsyncResp>& asyncResp) { constexpr char const* serviceName = "xyz.openbmc_project.Control.Host.NMI"; constexpr char const* objectPath = "/xyz/openbmc_project/control/host0/nmi"; constexpr char const* interfaceName = "xyz.openbmc_project.Control.Host.NMI"; constexpr char const* method = "NMI"; crow::connections::systemBus->async_method_call( [asyncResp](const boost::system::error_code ec) { if (ec) { BMCWEB_LOG_ERROR << " Bad D-Bus request error: " << ec; messages::internalError(asyncResp->res); return; } messages::success(asyncResp->res); }, serviceName, objectPath, interfaceName, method); } /** * SystemActionsReset class supports handle POST method for Reset action. * The class retrieves and sends data directly to D-Bus. */ inline void requestRoutesSystemActionsReset(App& app) { /** * Function handles POST method request. * Analyzes POST body message before sends Reset request data to D-Bus. */ BMCWEB_ROUTE(app, "/redfish/v1/Systems/system/Actions/ComputerSystem.Reset/") .privileges(redfish::privileges::postComputerSystem) .methods(boost::beast::http::verb::post)( [](const crow::Request& req, const std::shared_ptr<bmcweb::AsyncResp>& asyncResp) { std::string resetType; if (!json_util::readJson(req, asyncResp->res, "ResetType", resetType)) { return; } // Get the command and host vs. chassis std::string command; bool hostCommand; if ((resetType == "On") || (resetType == "ForceOn")) { command = "xyz.openbmc_project.State.Host.Transition.On"; hostCommand = true; } else if (resetType == "ForceOff") { command = "xyz.openbmc_project.State.Chassis.Transition.Off"; hostCommand = false; } else if (resetType == "GracefulShutdown") { command = "xyz.openbmc_project.State.Host.Transition.Off"; hostCommand = true; } else if (resetType == "GracefulRestart") { command = "xyz.openbmc_project.State.Host.Transition." "GracefulWarmReboot"; hostCommand = true; } else if (resetType == "PowerCycle") { command = "xyz.openbmc_project.State.Host.Transition.Reboot"; hostCommand = true; } else if (resetType == "Nmi") { doNMI(asyncResp); return; } else { messages::actionParameterUnknown(asyncResp->res, "Reset", resetType); return; } if (hostCommand) { crow::connections::systemBus->async_method_call( [asyncResp, resetType](const boost::system::error_code ec) { if (ec) { BMCWEB_LOG_ERROR << "D-Bus responses error: " << ec; if (ec.value() == boost::asio::error::invalid_argument) { messages::actionParameterNotSupported( asyncResp->res, resetType, "Reset"); } else { messages::internalError(asyncResp->res); } return; } messages::success(asyncResp->res); }, "xyz.openbmc_project.State.Host", "/xyz/openbmc_project/state/host0", "org.freedesktop.DBus.Properties", "Set", "xyz.openbmc_project.State.Host", "RequestedHostTransition", std::variant<std::string>{command}); } else { crow::connections::systemBus->async_method_call( [asyncResp, resetType](const boost::system::error_code ec) { if (ec) { BMCWEB_LOG_ERROR << "D-Bus responses error: " << ec; if (ec.value() == boost::asio::error::invalid_argument) { messages::actionParameterNotSupported( asyncResp->res, resetType, "Reset"); } else { messages::internalError(asyncResp->res); } return; } messages::success(asyncResp->res); }, "xyz.openbmc_project.State.Chassis", "/xyz/openbmc_project/state/chassis0", "org.freedesktop.DBus.Properties", "Set", "xyz.openbmc_project.State.Chassis", "RequestedPowerTransition", std::variant<std::string>{command}); } }); } /** * Systems derived class for delivering Computer Systems Schema. */ inline void requestRoutesSystems(App& app) { /** * Functions triggers appropriate requests on DBus */ BMCWEB_ROUTE(app, "/redfish/v1/Systems/system/") .privileges(redfish::privileges::getComputerSystem) .methods( boost::beast::http::verb:: get)([](const crow::Request&, const std::shared_ptr<bmcweb::AsyncResp>& asyncResp) { asyncResp->res.jsonValue["@odata.type"] = "#ComputerSystem.v1_16_0.ComputerSystem"; asyncResp->res.jsonValue["Name"] = "system"; asyncResp->res.jsonValue["Id"] = "system"; asyncResp->res.jsonValue["SystemType"] = "Physical"; asyncResp->res.jsonValue["Description"] = "Computer System"; asyncResp->res.jsonValue["ProcessorSummary"]["Count"] = 0; asyncResp->res.jsonValue["ProcessorSummary"]["Status"]["State"] = "Disabled"; asyncResp->res.jsonValue["MemorySummary"]["TotalSystemMemoryGiB"] = uint64_t(0); asyncResp->res.jsonValue["MemorySummary"]["Status"]["State"] = "Disabled"; asyncResp->res.jsonValue["@odata.id"] = "/redfish/v1/Systems/system"; asyncResp->res.jsonValue["Processors"] = { {"@odata.id", "/redfish/v1/Systems/system/Processors"}}; asyncResp->res.jsonValue["Memory"] = { {"@odata.id", "/redfish/v1/Systems/system/Memory"}}; asyncResp->res.jsonValue["Storage"] = { {"@odata.id", "/redfish/v1/Systems/system/Storage"}}; asyncResp->res.jsonValue["Actions"]["#ComputerSystem.Reset"] = { {"target", "/redfish/v1/Systems/system/Actions/ComputerSystem.Reset"}, {"@Redfish.ActionInfo", "/redfish/v1/Systems/system/ResetActionInfo"}}; asyncResp->res.jsonValue["LogServices"] = { {"@odata.id", "/redfish/v1/Systems/system/LogServices"}}; asyncResp->res.jsonValue["Bios"] = { {"@odata.id", "/redfish/v1/Systems/system/Bios"}}; asyncResp->res.jsonValue["Links"]["ManagedBy"] = { {{"@odata.id", "/redfish/v1/Managers/bmc"}}}; asyncResp->res.jsonValue["Status"] = { {"Health", "OK"}, {"State", "Enabled"}, }; // Fill in SerialConsole info asyncResp->res.jsonValue["SerialConsole"]["MaxConcurrentSessions"] = 15; asyncResp->res.jsonValue["SerialConsole"]["IPMI"] = { {"ServiceEnabled", true}, }; // TODO (Gunnar): Should look for obmc-console-ssh@2200.service asyncResp->res.jsonValue["SerialConsole"]["SSH"] = { {"ServiceEnabled", true}, {"Port", 2200}, // https://github.com/openbmc/docs/blob/master/console.md {"HotKeySequenceDisplay", "Press ~. to exit console"}, }; #ifdef BMCWEB_ENABLE_KVM // Fill in GraphicalConsole info asyncResp->res.jsonValue["GraphicalConsole"] = { {"ServiceEnabled", true}, {"MaxConcurrentSessions", 4}, {"ConnectTypesSupported", {"KVMIP"}}, }; #endif // BMCWEB_ENABLE_KVM asyncResp->res.jsonValue["FabricAdapters"] = { {"@odata.id", "/redfish/v1/Systems/system/FabricAdapters"}}; getMainChassisId( asyncResp, [](const std::string& chassisId, const std::shared_ptr<bmcweb::AsyncResp>& aRsp) { aRsp->res.jsonValue["Links"]["Chassis"] = { {{"@odata.id", "/redfish/v1/Chassis/" + chassisId}}}; }); getLocationIndicatorActive(asyncResp); // TODO (Gunnar): Remove IndicatorLED after enough time has passed getIndicatorLedState(asyncResp); getComputerSystem(asyncResp); getHostState(asyncResp); getBootProgress(asyncResp); getPCIeDeviceList(asyncResp, "PCIeDevices"); getHostWatchdogTimer(asyncResp); getPowerRestorePolicy(asyncResp); getStopBootOnFault(asyncResp); getAutomaticRetry(asyncResp); getLastResetTime(asyncResp); #ifdef BMCWEB_ENABLE_IBM_LAMP_TEST getLampTestState(asyncResp); #endif #ifdef BMCWEB_ENABLE_REDFISH_PROVISIONING_FEATURE getProvisioningStatus(asyncResp); #endif getTrustedModuleRequiredToBoot(asyncResp); getPowerMode(asyncResp); getIdlePowerSaver(asyncResp); }); BMCWEB_ROUTE(app, "/redfish/v1/Systems/system/") .privileges(redfish::privileges::patchComputerSystem) .methods(boost::beast::http::verb::patch)( [](const crow::Request& req, const std::shared_ptr<bmcweb::AsyncResp>& asyncResp) { std::optional<bool> locationIndicatorActive; std::optional<std::string> indicatorLed; std::optional<nlohmann::json> bootProps; std::optional<nlohmann::json> wdtTimerProps; std::optional<std::string> assetTag; std::optional<std::string> powerRestorePolicy; std::optional<std::string> powerMode; std::optional<nlohmann::json> oem; std::optional<nlohmann::json> ipsProps; if (!json_util::readJson( req, asyncResp->res, "IndicatorLED", indicatorLed, "LocationIndicatorActive", locationIndicatorActive, "Boot", bootProps, "WatchdogTimer", wdtTimerProps, "PowerRestorePolicy", powerRestorePolicy, "AssetTag", assetTag, "PowerMode", powerMode, "IdlePowerSaver", ipsProps, "Oem", oem)) { return; } asyncResp->res.result(boost::beast::http::status::no_content); if (assetTag) { setAssetTag(asyncResp, *assetTag); } if (wdtTimerProps) { std::optional<bool> wdtEnable; std::optional<std::string> wdtTimeOutAction; if (!json_util::readJson(*wdtTimerProps, asyncResp->res, "FunctionEnabled", wdtEnable, "TimeoutAction", wdtTimeOutAction)) { return; } setWDTProperties(asyncResp, wdtEnable, wdtTimeOutAction); } if (bootProps) { std::optional<std::string> automaticRetryConfig; std::optional<bool> trustedModuleRequiredToBoot; std::optional<std::string> stopBootOnFault; if (!json_util::readJson( *bootProps, asyncResp->res, "AutomaticRetryConfig", automaticRetryConfig, "TrustedModuleRequiredToBoot", trustedModuleRequiredToBoot, "StopBootOnFault", stopBootOnFault)) { return; } if (automaticRetryConfig) { setAutomaticRetry(asyncResp, *automaticRetryConfig); } if (trustedModuleRequiredToBoot) { setTrustedModuleRequiredToBoot( asyncResp, *trustedModuleRequiredToBoot); } if (stopBootOnFault) { setStopBootOnFault(asyncResp, *stopBootOnFault); } } if (locationIndicatorActive) { setLocationIndicatorActive(asyncResp, *locationIndicatorActive); } // TODO (Gunnar): Remove IndicatorLED after enough time has // passed if (indicatorLed) { setIndicatorLedState(asyncResp, *indicatorLed); asyncResp->res.addHeader( boost::beast::http::field::warning, "299 - \"IndicatorLED is deprecated. Use " "LocationIndicatorActive instead.\""); } if (powerRestorePolicy) { setPowerRestorePolicy(asyncResp, *powerRestorePolicy); } if (powerMode) { setPowerMode(asyncResp, *powerMode); } if (oem) { std::optional<nlohmann::json> ibmOem; if (!redfish::json_util::readJson(*oem, asyncResp->res, "IBM", ibmOem)) { return; } if (ibmOem) { std::optional<bool> lampTest; if (!json_util::readJson(*ibmOem, asyncResp->res, "LampTest", lampTest)) { return; } if (lampTest) { #ifdef BMCWEB_ENABLE_IBM_LAMP_TEST setLampTestState(asyncResp, *lampTest); #endif } } } if (ipsProps) { std::optional<bool> ipsEnable; std::optional<uint8_t> ipsEnterUtil; std::optional<uint64_t> ipsEnterTime; std::optional<uint8_t> ipsExitUtil; std::optional<uint64_t> ipsExitTime; if (!json_util::readJson( *ipsProps, asyncResp->res, "Enabled", ipsEnable, "EnterUtilizationPercent", ipsEnterUtil, "EnterDwellTimeSeconds", ipsEnterTime, "ExitUtilizationPercent", ipsExitUtil, "ExitDwellTimeSeconds", ipsExitTime)) { return; } setIdlePowerSaver(asyncResp, ipsEnable, ipsEnterUtil, ipsEnterTime, ipsExitUtil, ipsExitTime); } }); } /** * SystemResetActionInfo derived class for delivering Computer Systems * ResetType AllowableValues using ResetInfo schema. */ inline void requestRoutesSystemResetActionInfo(App& app) { /** * Functions triggers appropriate requests on DBus */ BMCWEB_ROUTE(app, "/redfish/v1/Systems/system/ResetActionInfo/") .privileges(redfish::privileges::getActionInfo) .methods(boost::beast::http::verb::get)( [](const crow::Request&, const std::shared_ptr<bmcweb::AsyncResp>& asyncResp) { asyncResp->res.jsonValue = { {"@odata.type", "#ActionInfo.v1_1_2.ActionInfo"}, {"@odata.id", "/redfish/v1/Systems/system/ResetActionInfo"}, {"Name", "Reset Action Info"}, {"Id", "ResetActionInfo"}, {"Parameters", {{{"Name", "ResetType"}, {"Required", true}, {"DataType", "String"}, {"AllowableValues", {"On", "ForceOff", "ForceOn", "GracefulRestart", "GracefulShutdown", "PowerCycle", "Nmi"}}}}}}; }); } } // namespace redfish
39.185299
165
0.475252
[ "object", "vector", "model" ]
4f829394a0861c2a0af336deee4112e99448d493
9,422
cpp
C++
src/modules/cpu/generator.cpp
gchagnotSpt/openperf
0ae14cb7a685b1b059f707379773fb3bcb421d40
[ "Apache-2.0" ]
null
null
null
src/modules/cpu/generator.cpp
gchagnotSpt/openperf
0ae14cb7a685b1b059f707379773fb3bcb421d40
[ "Apache-2.0" ]
null
null
null
src/modules/cpu/generator.cpp
gchagnotSpt/openperf
0ae14cb7a685b1b059f707379773fb3bcb421d40
[ "Apache-2.0" ]
null
null
null
#include <future> #include "generator.hpp" #include "task_cpu.hpp" #include "task_cpu_system.hpp" #include "config/op_config_file.hpp" #include "framework/core/op_uuid.hpp" #include "framework/core/op_cpuset.h" namespace openperf::cpu::generator { static uint16_t serial_counter = 0; constexpr auto NAME_PREFIX = "op_cpu"; std::optional<double> get_field(const cpu_stat& stat, std::string_view name) { if (name == "timestamp") return stat.available.count(); if (name == "available") return stat.available.count(); if (name == "utilization") return stat.utilization.count(); if (name == "target") return stat.target.count(); if (name == "system") return stat.system.count(); if (name == "user") return stat.user.count(); if (name == "steal") return stat.steal.count(); if (name == "error") return stat.error.count(); // Parse the cores[N] field name constexpr auto prefix = "cores["; auto prefix_size = std::strlen(prefix); if (name.substr(0, prefix_size) == prefix) { auto core_number = std::stoul(std::string(name.substr( prefix_size, name.find_first_of(']', prefix_size) - prefix_size))); if (core_number < stat.cores.size()) { auto field_name = name.substr(name.find_first_of('.', prefix_size) + 1); if (field_name == "available") return stat.cores[core_number].available.count(); if (field_name == "utilization") return stat.cores[core_number].utilization.count(); if (field_name == "target") return stat.cores[core_number].target.count(); if (field_name == "system") return stat.cores[core_number].system.count(); if (field_name == "user") return stat.cores[core_number].user.count(); if (field_name == "steal") return stat.cores[core_number].steal.count(); if (field_name == "error") return stat.cores[core_number].error.count(); // Parse the targest[N] field name constexpr auto target_prefix = "targets["; auto target_prefix_size = std::strlen(target_prefix); if (field_name.substr(0, target_prefix_size) == target_prefix) { auto target_number = std::stoul(std::string(field_name.substr( target_prefix_size, field_name.find_first_of(']', target_prefix_size) - target_prefix_size))); if (target_number < stat.cores[core_number].targets.size()) { auto target_field = field_name.substr( field_name.find_first_of('.', target_prefix_size) + 1); if (target_field == "operations") return stat.cores[core_number] .targets[target_number] .operations; } } } } return std::nullopt; } auto config_mode(double utilization, uint16_t core_count) { if (utilization <= 0 || 100 * core_count < utilization) { throw std::runtime_error("System utilization value " + std::to_string(utilization) + " is not valid. Available values from 0 to " + std::to_string(100 * core_count)); } std::vector<internal::task_cpu_system> tasks; for (uint16_t core = 0; core < core_count; ++core) { tasks.emplace_back(core, core_count, utilization / core_count); } return tasks; } auto config_mode(const cores_config& cores, uint16_t core_count) { if (cores.size() > core_count) { throw std::runtime_error( "Could not configure more cores than available (" + std::to_string(core_count) + ")."); } std::vector<internal::task_cpu> tasks; for (size_t core = 0; core < cores.size(); ++core) { auto core_conf = cores.at(core); for (const auto& target : core_conf.targets) { if (!available(target.set) || !enabled(target.set)) { throw std::runtime_error("Instruction set " + std::string(to_string(target.set)) + " is not supported"); } } if (core_conf.utilization <= 0.0 || 100.0 < core_conf.utilization) { throw std::runtime_error("Core utilization value " + std::to_string(core_conf.utilization) + " is not valid. Available values " "from 0 to 100 inclusive."); } core_conf.core = core; tasks.emplace_back(core_conf); } return tasks; } std::vector<uint16_t> available_cores() { // It is required to change thread affinity in order to be able to detect // available cores. Affinity of the current thread could be already set and // we should not touch it therefore this will be performed in a separate // thread. auto cores = std::async(op_get_cpu_online).get(); OP_LOG(OP_LOG_DEBUG, "Detected %zu cores", cores.size()); auto mask = openperf::config::file::op_config_get_param<OP_OPTION_TYPE_HEX>( "modules.cpu.cpu-mask"); if (mask) { std::vector<uint16_t> filtered_cores; for (size_t i = 0; i < cores.size(); i++) { if (mask.value() & (1 << i)) { filtered_cores.push_back(cores.at(i)); } } OP_LOG(OP_LOG_DEBUG, "Filtered %zu cores", filtered_cores.size()); return filtered_cores; } return cores; } // Constructors & Destructor generator::generator(const model::generator& generator_model) : model::generator(generator_model) , m_result_id(core::to_string(core::uuid::random())) , m_serial_number(++serial_counter) , m_stat_ptr(&m_stat) , m_dynamic(get_field) , m_controller(NAME_PREFIX + std::to_string(m_serial_number) + "_ctl") { m_controller.start<task_cpu_stat*>([this](const task_cpu_stat& stat) { auto stat_copy = m_stat; m_stat_ptr = &stat_copy; m_stat += stat; if (std::holds_alternative<double>(m_config)) { auto utilization = std::get<double>(m_config); auto process_stat = internal::cpu_process_time() - m_start_stat; m_stat.utilization = process_stat.utilization; m_stat.system = process_stat.system; m_stat.user = process_stat.user; m_stat.steal = process_stat.steal; m_stat.target = std::chrono::duration_cast<std::chrono::nanoseconds>( m_stat.available * utilization / (100.0 * m_core_count)); m_stat.error = m_stat.target - m_stat.utilization; } else { if (m_stat.steal == 0ns) { m_stat.steal = internal::cpu_steal_time() - m_start_stat.steal; } } m_dynamic.add(m_stat); m_stat_ptr = &m_stat; }); generator::config(generator_model.config()); } generator::~generator() { stop(); m_controller.clear(); } // Methods : public void generator::config(const generator_config& config) { m_controller.pause(); m_controller.clear(); reset(); std::visit( [this](auto&& conf) { auto cores = available_cores(); auto task_list = config_mode(conf, cores.size()); m_core_count = cores.size(); m_config = conf; m_stat = {task_list.size()}; m_controller.clear(); for (auto&& task : task_list) { auto task_config = task.config(); m_stat.cores[task_config.core].targets.resize( task_config.targets.size()); m_controller.add( std::move(task), NAME_PREFIX + std::to_string(m_serial_number) + "_c" + std::to_string(cores.at(task_config.core)), cores.at(task_config.core)); } }, config); if (m_running) m_controller.resume(); } model::generator_result generator::statistics() const { auto stat = model::generator_result{}; stat.id(m_result_id); stat.generator_id(m_id); stat.active(m_running); stat.timestamp(timesync::chrono::realtime::now()); stat.start_timestamp(m_start_time); stat.stats(*m_stat_ptr); stat.dynamic_results(m_dynamic.result()); return stat; } void generator::start(const dynamic::configuration& cfg) { if (m_running) return; m_dynamic.configure(cfg, m_stat); start(); } void generator::start() { if (m_running) return; reset(); m_controller.resume(); m_running = true; } void generator::stop() { m_controller.pause(); m_running = false; } void generator::running(bool is_running) { if (is_running) start(); else stop(); } void generator::reset() { m_controller.pause(); m_controller.reset(); m_dynamic.reset(); m_stat.clear(); m_result_id = core::to_string(core::uuid::random()); m_start_time = chronometer::now(); m_start_stat = internal::cpu_process_time(); if (m_running) m_controller.resume(); } } // namespace openperf::cpu::generator
32.156997
80
0.580768
[ "vector", "model" ]
4f83d701158e62f11fce5ae7788f7ffae7c41b8e
7,229
cpp
C++
Shared_input_stimulation/PSTH_simulations/psth_gcl/main.cpp
eolivaresb/Globus-pallidus-network
c19a4aa00b2af4f68d75e1df50d8c316e12ca131
[ "MIT" ]
null
null
null
Shared_input_stimulation/PSTH_simulations/psth_gcl/main.cpp
eolivaresb/Globus-pallidus-network
c19a4aa00b2af4f68d75e1df50d8c316e12ca131
[ "MIT" ]
null
null
null
Shared_input_stimulation/PSTH_simulations/psth_gcl/main.cpp
eolivaresb/Globus-pallidus-network
c19a4aa00b2af4f68d75e1df50d8c316e12ca131
[ "MIT" ]
null
null
null
// ============================================================= // ============================================================= #include <iostream> #include <iomanip> // cout precision #include <math.h> #include "VectorMatrix.h" #include "NervousSystem.h" using namespace std; ////////////////////////////////////////////////////////// ///////////////// Simulation and network configuration // Integration Parameters const double ttot = 6000, StepSize = 0.0001; // Network parameters const int N = 1000; const int n = 10; // numer of synapses going out and in of a neuron = 10 out of 1000 // Files for neurons and network configuration char path_to_files[] = "../../simulation_files/"; ifstream neurons_file(std::string(path_to_files) + "neurons.dat"); ifstream Connected_file(std::string(path_to_files) + "network_small.dat"); ifstream prc_file(std::string(path_to_files) + "diff_prc.dat"); ifstream volt_file(std::string(path_to_files) + "volt.dat"); // Stimuli parameters const double td = 3.5/1000; double Erev = -0.073; double gmax = 250; ////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////// int main (int argc, const char* argv[]){ ///////////////// read gmax and Erev from terminal //////////////////////////// gmax = atof(argv[1]); ////////////////////////////////////////////////////////// RandomState rs; long randomseed = static_cast<long>(time(NULL)); cout << "randomseed " << randomseed << endl; rs.SetRandomSeed(randomseed); cout.precision(10); ////////////////////////////////////////////////////////// TVector<double> NeuronsProp(1, 2*N); neurons_file >> NeuronsProp; neurons_file.close(); TVector<double> Connected(1, 2*n*N); Connected_file >> Connected; Connected_file.close(); TVector<double> prc_params(1, 7*N); prc_file >> prc_params; prc_file.close(); ///////////////// Construct connected network NervousSystem gp; // Connected GPe gp.SetCircuitSize(N, 3*n); NervousSystem dgp; // Disconnected GPe dgp.SetCircuitSize(N, 1); // Load mean Voltage trace gp.LoadVoltage(volt_file); dgp.LoadVoltage(volt_file); // Set conductance amplitud variability (Std normal distribution pS) gp.IpscStd = 1750; dgp.IpscStd = 1750; // load neurons propierties for (int i=1; i<=N; i++){ gp.SetNeuronW(i,NeuronsProp[2*i-1]); gp.SetNeuronCV(i, 0.05); dgp.SetNeuronW(i,NeuronsProp[2*i-1]); dgp.SetNeuronCV(i, 0.05); } // load network connectivity for (int i=1; i<=n*N; i++){ gp.SetChemicalSynapseWeight(Connected[2*i-1], Connected[2*i], 1); } // load neurons PRCs for (int i=1; i<=N; i++){ for (int p=1; p<=7; p++){ gp.PrcNeuron[i].PrcParam[p] = prc_params[7*(i-1)+p]; dgp.PrcNeuron[i].PrcParam[p] = prc_params[7*(i-1)+p]; } } ////////////////////////////////////////////// ////////////////////////////////////////////// // Inicialization gp.RandomizeCircuitPhase(0.0, 1.0, rs); dgp.RandomizeCircuitPhase(0.0, 1.0, rs); ////////////////////////////////////////////// ofstream First_spk_file("First_spk.dat", ios::out|ios::binary); //Record and generate stimuli time double gsyn = 0; double tmin = 0.6, tvar = 0.6; int nrep = 5000; double tinit = -0.025, tend = 0.175; double tadapt = tmin + rs.UniformRandom(0, tvar); ////////////////////////////////////////////// int pdens_bins = 250; int time_bins = 1+(tend-tinit)*1000;//200 TMatrix<int> pdens(1, pdens_bins, 1, N*time_bins); pdens.FillContents(0); TMatrix<int> conductances(1, N, 1,10*time_bins); conductances.FillContents(0); int tindx, tindx_cond; ////////////////////////////////////////////// gp.SetSaveSpikes(false);// Do not save spikes from parallel small world network for (int rep = 1; rep<=nrep; rep++){ //////////////////// PSTH preStim ////////////////////////// dgp.SetSaveSpikes(true); for (double t = tinit; t <0-StepSize/10; t += StepSize){ gp.EulerStep(StepSize, t, rs); tindx = int(1000*(t-tinit+StepSize/10)+1); tindx_cond = int(10000*(t-tinit+1.1*StepSize)+1); for (int i=1; i<=N; i++) { dgp.Conductance[i] = gp.Conductance_pre[i]; conductances[i][tindx_cond] += dgp.Conductance[i]; } dgp.EulerStep(StepSize, t, rs); for (int i=1; i<=N; i++) { pdens[int(1+dgp.NeuronPhase(i)*pdens_bins)][(i-1)*time_bins+tindx] +=1; } } dgp.TimeToFirstSpike.FillContents(-1); // rest vector with time of the first spike after stim ///////////////////// PSTH Stimulation ///////////////////////// for (double t = 0; t <tend-StepSize/10; t += StepSize){ gp.EulerStep(StepSize, t, rs); tindx = int(1000*(t-tinit+StepSize/10)+1); tindx_cond = int(10000*(t-tinit+1.1*StepSize)+1); gsyn = gmax*(exp(-t/td)); for (int i=1; i<=N; i++) { dgp.Conductance[i] = gp.Conductance_pre[i]; dgp.externalinputs[i] = gsyn * (Erev - dgp.VoltEval(dgp.NeuronPhase(i))); conductances[i][tindx_cond] += dgp.Conductance[i]; } dgp.EulerStep(StepSize, t, rs); for (int i=1; i<=N; i++) { pdens[int(1+dgp.NeuronPhase(i)*pdens_bins)][(i-1)*time_bins+tindx] +=1; } } ////////////////// Relaxation between PSTHs //////////////////////////// tadapt = tmin + rs.UniformRandom(0, tvar); dgp.SetSaveSpikes(false); // do not save adaptation time spikes (way too big files otherwise) for (double t = tend; t <(tend+tadapt); t += StepSize){ gp.EulerStep(StepSize, t, rs); for (int i=1; i<=N; i++) { dgp.Conductance[i] = gp.Conductance_pre[i]; } dgp.EulerStep(StepSize, t, rs); } /// Save time for the first spike for (int i=1; i<=N; i++) { First_spk_file.write((char*)&(dgp.TimeToFirstSpike(i)), sizeof(float)); } } ////////////////// Save Pdens & conductances //////////////////////////// ofstream pdens_file("pdens.dat", ios::out|ios::binary); for (int i=1; i<=pdens_bins; i++) { for (int j=1; j<=N*time_bins; j++) { pdens_file.write((char*)&pdens[i][j], sizeof(int)); } pdens_file << endl; } ofstream cond_file("cond.dat"); for (int i=1; i<=N; i++) { for (int j=1; j<=10*time_bins; j++) { cond_file << conductances[i][j] << " "; } cond_file << endl; } }
42.775148
105
0.476553
[ "vector" ]
4f8601f69dbd3aa359a3b6d93b1c71e5174be13b
5,117
cpp
C++
src/appleseed/renderer/modeling/material/imaterialfactory.cpp
istemi-bahceci/appleseed
2db1041acb04bad4742cf7826ce019f0e623fe35
[ "MIT" ]
1
2021-04-02T10:51:57.000Z
2021-04-02T10:51:57.000Z
src/appleseed/renderer/modeling/material/imaterialfactory.cpp
istemi-bahceci/appleseed
2db1041acb04bad4742cf7826ce019f0e623fe35
[ "MIT" ]
null
null
null
src/appleseed/renderer/modeling/material/imaterialfactory.cpp
istemi-bahceci/appleseed
2db1041acb04bad4742cf7826ce019f0e623fe35
[ "MIT" ]
null
null
null
// // This source file is part of appleseed. // Visit http://appleseedhq.net/ for additional information and resources. // // This software is released under the MIT license. // // Copyright (c) 2010-2013 Francois Beaune, Jupiter Jazz Limited // Copyright (c) 2014-2017 Francois Beaune, The appleseedhq Organization // // 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. // // Interface header. #include "imaterialfactory.h" // appleseed.foundation headers. #include "foundation/utility/api/specializedapiarrays.h" #include "foundation/utility/containers/dictionary.h" using namespace foundation; namespace renderer { void IMaterialFactory::add_surface_shader_metadata(DictionaryArray& metadata) { metadata.push_back( Dictionary() .insert("name", "shade_alpha_cutouts") .insert("label", "Shade Alpha Cutouts") .insert("type", "boolean") .insert("use", "optional") .insert("default", "false")); metadata.push_back( Dictionary() .insert("name", "surface_shader") .insert("label", "Surface Shader") .insert("type", "entity") .insert("entity_types", Dictionary().insert("surface_shader", "Surface Shaders")) .insert("use", "optional")); } void IMaterialFactory::add_alpha_map_metadata(DictionaryArray& metadata) { metadata.push_back( Dictionary() .insert("name", "alpha_map") .insert("label", "Alpha Map") .insert("type", "colormap") .insert("entity_types", Dictionary() .insert("color", "Colors") .insert("texture_instance", "Textures")) .insert("use", "optional")); } void IMaterialFactory::add_displacement_metadata(DictionaryArray& metadata) { metadata.push_back( Dictionary() .insert("name", "displacement_map") .insert("label", "Displacement Map") .insert("type", "colormap") .insert("entity_types", Dictionary().insert("texture_instance", "Textures")) .insert("use", "optional")); metadata.push_back( Dictionary() .insert("name", "displacement_method") .insert("label", "Displacement Method") .insert("type", "enumeration") .insert("items", Dictionary() .insert("Bump Mapping", "bump") .insert("Normal Mapping", "normal")) .insert("use", "required") .insert("default", "bump") .insert("on_change", "rebuild_form")); metadata.push_back( Dictionary() .insert("name", "bump_amplitude") .insert("label", "Bump Amplitude") .insert("type", "numeric") .insert("min_value", "0.0") .insert("max_value", "1.0") .insert("use", "optional") .insert("default", "1.0") .insert("visible_if", Dictionary() .insert("displacement_method", "bump"))); metadata.push_back( Dictionary() .insert("name", "bump_offset") .insert("label", "Bump Offset") .insert("type", "numeric") .insert("min_value", "0.01") .insert("max_value", "10.0") .insert("use", "optional") .insert("default", "2.0") .insert("visible_if", Dictionary())); // invisible metadata.push_back( Dictionary() .insert("name", "normal_map_up") .insert("label", "Normal Map Up Vector") .insert("type", "enumeration") .insert("items", Dictionary() .insert("Green Channel (Y)", "y") .insert("Blue Channel (Z)", "z")) .insert("use", "optional") .insert("default", "z") .insert("visible_if", Dictionary() .insert("displacement_method", "normal"))); } } // namespace renderer
36.29078
80
0.589994
[ "vector" ]
4f8667010c94b262098aa68a42c127160e327583
34,063
cc
C++
ui/base/native_theme/native_theme_base.cc
robclark/chromium
f097b6ea775c27e5352c94ddddd264dd2af21479
[ "BSD-3-Clause" ]
1
2019-07-22T23:03:26.000Z
2019-07-22T23:03:26.000Z
ui/base/native_theme/native_theme_base.cc
robclark/chromium
f097b6ea775c27e5352c94ddddd264dd2af21479
[ "BSD-3-Clause" ]
null
null
null
ui/base/native_theme/native_theme_base.cc
robclark/chromium
f097b6ea775c27e5352c94ddddd264dd2af21479
[ "BSD-3-Clause" ]
null
null
null
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ui/base/native_theme/native_theme_base.h" #include <limits> #include "base/logging.h" #include "grit/gfx_resources.h" #include "third_party/skia/include/effects/SkGradientShader.h" #include "ui/base/resource/resource_bundle.h" #include "ui/gfx/color_utils.h" #include "ui/gfx/rect.h" #include "ui/gfx/size.h" namespace { // These are the default dimensions of radio buttons and checkboxes. const int kCheckboxAndRadioWidth = 13; const int kCheckboxAndRadioHeight = 13; // These sizes match the sizes in Chromium Win. const int kSliderThumbWidth = 11; const int kSliderThumbHeight = 21; const SkColor kSliderTrackBackgroundColor = SkColorSetRGB(0xe3, 0xdd, 0xd8); const SkColor kSliderThumbLightGrey = SkColorSetRGB(0xf4, 0xf2, 0xef); const SkColor kSliderThumbDarkGrey = SkColorSetRGB(0xea, 0xe5, 0xe0); const SkColor kSliderThumbBorderDarkGrey = SkColorSetRGB(0x9d, 0x96, 0x8e); const SkColor kMenuPopupBackgroundColor = SkColorSetRGB(210, 225, 246); const unsigned int kDefaultScrollbarWidth = 15; const unsigned int kDefaultScrollbarButtonLength = 14; // Get lightness adjusted color. SkColor BrightenColor(const color_utils::HSL& hsl, SkAlpha alpha, double lightness_amount) { color_utils::HSL adjusted = hsl; adjusted.l += lightness_amount; if (adjusted.l > 1.0) adjusted.l = 1.0; if (adjusted.l < 0.0) adjusted.l = 0.0; return color_utils::HSLToSkColor(adjusted, alpha); } } // namespace namespace ui { gfx::Size NativeThemeBase::GetPartSize(Part part, State state, const ExtraParams& extra) const { switch (part) { // Please keep these in the order of NativeTheme::Part. case kCheckbox: return gfx::Size(kCheckboxAndRadioWidth, kCheckboxAndRadioHeight); case kInnerSpinButton: return gfx::Size(scrollbar_width_, 0); case kMenuList: return gfx::Size(); // No default size. case kMenuCheck: case kMenuCheckBackground: case kMenuPopupArrow: NOTIMPLEMENTED(); break; case kMenuPopupBackground: return gfx::Size(); // No default size. case kMenuPopupGutter: case kMenuPopupSeparator: NOTIMPLEMENTED(); break; case kMenuItemBackground: case kProgressBar: case kPushButton: return gfx::Size(); // No default size. case kRadio: return gfx::Size(kCheckboxAndRadioWidth, kCheckboxAndRadioHeight); case kScrollbarDownArrow: case kScrollbarUpArrow: return gfx::Size(scrollbar_width_, scrollbar_button_length_); case kScrollbarLeftArrow: case kScrollbarRightArrow: return gfx::Size(scrollbar_button_length_, scrollbar_width_); case kScrollbarHorizontalThumb: // This matches Firefox on Linux. return gfx::Size(2 * scrollbar_width_, scrollbar_width_); case kScrollbarVerticalThumb: // This matches Firefox on Linux. return gfx::Size(scrollbar_width_, 2 * scrollbar_width_); case kScrollbarHorizontalTrack: return gfx::Size(0, scrollbar_width_); case kScrollbarVerticalTrack: return gfx::Size(scrollbar_width_, 0); case kScrollbarHorizontalGripper: case kScrollbarVerticalGripper: NOTIMPLEMENTED(); break; case kSliderTrack: return gfx::Size(); // No default size. case kSliderThumb: // These sizes match the sizes in Chromium Win. return gfx::Size(kSliderThumbWidth, kSliderThumbHeight); case kTabPanelBackground: NOTIMPLEMENTED(); break; case kTextField: return gfx::Size(); // No default size. case kTrackbarThumb: case kTrackbarTrack: case kWindowResizeGripper: NOTIMPLEMENTED(); break; default: NOTREACHED() << "Unknown theme part: " << part; break; } return gfx::Size(); } void NativeThemeBase::Paint(SkCanvas* canvas, Part part, State state, const gfx::Rect& rect, const ExtraParams& extra) const { switch (part) { // Please keep these in the order of NativeTheme::Part. case kCheckbox: PaintCheckbox(canvas, state, rect, extra.button); break; case kInnerSpinButton: PaintInnerSpinButton(canvas, state, rect, extra.inner_spin); break; case kMenuList: PaintMenuList(canvas, state, rect, extra.menu_list); break; case kMenuCheck: case kMenuCheckBackground: case kMenuPopupArrow: NOTIMPLEMENTED(); break; case kMenuPopupBackground: PaintMenuPopupBackground(canvas, rect.size()); break; case kMenuPopupGutter: case kMenuPopupSeparator: NOTIMPLEMENTED(); break; case kMenuItemBackground: PaintMenuItemBackground(canvas, state, rect, extra.menu_list); break; case kProgressBar: PaintProgressBar(canvas, state, rect, extra.progress_bar); break; case kPushButton: PaintButton(canvas, state, rect, extra.button); break; case kRadio: PaintRadio(canvas, state, rect, extra.button); break; case kScrollbarDownArrow: case kScrollbarUpArrow: case kScrollbarLeftArrow: case kScrollbarRightArrow: PaintArrowButton(canvas, rect, part, state); break; case kScrollbarHorizontalThumb: case kScrollbarVerticalThumb: PaintScrollbarThumb(canvas, part, state, rect); break; case kScrollbarHorizontalTrack: case kScrollbarVerticalTrack: PaintScrollbarTrack(canvas, part, state, extra.scrollbar_track, rect); break; case kScrollbarHorizontalGripper: case kScrollbarVerticalGripper: NOTIMPLEMENTED(); break; case kSliderTrack: PaintSliderTrack(canvas, state, rect, extra.slider); break; case kSliderThumb: PaintSliderThumb(canvas, state, rect, extra.slider); break; case kTabPanelBackground: NOTIMPLEMENTED(); break; case kTextField: PaintTextField(canvas, state, rect, extra.text_field); break; case kTrackbarThumb: case kTrackbarTrack: case kWindowResizeGripper: NOTIMPLEMENTED(); break; default: NOTREACHED() << "Unknown theme part: " << part; break; } } NativeThemeBase::NativeThemeBase() : scrollbar_width_(kDefaultScrollbarWidth), scrollbar_button_length_(kDefaultScrollbarButtonLength) { } NativeThemeBase::~NativeThemeBase() { } void NativeThemeBase::PaintArrowButton( SkCanvas* canvas, const gfx::Rect& rect, Part direction, State state) const { int widthMiddle, lengthMiddle; SkPaint paint; if (direction == kScrollbarUpArrow || direction == kScrollbarDownArrow) { widthMiddle = rect.width() / 2 + 1; lengthMiddle = rect.height() / 2 + 1; } else { lengthMiddle = rect.width() / 2 + 1; widthMiddle = rect.height() / 2 + 1; } // Calculate button color. SkScalar trackHSV[3]; SkColorToHSV(track_color_, trackHSV); SkColor buttonColor = SaturateAndBrighten(trackHSV, 0, 0.2f); SkColor backgroundColor = buttonColor; if (state == kPressed) { SkScalar buttonHSV[3]; SkColorToHSV(buttonColor, buttonHSV); buttonColor = SaturateAndBrighten(buttonHSV, 0, -0.1f); } else if (state == kHovered) { SkScalar buttonHSV[3]; SkColorToHSV(buttonColor, buttonHSV); buttonColor = SaturateAndBrighten(buttonHSV, 0, 0.05f); } SkIRect skrect; skrect.set(rect.x(), rect.y(), rect.x() + rect.width(), rect.y() + rect.height()); // Paint the background (the area visible behind the rounded corners). paint.setColor(backgroundColor); canvas->drawIRect(skrect, paint); // Paint the button's outline and fill the middle SkPath outline; switch (direction) { case kScrollbarUpArrow: outline.moveTo(rect.x() + 0.5, rect.y() + rect.height() + 0.5); outline.rLineTo(0, -(rect.height() - 2)); outline.rLineTo(2, -2); outline.rLineTo(rect.width() - 5, 0); outline.rLineTo(2, 2); outline.rLineTo(0, rect.height() - 2); break; case kScrollbarDownArrow: outline.moveTo(rect.x() + 0.5, rect.y() - 0.5); outline.rLineTo(0, rect.height() - 2); outline.rLineTo(2, 2); outline.rLineTo(rect.width() - 5, 0); outline.rLineTo(2, -2); outline.rLineTo(0, -(rect.height() - 2)); break; case kScrollbarRightArrow: outline.moveTo(rect.x() - 0.5, rect.y() + 0.5); outline.rLineTo(rect.width() - 2, 0); outline.rLineTo(2, 2); outline.rLineTo(0, rect.height() - 5); outline.rLineTo(-2, 2); outline.rLineTo(-(rect.width() - 2), 0); break; case kScrollbarLeftArrow: outline.moveTo(rect.x() + rect.width() + 0.5, rect.y() + 0.5); outline.rLineTo(-(rect.width() - 2), 0); outline.rLineTo(-2, 2); outline.rLineTo(0, rect.height() - 5); outline.rLineTo(2, 2); outline.rLineTo(rect.width() - 2, 0); break; default: break; } outline.close(); paint.setStyle(SkPaint::kFill_Style); paint.setColor(buttonColor); canvas->drawPath(outline, paint); paint.setAntiAlias(true); paint.setStyle(SkPaint::kStroke_Style); SkScalar thumbHSV[3]; SkColorToHSV(thumb_inactive_color_, thumbHSV); paint.setColor(OutlineColor(trackHSV, thumbHSV)); canvas->drawPath(outline, paint); // If the button is disabled or read-only, the arrow is drawn with the // outline color. if (state != kDisabled) paint.setColor(SK_ColorBLACK); paint.setAntiAlias(false); paint.setStyle(SkPaint::kFill_Style); SkPath path; // The constants in this block of code are hand-tailored to produce good // looking arrows without anti-aliasing. switch (direction) { case kScrollbarUpArrow: path.moveTo(rect.x() + widthMiddle - 4, rect.y() + lengthMiddle + 2); path.rLineTo(7, 0); path.rLineTo(-4, -4); break; case kScrollbarDownArrow: path.moveTo(rect.x() + widthMiddle - 4, rect.y() + lengthMiddle - 3); path.rLineTo(7, 0); path.rLineTo(-4, 4); break; case kScrollbarRightArrow: path.moveTo(rect.x() + lengthMiddle - 3, rect.y() + widthMiddle - 4); path.rLineTo(0, 7); path.rLineTo(4, -4); break; case kScrollbarLeftArrow: path.moveTo(rect.x() + lengthMiddle + 1, rect.y() + widthMiddle - 5); path.rLineTo(0, 9); path.rLineTo(-4, -4); break; default: break; } path.close(); canvas->drawPath(path, paint); } void NativeThemeBase::PaintScrollbarTrack(SkCanvas* canvas, Part part, State state, const ScrollbarTrackExtraParams& extra_params, const gfx::Rect& rect) const { SkPaint paint; SkIRect skrect; skrect.set(rect.x(), rect.y(), rect.right(), rect.bottom()); SkScalar track_hsv[3]; SkColorToHSV(track_color_, track_hsv); paint.setColor(SaturateAndBrighten(track_hsv, 0, 0)); canvas->drawIRect(skrect, paint); SkScalar thumb_hsv[3]; SkColorToHSV(thumb_inactive_color_, thumb_hsv); paint.setColor(OutlineColor(track_hsv, thumb_hsv)); DrawBox(canvas, rect, paint); } void NativeThemeBase::PaintScrollbarThumb(SkCanvas* canvas, Part part, State state, const gfx::Rect& rect) const { const bool hovered = state == kHovered; const int midx = rect.x() + rect.width() / 2; const int midy = rect.y() + rect.height() / 2; const bool vertical = part == kScrollbarVerticalThumb; SkScalar thumb[3]; SkColorToHSV(hovered ? thumb_active_color_ : thumb_inactive_color_, thumb); SkPaint paint; paint.setColor(SaturateAndBrighten(thumb, 0, 0.02f)); SkIRect skrect; if (vertical) skrect.set(rect.x(), rect.y(), midx + 1, rect.y() + rect.height()); else skrect.set(rect.x(), rect.y(), rect.x() + rect.width(), midy + 1); canvas->drawIRect(skrect, paint); paint.setColor(SaturateAndBrighten(thumb, 0, -0.02f)); if (vertical) { skrect.set( midx + 1, rect.y(), rect.x() + rect.width(), rect.y() + rect.height()); } else { skrect.set( rect.x(), midy + 1, rect.x() + rect.width(), rect.y() + rect.height()); } canvas->drawIRect(skrect, paint); SkScalar track[3]; SkColorToHSV(track_color_, track); paint.setColor(OutlineColor(track, thumb)); DrawBox(canvas, rect, paint); if (rect.height() > 10 && rect.width() > 10) { const int grippy_half_width = 2; const int inter_grippy_offset = 3; if (vertical) { DrawHorizLine(canvas, midx - grippy_half_width, midx + grippy_half_width, midy - inter_grippy_offset, paint); DrawHorizLine(canvas, midx - grippy_half_width, midx + grippy_half_width, midy, paint); DrawHorizLine(canvas, midx - grippy_half_width, midx + grippy_half_width, midy + inter_grippy_offset, paint); } else { DrawVertLine(canvas, midx - inter_grippy_offset, midy - grippy_half_width, midy + grippy_half_width, paint); DrawVertLine(canvas, midx, midy - grippy_half_width, midy + grippy_half_width, paint); DrawVertLine(canvas, midx + inter_grippy_offset, midy - grippy_half_width, midy + grippy_half_width, paint); } } } void NativeThemeBase::PaintCheckbox(SkCanvas* canvas, State state, const gfx::Rect& rect, const ButtonExtraParams& button) const { ResourceBundle& rb = ResourceBundle::GetSharedInstance(); SkBitmap* image = NULL; if (button.indeterminate) { image = state == kDisabled ? rb.GetBitmapNamed(IDR_CHECKBOX_DISABLED_INDETERMINATE) : rb.GetBitmapNamed(IDR_CHECKBOX_INDETERMINATE); } else if (button.checked) { image = state == kDisabled ? rb.GetBitmapNamed(IDR_CHECKBOX_DISABLED_ON) : rb.GetBitmapNamed(IDR_CHECKBOX_ON); } else { image = state == kDisabled ? rb.GetBitmapNamed(IDR_CHECKBOX_DISABLED_OFF) : rb.GetBitmapNamed(IDR_CHECKBOX_OFF); } gfx::Rect bounds = rect.Center(gfx::Size(image->width(), image->height())); DrawBitmapInt(canvas, *image, 0, 0, image->width(), image->height(), bounds.x(), bounds.y(), bounds.width(), bounds.height()); } void NativeThemeBase::PaintRadio(SkCanvas* canvas, State state, const gfx::Rect& rect, const ButtonExtraParams& button) const { ResourceBundle& rb = ResourceBundle::GetSharedInstance(); SkBitmap* image = NULL; if (state == kDisabled) { image = button.checked ? rb.GetBitmapNamed(IDR_RADIO_DISABLED_ON) : rb.GetBitmapNamed(IDR_RADIO_DISABLED_OFF); } else { image = button.checked ? rb.GetBitmapNamed(IDR_RADIO_ON) : rb.GetBitmapNamed(IDR_RADIO_OFF); } gfx::Rect bounds = rect.Center(gfx::Size(image->width(), image->height())); DrawBitmapInt(canvas, *image, 0, 0, image->width(), image->height(), bounds.x(), bounds.y(), bounds.width(), bounds.height()); } void NativeThemeBase::PaintButton(SkCanvas* canvas, State state, const gfx::Rect& rect, const ButtonExtraParams& button) const { SkPaint paint; const int kRight = rect.right(); const int kBottom = rect.bottom(); SkRect skrect = SkRect::MakeLTRB(rect.x(), rect.y(), kRight, kBottom); SkColor base_color = button.background_color; color_utils::HSL base_hsl; color_utils::SkColorToHSL(base_color, &base_hsl); // Our standard gradient is from 0xdd to 0xf8. This is the amount of // increased luminance between those values. SkColor light_color(BrightenColor(base_hsl, SkColorGetA(base_color), 0.105)); // If the button is too small, fallback to drawing a single, solid color if (rect.width() < 5 || rect.height() < 5) { paint.setColor(base_color); canvas->drawRect(skrect, paint); return; } paint.setColor(SK_ColorBLACK); const int kLightEnd = state == kPressed ? 1 : 0; const int kDarkEnd = !kLightEnd; SkPoint gradient_bounds[2]; gradient_bounds[kLightEnd].iset(rect.x(), rect.y()); gradient_bounds[kDarkEnd].iset(rect.x(), kBottom - 1); SkColor colors[2]; colors[0] = light_color; colors[1] = base_color; SkShader* shader = SkGradientShader::CreateLinear( gradient_bounds, colors, NULL, 2, SkShader::kClamp_TileMode, NULL); paint.setStyle(SkPaint::kFill_Style); paint.setAntiAlias(true); paint.setShader(shader); shader->unref(); canvas->drawRoundRect(skrect, SkIntToScalar(1), SkIntToScalar(1), paint); paint.setShader(NULL); if (button.has_border) { const int kBorderAlpha = state == kHovered ? 0x80 : 0x55; paint.setStyle(SkPaint::kStroke_Style); paint.setStrokeWidth(SkIntToScalar(1)); paint.setARGB(kBorderAlpha, 0, 0, 0); skrect.inset(SkFloatToScalar(.5f), SkFloatToScalar(.5f)); canvas->drawRoundRect(skrect, SkIntToScalar(1), SkIntToScalar(1), paint); } } void NativeThemeBase::PaintTextField(SkCanvas* canvas, State state, const gfx::Rect& rect, const TextFieldExtraParams& text) const { // The following drawing code simulates the user-agent css border for // text area and text input so that we do not break layout tests. Once we // have decided the desired looks, we should update the code here and // the layout test expectations. SkRect bounds; bounds.set(rect.x(), rect.y(), rect.right() - 1, rect.bottom() - 1); SkPaint fill_paint; fill_paint.setStyle(SkPaint::kFill_Style); fill_paint.setColor(text.background_color); canvas->drawRect(bounds, fill_paint); if (text.is_text_area) { // Draw text area border: 1px solid black SkPaint stroke_paint; fill_paint.setStyle(SkPaint::kStroke_Style); fill_paint.setColor(SK_ColorBLACK); canvas->drawRect(bounds, fill_paint); } else { // Draw text input and listbox inset border // Text Input: 2px inset #eee // Listbox: 1px inset #808080 const SkColor kLightColor = text.is_listbox ? SkColorSetRGB(0x80, 0x80, 0x80) : SkColorSetRGB(0xee, 0xee, 0xee); const SkColor kDarkColor = text.is_listbox ? SkColorSetRGB(0x2c, 0x2c, 0x2c) : SkColorSetRGB(0x9a, 0x9a, 0x9a); const int kBorderWidth = text.is_listbox ? 1 : 2; SkPaint dark_paint; dark_paint.setAntiAlias(true); dark_paint.setStyle(SkPaint::kFill_Style); dark_paint.setColor(kDarkColor); SkPaint light_paint; light_paint.setAntiAlias(true); light_paint.setStyle(SkPaint::kFill_Style); light_paint.setColor(kLightColor); int left = rect.x(); int top = rect.y(); int right = rect.right(); int bottom = rect.bottom(); SkPath path; path.incReserve(4); // Top path.moveTo(SkIntToScalar(left), SkIntToScalar(top)); path.lineTo(SkIntToScalar(left + kBorderWidth), SkIntToScalar(top + kBorderWidth)); path.lineTo(SkIntToScalar(right - kBorderWidth), SkIntToScalar(top + kBorderWidth)); path.lineTo(SkIntToScalar(right), SkIntToScalar(top)); canvas->drawPath(path, dark_paint); // Bottom path.reset(); path.moveTo(SkIntToScalar(left + kBorderWidth), SkIntToScalar(bottom - kBorderWidth)); path.lineTo(SkIntToScalar(left), SkIntToScalar(bottom)); path.lineTo(SkIntToScalar(right), SkIntToScalar(bottom)); path.lineTo(SkIntToScalar(right - kBorderWidth), SkIntToScalar(bottom - kBorderWidth)); canvas->drawPath(path, light_paint); // Left path.reset(); path.moveTo(SkIntToScalar(left), SkIntToScalar(top)); path.lineTo(SkIntToScalar(left), SkIntToScalar(bottom)); path.lineTo(SkIntToScalar(left + kBorderWidth), SkIntToScalar(bottom - kBorderWidth)); path.lineTo(SkIntToScalar(left + kBorderWidth), SkIntToScalar(top + kBorderWidth)); canvas->drawPath(path, dark_paint); // Right path.reset(); path.moveTo(SkIntToScalar(right - kBorderWidth), SkIntToScalar(top + kBorderWidth)); path.lineTo(SkIntToScalar(right - kBorderWidth), SkIntToScalar(bottom)); path.lineTo(SkIntToScalar(right), SkIntToScalar(bottom)); path.lineTo(SkIntToScalar(right), SkIntToScalar(top)); canvas->drawPath(path, light_paint); } } void NativeThemeBase::PaintMenuList( SkCanvas* canvas, State state, const gfx::Rect& rect, const MenuListExtraParams& menu_list) const { // If a border radius is specified, we let the WebCore paint the background // and the border of the control. if (!menu_list.has_border_radius) { ButtonExtraParams button = { 0 }; button.background_color = menu_list.background_color; button.has_border = menu_list.has_border; PaintButton(canvas, state, rect, button); } SkPaint paint; paint.setColor(SK_ColorBLACK); paint.setAntiAlias(true); paint.setStyle(SkPaint::kFill_Style); SkPath path; path.moveTo(menu_list.arrow_x, menu_list.arrow_y - 3); path.rLineTo(6, 0); path.rLineTo(-3, 6); path.close(); canvas->drawPath(path, paint); } void NativeThemeBase::PaintMenuPopupBackground(SkCanvas* canvas, const gfx::Size& size) const { canvas->drawColor(kMenuPopupBackgroundColor, SkXfermode::kSrc_Mode); } void NativeThemeBase::PaintMenuItemBackground( SkCanvas* canvas, State state, const gfx::Rect& rect, const MenuListExtraParams& menu_list) const { // By default don't draw anything over the normal background. } void NativeThemeBase::PaintSliderTrack(SkCanvas* canvas, State state, const gfx::Rect& rect, const SliderExtraParams& slider) const { const int kMidX = rect.x() + rect.width() / 2; const int kMidY = rect.y() + rect.height() / 2; SkPaint paint; paint.setColor(kSliderTrackBackgroundColor); SkRect skrect; if (slider.vertical) { skrect.set(std::max(rect.x(), kMidX - 2), rect.y(), std::min(rect.right(), kMidX + 2), rect.bottom()); } else { skrect.set(rect.x(), std::max(rect.y(), kMidY - 2), rect.right(), std::min(rect.bottom(), kMidY + 2)); } canvas->drawRect(skrect, paint); } void NativeThemeBase::PaintSliderThumb(SkCanvas* canvas, State state, const gfx::Rect& rect, const SliderExtraParams& slider) const { const bool hovered = (state == kHovered) || slider.in_drag; const int kMidX = rect.x() + rect.width() / 2; const int kMidY = rect.y() + rect.height() / 2; SkPaint paint; paint.setColor(hovered ? SK_ColorWHITE : kSliderThumbLightGrey); SkIRect skrect; if (slider.vertical) skrect.set(rect.x(), rect.y(), kMidX + 1, rect.bottom()); else skrect.set(rect.x(), rect.y(), rect.right(), kMidY + 1); canvas->drawIRect(skrect, paint); paint.setColor(hovered ? kSliderThumbLightGrey : kSliderThumbDarkGrey); if (slider.vertical) skrect.set(kMidX + 1, rect.y(), rect.right(), rect.bottom()); else skrect.set(rect.x(), kMidY + 1, rect.right(), rect.bottom()); canvas->drawIRect(skrect, paint); paint.setColor(kSliderThumbBorderDarkGrey); DrawBox(canvas, rect, paint); if (rect.height() > 10 && rect.width() > 10) { DrawHorizLine(canvas, kMidX - 2, kMidX + 2, kMidY, paint); DrawHorizLine(canvas, kMidX - 2, kMidX + 2, kMidY - 3, paint); DrawHorizLine(canvas, kMidX - 2, kMidX + 2, kMidY + 3, paint); } } void NativeThemeBase::PaintInnerSpinButton(SkCanvas* canvas, State state, const gfx::Rect& rect, const InnerSpinButtonExtraParams& spin_button) const { if (spin_button.read_only) state = kDisabled; State north_state = state; State south_state = state; if (spin_button.spin_up) south_state = south_state != kDisabled ? kNormal : kDisabled; else north_state = north_state != kDisabled ? kNormal : kDisabled; gfx::Rect half = rect; half.set_height(rect.height() / 2); PaintArrowButton(canvas, half, kScrollbarUpArrow, north_state); half.set_y(rect.y() + rect.height() / 2); PaintArrowButton(canvas, half, kScrollbarDownArrow, south_state); } void NativeThemeBase::PaintProgressBar(SkCanvas* canvas, State state, const gfx::Rect& rect, const ProgressBarExtraParams& progress_bar) const { ResourceBundle& rb = ResourceBundle::GetSharedInstance(); SkBitmap* bar_image = rb.GetBitmapNamed(IDR_PROGRESS_BAR); SkBitmap* left_border_image = rb.GetBitmapNamed(IDR_PROGRESS_BORDER_LEFT); SkBitmap* right_border_image = rb.GetBitmapNamed(IDR_PROGRESS_BORDER_RIGHT); double tile_scale = static_cast<double>(rect.height()) / bar_image->height(); int new_tile_width = static_cast<int>(bar_image->width() * tile_scale); double tile_scale_x = static_cast<double>(new_tile_width) / bar_image->width(); DrawTiledImage(canvas, *bar_image, 0, 0, tile_scale_x, tile_scale, rect.x(), rect.y(), rect.width(), rect.height()); if (progress_bar.value_rect_width) { SkBitmap* value_image = rb.GetBitmapNamed(IDR_PROGRESS_VALUE); new_tile_width = static_cast<int>(value_image->width() * tile_scale); tile_scale_x = static_cast<double>(new_tile_width) / value_image->width(); DrawTiledImage(canvas, *value_image, 0, 0, tile_scale_x, tile_scale, progress_bar.value_rect_x, progress_bar.value_rect_y, progress_bar.value_rect_width, progress_bar.value_rect_height); } int dest_left_border_width = static_cast<int>(left_border_image->width() * tile_scale); SkRect dest_rect; dest_rect.iset(rect.x(), rect.y(), rect.x() + dest_left_border_width, rect.bottom()); canvas->drawBitmapRect(*left_border_image, NULL, dest_rect); int dest_right_border_width = static_cast<int>(right_border_image->width() * tile_scale); dest_rect.iset(rect.right() - dest_right_border_width, rect.y(), rect.right(), rect.bottom()); canvas->drawBitmapRect(*right_border_image, NULL, dest_rect); } bool NativeThemeBase::IntersectsClipRectInt(SkCanvas* canvas, int x, int y, int w, int h) const { SkRect clip; return canvas->getClipBounds(&clip) && clip.intersect(SkIntToScalar(x), SkIntToScalar(y), SkIntToScalar(x + w), SkIntToScalar(y + h)); } void NativeThemeBase::DrawBitmapInt( SkCanvas* canvas, const SkBitmap& bitmap, int src_x, int src_y, int src_w, int src_h, int dest_x, int dest_y, int dest_w, int dest_h) const { DLOG_ASSERT(src_x + src_w < std::numeric_limits<int16_t>::max() && src_y + src_h < std::numeric_limits<int16_t>::max()); if (src_w <= 0 || src_h <= 0 || dest_w <= 0 || dest_h <= 0) { NOTREACHED() << "Attempting to draw bitmap to/from an empty rect!"; return; } if (!IntersectsClipRectInt(canvas, dest_x, dest_y, dest_w, dest_h)) return; SkRect dest_rect = { SkIntToScalar(dest_x), SkIntToScalar(dest_y), SkIntToScalar(dest_x + dest_w), SkIntToScalar(dest_y + dest_h) }; if (src_w == dest_w && src_h == dest_h) { // Workaround for apparent bug in Skia that causes image to occasionally // shift. SkIRect src_rect = { src_x, src_y, src_x + src_w, src_y + src_h }; canvas->drawBitmapRect(bitmap, &src_rect, dest_rect); return; } // Make a bitmap shader that contains the bitmap we want to draw. This is // basically what SkCanvas.drawBitmap does internally, but it gives us // more control over quality and will use the mipmap in the source image if // it has one, whereas drawBitmap won't. SkShader* shader = SkShader::CreateBitmapShader(bitmap, SkShader::kRepeat_TileMode, SkShader::kRepeat_TileMode); SkMatrix shader_scale; shader_scale.setScale(SkFloatToScalar(static_cast<float>(dest_w) / src_w), SkFloatToScalar(static_cast<float>(dest_h) / src_h)); shader_scale.preTranslate(SkIntToScalar(-src_x), SkIntToScalar(-src_y)); shader_scale.postTranslate(SkIntToScalar(dest_x), SkIntToScalar(dest_y)); shader->setLocalMatrix(shader_scale); // The rect will be filled by the bitmap. SkPaint p; p.setFilterBitmap(true); p.setShader(shader); shader->unref(); canvas->drawRect(dest_rect, p); } void NativeThemeBase::DrawTiledImage(SkCanvas* canvas, const SkBitmap& bitmap, int src_x, int src_y, double tile_scale_x, double tile_scale_y, int dest_x, int dest_y, int w, int h) const { SkShader* shader = SkShader::CreateBitmapShader(bitmap, SkShader::kRepeat_TileMode, SkShader::kRepeat_TileMode); if (tile_scale_x != 1.0 || tile_scale_y != 1.0) { SkMatrix shader_scale; shader_scale.setScale(SkDoubleToScalar(tile_scale_x), SkDoubleToScalar(tile_scale_y)); shader->setLocalMatrix(shader_scale); } SkPaint paint; paint.setShader(shader); paint.setXfermodeMode(SkXfermode::kSrcOver_Mode); // CreateBitmapShader returns a Shader with a reference count of one, we // need to unref after paint takes ownership of the shader. shader->unref(); canvas->save(); canvas->translate(SkIntToScalar(dest_x - src_x), SkIntToScalar(dest_y - src_y)); canvas->clipRect(SkRect::MakeXYWH(src_x, src_y, w, h)); canvas->drawPaint(paint); canvas->restore(); } SkColor NativeThemeBase::SaturateAndBrighten(SkScalar* hsv, SkScalar saturate_amount, SkScalar brighten_amount) const { SkScalar color[3]; color[0] = hsv[0]; color[1] = Clamp(hsv[1] + saturate_amount, 0.0, 1.0); color[2] = Clamp(hsv[2] + brighten_amount, 0.0, 1.0); return SkHSVToColor(color); } void NativeThemeBase::DrawVertLine(SkCanvas* canvas, int x, int y1, int y2, const SkPaint& paint) const { SkIRect skrect; skrect.set(x, y1, x + 1, y2 + 1); canvas->drawIRect(skrect, paint); } void NativeThemeBase::DrawHorizLine(SkCanvas* canvas, int x1, int x2, int y, const SkPaint& paint) const { SkIRect skrect; skrect.set(x1, y, x2 + 1, y + 1); canvas->drawIRect(skrect, paint); } void NativeThemeBase::DrawBox(SkCanvas* canvas, const gfx::Rect& rect, const SkPaint& paint) const { const int right = rect.x() + rect.width() - 1; const int bottom = rect.y() + rect.height() - 1; DrawHorizLine(canvas, rect.x(), right, rect.y(), paint); DrawVertLine(canvas, right, rect.y(), bottom, paint); DrawHorizLine(canvas, rect.x(), right, bottom, paint); DrawVertLine(canvas, rect.x(), rect.y(), bottom, paint); } SkScalar NativeThemeBase::Clamp(SkScalar value, SkScalar min, SkScalar max) const { return std::min(std::max(value, min), max); } SkColor NativeThemeBase::OutlineColor(SkScalar* hsv1, SkScalar* hsv2) const { // GTK Theme engines have way too much control over the layout of // the scrollbar. We might be able to more closely approximate its // look-and-feel, if we sent whole images instead of just colors // from the browser to the renderer. But even then, some themes // would just break. // // So, instead, we don't even try to 100% replicate the look of // the native scrollbar. We render our own version, but we make // sure to pick colors that blend in nicely with the system GTK // theme. In most cases, we can just sample a couple of pixels // from the system scrollbar and use those colors to draw our // scrollbar. // // This works fine for the track color and the overall thumb // color. But it fails spectacularly for the outline color used // around the thumb piece. Not all themes have a clearly defined // outline. For some of them it is partially transparent, and for // others the thickness is very unpredictable. // // So, instead of trying to approximate the system theme, we // instead try to compute a reasonable looking choice based on the // known color of the track and the thumb piece. This is difficult // when trying to deal both with high- and low-contrast themes, // and both with positive and inverted themes. // // The following code has been tested to look OK with all of the // default GTK themes. SkScalar min_diff = Clamp((hsv1[1] + hsv2[1]) * 1.2f, 0.28f, 0.5f); SkScalar diff = Clamp(fabs(hsv1[2] - hsv2[2]) / 2, min_diff, 0.5f); if (hsv1[2] + hsv2[2] > 1.0) diff = -diff; return SaturateAndBrighten(hsv2, -0.2f, diff); } } // namespace ui
34.972279
80
0.643161
[ "render", "solid" ]
4f8798dcb54ba84db5cd08fca352bb9051f245c3
28,564
cpp
C++
Userland/Libraries/LibGUI/TextDocument.cpp
AristodamusAdairs/SegueBaseOS
36e8546009cfea6acd25f111b1cd0ce766271a77
[ "BSD-2-Clause", "MIT" ]
1
2021-07-05T13:51:23.000Z
2021-07-05T13:51:23.000Z
Userland/Libraries/LibGUI/TextDocument.cpp
AristodamusAdairs/SegueBaseOS
36e8546009cfea6acd25f111b1cd0ce766271a77
[ "BSD-2-Clause", "MIT" ]
1
2021-08-02T21:33:29.000Z
2021-08-06T21:22:19.000Z
Userland/Libraries/LibGUI/TextDocument.cpp
AristodamusAdairs/SegueBaseOS
36e8546009cfea6acd25f111b1cd0ce766271a77
[ "BSD-2-Clause", "MIT" ]
null
null
null
/* * Copyright (c) 2018-2020, Andreas Kling <kling@seguebaseos.org> * * SPDX-License-Identifier: BSD-2-Clause */ #include <AK/Badge.h> #include <AK/CharacterTypes.h> #include <AK/ScopeGuard.h> #include <AK/StringBuilder.h> #include <AK/Utf8View.h> #include <LibCore/Timer.h> #include <LibGUI/TextDocument.h> #include <LibGUI/TextEditor.h> #include <LibRegex/Regex.h> namespace GUI { NonnullRefPtr<TextDocument> TextDocument::create(Client* client) { return adopt_ref(*new TextDocument(client)); } TextDocument::TextDocument(Client* client) { if (client) m_clients.set(client); append_line(make<TextDocumentLine>(*this)); set_unmodified(); m_undo_stack.on_state_change = [this] { if (m_client_notifications_enabled) { for (auto* client : m_clients) client->document_did_update_undo_stack(); } }; } TextDocument::~TextDocument() { } bool TextDocument::set_text(const StringView& text) { m_client_notifications_enabled = false; m_undo_stack.clear(); m_spans.clear(); remove_all_lines(); ArmedScopeGuard clear_text_guard([this]() { set_text({}); }); size_t start_of_current_line = 0; auto add_line = [&](size_t current_position) -> bool { size_t line_length = current_position - start_of_current_line; auto line = make<TextDocumentLine>(*this); bool success = true; if (line_length) success = line->set_text(*this, text.substring_view(start_of_current_line, current_position - start_of_current_line)); if (!success) return false; append_line(move(line)); start_of_current_line = current_position + 1; return true; }; size_t i = 0; for (i = 0; i < text.length(); ++i) { if (text[i] != '\n') continue; auto success = add_line(i); if (!success) return false; } auto success = add_line(i); if (!success) return false; // Don't show the file's trailing newline as an actual new line. if (line_count() > 1 && line(line_count() - 1).is_empty()) m_lines.take_last(); m_client_notifications_enabled = true; for (auto* client : m_clients) client->document_did_set_text(); clear_text_guard.disarm(); // FIXME: Should the modified state be cleared on some of the earlier returns as well? set_unmodified(); return true; } size_t TextDocumentLine::first_non_whitespace_column() const { for (size_t i = 0; i < length(); ++i) { auto code_point = code_points()[i]; if (!is_ascii_space(code_point)) return i; } return length(); } Optional<size_t> TextDocumentLine::last_non_whitespace_column() const { for (ssize_t i = length() - 1; i >= 0; --i) { auto code_point = code_points()[i]; if (!is_ascii_space(code_point)) return i; } return {}; } bool TextDocumentLine::ends_in_whitespace() const { if (!length()) return false; return is_ascii_space(code_points()[length() - 1]); } bool TextDocumentLine::can_select() const { if (is_empty()) return false; for (size_t i = 0; i < length(); ++i) { auto code_point = code_points()[i]; if (code_point != '\n' && code_point != '\r' && code_point != '\f' && code_point != '\v') return true; } return false; } size_t TextDocumentLine::leading_spaces() const { size_t count = 0; for (; count < m_text.size(); ++count) { if (m_text[count] != ' ') { break; } } return count; } String TextDocumentLine::to_utf8() const { StringBuilder builder; builder.append(view()); return builder.to_string(); } TextDocumentLine::TextDocumentLine(TextDocument& document) { clear(document); } TextDocumentLine::TextDocumentLine(TextDocument& document, const StringView& text) { set_text(document, text); } void TextDocumentLine::clear(TextDocument& document) { m_text.clear(); document.update_views({}); } void TextDocumentLine::set_text(TextDocument& document, const Vector<u32> text) { m_text = move(text); document.update_views({}); } bool TextDocumentLine::set_text(TextDocument& document, const StringView& text) { if (text.is_empty()) { clear(document); return true; } m_text.clear(); Utf8View utf8_view(text); if (!utf8_view.validate()) { return false; } for (auto code_point : utf8_view) m_text.append(code_point); document.update_views({}); return true; } void TextDocumentLine::append(TextDocument& document, const u32* code_points, size_t length) { if (length == 0) return; m_text.append(code_points, length); document.update_views({}); } void TextDocumentLine::append(TextDocument& document, u32 code_point) { insert(document, length(), code_point); } void TextDocumentLine::prepend(TextDocument& document, u32 code_point) { insert(document, 0, code_point); } void TextDocumentLine::insert(TextDocument& document, size_t index, u32 code_point) { if (index == length()) { m_text.append(code_point); } else { m_text.insert(index, code_point); } document.update_views({}); } void TextDocumentLine::remove(TextDocument& document, size_t index) { if (index == length()) { m_text.take_last(); } else { m_text.remove(index); } document.update_views({}); } void TextDocumentLine::remove_range(TextDocument& document, size_t start, size_t length) { VERIFY(length <= m_text.size()); Vector<u32> new_data; new_data.ensure_capacity(m_text.size() - length); for (size_t i = 0; i < start; ++i) new_data.append(m_text[i]); for (size_t i = (start + length); i < m_text.size(); ++i) new_data.append(m_text[i]); m_text = move(new_data); document.update_views({}); } void TextDocumentLine::truncate(TextDocument& document, size_t length) { m_text.resize(length); document.update_views({}); } void TextDocument::append_line(NonnullOwnPtr<TextDocumentLine> line) { lines().append(move(line)); if (m_client_notifications_enabled) { for (auto* client : m_clients) client->document_did_append_line(); } } void TextDocument::insert_line(size_t line_index, NonnullOwnPtr<TextDocumentLine> line) { lines().insert((int)line_index, move(line)); if (m_client_notifications_enabled) { for (auto* client : m_clients) client->document_did_insert_line(line_index); } } void TextDocument::remove_line(size_t line_index) { lines().remove((int)line_index); if (m_client_notifications_enabled) { for (auto* client : m_clients) client->document_did_remove_line(line_index); } } void TextDocument::remove_all_lines() { lines().clear(); if (m_client_notifications_enabled) { for (auto* client : m_clients) client->document_did_remove_all_lines(); } } TextDocument::Client::~Client() { } void TextDocument::register_client(Client& client) { m_clients.set(&client); } void TextDocument::unregister_client(Client& client) { m_clients.remove(&client); } void TextDocument::update_views(Badge<TextDocumentLine>) { notify_did_change(); } void TextDocument::notify_did_change() { if (m_client_notifications_enabled) { for (auto* client : m_clients) client->document_did_change(); } m_regex_needs_update = true; } void TextDocument::set_all_cursors(const TextPosition& position) { if (m_client_notifications_enabled) { for (auto* client : m_clients) client->document_did_set_cursor(position); } } String TextDocument::text() const { StringBuilder builder; for (size_t i = 0; i < line_count(); ++i) { auto& line = this->line(i); builder.append(line.view()); if (i != line_count() - 1) builder.append('\n'); } return builder.to_string(); } String TextDocument::text_in_range(const TextRange& a_range) const { auto range = a_range.normalized(); if (is_empty() || line_count() < range.end().line() - range.start().line()) return String(""); StringBuilder builder; for (size_t i = range.start().line(); i <= range.end().line(); ++i) { auto& line = this->line(i); size_t selection_start_column_on_line = range.start().line() == i ? range.start().column() : 0; size_t selection_end_column_on_line = range.end().line() == i ? range.end().column() : line.length(); builder.append(Utf32View(line.code_points() + selection_start_column_on_line, selection_end_column_on_line - selection_start_column_on_line)); if (i != range.end().line()) builder.append('\n'); } return builder.to_string(); } u32 TextDocument::code_point_at(const TextPosition& position) const { VERIFY(position.line() < line_count()); auto& line = this->line(position.line()); if (position.column() == line.length()) return '\n'; return line.code_points()[position.column()]; } TextPosition TextDocument::next_position_after(const TextPosition& position, SearchShouldWrap should_wrap) const { auto& line = this->line(position.line()); if (position.column() == line.length()) { if (position.line() == line_count() - 1) { if (should_wrap == SearchShouldWrap::Yes) return { 0, 0 }; return {}; } return { position.line() + 1, 0 }; } return { position.line(), position.column() + 1 }; } TextPosition TextDocument::previous_position_before(const TextPosition& position, SearchShouldWrap should_wrap) const { if (position.column() == 0) { if (position.line() == 0) { if (should_wrap == SearchShouldWrap::Yes) { auto& last_line = this->line(line_count() - 1); return { line_count() - 1, last_line.length() }; } return {}; } auto& prev_line = this->line(position.line() - 1); return { position.line() - 1, prev_line.length() }; } return { position.line(), position.column() - 1 }; } void TextDocument::update_regex_matches(const StringView& needle) { if (m_regex_needs_update || needle != m_regex_needle) { Regex<PosixExtended> re(needle); Vector<RegexStringView> views; for (size_t line = 0; line < m_lines.size(); ++line) { views.append(m_lines.at(line).view()); } re.search(views, m_regex_result); m_regex_needs_update = false; m_regex_needle = String { needle }; m_regex_result_match_index = -1; m_regex_result_match_capture_group_index = -1; } } TextRange TextDocument::find_next(const StringView& needle, const TextPosition& start, SearchShouldWrap should_wrap, bool regmatch, bool match_case) { if (needle.is_empty()) return {}; if (regmatch) { if (!m_regex_result.matches.size()) return {}; regex::Match match; bool use_whole_match { false }; auto next_match = [&] { m_regex_result_match_capture_group_index = 0; if (m_regex_result_match_index == m_regex_result.matches.size() - 1) { if (should_wrap == SearchShouldWrap::Yes) m_regex_result_match_index = 0; else ++m_regex_result_match_index; } else ++m_regex_result_match_index; }; if (m_regex_result.n_capture_groups) { if (m_regex_result_match_index >= m_regex_result.capture_group_matches.size()) next_match(); else { // check if last capture group has been reached if (m_regex_result_match_capture_group_index >= m_regex_result.capture_group_matches.at(m_regex_result_match_index).size()) { next_match(); } else { // get to the next capture group item ++m_regex_result_match_capture_group_index; } } // use whole match, if there is no capture group for current index if (m_regex_result_match_index >= m_regex_result.capture_group_matches.size()) use_whole_match = true; else if (m_regex_result_match_capture_group_index >= m_regex_result.capture_group_matches.at(m_regex_result_match_index).size()) next_match(); } else { next_match(); } if (use_whole_match || !m_regex_result.capture_group_matches.at(m_regex_result_match_index).size()) match = m_regex_result.matches.at(m_regex_result_match_index); else match = m_regex_result.capture_group_matches.at(m_regex_result_match_index).at(m_regex_result_match_capture_group_index); return TextRange { { match.line, match.column }, { match.line, match.column + match.view.length() } }; } TextPosition position = start.is_valid() ? start : TextPosition(0, 0); TextPosition original_position = position; TextPosition start_of_potential_match; size_t needle_index = 0; do { auto ch = code_point_at(position); // FIXME: This is not the right way to use a Unicode needle! if (match_case ? ch == (u32)needle[needle_index] : tolower(ch) == tolower((u32)needle[needle_index])) { if (needle_index == 0) start_of_potential_match = position; ++needle_index; if (needle_index >= needle.length()) return { start_of_potential_match, next_position_after(position, should_wrap) }; } else { if (needle_index > 0) position = start_of_potential_match; needle_index = 0; } position = next_position_after(position, should_wrap); } while (position.is_valid() && position != original_position); return {}; } TextRange TextDocument::find_previous(const StringView& needle, const TextPosition& start, SearchShouldWrap should_wrap, bool regmatch, bool match_case) { if (needle.is_empty()) return {}; if (regmatch) { if (!m_regex_result.matches.size()) return {}; regex::Match match; bool use_whole_match { false }; auto next_match = [&] { if (m_regex_result_match_index == 0) { if (should_wrap == SearchShouldWrap::Yes) m_regex_result_match_index = m_regex_result.matches.size() - 1; else --m_regex_result_match_index; } else --m_regex_result_match_index; m_regex_result_match_capture_group_index = m_regex_result.capture_group_matches.at(m_regex_result_match_index).size() - 1; }; if (m_regex_result.n_capture_groups) { if (m_regex_result_match_index >= m_regex_result.capture_group_matches.size()) next_match(); else { // check if last capture group has been reached if (m_regex_result_match_capture_group_index >= m_regex_result.capture_group_matches.at(m_regex_result_match_index).size()) { next_match(); } else { // get to the next capture group item --m_regex_result_match_capture_group_index; } } // use whole match, if there is no capture group for current index if (m_regex_result_match_index >= m_regex_result.capture_group_matches.size()) use_whole_match = true; else if (m_regex_result_match_capture_group_index >= m_regex_result.capture_group_matches.at(m_regex_result_match_index).size()) next_match(); } else { next_match(); } if (use_whole_match || !m_regex_result.capture_group_matches.at(m_regex_result_match_index).size()) match = m_regex_result.matches.at(m_regex_result_match_index); else match = m_regex_result.capture_group_matches.at(m_regex_result_match_index).at(m_regex_result_match_capture_group_index); return TextRange { { match.line, match.column }, { match.line, match.column + match.view.length() } }; } TextPosition position = start.is_valid() ? start : TextPosition(0, 0); position = previous_position_before(position, should_wrap); if (position.line() >= line_count()) return {}; TextPosition original_position = position; TextPosition end_of_potential_match; size_t needle_index = needle.length() - 1; do { auto ch = code_point_at(position); // FIXME: This is not the right way to use a Unicode needle! if (match_case ? ch == (u32)needle[needle_index] : tolower(ch) == tolower((u32)needle[needle_index])) { if (needle_index == needle.length() - 1) end_of_potential_match = position; if (needle_index == 0) return { position, next_position_after(end_of_potential_match, should_wrap) }; --needle_index; } else { if (needle_index < needle.length() - 1) position = end_of_potential_match; needle_index = needle.length() - 1; } position = previous_position_before(position, should_wrap); } while (position.is_valid() && position != original_position); return {}; } Vector<TextRange> TextDocument::find_all(const StringView& needle, bool regmatch) { Vector<TextRange> ranges; TextPosition position; for (;;) { auto range = find_next(needle, position, SearchShouldWrap::No, regmatch); if (!range.is_valid()) break; ranges.append(range); position = range.end(); } return ranges; } Optional<TextDocumentSpan> TextDocument::first_non_skippable_span_before(const TextPosition& position) const { for (int i = m_spans.size() - 1; i >= 0; --i) { if (!m_spans[i].range.contains(position)) continue; while ((i - 1) >= 0 && m_spans[i - 1].is_skippable) --i; if (i <= 0) return {}; return m_spans[i - 1]; } return {}; } Optional<TextDocumentSpan> TextDocument::first_non_skippable_span_after(const TextPosition& position) const { for (size_t i = 0; i < m_spans.size(); ++i) { if (!m_spans[i].range.contains(position)) continue; while ((i + 1) < m_spans.size() && m_spans[i + 1].is_skippable) ++i; if (i >= (m_spans.size() - 1)) return {}; return m_spans[i + 1]; } return {}; } TextPosition TextDocument::first_word_break_before(const TextPosition& position, bool start_at_column_before) const { if (position.column() == 0) { if (position.line() == 0) { return TextPosition(0, 0); } auto previous_line = this->line(position.line() - 1); return TextPosition(position.line() - 1, previous_line.length()); } auto target = position; auto line = this->line(target.line()); auto modifier = start_at_column_before ? 1 : 0; if (target.column() == line.length()) modifier = 1; auto is_start_alphanumeric = is_ascii_alphanumeric(line.code_points()[target.column() - modifier]); while (target.column() > 0) { auto prev_code_point = line.code_points()[target.column() - 1]; if ((is_start_alphanumeric && !is_ascii_alphanumeric(prev_code_point)) || (!is_start_alphanumeric && is_ascii_alphanumeric(prev_code_point))) break; target.set_column(target.column() - 1); } return target; } TextPosition TextDocument::first_word_break_after(const TextPosition& position) const { auto target = position; auto line = this->line(target.line()); if (position.column() >= line.length()) { if (position.line() >= this->line_count() - 1) { return position; } return TextPosition(position.line() + 1, 0); } auto is_start_alphanumeric = is_ascii_alphanumeric(line.code_points()[target.column()]); while (target.column() < line.length()) { auto next_code_point = line.code_points()[target.column()]; if ((is_start_alphanumeric && !is_ascii_alphanumeric(next_code_point)) || (!is_start_alphanumeric && is_ascii_alphanumeric(next_code_point))) break; target.set_column(target.column() + 1); } return target; } void TextDocument::undo() { if (!can_undo()) return; m_undo_stack.undo(); notify_did_change(); } void TextDocument::redo() { if (!can_redo()) return; m_undo_stack.redo(); notify_did_change(); } void TextDocument::add_to_undo_stack(NonnullOwnPtr<TextDocumentUndoCommand> undo_command) { m_undo_stack.push(move(undo_command)); } TextDocumentUndoCommand::TextDocumentUndoCommand(TextDocument& document) : m_document(document) { } TextDocumentUndoCommand::~TextDocumentUndoCommand() { } InsertTextCommand::InsertTextCommand(TextDocument& document, const String& text, const TextPosition& position) : TextDocumentUndoCommand(document) , m_text(text) , m_range({ position, position }) { } String InsertTextCommand::action_text() const { return "Insert Text"; } bool InsertTextCommand::merge_with(GUI::Command const& other) { if (!is<InsertTextCommand>(other)) return false; auto& typed_other = static_cast<InsertTextCommand const&>(other); if (m_range.end() != typed_other.m_range.start()) return false; if (m_range.start().line() != m_range.end().line()) return false; StringBuilder builder(m_text.length() + typed_other.m_text.length()); builder.append(m_text); builder.append(typed_other.m_text); m_text = builder.to_string(); m_range.set_end(typed_other.m_range.end()); return true; } void InsertTextCommand::perform_formatting(const TextDocument::Client& client) { const size_t tab_width = client.soft_tab_width(); const auto& dest_line = m_document.line(m_range.start().line()); const bool should_auto_indent = client.is_automatic_indentation_enabled(); StringBuilder builder; size_t column = m_range.start().column(); size_t line_indentation = dest_line.leading_spaces(); bool at_start_of_line = line_indentation == column; for (auto input_char : m_text) { if (input_char == '\n') { builder.append('\n'); column = 0; if (should_auto_indent) { for (; column < line_indentation; ++column) { builder.append(' '); } } at_start_of_line = true; } else if (input_char == '\t') { size_t next_soft_tab_stop = ((column + tab_width) / tab_width) * tab_width; size_t spaces_to_insert = next_soft_tab_stop - column; for (size_t i = 0; i < spaces_to_insert; ++i) { builder.append(' '); } column = next_soft_tab_stop; if (at_start_of_line) { line_indentation = column; } } else { if (input_char == ' ') { if (at_start_of_line) { ++line_indentation; } } else { at_start_of_line = false; } builder.append(input_char); ++column; } } m_text = builder.build(); } void InsertTextCommand::redo() { auto new_cursor = m_document.insert_at(m_range.start(), m_text, m_client); // NOTE: We don't know where the range ends until after doing redo(). // This is okay since we always do redo() after adding this to the undo stack. m_range.set_end(new_cursor); m_document.set_all_cursors(new_cursor); } void InsertTextCommand::undo() { m_document.remove(m_range); m_document.set_all_cursors(m_range.start()); } RemoveTextCommand::RemoveTextCommand(TextDocument& document, const String& text, const TextRange& range) : TextDocumentUndoCommand(document) , m_text(text) , m_range(range) { } String RemoveTextCommand::action_text() const { return "Remove Text"; } bool RemoveTextCommand::merge_with(GUI::Command const& other) { if (!is<RemoveTextCommand>(other)) return false; auto& typed_other = static_cast<RemoveTextCommand const&>(other); if (m_range.start() != typed_other.m_range.end()) return false; if (m_range.start().line() != m_range.end().line()) return false; // Merge backspaces StringBuilder builder(m_text.length() + typed_other.m_text.length()); builder.append(typed_other.m_text); builder.append(m_text); m_text = builder.to_string(); m_range.set_start(typed_other.m_range.start()); return true; return false; } void RemoveTextCommand::redo() { m_document.remove(m_range); m_document.set_all_cursors(m_range.start()); } void RemoveTextCommand::undo() { auto new_cursor = m_document.insert_at(m_range.start(), m_text); m_document.set_all_cursors(new_cursor); } TextPosition TextDocument::insert_at(const TextPosition& position, const StringView& text, const Client* client) { TextPosition cursor = position; Utf8View utf8_view(text); for (auto code_point : utf8_view) cursor = insert_at(cursor, code_point, client); return cursor; } TextPosition TextDocument::insert_at(const TextPosition& position, u32 code_point, const Client*) { if (code_point == '\n') { auto new_line = make<TextDocumentLine>(*this); new_line->append(*this, line(position.line()).code_points() + position.column(), line(position.line()).length() - position.column()); line(position.line()).truncate(*this, position.column()); insert_line(position.line() + 1, move(new_line)); notify_did_change(); return { position.line() + 1, 0 }; } else { line(position.line()).insert(*this, position.column(), code_point); notify_did_change(); return { position.line(), position.column() + 1 }; } } void TextDocument::remove(const TextRange& unnormalized_range) { if (!unnormalized_range.is_valid()) return; auto range = unnormalized_range.normalized(); // First delete all the lines in between the first and last one. for (size_t i = range.start().line() + 1; i < range.end().line();) { remove_line(i); range.end().set_line(range.end().line() - 1); } if (range.start().line() == range.end().line()) { // Delete within same line. auto& line = this->line(range.start().line()); if (line.length() == 0) return; bool whole_line_is_selected = range.start().column() == 0 && range.end().column() == line.length(); if (whole_line_is_selected) { line.clear(*this); } else { line.remove_range(*this, range.start().column(), range.end().column() - range.start().column()); } } else { // Delete across a newline, merging lines. VERIFY(range.start().line() == range.end().line() - 1); auto& first_line = line(range.start().line()); auto& second_line = line(range.end().line()); Vector<u32> code_points; code_points.append(first_line.code_points(), range.start().column()); code_points.append(second_line.code_points() + range.end().column(), second_line.length() - range.end().column()); first_line.set_text(*this, move(code_points)); remove_line(range.end().line()); } if (lines().is_empty()) { append_line(make<TextDocumentLine>(*this)); } notify_did_change(); } bool TextDocument::is_empty() const { return line_count() == 1 && line(0).is_empty(); } TextRange TextDocument::range_for_entire_line(size_t line_index) const { if (line_index >= line_count()) return {}; return { { line_index, 0 }, { line_index, line(line_index).length() } }; } const TextDocumentSpan* TextDocument::span_at(const TextPosition& position) const { for (auto& span : m_spans) { if (span.range.contains(position)) return &span; } return nullptr; } void TextDocument::set_unmodified() { m_undo_stack.set_current_unmodified(); } }
30.452026
152
0.629079
[ "vector" ]
4f88d76aedff62fab731746dc7b18800eb47eb07
11,328
cpp
C++
pxr/usd/lib/sdf/specType.cpp
octarrow/USD
1845291a9701ab0a3a7d591bc243a1a80fdcba8a
[ "Unlicense" ]
18
2017-10-28T22:37:48.000Z
2022-01-26T12:00:24.000Z
pxr/usd/lib/sdf/specType.cpp
piscees/USD
65320d266057ae0a68626217f54a0298ac092799
[ "AML" ]
1
2021-08-14T23:57:51.000Z
2021-08-14T23:57:51.000Z
pxr/usd/lib/sdf/specType.cpp
piscees/USD
65320d266057ae0a68626217f54a0298ac092799
[ "AML" ]
4
2018-06-14T18:14:59.000Z
2021-09-13T22:20:50.000Z
// // Copyright 2016 Pixar // // Licensed under the Apache License, Version 2.0 (the "Apache License") // with the following modification; you may not use this file except in // compliance with the Apache License and the following modification to it: // Section 6. Trademarks. is deleted and replaced with: // // 6. Trademarks. This License does not grant permission to use the trade // names, trademarks, service marks, or product names of the Licensor // and its affiliates, except as required to comply with Section 4(c) of // the License and to reproduce the content of the NOTICE file. // // You may obtain a copy of the Apache License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the Apache License with the above modification is // distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the Apache License for the specific // language governing permissions and limitations under the Apache License. // /// \file SpecType.cpp #include "pxr/pxr.h" #include "pxr/usd/sdf/specType.h" #include "pxr/usd/sdf/schema.h" #include "pxr/usd/sdf/spec.h" #include "pxr/base/arch/demangle.h" #include "pxr/base/tf/diagnostic.h" #include "pxr/base/tf/hash.h" #include "pxr/base/tf/instantiateSingleton.h" #include "pxr/base/tf/registryManager.h" #include "pxr/base/tf/singleton.h" #include "pxr/base/tf/stl.h" #include "pxr/base/tf/type.h" #include "pxr/base/tf/hashmap.h" #include <map> #include <utility> #include <vector> using std::pair; using std::make_pair; using std::vector; PXR_NAMESPACE_OPEN_SCOPE static inline size_t _GetBitmaskForSpecType(SdfSpecType specType) { return (size_t(1) << specType); } struct Sdf_SpecTypeInfo { static Sdf_SpecTypeInfo& GetInstance() { return TfSingleton<Sdf_SpecTypeInfo>::GetInstance(); } // Mapping from C++ spec type to bitmask indicating the possible source // spec types. This table lets us answer the question, "If I have an // spec whose SdfSpecType is X, can I create the C++ spec type Y from // that?" For example, a possible entry in this table could be // (SdfPrimSpec, SdfSpecTypePrim), indicating that consumers can create // an SdfPrimSpec from any spec whose spec type is SdfSpecTypePrim. typedef TfHashMap<TfType, size_t, TfHash> SpecTypeToBitmask; SpecTypeToBitmask specTypeToBitmask; // Cache of type_info -> TfType used during cast operations to avoid TfType // lookups. This speeds up these operations, especially when run // concurrently since TfType has a global lock. typedef vector<pair<std::type_info const *, TfType> > SpecTypeInfoToTfType; SpecTypeInfoToTfType specTypeInfoToTfType; // Mapping from schema class to mapping from SdfSpecType to spec class. // In other words, for a given schema and spec type, what is the // corresponding C++ spec class? typedef std::vector<TfType> SpecTypeToTfType; typedef TfHashMap<TfType, SpecTypeToTfType, TfHash> SchemaTypeToSpecTypes; SchemaTypeToSpecTypes schemaTypeToSpecTypes; // Mapping from spec class to schema class. In other words, what schema // is associated with a given C++ spec class. typedef TfHashMap<TfType, TfType, TfHash> SpecTypeToSchemaType; SpecTypeToSchemaType specTypeToSchemaType; std::atomic<bool> registrationsCompleted; // Helper function for creating an entry in the specTypeToBitmask table. SpecTypeToBitmask::iterator CreateSpecTypeEntry(const std::type_info& specCPPType) { const TfType& specTfType = TfType::Find(specCPPType); if (specTfType.IsUnknown()) { TF_CODING_ERROR( "Spec type %s must be registered with the TfType system.", ArchGetDemangled(specCPPType).c_str()); return specTypeToBitmask.end(); } const std::pair<SpecTypeToBitmask::iterator, bool> mapStatus = specTypeToBitmask.insert(std::make_pair(specTfType, 0)); if (!mapStatus.second) { TF_CODING_ERROR( "Duplicate registration for spec type %s.", specTfType.GetTypeName().c_str()); return specTypeToBitmask.end(); } // Add an entry into the specTypeInfoToTfType. specTypeInfoToTfType.push_back(make_pair(&specCPPType, specTfType)); return mapStatus.first; } // Find the TfType corresponding to specCPPType. This will look in the // specTypeInfoToTfType cache first to avoid hitting the TfType lock. inline TfType TfTypeFind(const std::type_info &specCPPtype) const { typedef pair<const std::type_info *, TfType> Pair; for (const auto& p : specTypeInfoToTfType) { if (p.first == &specCPPtype) return p.second; } return TfType::Find(specCPPtype); } private: friend class TfSingleton<Sdf_SpecTypeInfo>; Sdf_SpecTypeInfo() : specTypeToBitmask(0) , registrationsCompleted(false) { TfSingleton<Sdf_SpecTypeInfo>::SetInstanceConstructed(*this); TfRegistryManager::GetInstance().SubscribeTo<SdfSpecTypeRegistration>(); // Basic registration is complete. Note, however that this does not // account for registrations from downstream libraries like Sd. See bug // 111728. registrationsCompleted = true; } }; TF_INSTANTIATE_SINGLETON(Sdf_SpecTypeInfo); void SdfSpecTypeRegistration::_RegisterSpecType( const std::type_info& specCPPType, SdfSpecType specEnumType, const std::type_info& schemaType) { Sdf_SpecTypeInfo& specTypeInfo = Sdf_SpecTypeInfo::GetInstance(); const TfType& schemaTfType = specTypeInfo.TfTypeFind(schemaType); if (schemaTfType.IsUnknown()) { TF_CODING_ERROR( "Schema type %s must be registered with the TfType system.", ArchGetDemangled(schemaType).c_str()); } Sdf_SpecTypeInfo::SpecTypeToBitmask::iterator specEntry = specTypeInfo.CreateSpecTypeEntry(specCPPType); if (specEntry == specTypeInfo.specTypeToBitmask.end()) { // Error already emitted, bail out. return; } const TfType& specTfType = specEntry->first; size_t& specAllowedBitmask = specEntry->second; // Check every entry currently in the specTypeToBitmask (including the // one that was just added above) and indicate whether each spec type // can be created from the spec type we're registering. TF_FOR_ALL(it, specTypeInfo.specTypeToBitmask) { if (specTfType.IsA(it->first)) it->second |= _GetBitmaskForSpecType(specEnumType); else if (it->first.IsA(specTfType)) specAllowedBitmask |= it->second; } // XXX: See comments in Sdf_SpecType::Cast if (specEnumType == SdfSpecTypePrim) { specAllowedBitmask |= _GetBitmaskForSpecType(SdfSpecTypeVariant); } Sdf_SpecTypeInfo::SpecTypeToTfType& specTypeToTfType = specTypeInfo.schemaTypeToSpecTypes[schemaTfType]; if (specTypeToTfType.empty()) { specTypeToTfType.resize(SdfNumSpecTypes); } specTypeToTfType[specEnumType] = specTfType; specTypeInfo.specTypeToSchemaType[specTfType] = schemaTfType; } void SdfSpecTypeRegistration::_RegisterAbstractSpecType( const std::type_info& specCPPType, const std::type_info& schemaType) { Sdf_SpecTypeInfo& specTypeInfo = Sdf_SpecTypeInfo::GetInstance(); const TfType& schemaTfType = specTypeInfo.TfTypeFind(schemaType); if (schemaTfType.IsUnknown()) { TF_CODING_ERROR( "Schema type %s must be registered with the TfType system.", ArchGetDemangled(schemaType).c_str()); } Sdf_SpecTypeInfo::SpecTypeToBitmask::iterator specEntry = specTypeInfo.CreateSpecTypeEntry(specCPPType); if (specEntry == specTypeInfo.specTypeToBitmask.end()) { // Error already emitted, bail out. return; } const TfType& specTfType = specEntry->first; size_t& specAllowedBitmask = specEntry->second; // Check every entry currently in the specTypeToBitmask (including the // one that was just added above) and indicate whether each spec type // can be created from the spec type we're registering. TF_FOR_ALL(it, specTypeInfo.specTypeToBitmask) { if (it->first.IsA(specTfType)) specAllowedBitmask |= it->second; } specTypeInfo.specTypeToSchemaType[specTfType] = schemaTfType; } // XXX: Note, this function must be invoked by all public API in order to wait // on basic registry initialization before accessing the registry contents. static bool _CanCast(SdfSpecType fromType, const TfType& toType) { if (toType.IsUnknown()) { return TfType(); } const Sdf_SpecTypeInfo& specTypeInfo = Sdf_SpecTypeInfo::GetInstance(); while (!specTypeInfo.registrationsCompleted) { // spin until registration has completed. } const size_t allowedBitmask = TfMapLookupByValue(specTypeInfo.specTypeToBitmask, toType, size_t(0)); return allowedBitmask & _GetBitmaskForSpecType(fromType); } TfType Sdf_SpecType::Cast(const SdfSpec& from, const std::type_info& to) { const Sdf_SpecTypeInfo& specTypeInfo = Sdf_SpecTypeInfo::GetInstance(); const SdfSpecType fromType = from.GetSpecType(); const TfType& toType = specTypeInfo.TfTypeFind(to); if (!_CanCast(fromType, toType)) { return TfType(); } const TfType& schemaType = TfType::Find(typeid(from.GetSchema())); if (!TF_VERIFY(!schemaType.IsUnknown())) { return TfType(); } const Sdf_SpecTypeInfo::SpecTypeToTfType* specTypeToTfType = TfMapLookupPtr(specTypeInfo.schemaTypeToSpecTypes, schemaType); // Allow casting to go through if we're trying to cast from a // variant spec to a prim spec. // // XXX: This is required to allow variant specs to be treated as prim // specs. However, if we're going to do that, shouldn't we just make // variant specs derive from prim specs? if (fromType == SdfSpecTypeVariant) { const TfType primSpecType = (*specTypeToTfType)[SdfSpecTypePrim]; if (toType == primSpecType) { return toType; } } return (*specTypeToTfType)[fromType]; } bool Sdf_SpecType::CanCast(SdfSpecType fromType, const std::type_info& to) { const Sdf_SpecTypeInfo& specTypeInfo = Sdf_SpecTypeInfo::GetInstance(); const TfType& toType = specTypeInfo.TfTypeFind(to); return _CanCast(fromType, toType); } bool Sdf_SpecType::CanCast(const SdfSpec& from, const std::type_info& to) { const Sdf_SpecTypeInfo& specTypeInfo = Sdf_SpecTypeInfo::GetInstance(); const SdfSpecType fromType = from.GetSpecType(); const TfType& toType = specTypeInfo.TfTypeFind(to); if (!_CanCast(fromType, toType)) { return false; } const TfType& fromSchemaType = TfType::Find(typeid(from.GetSchema())); const TfType* toSchemaType = TfMapLookupPtr(specTypeInfo.specTypeToSchemaType, toType); if (!toSchemaType || !fromSchemaType.IsA(*toSchemaType)) { return false; } return true; } PXR_NAMESPACE_CLOSE_SCOPE
35.28972
80
0.699859
[ "vector" ]
4f8ba95428b98761eab6e428e818cc2810e27fde
5,381
hpp
C++
Firmware/fibre-cpp/legacy_object_client.hpp
deafloo/ODrive
bae459bb71b39c0169f4b8a322b7371eada58112
[ "MIT" ]
1,068
2016-05-31T22:39:08.000Z
2020-12-20T22:13:01.000Z
Firmware/fibre-cpp/legacy_object_client.hpp
deafloo/ODrive
bae459bb71b39c0169f4b8a322b7371eada58112
[ "MIT" ]
389
2017-10-16T09:44:20.000Z
2020-12-21T14:19:38.000Z
Firmware/fibre-cpp/legacy_object_client.hpp
deafloo/ODrive
bae459bb71b39c0169f4b8a322b7371eada58112
[ "MIT" ]
681
2016-06-12T01:41:00.000Z
2020-12-21T12:49:32.000Z
#ifndef __FIBRE_LEGACY_OBJECT_MODEL_HPP #define __FIBRE_LEGACY_OBJECT_MODEL_HPP #include <fibre/async_stream.hpp> #include <unordered_map> #include <vector> #include <memory> #include <string> #include <fibre/callback.hpp> #include <fibre/cpp_utils.hpp> // std::variant and std::optional C++ backport #include <fibre/fibre.hpp> struct json_value; namespace fibre { struct EndpointOperationResult { StreamStatus status; const uint8_t* tx_end; uint8_t* rx_end; }; // Lower 16 bits are the seqno. Upper 16 bits are all 1 for valid handles // (such that seqno 0 doesn't cause the handle to be 0) using EndpointOperationHandle = uint32_t; struct LegacyProtocolPacketBased; struct LegacyFibreArg { std::string name; std::string protocol_codec; std::string app_codec; size_t protocol_size; size_t app_size; size_t ep_num; }; struct LegacyObject; struct LegacyFunction : Function { LegacyFunction(std::vector<LegacyFibreArg> inputs, std::vector<LegacyFibreArg> outputs) : ep_num(0), obj_(nullptr), inputs(inputs), outputs(outputs) {} LegacyFunction(size_t ep_num, LegacyObject* obj, std::vector<LegacyFibreArg> inputs, std::vector<LegacyFibreArg> outputs) : ep_num(ep_num), obj_(obj), inputs(inputs), outputs(outputs) {} std::optional<CallBufferRelease> call(void**, CallBuffers, Callback<std::optional<CallBuffers>, CallBufferRelease>) final; size_t ep_num; // 0 for property read/write/exchange functions LegacyObject* obj_; // null for property read/write/exchange functions (all other functions are associated with one object only) std::vector<LegacyFibreArg> inputs; std::vector<LegacyFibreArg> outputs; }; struct FibreInterface; class LegacyObjectClient; struct LegacyFibreAttribute { std::shared_ptr<LegacyObject> object; }; struct FibreInterface { std::string name; std::unordered_map<std::string, LegacyFunction> functions; std::unordered_map<std::string, LegacyFibreAttribute> attributes; }; struct LegacyObject { LegacyObjectClient* client; size_t ep_num; std::shared_ptr<FibreInterface> intf; bool known_to_application; }; struct LegacyCallContext { LegacyFunction* func_; size_t progress = 0; //!< 0: expecting more tx data //!< [1...n_inputs]: endpoint operations for sending inputs //!< n_inputs + 1: trigger endpoint operation //!< [n_inputs + 2, n_inputs + 2 + n_outputs]: endpoint operations for receiving outputs //!< n_inputs + 3 + n_outputs: reporting outputs to application EndpointOperationHandle op_handle_ = 0; std::vector<uint8_t> tx_buf_; size_t tx_pos_ = 0; std::vector<uint8_t> rx_buf_; size_t rx_pos_ = 0; const uint8_t* app_tx_end_; bufptr_t app_rx_buf_; Callback<std::optional<CallBuffers>, CallBufferRelease> callback; std::optional<EndpointOperationResult> ep_result; LegacyObject* obj_; std::optional<CallBufferRelease> resume_from_app(CallBuffers, Callback<std::optional<CallBuffers>, CallBufferRelease>); void resume_from_protocol(EndpointOperationResult result); struct ContinueWithProtocol { LegacyProtocolPacketBased* client; size_t ep_num; cbufptr_t tx_buf; bufptr_t rx_buf; }; using ContinueWithApp = CallBufferRelease; using ResultFromProtocol = EndpointOperationResult; using ResultFromApp = CallBuffers; struct InternalError {}; // Returns control either to the application or to the next endpoint operation std::variant<ContinueWithApp, ContinueWithProtocol, InternalError> get_next_task(std::variant<ResultFromApp, ResultFromProtocol> continue_from); }; class LegacyObjectClient { public: LegacyObjectClient(LegacyProtocolPacketBased* protocol) : protocol_(protocol) {} void start(Callback<void, LegacyObjectClient*, std::shared_ptr<LegacyObject>> on_found_root_object, Callback<void, LegacyObjectClient*, std::shared_ptr<LegacyObject>> on_lost_root_object); bool transcode(cbufptr_t src, bufptr_t dst, std::string src_codec, std::string dst_codec); // For direct access by LegacyProtocolPacketBased and libfibre.cpp uint16_t json_crc_ = 0; Callback<void, LegacyObjectClient*, std::shared_ptr<LegacyObject>> on_lost_root_object_; std::shared_ptr<LegacyObject> root_obj_; std::vector<std::shared_ptr<LegacyObject>> objects_; void* user_data_; // used by libfibre to store the libfibre context pointer LegacyProtocolPacketBased* protocol_; private: std::shared_ptr<FibreInterface> get_property_interfaces(std::string codec, bool write); std::shared_ptr<LegacyObject> load_object(json_value list_val); void receive_more_json(); void on_received_json(EndpointOperationResult result); Callback<void, LegacyObjectClient*, std::shared_ptr<LegacyObject>> on_found_root_object_; uint8_t tx_buf_[4] = {0xff, 0xff, 0xff, 0xff}; EndpointOperationHandle op_handle_ = 0; std::vector<uint8_t> json_; //std::vector<LegacyCallContext*> pending_calls_; std::unordered_map<std::string, std::shared_ptr<FibreInterface>> rw_property_interfaces; std::unordered_map<std::string, std::shared_ptr<FibreInterface>> ro_property_interfaces; }; } #endif // __FIBRE_LEGACY_OBJECT_MODEL_HPP
35.401316
192
0.733878
[ "object", "vector" ]
4f8f48d0cbbbd3b08d0f405428ed3e6688f6a6e2
19,738
cpp
C++
esbmc/bmc.cpp
holao09/esbmc
659c006a45e9aaf8539b12484e2ec2b093cc6f02
[ "BSD-3-Clause" ]
null
null
null
esbmc/bmc.cpp
holao09/esbmc
659c006a45e9aaf8539b12484e2ec2b093cc6f02
[ "BSD-3-Clause" ]
null
null
null
esbmc/bmc.cpp
holao09/esbmc
659c006a45e9aaf8539b12484e2ec2b093cc6f02
[ "BSD-3-Clause" ]
null
null
null
/*******************************************************************\ Module: Symbolic Execution of ANSI-C Authors: Daniel Kroening, kroening@kroening.com Lucas Cordeiro, lcc08r@ecs.soton.ac.uk \*******************************************************************/ #include <sys/types.h> #include <signal.h> #ifndef _WIN32 #include <unistd.h> #else #include <windows.h> #include <winbase.h> #undef ERROR #undef small #endif #include <sstream> #include <fstream> #include <irep2.h> #include <i2string.h> #include <location.h> #include <time_stopping.h> #include <message_stream.h> #include <migrate.h> #include <langapi/mode.h> #include <langapi/languages.h> #include <langapi/language_util.h> #include <goto-symex/goto_trace.h> #include <goto-symex/build_goto_trace.h> #include <goto-symex/slice.h> #include <goto-symex/xml_goto_trace.h> #include <goto-symex/reachability_tree.h> #include "bmc.h" #include "document_subgoals.h" #include <ac_config.h> static volatile bool checkpoint_sig = false; void sigusr1_handler(int sig __attribute__((unused))) { checkpoint_sig = true; return; } /*******************************************************************\ Function: bmct::do_cbmc Inputs: Outputs: Purpose: \*******************************************************************/ void bmct::do_cbmc(smt_convt &solver, symex_target_equationt &equation) { solver.set_message_handler(message_handler); equation.convert(solver); } /*******************************************************************\ Function: bmct::error_trace Inputs: Outputs: Purpose: \*******************************************************************/ void bmct::error_trace(smt_convt &smt_conv, symex_target_equationt &equation) { status("Building error trace"); goto_tracet goto_trace; build_goto_trace(equation, smt_conv, goto_trace); std::string graphml_output_filename = options.get_option("witnesspath"); std::string tokenizer_path; if(!graphml_output_filename.empty()) { set_ui(ui_message_handlert::GRAPHML); tokenizer_path = options.get_option("tokenizer"); } switch (ui) { case ui_message_handlert::GRAPHML: std::cout << "The counterexample in GraphML format is available in: " << options.get_option("witnesspath") << std::endl; generate_goto_trace_in_graphml_format( tokenizer_path, graphml_output_filename, ns, goto_trace); case ui_message_handlert::PLAIN: std::cout << std::endl << "Counterexample:" << std::endl; show_goto_trace(std::cout, ns, goto_trace); break; case ui_message_handlert::OLD_GUI: show_goto_trace_gui(std::cout, ns, goto_trace); break; case ui_message_handlert::XML_UI: { xmlt xml; convert(ns, goto_trace, xml); std::cout << xml << std::endl; break; } default: assert(false); } } smt_convt::resultt bmct::run_decision_procedure(smt_convt &smt_conv, symex_target_equationt &equation) { std::string logic; if (!options.get_bool_option("int-encoding")) logic = "bit-vector arithmetic"; else logic = "integer/real arithmetic"; if (!options.get_bool_option("smt")) std::cout << "Encoding remaining VCC(s) using " << logic << "\n"; smt_conv.set_message_handler(message_handler); smt_conv.set_verbosity(get_verbosity()); fine_timet encode_start = current_time(); do_cbmc(smt_conv, equation); fine_timet encode_stop = current_time(); if (!options.get_bool_option("smt")) { std::ostringstream str; str << "Encoding to solver time: "; output_time(encode_stop - encode_start, str); str << "s"; status(str.str()); } std::stringstream ss; ss << "Solving with solver " << smt_conv.solver_text(); status(ss.str()); fine_timet sat_start=current_time(); smt_convt::resultt dec_result=smt_conv.dec_solve(); fine_timet sat_stop=current_time(); // output runtime if (!options.get_bool_option("smt")) { std::ostringstream str; str << "Runtime decision procedure: "; output_time(sat_stop-sat_start, str); str << "s"; status(str.str()); } return dec_result; } /*******************************************************************\ Function: bmct::report_success Inputs: Outputs: Purpose: \*******************************************************************/ void bmct::report_success() { if(options.get_bool_option("base-case")) { status("No bug has been found in the base case"); return ; } status("VERIFICATION SUCCESSFUL"); switch(ui) { case ui_message_handlert::OLD_GUI: std::cout << "SUCCESS" << std::endl << "Verification successful" << std::endl << "" << std::endl << "" << std::endl << "" << std::endl << "" << std::endl; break; case ui_message_handlert::PLAIN: break; case ui_message_handlert::XML_UI: { xmlt xml("cprover-status"); xml.data="SUCCESS"; std::cout << xml; std::cout << std::endl; } break; default: assert(false); } } /*******************************************************************\ Function: bmct::report_failure Inputs: Outputs: Purpose: \*******************************************************************/ void bmct::report_failure() { status("VERIFICATION FAILED"); switch(ui) { case ui_message_handlert::OLD_GUI: break; case ui_message_handlert::PLAIN: break; case ui_message_handlert::XML_UI: { xmlt xml("cprover-status"); xml.data="FAILURE"; std::cout << xml; std::cout << std::endl; } break; case ui_message_handlert::GRAPHML: break; default: assert(false); } } /*******************************************************************\ Function: bmct::show_program Inputs: Outputs: Purpose: \*******************************************************************/ void bmct::show_program(symex_target_equationt &equation) { unsigned count=1; languagest languages(ns, MODE_C); std::cout << "\n" << "Program constraints:" << "\n"; bool print_guard = config.options.get_bool_option("no-guard-printing"); for(symex_target_equationt::SSA_stepst::const_iterator it=equation.SSA_steps.begin(); it!=equation.SSA_steps.end(); it++) { std::cout << "// " << it->source.pc->location_number << " "; std::cout << it->source.pc->location.as_string() << "\n"; std::string string_value; if(it->is_assignment()) { languages.from_expr(migrate_expr_back(it->cond), string_value); std::cout << "(" << count << ") " << string_value << "\n"; } else if(it->is_assert()) { languages.from_expr(migrate_expr_back(it->cond), string_value); std::cout << "(" << count << ") " << "(assert)" << string_value << "\n"; } else if(it->is_assume()) { languages.from_expr(migrate_expr_back(it->cond), string_value); std::cout << "(" << count << ") " << "(assume)" << string_value << "\n"; } else if (it->is_renumber()) { std::cout << "(" << count << ") " << "renumber: " << from_expr(ns, "", it->lhs) << "\n"; } if(!migrate_expr_back(it->guard).is_true() && !print_guard) { languages.from_expr(migrate_expr_back(it->guard), string_value); std::cout << std::string(i2string(count).size()+3, ' '); std::cout << "guard: " << string_value << "\n"; } std::cout << "\n"; count++; } } /*******************************************************************\ Function: bmct::run Inputs: Outputs: Purpose: \*******************************************************************/ bool bmct::run(void) { #ifndef _WIN32 struct sigaction act; #endif bool resp; #ifndef _WIN32 // Collect SIGUSR1, indicating that we're supposed to checkpoint. act.sa_handler = sigusr1_handler; sigemptyset(&act.sa_mask); act.sa_flags = 0; sigaction(SIGUSR1, &act, NULL); #endif symex->options.set_option("unwind", options.get_option("unwind")); symex->setup_for_new_explore(); if(options.get_bool_option("schedule")) { resp = run_thread(); return resp; } else { if (options.get_bool_option("from-checkpoint")) { if (options.get_option("checkpoint-file") == "") { std::cerr << "Please provide a checkpoint file" << std::endl; abort(); } reachability_treet::dfs_position pos( options.get_option("checkpoint-file")); symex->restore_from_dfs_state((void*)&pos); } do { if(!options.get_bool_option("k-induction") && !options.get_bool_option("k-induction-parallel")) if (++interleaving_number>1) { print(8, "*** Thread interleavings "+ i2string((unsigned long)interleaving_number)+ " ***"); } fine_timet bmc_start = current_time(); if(run_thread()) { ++interleaving_failed; if (options.get_bool_option("checkpoint-on-cex")) { write_checkpoint(); } if(!options.get_bool_option("all-runs")) { return true; } } fine_timet bmc_stop = current_time(); std::ostringstream str; str << "BMC program time: "; output_time(bmc_stop-bmc_start, str); str << "s"; status(str.str()); if (checkpoint_sig) { write_checkpoint(); } // Only run for one run if (options.get_bool_option("interactive-ileaves")) return false; } while(symex->setup_next_formula()); } if (options.get_bool_option("all-runs")) { std::cout << "*** number of generated interleavings: " << interleaving_number << " ***" << std::endl; std::cout << "*** number of failed interleavings: " << interleaving_failed << " ***" << std::endl; } if (options.get_bool_option("ltl")) { // So, what was the lowest value ltl outcome that we saw? if (ltl_results_seen[ltl_res_bad]) { std::cout << "Final lowest outcome: LTL_BAD" << std::endl; return false; } else if (ltl_results_seen[ltl_res_failing]) { std::cout << "Final lowest outcome: LTL_FAILING" << std::endl; return false; } else if (ltl_results_seen[ltl_res_succeeding]) { std::cout << "Final lowest outcome: LTL_SUCCEEDING" << std::endl; return false; } else if (ltl_results_seen[ltl_res_good]) { std::cout << "Final lowest outcome: LTL_GOOD" << std::endl; return false; } else { std::cout << "No traces seen, apparently" << std::endl; return false; } } return false; } bool bmct::run_thread() { std::shared_ptr<goto_symext::symex_resultt> result; bool ret; fine_timet symex_start = current_time(); try { if(options.get_bool_option("schedule")) { result = symex->generate_schedule_formula(); } else { result = symex->get_next_formula(); } } catch(std::string &error_str) { message_streamt message_stream(*get_message_handler()); message_stream.error(error_str); return true; } catch(const char *error_str) { message_streamt message_stream(*get_message_handler()); message_stream.error(error_str); return true; } catch(std::bad_alloc&) { std::cout << "Out of memory" << std::endl; return true; } fine_timet symex_stop = current_time(); std::ostringstream str; str << "Symex completed in: "; output_time(symex_stop - symex_start, str); str << "s"; status(str.str()); auto equation = std::dynamic_pointer_cast<symex_target_equationt>(result->target); print(8, "size of program expression: "+ i2string((unsigned long)equation.get()->SSA_steps.size())+ " assignments"); if (options.get_bool_option("double-assign-check")) { equation.get()->check_for_duplicate_assigns(); } try { fine_timet slice_start = current_time(); if(!options.get_bool_option("no-slice")) { slice(*equation); } else { simple_slice(*equation); } fine_timet slice_stop = current_time(); std::ostringstream str; str << "Slicing time: "; output_time(slice_stop - slice_start, str); str << "s"; status(str.str()); if (options.get_bool_option("program-only") || options.get_bool_option("program-too")) show_program(*equation); if (options.get_bool_option("program-only")) return false; { std::string msg; msg="Generated "+i2string(result->total_claims)+ " VCC(s), "+i2string(result->remaining_claims)+ " remaining after simplification"; print(8, msg); } if(options.get_bool_option("document-subgoals")) { document_subgoals(*equation, std::cout); return false; } if(options.get_bool_option("show-vcc")) { show_vcc(*equation); return false; } if(result->remaining_claims==0) { report_success(); return false; } if (options.get_bool_option("ltl")) { int res = ltl_run_thread(equation.get()); // Record that we've seen this outcome; later decide what the least // outcome was. ltl_results_seen[res]++; return false; } if (options.get_bool_option("smt")) if (interleaving_number != (unsigned int) strtol(options.get_option("smtlib-ileave-num").c_str(), NULL, 10)) return false; if (!options.get_bool_option("smt-during-symex")) { delete runtime_solver; runtime_solver = create_solver_factory("", is_cpp, options.get_bool_option("int-encoding"), ns, options); } ret = run_solver(*equation, runtime_solver); return ret; } catch(std::string &error_str) { error(error_str); return true; } catch(const char *error_str) { error(error_str); return true; } catch(std::bad_alloc&) { std::cout << "Out of memory" << std::endl; return true; } } int bmct::ltl_run_thread(symex_target_equationt *equation __attribute__((unused))) { smt_convt *solver; bool ret; unsigned int num_asserts = 0; // LTL checking - first check for whether we have an indeterminate prefix, // and then check for all others. // Start by turning all assertions that aren't the negative prefix // assertion into skips. for(symex_target_equationt::SSA_stepst::iterator it=equation->SSA_steps.begin(); it!=equation->SSA_steps.end(); it++) { if (it->is_assert()) { if (it->comment != "LTL_BAD") { it->type = goto_trace_stept::SKIP; } else { num_asserts++; } } } std::cout << "Checking for LTL_BAD" << std::endl; if (num_asserts != 0) { solver = create_solver_factory("z3", is_cpp, options.get_bool_option("int-encoding"), ns, options); ret = run_solver(*equation, solver); delete solver; if (ret) { std::cout << "Found trace satisfying LTL_BAD" << std::endl; return ltl_res_bad; } } else { std::cerr << "Warning: Couldn't find LTL_BAD assertion" << std::endl; } // Didn't find it; turn skip steps back into assertions. for(symex_target_equationt::SSA_stepst::iterator it=equation->SSA_steps.begin(); it!=equation->SSA_steps.end(); it++) { if (it->type == goto_trace_stept::SKIP) it->type = goto_trace_stept::ASSERT; } // Try again, with LTL_FAILING num_asserts = 0; for(symex_target_equationt::SSA_stepst::iterator it=equation->SSA_steps.begin(); it!=equation->SSA_steps.end(); it++) { if (it->is_assert()) { if (it->comment != "LTL_FAILING") { it->type = goto_trace_stept::SKIP; } else { num_asserts++; } } } std::cout << "Checking for LTL_FAILING" << std::endl; if (num_asserts != 0) { solver = create_solver_factory("z3", is_cpp, options.get_bool_option("int-encoding"), ns, options); ret = run_solver(*equation, solver); delete solver; if (ret) { std::cout << "Found trace satisfying LTL_FAILING" << std::endl; return ltl_res_failing; } } else { std::cerr << "Warning: Couldn't find LTL_FAILING assertion" <<std::endl; } // Didn't find it; turn skip steps back into assertions. for(symex_target_equationt::SSA_stepst::iterator it=equation->SSA_steps.begin(); it!=equation->SSA_steps.end(); it++) { if (it->type == goto_trace_stept::SKIP) it->type = goto_trace_stept::ASSERT; } // Try again, with LTL_SUCCEEDING num_asserts = 0; for(symex_target_equationt::SSA_stepst::iterator it=equation->SSA_steps.begin(); it!=equation->SSA_steps.end(); it++) { if (it->is_assert()) { if (it->comment != "LTL_SUCCEEDING") { it->type = goto_trace_stept::SKIP; } else { num_asserts++; } } } std::cout << "Checking for LTL_SUCCEEDING" << std::endl; if (num_asserts != 0) { solver = create_solver_factory("z3", is_cpp, options.get_bool_option("int-encoding"), ns, options); ret = run_solver(*equation, solver); delete solver; if (ret) { std::cout << "Found trace satisfying LTL_SUCCEEDING" << std::endl; return ltl_res_succeeding; } } else { std::cerr << "Warning: Couldn't find LTL_SUCCEEDING assertion" << std::endl; } // Otherwise, we just got a good prefix. for(symex_target_equationt::SSA_stepst::iterator it=equation->SSA_steps.begin(); it!=equation->SSA_steps.end(); it++) { if (it->type == goto_trace_stept::SKIP) it->type = goto_trace_stept::ASSERT; } return ltl_res_good; } bool bmct::run_solver(symex_target_equationt &equation, smt_convt *solver) { switch(run_decision_procedure(*solver, equation)) { case smt_convt::P_UNSATISFIABLE: if(!options.get_bool_option("base-case")) report_success(); else status("No bug has been found in the base case"); return false; case smt_convt::P_SATISFIABLE: if (options.get_bool_option("inductive-step") && options.get_bool_option("show-counter-example")) { error_trace(*solver, equation); } else if(!options.get_bool_option("inductive-step") && !options.get_bool_option("forward-condition")) { error_trace(*solver, equation); report_failure(); } else if (options.get_bool_option("forward-condition")) status("The forward condition is unable to prove the property"); else status("The inductive step is unable to prove the property"); return true; // Return failure if we didn't actually check anything, we just emitted the // test information to an SMTLIB formatted file. Causes esbmc to quit // immediately (with no error reported) case smt_convt::P_SMTLIB: return true; default: error("decision procedure failed"); return true; } } void bmct::write_checkpoint(void) { std::string f; if (options.get_option("checkpoint-file") == "") { char buffer[32]; #ifndef _WIN32 pid_t pid = getpid(); #else unsigned long pid = GetCurrentProcessId(); #endif sprintf(buffer, "%d", pid); f = "esbmc_checkpoint." + std::string(buffer); } else { f = options.get_option("checkpoint-file"); } symex->save_checkpoint(f); return; }
24.277983
105
0.586787
[ "vector" ]
4f90a82508cfffc0a28f8bfef612bc3687abcd6a
9,695
cc
C++
pw_minimal_cpp_stdlib/isolated_test.cc
LuDuda/pigweed
dcd7230895a234156bc7b6e5061e6936627c5fbb
[ "Apache-2.0" ]
1
2020-12-19T19:42:46.000Z
2020-12-19T19:42:46.000Z
pw_minimal_cpp_stdlib/isolated_test.cc
LuDuda/pigweed
dcd7230895a234156bc7b6e5061e6936627c5fbb
[ "Apache-2.0" ]
3
2021-03-11T06:53:56.000Z
2022-02-13T21:59:25.000Z
pw_minimal_cpp_stdlib/isolated_test.cc
LuDuda/pigweed
dcd7230895a234156bc7b6e5061e6936627c5fbb
[ "Apache-2.0" ]
null
null
null
// Copyright 2019 The Pigweed 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 // // https://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 all of the provided headers, even if they aren't tested. #include <algorithm> #include <array> #include <cinttypes> #include <cmath> #include <cstdarg> #include <cstddef> #include <cstdint> #include <cstdio> #include <cstring> #include <initializer_list> #include <iterator> #include <limits> #include <new> #include <string_view> #include <type_traits> #include <utility> #include "pw_preprocessor/compiler.h" namespace { // In order to test this file without dependencies on the C++ standard library, // this file needs to be fully isolated from the regular Pigweed testing // infrastructure. pw_unit_test's dependencies do compile with the C++ standard // library, which could conflict with pw_minimal_cpp_stdlib. // // SimpleTest provides the basic features of pw_unit_test without dependencies. class SimpleTest { public: virtual ~SimpleTest() = default; static bool RunAllTests() { for (SimpleTest* test = all_tests; test != nullptr; test = test->next_) { test->Run(); if (!test->passed_) { return false; } } return true; } protected: SimpleTest() : next_(all_tests) { all_tests = this; } void RecordTestFailure() { passed_ = false; } private: virtual void Run() = 0; static SimpleTest* all_tests; bool passed_ = true; SimpleTest* next_; }; SimpleTest* SimpleTest::all_tests = nullptr; #define EXPECT_EQ(lhs, rhs) \ do { \ if ((lhs) != (rhs)) { \ RecordTestFailure(); \ } \ } while (0) #define EXPECT_TRUE(expr) EXPECT_EQ(true, expr) #define EXPECT_FALSE(expr) EXPECT_EQ(false, expr) #define EXPECT_STREQ(lhs, rhs) EXPECT_EQ(std::strcmp((lhs), (rhs)), 0) #define TEST(suite, name) \ class SimpleTest_##suite##_##name : public SimpleTest { \ void Run() override; \ } test_##suite##_##name; \ \ void SimpleTest_##suite##_##name::Run() TEST(Algorithm, Basic) { static_assert(std::min(1, 2) == 1); static_assert(std::max(1, 2) == 2); EXPECT_EQ(std::forward<int>(2), 2); } TEST(Algorithm, Copy) { constexpr size_t kCopyOffset = 1; std::array<int, 3> foo{3, 2, 1}; std::array<int, 5> bar{0}; // Ensure zero-element iterator doesn't modify the destination object when // copied. int temp = foo[0]; std::copy(foo.end(), foo.end(), bar.begin()); EXPECT_EQ(foo[0], temp); // Copy a single element. std::array<int, 1> one{-101}; std::copy(one.begin(), one.end(), foo.begin()); EXPECT_EQ(foo[0], -101); auto copy_end = std::copy(foo.begin(), foo.end(), bar.begin() + kCopyOffset); // Verify the iterator points to the end of the copied region. EXPECT_EQ(copy_end, bar.begin() + foo.size() + kCopyOffset); // Verify all the values were properly copied from foo to bar. { size_t i = 0; for (auto it = bar.begin() + kCopyOffset; it != copy_end; ++it) { EXPECT_EQ(*it, foo[i++]); } } } TEST(Algorithm, Find) { std::array<int, 5> foo{3, 2, 1, 42, 17}; // Ensure a value in the middle of the array is properly found. EXPECT_EQ(*std::find(std::begin(foo), std::end(foo), 42), 42); // Ensure the iterator returned by find() matches the expected location of the // element. EXPECT_EQ(std::find(std::begin(foo), std::end(foo), 42), std::begin(foo) + 3); // Ensure an element at the beginning of an array is found. EXPECT_EQ(*std::find(std::begin(foo), std::end(foo), 3), foo[0]); // Ensure an element at the end of an array is found. EXPECT_EQ(*std::find(std::begin(foo), std::end(foo), 17), foo[foo.size() - 1]); } TEST(Algorithm, NotFound) { std::array<int, 3> foo{3, 2, 1}; // Ensure that if an element is not found, an iterator matching foo.end() is // returned. EXPECT_EQ(std::find(std::begin(foo), std::end(foo), -99), std::end(foo)); // Ensure that a zero-element iterator range returns the end iterator passed // to std::find(). EXPECT_EQ(std::find(std::end(foo), std::end(foo), 3), std::end(foo)); } TEST(Array, Basic) { constexpr std::array<int, 4> array{0, 1, 2, 3}; static_assert(array[2] == 2); for (int i = 0; i < static_cast<int>(array.size()); ++i) { EXPECT_EQ(i, array[i]); } } TEST(Cmath, Basic) PW_NO_SANITIZE("float-divide-by-zero") { EXPECT_EQ(std::abs(-1), 1); EXPECT_EQ(std::abs(1), 1); // Although Clang/LLVM do not fully support __STDC_IEC_559__, they do have the // necessary IEEE 754 support for floating point division by zero. EXPECT_TRUE(std::isfinite(1.0)); EXPECT_FALSE(std::isfinite(1.0 / 0.0)); EXPECT_FALSE(std::isnan(1.0)); EXPECT_TRUE(std::isnan(0.0 / 0.0)); EXPECT_FALSE(std::signbit(1.0)); EXPECT_TRUE(std::signbit(-1.0)); } TEST(Cstddef, Basic) { using std::byte; byte foo = byte{12}; EXPECT_EQ(foo, byte{12}); } TEST(Iterator, Basic) { std::array<int, 3> foo{3, 2, 1}; EXPECT_EQ(std::data(foo), foo.data()); EXPECT_EQ(std::size(foo), foo.size()); EXPECT_EQ(*std::begin(foo), foo[0]); EXPECT_EQ(std::end(foo), std::begin(foo) + foo.size()); foo.fill(99); EXPECT_EQ(foo[0], 99); EXPECT_EQ(foo[1], 99); EXPECT_EQ(foo[2], 99); } template <typename T> int SumFromInitializerList(std::initializer_list<T> values) { int sum = 0; for (auto value : values) { sum += value; } return sum; } TEST(InitializerList, Empty) { std::initializer_list<int> mt; EXPECT_EQ(0, SumFromInitializerList(mt)); EXPECT_EQ(0, SumFromInitializerList<float>({})); } TEST(InitializerList, Declared) { std::initializer_list<char> list{'\3', '\3', '\4'}; EXPECT_EQ(10, SumFromInitializerList(list)); } TEST(InitializerList, Inline) { EXPECT_EQ(42, SumFromInitializerList<long>({42})); EXPECT_EQ(2, SumFromInitializerList<bool>({true, false, true})); EXPECT_EQ(15, SumFromInitializerList({1, 2, 3, 4, 5})); } TEST(Limits, Basic) { static_assert(std::numeric_limits<unsigned char>::is_specialized); static_assert(std::numeric_limits<unsigned char>::is_integer); static_assert(std::numeric_limits<unsigned char>::min() == 0u); static_assert(std::numeric_limits<unsigned char>::max() == 255u); static_assert(std::numeric_limits<signed char>::is_specialized); static_assert(std::numeric_limits<signed char>::is_integer); static_assert(std::numeric_limits<signed char>::min() == -128); static_assert(std::numeric_limits<signed char>::max() == 127); // Assume 64-bit long long static_assert(std::numeric_limits<long long>::is_specialized); static_assert(std::numeric_limits<long long>::is_integer); static_assert(std::numeric_limits<long long>::min() == (-9223372036854775807ll - 1)); static_assert(std::numeric_limits<long long>::max() == 9223372036854775807ll); static_assert(std::numeric_limits<unsigned long long>::is_specialized); static_assert(std::numeric_limits<unsigned long long>::is_integer); static_assert(std::numeric_limits<unsigned long long>::min() == 0u); static_assert(std::numeric_limits<unsigned long long>::max() == 18446744073709551615ull); } TEST(New, PlacementNew) { unsigned char value[4]; new (value) int(1234); int int_value; std::memcpy(&int_value, value, sizeof(int_value)); EXPECT_EQ(1234, int_value); } TEST(New, Launder) { unsigned char value[4]; int* int_ptr = std::launder(reinterpret_cast<int*>(value)); EXPECT_EQ(static_cast<void*>(int_ptr), static_cast<void*>(value)); } TEST(StringView, Basic) { constexpr std::string_view value("1234567890"); static_assert(value.size() == 10); static_assert(value[1] == '2'); char buffer[] = "!!!!!"; constexpr size_t buffer_size = sizeof(buffer) - 1; // always keep the \0 value.copy(buffer, buffer_size, 10); EXPECT_STREQ(buffer, "!!!!!"); value.copy(buffer, buffer_size, 9); EXPECT_STREQ(buffer, "0!!!!"); value.copy(buffer, buffer_size, 2); EXPECT_STREQ(buffer, "34567"); value.copy(buffer, buffer_size); EXPECT_STREQ(buffer, "12345"); } TEST(TypeTraits, Basic) { static_assert(std::is_integral_v<bool>); static_assert(!std::is_integral_v<float>); static_assert(std::is_floating_point_v<float>); static_assert(!std::is_floating_point_v<bool>); static_assert(std::is_same_v<float, float>); static_assert(!std::is_same_v<char, unsigned char>); } struct MoveTester { MoveTester(int value) : magic_value(value), moved(false) {} MoveTester(const MoveTester&) = default; MoveTester(MoveTester&& other) : magic_value(other.magic_value), moved(true) { other.magic_value = 0xffff; } int magic_value; bool moved; }; TEST(Utility, Move) { MoveTester test(123); MoveTester copied(test); EXPECT_EQ(copied.magic_value, 123); EXPECT_FALSE(copied.moved); MoveTester moved(std::move(copied)); EXPECT_EQ(123, moved.magic_value); EXPECT_EQ(0xffff, copied.magic_value); EXPECT_TRUE(moved.moved); } } // namespace namespace pw::minimal_cpp_stdlib { bool RunAllTests() { return SimpleTest::RunAllTests(); } } // namespace pw::minimal_cpp_stdlib
29.026946
80
0.668386
[ "object" ]
4f90e2adf1bacc79dd66a6722759688c7539bba6
16,947
cpp
C++
Ipopt-3.12.7/Ipopt/contrib/MatlabInterface/src/callbackfunctions.cpp
MikeBMW/CarND-MPC-Project
81e6e92de2768dce9fbfd1848de6f4465d468a0e
[ "MIT" ]
9
2020-07-09T06:40:31.000Z
2022-03-28T02:50:21.000Z
third-party/CoinIpopt/Ipopt/contrib/MatlabInterface/src/callbackfunctions.cpp
WatsonZhouAnda/Cheetah-Software
05e416fb26f968300826f0deb0953be9afb22bfe
[ "MIT" ]
null
null
null
third-party/CoinIpopt/Ipopt/contrib/MatlabInterface/src/callbackfunctions.cpp
WatsonZhouAnda/Cheetah-Software
05e416fb26f968300826f0deb0953be9afb22bfe
[ "MIT" ]
5
2020-12-01T01:41:12.000Z
2022-01-04T01:21:49.000Z
// Copyright (C) 2008 Peter Carbonetto. All Rights Reserved. // This code is published under the Eclipse Public License. // // Author: Peter Carbonetto // Dept. of Computer Science // University of British Columbia // September 18, 2008 #include "callbackfunctions.hpp" #include "matlabexception.hpp" // Functions for class CallbackFunctions. // ----------------------------------------------------------------- CallbackFunctions::CallbackFunctions (const mxArray* ptr) : objfunc(0), gradfunc(0), constraintfunc(0), jacobianfunc(0), jacstrucfunc(0), hessianfunc(0), hesstrucfunc(0), iterfunc(0) { const mxArray* p; // A pointer to a MATLAB array. // Check whether we are provided with a structure array. if (!mxIsStruct(ptr)) throw MatlabException("The second input must be a STRUCT"); // Get the function handle for computing the objective. p = mxGetField(ptr,0,"objective"); if (!p) throw MatlabException("You must specify a callback routine for \ computing the value of the objective function"); if (mxIsEmpty(p) || !isFunctionHandle(p)) throw MatlabException("You did not provide a valid function handle for \ computing the value of the objective function"); objfunc = new MatlabFunctionHandle(p); // Get the function handle for computing the gradient. p = mxGetField(ptr,0,"gradient"); if (!p) throw MatlabException("You must specify a callback routine for \ computing the gradient of the objective"); if (mxIsEmpty(p) || !isFunctionHandle(p)) throw MatlabException("You did not provide a valid function handle for \ computing the gradient of the objective"); gradfunc = new MatlabFunctionHandle(p); // Get the function handle for computing the constraints, if such a // function was specified. p = mxGetField(ptr,0,"constraints"); if (p) { if (mxIsEmpty(p) || !isFunctionHandle(p)) throw MatlabException("You did not provide a valid function handle \ for computing the response of the constraints"); constraintfunc = new MatlabFunctionHandle(p); } else constraintfunc = new MatlabFunctionHandle(); // Get the function handle for computing the Jacobian. This function // is necessary if there are constraints. p = mxGetField(ptr,0,"jacobian"); if (p) { if (mxIsEmpty(p) || !isFunctionHandle(p)) throw MatlabException("You did not provide a valid function handle \ for computing the first derivatives (Jacobian) of the constraints"); jacobianfunc = new MatlabFunctionHandle(p); } else { if (*constraintfunc) throw MatlabException("You must provide a function that returns the \ first derivatives (Jacobian) of the constraints"); jacobianfunc = new MatlabFunctionHandle(); } // Get the function handle for computing the sparsity structure of // the Jacobian. This function is necessary if the Jacobian is being // computed. p = mxGetField(ptr,0,"jacobianstructure"); if (p) { if (mxIsEmpty(p) || !isFunctionHandle(p)) throw MatlabException("You did not provide a valid function handle \ for computing the sparsity structure of the Jacobian"); jacstrucfunc = new MatlabFunctionHandle(p); } else { if (*jacobianfunc) throw MatlabException("You must provide a function that returns the \ sparsity structure of the Jacobian"); jacstrucfunc = new MatlabFunctionHandle(); } // Get the function handle for computing the Hessian. This function // is always optional. p = mxGetField(ptr,0,"hessian"); if (p) { if (mxIsEmpty(p) || !isFunctionHandle(p)) throw MatlabException("You did not provide a valid function handle \ for computing the Hessian of the Lagrangian"); hessianfunc = new MatlabFunctionHandle(p); } else hessianfunc = new MatlabFunctionHandle(); // Get the function handle for computing the sparsity structure of // the Hessian of the Lagrangian. This function is necessary if the // Hessian is being computed. p = mxGetField(ptr,0,"hessianstructure"); if (p) { if (mxIsEmpty(p) || !isFunctionHandle(p)) throw MatlabException("You did not provide a valid function handle \ for computing the sparsity structure of the Hessian"); hesstrucfunc = new MatlabFunctionHandle(p); } else { if (*hessianfunc) throw MatlabException("You must provide a function that returns the \ sparsity structure of the Hessian"); hesstrucfunc = new MatlabFunctionHandle(); } // Get the iterative callback function handle. This function is // always optional. p = mxGetField(ptr,0,"iterfunc"); if (p) { if (mxIsEmpty(p) || !isFunctionHandle(p)) throw MatlabException("You did not provide a valid function handle \ for the iterative callback"); iterfunc = new MatlabFunctionHandle(p); } else iterfunc = new MatlabFunctionHandle(); } CallbackFunctions::~CallbackFunctions() { if (objfunc) delete objfunc; if (gradfunc) delete gradfunc; if (constraintfunc) delete constraintfunc; if (jacobianfunc) delete jacobianfunc; if (jacstrucfunc) delete jacstrucfunc; if (hessianfunc) delete hessianfunc; if (hesstrucfunc) delete hesstrucfunc; if (iterfunc) delete iterfunc; } double CallbackFunctions::computeObjective (const Iterate& x) const { double f; // The return value. bool success; const mxArray* inputs[1]; mxArray* outputs[1]; // Call the MATLAB callback function. inputs[0] = x; success = objfunc->evaluate(1,1,inputs,outputs); if (!success) throw MatlabException("There was an error when executing the objective \ callback function"); // Get the output from the MATLAB callback function, which is the // value of the objective function at x. mxArray* ptr = outputs[0]; if (!mxIsDouble(ptr) || mxIsComplex(ptr) || mxGetNumberOfElements(ptr) != 1) throw MatlabException("The first return value of the objective \ callback function must be a real double scalar"); if (mxIsSparse(ptr)) { // convert sparse objective (unlikely but possible) to full mexCallMATLAB(1, &ptr, 1, outputs, "full"); mxDestroyArray(outputs[0]); } f = *mxGetPr(ptr); // Free the dynamically allocated memory. mxDestroyArray(ptr); return f; } void CallbackFunctions::computeGradient (const Iterate& x, double* g) const { bool success; const mxArray* inputs[1]; mxArray* outputs[1]; // Call the MATLAB callback function. inputs[0] = x; success = gradfunc->evaluate(1,1,inputs,outputs); if (!success) throw MatlabException("There was an error when executing the \ gradient callback function"); // Get the output from the MATLAB callback function, which is the // value of the gradient of the objective function at x. mxArray* ptr = outputs[0]; if (!mxIsCell(ptr) && (!mxIsDouble(ptr) || mxIsComplex(ptr))) throw MatlabException("The gradient callback must return a real double vector"); if (mxIsSparse(ptr)) { // convert sparse gradient to full (simplest method, not fastest) mexCallMATLAB(1, &ptr, 1, outputs, "full"); mxDestroyArray(outputs[0]); } Iterate grad(ptr); if (numvars(x) != numvars(grad)) throw MatlabException("Invalid gradient passed back from MATLAB \ routine"); grad.copyto(g); // Free the dynamically allocated memory. mxDestroyArray(ptr); } void CallbackFunctions::computeConstraints(const Iterate& x, int m, double* c) const { bool success; const mxArray* inputs[1]; mxArray* outputs[1]; // Call the MATLAB callback function. inputs[0] = x; success = constraintfunc->evaluate(1,1,inputs,outputs); if (!success) throw MatlabException("There was an error when executing the \ constraints callback function"); // Get the output from the MATLAB callback function, which is the // value of vector-valued constraint function at x. mxArray* ptr = outputs[0]; if ((unsigned) m != mxGetNumberOfElements(ptr)) throw MatlabException("Invalid constraint values passed back from \ Matlab routine"); if (!mxIsDouble(ptr) || mxIsComplex(ptr)) throw MatlabException("The constraint callback must return a real double vector"); if (mxIsSparse(ptr)) { // convert sparse constraint vector (unlikely but possible) to full mexCallMATLAB(1, &ptr, 1, outputs, "full"); mxDestroyArray(outputs[0]); } copymemory(mxGetPr(ptr),c,m); // Free the dynamically allocated memory. mxDestroyArray(ptr); } SparseMatrix* CallbackFunctions::getJacobianStructure (int n, int m) const { const mxArray* inputs[1]; mxArray* outputs[1]; bool success; // Call the MATLAB callback function. success = jacstrucfunc->evaluate(0,1,inputs,outputs); if (!success) throw MatlabException("There was an error when getting the structure \ of the Jacobian matrix from MATLAB"); // Get the output from the MATLAB callback function, which is the // sparse matrix specifying the structure of the Jacobian. mxArray* ptr = outputs[0]; if (!mxIsSparse(ptr) || mxIsComplex(ptr)) throw MatlabException("Jacobian must be a real sparse matrix"); if ((int) mxGetM(ptr) != m || (int) mxGetN(ptr) != n || !SparseMatrix::inIncOrder(ptr)) throw MatlabException("Jacobian must be an m x n sparse matrix with \ row indices in increasing order, where m is the number of constraints and \ n is the number of variables"); if (!mxIsDouble(ptr)) { // convert non-double Jacobian structure to double mexCallMATLAB(1, &ptr, 1, outputs, "double"); mxDestroyArray(outputs[0]); } SparseMatrix* J = new SparseMatrix(ptr); // The return value. // Free the dynamically allocated memory. mxDestroyArray(ptr); return J; } SparseMatrix* CallbackFunctions::getHessianStructure (int n) const { const mxArray* inputs[1]; mxArray* outputs[1]; bool success; // Call the MATLAB callback function. success = hesstrucfunc->evaluate(0,1,inputs,outputs); if (!success) throw MatlabException("There was an error when getting the structure \ of the Hessian matrix from MATLAB"); // Get the output from the MATLAB callback function, which is the // sparse matrix specifying the structure of the Hessian. mxArray* ptr = outputs[0]; if (!mxIsSparse(ptr) || mxIsComplex(ptr)) throw MatlabException("Hessian must be a real sparse matrix"); if ((int) mxGetM(ptr) != n || (int) mxGetN(ptr) != n || !SparseMatrix::isLowerTri(ptr) || !SparseMatrix::inIncOrder(ptr)) throw MatlabException("Hessian must be an n x n sparse, symmetric and \ lower triangular matrix with row indices in increasing order, where n is \ the number of variables"); if (!mxIsDouble(ptr)) { // convert non-double Hessian structure to double mexCallMATLAB(1, &ptr, 1, outputs, "double"); mxDestroyArray(outputs[0]); } SparseMatrix* H = new SparseMatrix(ptr); // The return value. // Free the dynamically allocated memory. mxDestroyArray(ptr); return H; } void CallbackFunctions::computeJacobian (int m, const Iterate& x, SparseMatrix& J) const { bool success; const mxArray* inputs[1]; mxArray* outputs[1]; // Call the MATLAB callback function. inputs[0] = x; success = jacobianfunc->evaluate(1,1,inputs,outputs); if (!success) throw MatlabException("There was an error when executing the \ Jacobian callback function"); // Get the output from the MATLAB callback function, which is the // sparse matrix specifying the value the Jacobian. mxArray* ptr = outputs[0]; if (!mxIsSparse(ptr) || mxIsComplex(ptr)) throw MatlabException("Jacobian must be a real sparse matrix"); if ((int) mxGetM(ptr) != m || (int) mxGetN(ptr) != numvars(x) || !SparseMatrix::inIncOrder(ptr)) throw MatlabException("Jacobian must be an m x n sparse matrix with \ row indices in increasing order, where m is the number of constraints and \ n is the number of variables"); if (!mxIsDouble(ptr)) { // convert non-double Jacobian to double mexCallMATLAB(1, &ptr, 1, outputs, "double"); mxDestroyArray(outputs[0]); } SparseMatrix Jnew(ptr); Jnew.copyto(J); // Free the dynamically allocated memory. mxDestroyArray(ptr); } void CallbackFunctions::computeHessian (const Iterate& x, double sigma, int m, const double* lambda, SparseMatrix& H) const { bool success; const mxArray* inputs[3]; mxArray* outputs[1]; // Create the input arguments to the MATLAB routine, sigma and lambda. mxArray* psigma = mxCreateDoubleScalar(sigma); mxArray* plambda = mxCreateDoubleMatrix(m,1,mxREAL); copymemory(lambda,mxGetPr(plambda),m); // Call the MATLAB callback function. inputs[0] = x; inputs[1] = psigma; inputs[2] = plambda; success = hessianfunc->evaluate(3,1,inputs,outputs); if (!success) throw MatlabException("There was an error when executing the Hessian \ callback function"); // Get the output from the MATLAB callback function, which is the // sparse matrix specifying the value the Hessian. mxArray* ptr = outputs[0]; if (!mxIsSparse(ptr) || mxIsComplex(ptr)) throw MatlabException("Hessian must be a real sparse matrix"); if ((int) mxGetM(ptr) != numvars(x) || (int) mxGetN(ptr) != numvars(x) || !SparseMatrix::isLowerTri(ptr) || !SparseMatrix::inIncOrder(ptr)) throw MatlabException("Hessian must be an n x n sparse, symmetric and \ lower triangular matrix with row indices in increasing order, where n is \ the number of variables"); if (!mxIsDouble(ptr)) { // convert non-double Hessian to double mexCallMATLAB(1, &ptr, 1, outputs, "double"); mxDestroyArray(outputs[0]); } SparseMatrix Hnew(ptr); Hnew.copyto(H); // Free the dynamically allocated memory. mxDestroyArray(ptr); mxDestroyArray(psigma); mxDestroyArray(plambda); } bool CallbackFunctions::iterCallback (int t, double f, double inf_pr, double inf_du, double mu, double d_norm, double regularization_size, double alpha_du, double alpha_pr, int ls_trials, const Ipopt::IpoptData* ip_data, Ipopt::IpoptCalculatedQuantities* ip_cq, int n) const { bool success; const mxArray* inputs[3]; mxArray* outputs[1]; // Create the input arguments to the MATLAB routine. mxArray* pt = mxCreateDoubleScalar(t); mxArray* pf = mxCreateDoubleScalar(f); // Create structure to hold extra IPOPT variables const char* varfields[9]; varfields[0] = "x"; varfields[1] = "inf_pr"; varfields[2] = "inf_du"; varfields[3] = "mu"; varfields[4] = "d_norm"; varfields[5] = "regularization_size"; varfields[6] = "alpha_du"; varfields[7] = "alpha_pr"; varfields[8] = "ls_trials"; mxArray *varStruct = mxCreateStructMatrix(1,1,9,varfields); mxSetField(varStruct,0,"inf_pr",mxCreateDoubleScalar(inf_pr)); mxSetField(varStruct,0,"inf_du",mxCreateDoubleScalar(inf_du)); mxSetField(varStruct,0,"mu",mxCreateDoubleScalar(mu)); mxSetField(varStruct,0,"d_norm",mxCreateDoubleScalar(d_norm)); mxSetField(varStruct,0,"regularization_size",mxCreateDoubleScalar(regularization_size)); mxSetField(varStruct,0,"alpha_du",mxCreateDoubleScalar(alpha_du)); mxSetField(varStruct,0,"alpha_pr",mxCreateDoubleScalar(alpha_pr)); mxSetField(varStruct,0,"ls_trials",mxCreateDoubleScalar(ls_trials)); //The following code translates IPOPT's NLP to the Original NLP, so we can extract x //Original code by Steven Dirske, Stefan Vigerske [GAMS] Ipopt::TNLPAdapter* tnlp_adapter = NULL; if(ip_cq != NULL) { Ipopt::OrigIpoptNLP* orignlp = dynamic_cast<Ipopt::OrigIpoptNLP*>(GetRawPtr(ip_cq->GetIpoptNLP())); if(orignlp != NULL) tnlp_adapter = dynamic_cast<Ipopt::TNLPAdapter*>(GetRawPtr(orignlp->nlp())); } //If we successfully converted the NLP, extract x [ResortX auto sorts and fills in fixed vars] if(tnlp_adapter != NULL && ip_data != NULL && IsValid(ip_data->curr())) { mxSetField(varStruct,0,"x",mxCreateDoubleMatrix(n,1,mxREAL)); //ip_data->curr()->x()->Dim()+1 tnlp_adapter->ResortX(*ip_data->curr()->x(),mxGetPr(mxGetField(varStruct,0,"x"))); } // Call the MATLAB callback function. inputs[0] = pt; inputs[1] = pf; inputs[2] = varStruct; success = iterfunc->evaluate(3,1,inputs,outputs); if (!success) throw MatlabException("There was an error when executing the iterative \ callback function"); // Get the output from the MATLAB callback function, which is a // boolean value telling whether or not IPOPT should continue. mxArray* ptr = outputs[0]; if (!mxIsLogicalScalar(ptr)) throw MatlabException("The return value for the iterative callback must \ either be TRUE or FALSE"); bool b = mxIsLogicalScalarTrue(ptr); // Free the dynamically allocated memory. mxDestroyArray(ptr); mxDestroyArray(pt); mxDestroyArray(pf); mxDestroyArray(varStruct); return b; }
36.921569
105
0.697941
[ "vector" ]
4f91d9d218132e6ebb037c4a5c7247918c7fdf1e
5,230
cpp
C++
kdl/parser/sema/project/scene.cpp
EvocationGames/libKDL
90eb2ce71a1545f6e33164230f0e5d6ece0acaa7
[ "MIT" ]
null
null
null
kdl/parser/sema/project/scene.cpp
EvocationGames/libKDL
90eb2ce71a1545f6e33164230f0e5d6ece0acaa7
[ "MIT" ]
null
null
null
kdl/parser/sema/project/scene.cpp
EvocationGames/libKDL
90eb2ce71a1545f6e33164230f0e5d6ece0acaa7
[ "MIT" ]
null
null
null
// Copyright (c) 2022 Tom Hancocks // // 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 <kdl/parser/sema/project/scene.hpp> #include <kdl/parser/sema/function/function_call.hpp> #include <kdl/schema/project/scene.hpp> #include <kdl/schema/module.hpp> #include <kdl/report/reporting.hpp> namespace kdl::lib::spec::keywords { constexpr const char *scene { "scene" }; constexpr const char *event { "event" }; } auto kdl::lib::sema::project::scene::parse(lexeme_consumer &consumer, const std::shared_ptr<kdl::lib::module> &module) -> void { if (!consumer.expect_all({ expect(lexeme_type::identifier, spec::keywords::scene).t(), expect(lexeme_type::identifier).t(), expect(lexeme_type::lbrace).t() })) { report::error(consumer.peek(), "Expected scene structure"); } consumer.advance(); auto scene_name = consumer.read(); consumer.advance(); auto scene = std::make_shared<class kdl::lib::scene>(scene_name.string_value()); while (consumer.expect( expect(lexeme_type::rbrace).f() )) { if (consumer.expect_all({ expect(lexeme_type::identifier, spec::keywords::event).t(), expect(lexeme_type::lparen).t(), expect(lexeme_type::identifier).t(), expect(lexeme_type::rparen).t(), expect(lexeme_type::equals).t(), expect(lexeme_type::lbracket).t() })) { consumer.advance(2); auto event_name = consumer.read(); consumer.advance(3); std::vector<lexeme> scripts; while (consumer.expect( expect(lexeme_type::rbracket).f() )) { if (consumer.expect( expect(lexeme_type::resource_ref).t() )) { scripts.emplace_back(consumer.read()); } else { report::error(consumer.peek(), "Unexpected value provided."); } if (consumer.expect( expect(lexeme_type::rbracket).t() )) { break; } else if (consumer.expect( expect(lexeme_type::comma).t() )) { consumer.advance(); continue; } else { report::error(consumer.peek(), "Unexpected token encountered."); } } consumer.assert_lexemes({ expect(lexeme_type::rbracket).t() }); } else if (consumer.expect_all({ expect(lexeme_type::identifier).t(), expect(lexeme_type::equals).t(), expect(lexeme_type::identifier).f() })) { auto attribute = consumer.read(); consumer.advance(); std::vector<lexeme> v; while (consumer.expect_any({ expect(lexeme_type::identifier).t(), expect(lexeme_type::color).t(), expect(lexeme_type::any_integer).t(), expect(lexeme_type::any_string).t(), expect(lexeme_type::resource_ref).t(), expect(lexeme_type::percentage).t(), expect(lexeme_type::hex).t(), expect(lexeme_type::character).t(), })) { v.emplace_back(consumer.read()); } scene->set_attribute(attribute.string_value(), v); } else if (consumer.expect_all({ expect(lexeme_type::identifier).t(), expect(lexeme_type::equals).t(), expect(lexeme_type::identifier).t() })) { auto attribute = consumer.read(); consumer.advance(); auto result = consumer.peek(); if (sema::function::call::look_ahead(consumer)) { // We're looking at a function result = sema::function::call::parse(consumer, module); } else { consumer.advance(); } scene->set_attribute(attribute.string_value(), result); } else { report::error(consumer.peek(), "Unexpected token in scene."); } consumer.assert_lexemes({ expect(lexeme_type::semicolon).t() }); } consumer.assert_lexemes({ expect(lexeme_type::rbrace).t() }); module->add_scene(scene); }
39.923664
126
0.597514
[ "vector" ]
4f94eea0ad9d7b094dac6e86c5c9490eab8a35eb
23,469
cpp
C++
src/Cluster/Cluster.cpp
gravitationalwavedc/gwcloud_job_server
fb96ed1dc6baa240d1a38ac1adcd246577285294
[ "MIT" ]
null
null
null
src/Cluster/Cluster.cpp
gravitationalwavedc/gwcloud_job_server
fb96ed1dc6baa240d1a38ac1adcd246577285294
[ "MIT" ]
8
2020-06-06T08:39:37.000Z
2021-09-22T18:01:47.000Z
src/Cluster/Cluster.cpp
gravitationalwavedc/gwcloud_job_server
fb96ed1dc6baa240d1a38ac1adcd246577285294
[ "MIT" ]
null
null
null
// // Created by lewis on 2/27/20. // #include "Cluster.h" #include "../DB/MySqlConnector.h" #include "../Lib/jobserver_schema.h" #include "../Lib/JobStatus.h" #include "../HTTP/HttpServer.h" #include <iostream> #include <client_https.hpp> #include <client_http.hpp> #include <folly/Uri.h> // Packet Queue is a: // list of priorities - doesn't need any sync because it never changes // -> map of sources - needs sync when adding/removing sources // -> vector of packets - make this a MPSC queue // When the number of bytes in a packet of vectors exceeds some amount, a message should be sent that stops more // packets from being sent, when the vector then falls under some threshold // Track sources in the map, add them when required - delete them after some amount (1 minute?) of inactivity. // Send sources round robin, starting from the highest priority // Define a global map that can be used for storing information about file downloads folly::ConcurrentHashMap<std::string, sFileDownload *> fileDownloadMap; // Define a global map that can be used for storing information about file lists folly::ConcurrentHashMap<std::string, sFileList *> fileListMap; // Define a mutex that can be used for safely removing entries from the fileDownloadMap std::mutex fileDownloadMapDeletionLockMutex; // Define a mutex that can be used for synchronising pause/resume messages std::mutex fileDownloadPauseResumeLockMutex; // Define a mutex that can be used for safely removing entries from the fileListMap std::mutex fileListMapDeletionLockMutex; // Define a simple HTTP/S client for fetching bundles using HttpClient = SimpleWeb::Client<SimpleWeb::HTTP>; using HttpsClient = SimpleWeb::Client<SimpleWeb::HTTPS>; extern void handleFileList( ClusterManager *clusterManager, uint32_t jobId, bool bRecursive, const std::string &filePath, const std::string &appName, const std::vector<std::string> &applications, HttpServerImpl::Response *response ); using namespace schema; Cluster::Cluster(sClusterDetails *details, ClusterManager *pClusterManager) { this->pClusterDetails = details; this->pClusterManager = pClusterManager; // Create the list of priorities in order for (auto i = (uint32_t) Message::Priority::Highest; i <= (uint32_t) Message::Priority::Lowest; i++) queue.emplace_back(); #ifndef BUILD_TESTS // Start the scheduler thread schedulerThread = std::thread([this] { this->run(); }); // Start the prune thread pruneThread = std::thread([this] { this->pruneSources(); }); // Start the resend thread resendThread = std::thread([this] { this->resendMessages(); }); #endif } Cluster::~Cluster() { delete pClusterDetails; for (auto &p : queue) { auto pMap = &p; for (auto s = pMap->begin(); s != pMap->end();) { while (!(*s).second->empty()) delete *(*s).second->try_dequeue(); delete (*s).second; s = pMap->erase(s); } } } void Cluster::handleMessage(Message &message) { auto msgId = message.getId(); switch (msgId) { case UPDATE_JOB: this->updateJob(message); break; case FILE_ERROR: Cluster::handleFileError(message); break; case FILE_DETAILS: Cluster::handleFileDetails(message); break; case FILE_CHUNK: this->handleFileChunk(message); break; case FILE_LIST: this->handleFileList(message); break; case FILE_LIST_ERROR: this->handleFileListError(message); break; default: std::cout << "Got invalid message ID " << msgId << " from " << this->getName() << std::endl; }; } void Cluster::setConnection(WsServer::Connection *pCon) { this->pConnection = pCon; if (pCon != nullptr) { // See if there are any pending jobs that should be sent checkUnsubmittedJobs(); // See if there are any cancelling jobs that should be sent checkCancellingJobs(); // See if there are any deleting jobs that should be sent checkDeletingJobs(); } } void Cluster::queueMessage(std::string source, std::vector<uint8_t> *data, Message::Priority priority) { // Copy the message auto pData = new std::vector<uint8_t>(*data); // Get a pointer to the relevant map auto pMap = &queue[priority]; // Lock the access mutex to check if the source exists in the map { std::shared_lock<std::shared_mutex> lock(mutex_); // Make sure that this source exists in the map auto sQueue = new folly::UMPSCQueue<std::vector<uint8_t> *, false, 8>(); // try_emplace().second is a bool representing if the value was emplaced or not if (!pMap->try_emplace(source, sQueue).second) { // sQueue was not emplaced - so it already existed in the map, we can delete the new one // TODO: new then delete might be quite inefficient - perhaps we can refactor this later delete sQueue; } // Write the data in the queue (*pMap)[source]->enqueue(pData); // Trigger the new data event to start sending this->dataReady = true; dataCV.notify_one(); } } #ifndef BUILD_TESTS [[noreturn]] void Cluster::pruneSources() { // Iterate forever while (true) { // Wait 1 minute until the next prune std::this_thread::sleep_for(std::chrono::seconds(60)); #else void Cluster::pruneSources() { #endif // Aquire the exclusive lock to prevent more data being pushed on while we are pruning { std::unique_lock<std::shared_mutex> lock(mutex_); // Iterate over the priorities for (auto &p : queue) { // Get a pointer to the relevant map auto pMap = &p; // Iterate over the map for (auto s = pMap->begin(); s != pMap->end();) { // Check if the vector for this source is empty if ((*s).second->empty()) { // Destroy the queue delete (*s).second; // Remove this source from the map and continue s = pMap->erase(s); continue; } // Manually increment the iterator ++s; } } } #ifndef BUILD_TESTS } #endif } #ifndef BUILD_TESTS [[noreturn]] void Cluster::run() { // Iterate forever while (true) { #else void Cluster::run() { #endif { std::unique_lock<std::mutex> lock(dataCVMutex); // Wait for data to be ready to send dataCV.wait(lock, [this] { return this->dataReady; }); // Reset the condition this->dataReady = false; } reset: // Iterate over the priorities for (auto p = queue.begin(); p != queue.end(); p++) { // Get a pointer to the relevant map auto pMap = &(*p); // Get the current priority auto currentPriority = p - queue.begin(); // While there is still data for this priority, send it bool hadData; do { hadData = false; std::shared_lock<std::shared_mutex> lock(mutex_); // Iterate over the map for (auto s = pMap->begin(); s != pMap->end(); ++s) { // Check if the vector for this source is empty if (!(*s).second->empty()) { // Pop the next item from the queue auto data = (*s).second->try_dequeue(); try { // data should never be null as we're checking for empty if (data) { // Convert the message auto o = std::make_shared<WsServer::OutMessage>((*data)->size()); std::ostream_iterator<uint8_t> iter(*o); std::copy((*data)->begin(), (*data)->end(), iter); // Send the message on the websocket if (pConnection) pConnection->send(o, nullptr, 130); else std::cout << "SCHED: Discarding packet because connection is closed" << std::endl; // Clean up the message delete (*data); } } catch (std::exception& e) { dumpExceptions(e); // Cluster has gone offline, reset the connection. Missed packets shouldn't matter too much, // they should be resent by other threads after some time setConnection(nullptr); } // Data existed hadData = true; } } // Check if there is higher priority data to send if (doesHigherPriorityDataExist(currentPriority)) // Yes, so start the entire send process again goto reset; // Higher priority data does not exist, so keep sending data from this priority } while (hadData); } #ifndef BUILD_TESTS } #endif } bool Cluster::doesHigherPriorityDataExist(uint64_t maxPriority) { for (auto p = queue.begin(); p != queue.end(); p++) { // Get a pointer to the relevant map auto pMap = &(*p); // Check if the current priority is greater or equal to max priority and return false if not. auto currentPriority = p - queue.begin(); if (currentPriority >= maxPriority) return false; // Iterate over the map for (auto s = pMap->begin(); s != pMap->end();) { // Check if the vector for this source is empty if (!(*s).second->empty()) { // It's not empty so data does exist return true; } // Increment the iterator ++s; } } return false; } void Cluster::updateJob(Message &message) { // Read the details from the message auto jobId = message.pop_uint(); auto what = message.pop_string(); auto status = message.pop_uint(); auto details = message.pop_string(); // Create a database connection auto db = MySqlConnector(); // Get the job history table JobserverJobhistory jobHistoryTable; // Todo: Verify the job id belongs to this cluster, and that the status is valid // Add the new job history record db->run( insert_into(jobHistoryTable) .set( jobHistoryTable.jobId = jobId, jobHistoryTable.timestamp = std::chrono::system_clock::now(), jobHistoryTable.what = what, jobHistoryTable.state = status, jobHistoryTable.details = details ) ); // Check if this status update was the final job complete status, then try to cache the file list by listing the // files for the job. If for some reason this call fails internally (Maybe cluster is under load, or network issues) // then the next time the HTTP side requests files for the job the file list will be cached if (what == "_job_completion_") { ::handleFileList(pClusterManager, jobId, true, "", "job_controller", {}, nullptr); } } bool Cluster::isOnline() { return pConnection != nullptr; } [[noreturn]] void Cluster::resendMessages() { // Iterate forever while (true) { // Wait 1 minute until the next check std::this_thread::sleep_for(std::chrono::seconds(60)); // Check for jobs that need to be resubmitted checkUnsubmittedJobs(); // Check for jobs that need to be cancelled checkCancellingJobs(); // Check for jobs that need to be deleted checkDeletingJobs(); } } auto getJobsByMostRecentStatus(const std::vector<uint32_t>& states, const std::string& cluster) { /* Finds all jobs currently in a state provided by the states argument that are older than 60 seconds, for the current cluster */ // Create a database connection auto db = MySqlConnector(); // Get the tables JobserverJob jobTable; JobserverJobhistory jobHistoryTable; // Find any jobs with a state in states older than 60 seconds auto jobResults = db->run( select(all_of(jobTable)) .from(jobTable) .where( jobTable.cluster == cluster and jobTable.id == select(jobHistoryTable.jobId) .from(jobHistoryTable) .where( jobHistoryTable.state.in( sqlpp::value_list( states ) ) and jobHistoryTable.id == select(jobHistoryTable.id) .from(jobHistoryTable) .where( jobHistoryTable.jobId == jobTable.id and jobHistoryTable.timestamp <= std::chrono::system_clock::now() - std::chrono::seconds(60) ) .order_by(jobHistoryTable.timestamp.desc()) .limit(1u) ) ) ); return jobResults; } void Cluster::checkUnsubmittedJobs() { // Check if the cluster is online and resend the submit messages if (!isOnline()) return; // Get all jobs where the most recent job history is // pending or submitting and is more than a minute old auto states = std::vector<uint32_t>( { (uint32_t) PENDING, (uint32_t) SUBMITTING } ); auto jobs = getJobsByMostRecentStatus(states, this->getName()); auto db = MySqlConnector(); schema::JobserverJobhistory jobHistoryTable; // Resubmit any jobs that matched for (auto &job : jobs) { std::cout << "Resubmitting: " << job.id << std::endl; // Submit the job to the cluster auto msg = Message(SUBMIT_JOB, Message::Priority::Medium, std::to_string(job.id) + "_" + std::string(job.cluster)); msg.push_uint(job.id); msg.push_string(job.bundle); msg.push_string(job.parameters); msg.send(this); // Check that the job status is submitting and update it if not auto jobHistoryResults = db->run( select(all_of(jobHistoryTable)) .from(jobHistoryTable) .where(jobHistoryTable.jobId == job.id) .order_by(jobHistoryTable.timestamp.desc()) .limit(1u) ); auto dbHistory = &jobHistoryResults.front(); if ((uint32_t) dbHistory->state == (uint32_t) JobStatus::PENDING) { // The current state is pending for this job, so update the status to submitting db->run( insert_into(jobHistoryTable) .set( jobHistoryTable.jobId = job.id, jobHistoryTable.timestamp = std::chrono::system_clock::now(), jobHistoryTable.what = SYSTEM_SOURCE, jobHistoryTable.state = (uint32_t) JobStatus::SUBMITTING, jobHistoryTable.details = "Job submitting" ) ); } } } void Cluster::checkCancellingJobs() { // Check if the cluster is online and resend the submit messages if (!isOnline()) return; // Get all jobs where the most recent job history is // deleting and is more than a minute old auto states = std::vector<uint32_t>( { (uint32_t) CANCELLING } ); auto jobs = getJobsByMostRecentStatus(states, this->getName()); // Resubmit any jobs that matched for (auto &job : jobs) { std::cout << "Recancelling: " << job.id << std::endl; // Ask the cluster to cancel the job auto msg = Message(CANCEL_JOB, Message::Priority::Medium, std::to_string(job.id) + "_" + std::string(job.cluster)); msg.push_uint(job.id); msg.send(this); } } void Cluster::checkDeletingJobs() { // Check if the cluster is online and resend the submit messages if (!isOnline()) return; // Get all jobs where the most recent job history is // deleting and is more than a minute old auto states = std::vector<uint32_t>( { (uint32_t) DELETING } ); auto jobs = getJobsByMostRecentStatus(states, this->getName()); // Resubmit any jobs that matched for (auto &job : jobs) { std::cout << "Redeleting: " << job.id << std::endl; // Ask the cluster to delete the job auto msg = Message(DELETE_JOB, Message::Priority::Medium, std::to_string(job.id) + "_" + std::string(job.cluster)); msg.push_uint(job.id); msg.send(this); } } void Cluster::handleFileError(Message &message) { auto uuid = message.pop_string(); auto detail = message.pop_string(); // Acquire the lock std::unique_lock<std::mutex> fileDownloadMapDeletionLock(fileDownloadMapDeletionLockMutex); // Check that the uuid is valid if (fileDownloadMap.find(uuid) == fileDownloadMap.end()) return; auto fdObj = fileDownloadMap[uuid]; // Set the error fdObj->errorDetails = detail; fdObj->error = true; // Trigger the file transfer event fdObj->dataReady = true; fdObj->dataCV.notify_one(); } void Cluster::handleFileListError(Message &message) { auto uuid = message.pop_string(); auto detail = message.pop_string(); // Acquire the lock std::unique_lock<std::mutex> fileListMapDeletionLock(fileListMapDeletionLockMutex); // Check that the uuid is valid if (fileListMap.find(uuid) == fileListMap.end()) return; auto flObj = fileListMap[uuid]; // Set the error flObj->errorDetails = detail; flObj->error = true; // Trigger the file transfer event flObj->dataReady = true; flObj->dataCV.notify_one(); } void Cluster::handleFileDetails(Message &message) { auto uuid = message.pop_string(); auto fileSize = message.pop_ulong(); // Acquire the lock std::unique_lock<std::mutex> fileDownloadMapDeletionLock(fileDownloadMapDeletionLockMutex); // Check that the uuid is valid if (fileDownloadMap.find(uuid) == fileDownloadMap.end()) return; auto fdObj = fileDownloadMap[uuid]; // Set the file size fdObj->fileSize = fileSize; fdObj->receivedData = true; // Trigger the file transfer event fdObj->dataReady = true; fdObj->dataCV.notify_one(); } void Cluster::handleFileChunk(Message &message) { auto uuid = message.pop_string(); auto chunk = message.pop_bytes(); // It's only possible for the fdObj to be deleted from now on to the end of this function. That's because in the // HTTP file download code, the fdObj won't be deleted until after all bytes have been received and sent to the // HTTP client. If the enqueue above is the last chunk of data, and the HTTP client is slow, then there will never // be an opportunity for the dataReady check to be done by the HTTP file download code since it'll be in a loop // until there are no more chunks to send. This leads to a case where the fdObj might be deleted immediately after // the enqueue call above, so we need to protect any further accesses below in a unique lock. // Acquire the lock std::unique_lock<std::mutex> fileDownloadMapDeletionLock(fileDownloadMapDeletionLockMutex); // Now we're in a critical section, if the UUID still exists in the fileDownloadMap, then the fdObj hasn't yet // been destroyed, and we're right to continue using it. The HTTP file download code, will wait for this mutex to // be released before it tries to clean up. // Check that the uuid is valid if (fileDownloadMap.find(uuid) == fileDownloadMap.end()) return; auto fdObj = fileDownloadMap[uuid]; fdObj->receivedBytes += chunk.size(); // Copy the chunk and push it on to the queue fdObj->queue.enqueue(new std::vector<uint8_t>(chunk)); { // The Pause/Resume messages must be synchronized to avoid a deadlock std::unique_lock<std::mutex> fileDownloadPauseResumeLock(fileDownloadPauseResumeLockMutex); if (!fdObj->clientPaused) { // Check if our buffer is too big if (fdObj->receivedBytes - fdObj->sentBytes > MAX_FILE_BUFFER_SIZE) { // Ask the client to pause the file transfer fdObj->clientPaused = true; auto msg = Message(PAUSE_FILE_CHUNK_STREAM, Message::Priority::Highest, uuid); msg.push_string(uuid); msg.send(this); } } } // Trigger the file transfer event fdObj->dataReady = true; fdObj->dataCV.notify_one(); } void Cluster::handleFileList(Message &message) { auto uuid = message.pop_string(); // Acquire the lock std::unique_lock<std::mutex> fileListMapDeletionLock(fileListMapDeletionLockMutex); // Check that the uuid is valid if (fileListMap.find(uuid) == fileListMap.end()) return; auto flObj = fileListMap[uuid]; // Get the number of files in the message auto numFiles = message.pop_uint(); // Iterate over the files and add them to the file list map for (auto i = 0; i < numFiles; i++) { sFile s; // todo: Need to get file permissions s.fileName = message.pop_string(); s.isDirectory = message.pop_bool(); s.fileSize = message.pop_ulong(); // Add the file to the list flObj->files.push_back(s); } // Tell the HTTP side that the data is ready flObj->dataReady = true; flObj->dataCV.notify_one(); }
34.311404
120
0.563637
[ "vector" ]
4f995a6c3c33c907c48f5ca66751df1848da4a9b
20,104
cpp
C++
folly/test/FormatTest.cpp
Aoikiseki/folly
df3633c731d08bab0173039a050a30853fb47212
[ "Apache-2.0" ]
19,046
2015-01-01T17:01:10.000Z
2022-03-31T23:01:43.000Z
folly/test/FormatTest.cpp
Aoikiseki/folly
df3633c731d08bab0173039a050a30853fb47212
[ "Apache-2.0" ]
1,493
2015-01-11T15:47:13.000Z
2022-03-28T18:13:58.000Z
folly/test/FormatTest.cpp
Aoikiseki/folly
df3633c731d08bab0173039a050a30853fb47212
[ "Apache-2.0" ]
4,818
2015-01-01T12:28:16.000Z
2022-03-31T16:22:10.000Z
/* * Copyright (c) Facebook, Inc. and its affiliates. * * 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 <folly/Format.h> #include <string> #include <folly/Utility.h> #include <folly/portability/GTest.h> FOLLY_GNU_DISABLE_WARNING("-Wdeprecated") using namespace folly; template <class Uint> void compareOctal(Uint u) { char buf1[detail::kMaxOctalLength + 1]; buf1[detail::kMaxOctalLength] = '\0'; char* p = buf1 + detail::uintToOctal(buf1, detail::kMaxOctalLength, u); char buf2[detail::kMaxOctalLength + 1]; EXPECT_LT( snprintf(buf2, sizeof(buf2), "%jo", static_cast<uintmax_t>(u)), sizeof(buf2)); EXPECT_EQ(std::string(buf2), std::string(p)); } template <class Uint> void compareHex(Uint u) { char buf1[detail::kMaxHexLength + 1]; buf1[detail::kMaxHexLength] = '\0'; char* p = buf1 + detail::uintToHexLower(buf1, detail::kMaxHexLength, u); char buf2[detail::kMaxHexLength + 1]; EXPECT_LT( snprintf(buf2, sizeof(buf2), "%jx", static_cast<uintmax_t>(u)), sizeof(buf2)); EXPECT_EQ(std::string(buf2), std::string(p)); } template <class Uint> void compareBinary(Uint u) { char buf[detail::kMaxBinaryLength + 1]; buf[detail::kMaxBinaryLength] = '\0'; char* p = buf + detail::uintToBinary(buf, detail::kMaxBinaryLength, u); std::string repr; if (u == 0) { repr = '0'; } else { std::string tmp; for (; u; u >>= 1) { tmp.push_back(u & 1 ? '1' : '0'); } repr.assign(tmp.rbegin(), tmp.rend()); } EXPECT_EQ(repr, std::string(p)); } TEST(Format, uintToOctal) { for (unsigned i = 0; i < (1u << 16) + 2; i++) { compareOctal(i); } } TEST(Format, uintToHex) { for (unsigned i = 0; i < (1u << 16) + 2; i++) { compareHex(i); } } TEST(Format, uintToBinary) { for (unsigned i = 0; i < (1u << 16) + 2; i++) { compareBinary(i); } } TEST(Format, Simple) { EXPECT_EQ("hello", sformat("hello")); EXPECT_EQ("42", sformat("{}", 42)); EXPECT_EQ("42 42", sformat("{0} {0}", 42)); EXPECT_EQ("00042 23 42", sformat("{0:05} {1:3} {0:4}", 42, 23)); EXPECT_EQ( "hello world hello 42", sformat("{0} {1} {0} {2}", "hello", "world", 42)); EXPECT_EQ("XXhelloXX", sformat("{:X^9}", "hello")); EXPECT_EQ("XXX42XXXX", sformat("{:X^9}", 42)); EXPECT_EQ("-0xYYYY2a", sformat("{:Y=#9x}", -42)); EXPECT_EQ("*", sformat("{}", '*')); EXPECT_EQ("42", sformat("{}", 42)); EXPECT_EQ("0042", sformat("{:04}", 42)); EXPECT_EQ("hello ", sformat("{:7}", "hello")); EXPECT_EQ("hello ", sformat("{:<7}", "hello")); EXPECT_EQ(" hello", sformat("{:>7}", "hello")); EXPECT_EQ(" hi", sformat("{:>*}", 4, "hi")); EXPECT_EQ(" hi!", sformat("{:*}{}", 3, "", "hi!")); EXPECT_EQ(" 123", sformat("{:*}", 7, 123)); EXPECT_EQ("123 ", sformat("{:<*}", 7, 123)); EXPECT_EQ("----<=>----", sformat("{:-^*}", 11, "<=>")); EXPECT_EQ("+++456+++", sformat("{2:+^*0}", 9, "unused", 456)); std::vector<int> v1{10, 20, 30}; EXPECT_EQ("0020", sformat("{0[1]:04}", v1)); EXPECT_EQ("0020", svformat("{1:04}", v1)); EXPECT_EQ("10 20", svformat("{} {}", v1)); const std::vector<int> v2 = v1; EXPECT_EQ("0020", sformat("{0[1]:04}", v2)); EXPECT_EQ("0020", svformat("{1:04}", v2)); EXPECT_THROW(sformat("{0[3]:04}", v2), std::out_of_range); EXPECT_THROW(svformat("{3:04}", v2), std::out_of_range); EXPECT_EQ("0020", sformat("{0[1]:04}", defaulted(v2, 42))); EXPECT_EQ("0020", svformat("{1:04}", defaulted(v2, 42))); EXPECT_EQ("0042", sformat("{0[3]:04}", defaulted(v2, 42))); EXPECT_EQ("0042", svformat("{3:04}", defaulted(v2, 42))); { const int p[] = {10, 20, 30}; const int* q = p; EXPECT_EQ("0020", sformat("{0[1]:04}", p)); EXPECT_EQ("0020", svformat("{1:04}", p)); EXPECT_EQ("0020", sformat("{0[1]:04}", q)); EXPECT_EQ("0020", svformat("{1:04}", q)); EXPECT_NE("", sformat("{}", q)); EXPECT_EQ("0x", sformat("{}", p).substr(0, 2)); EXPECT_EQ("10", svformat("{}", p)); EXPECT_EQ("0x", sformat("{}", q).substr(0, 2)); EXPECT_EQ("10", svformat("{}", q)); q = nullptr; EXPECT_EQ("(null)", sformat("{}", q)); } std::map<int, std::string> m{{10, "hello"}, {20, "world"}}; EXPECT_EQ("worldXX", sformat("{[20]:X<7}", m)); EXPECT_EQ("worldXX", svformat("{20:X<7}", m)); EXPECT_THROW(sformat("{[42]:X<7}", m), std::out_of_range); EXPECT_THROW(svformat("{42:X<7}", m), std::out_of_range); EXPECT_EQ("worldXX", sformat("{[20]:X<7}", defaulted(m, "meow"))); EXPECT_EQ("worldXX", svformat("{20:X<7}", defaulted(m, "meow"))); EXPECT_EQ("meowXXX", sformat("{[42]:X<7}", defaulted(m, "meow"))); EXPECT_EQ("meowXXX", svformat("{42:X<7}", defaulted(m, "meow"))); std::map<std::string, std::string> m2{{"hello", "world"}}; EXPECT_EQ("worldXX", sformat("{[hello]:X<7}", m2)); EXPECT_EQ("worldXX", svformat("{hello:X<7}", m2)); EXPECT_THROW(sformat("{[none]:X<7}", m2), std::out_of_range); EXPECT_THROW(svformat("{none:X<7}", m2), std::out_of_range); EXPECT_EQ("worldXX", sformat("{[hello]:X<7}", defaulted(m2, "meow"))); EXPECT_EQ("worldXX", svformat("{hello:X<7}", defaulted(m2, "meow"))); EXPECT_EQ("meowXXX", sformat("{[none]:X<7}", defaulted(m2, "meow"))); EXPECT_EQ("meowXXX", svformat("{none:X<7}", defaulted(m2, "meow"))); try { svformat("{none:X<7}", m2); EXPECT_FALSE(true) << "svformat should throw on missing key"; } catch (const FormatKeyNotFoundException& e) { EXPECT_STREQ("none", e.key()); } // Test indexing in strings EXPECT_EQ("61 62", sformat("{0[0]:x} {0[1]:x}", "abcde")); EXPECT_EQ("61 62", svformat("{0:x} {1:x}", "abcde")); EXPECT_EQ("61 62", sformat("{0[0]:x} {0[1]:x}", std::string("abcde"))); EXPECT_EQ("61 62", svformat("{0:x} {1:x}", std::string("abcde"))); // Test booleans EXPECT_EQ("true", sformat("{}", true)); EXPECT_EQ("1", sformat("{:d}", true)); EXPECT_EQ("false", sformat("{}", false)); EXPECT_EQ("0", sformat("{:d}", false)); // Test pairs { std::pair<int, std::string> p{42, "hello"}; EXPECT_EQ(" 42 hello ", sformat("{0[0]:6} {0[1]:6}", p)); EXPECT_EQ(" 42 hello ", svformat("{:6} {:6}", p)); } // Test tuples { std::tuple<int, std::string, int> t{42, "hello", 23}; EXPECT_EQ(" 42 hello 23", sformat("{0[0]:6} {0[1]:6} {0[2]:6}", t)); EXPECT_EQ(" 42 hello 23", svformat("{:6} {:6} {:6}", t)); } // Test writing to stream std::ostringstream os; os << format("{} {}", 42, 23); EXPECT_EQ("42 23", os.str()); // Test appending to string std::string s; format(&s, "{} {}", 42, 23); format(&s, " hello {:X<7}", "world"); EXPECT_EQ("42 23 hello worldXX", s); } TEST(Format, Float) { EXPECT_EQ("1", sformat("{}", 1.0)); EXPECT_EQ("0.1", sformat("{}", 0.1)); EXPECT_EQ("0.01", sformat("{}", 0.01)); EXPECT_EQ("0.001", sformat("{}", 0.001)); EXPECT_EQ("0.0001", sformat("{}", 0.0001)); EXPECT_EQ("1e-5", sformat("{}", 0.00001)); EXPECT_EQ("1e-6", sformat("{}", 0.000001)); EXPECT_EQ("10", sformat("{}", 10.0)); EXPECT_EQ("100", sformat("{}", 100.0)); EXPECT_EQ("1000", sformat("{}", 1000.0)); EXPECT_EQ("10000", sformat("{}", 10000.0)); EXPECT_EQ("100000", sformat("{}", 100000.0)); EXPECT_EQ("1e+6", sformat("{}", 1000000.0)); EXPECT_EQ("1e+7", sformat("{}", 10000000.0)); EXPECT_EQ("1.00", sformat("{:.2f}", 1.0)); EXPECT_EQ("0.10", sformat("{:.2f}", 0.1)); EXPECT_EQ("0.01", sformat("{:.2f}", 0.01)); EXPECT_EQ("0.00", sformat("{:.2f}", 0.001)); EXPECT_EQ("100000. !== 100000", sformat("{:.} !== {:.}", 100000.0, 100000)); EXPECT_EQ("100000.", sformat("{:.}", 100000.0)); EXPECT_EQ("1e+6", sformat("{:.}", 1000000.0)); EXPECT_EQ(" 100000.", sformat("{:8.}", 100000.0)); EXPECT_EQ("100000.", sformat("{:4.}", 100000.0)); EXPECT_EQ(" 100000", sformat("{:8.8}", 100000.0)); EXPECT_EQ(" 100000.", sformat("{:8.8.}", 100000.0)); } TEST(Format, MultiLevel) { std::vector<std::map<std::string, std::string>> v = { { {"hello", "world"}, }, }; EXPECT_EQ("world", sformat("{[0.hello]}", v)); } TEST(Format, separatorDecimalInteger) { EXPECT_EQ("0", sformat("{:,d}", 0)); EXPECT_EQ("1", sformat("{:d}", 1)); EXPECT_EQ("1", sformat("{:,d}", 1)); EXPECT_EQ("1", sformat("{:,}", 1)); EXPECT_EQ("123", sformat("{:d}", 123)); EXPECT_EQ("123", sformat("{:,d}", 123)); EXPECT_EQ("123", sformat("{:,}", 123)); EXPECT_EQ("1234", sformat("{:d}", 1234)); EXPECT_EQ("1,234", sformat("{:,d}", 1234)); EXPECT_EQ("1,234", sformat("{:,}", 1234)); EXPECT_EQ("12345678", sformat("{:d}", 12345678)); EXPECT_EQ("12,345,678", sformat("{:,d}", 12345678)); EXPECT_EQ("12,345,678", sformat("{:,}", 12345678)); EXPECT_EQ("-1234", sformat("{:d}", -1234)); EXPECT_EQ("-1,234", sformat("{:,d}", -1234)); EXPECT_EQ("-1,234", sformat("{:,}", -1234)); int64_t max_int64_t = std::numeric_limits<int64_t>::max(); int64_t min_int64_t = std::numeric_limits<int64_t>::min(); uint64_t max_uint64_t = std::numeric_limits<uint64_t>::max(); EXPECT_EQ("9223372036854775807", sformat("{:d}", max_int64_t)); EXPECT_EQ("9,223,372,036,854,775,807", sformat("{:,d}", max_int64_t)); EXPECT_EQ("9,223,372,036,854,775,807", sformat("{:,}", max_int64_t)); EXPECT_EQ("-9223372036854775808", sformat("{:d}", min_int64_t)); EXPECT_EQ("-9,223,372,036,854,775,808", sformat("{:,d}", min_int64_t)); EXPECT_EQ("-9,223,372,036,854,775,808", sformat("{:,}", min_int64_t)); EXPECT_EQ("18446744073709551615", sformat("{:d}", max_uint64_t)); EXPECT_EQ("18,446,744,073,709,551,615", sformat("{:,d}", max_uint64_t)); EXPECT_EQ("18,446,744,073,709,551,615", sformat("{:,}", max_uint64_t)); EXPECT_EQ(" -1,234", sformat("{: 8,}", -1234)); EXPECT_EQ("-001,234", sformat("{:08,d}", -1234)); EXPECT_EQ("-00001,234", sformat("{:010,d}", -1234)); EXPECT_EQ(" -1,234 ", sformat("{:^ 8,d}", -1234)); } // Note that sformat("{:n}", ...) uses the current locale setting to insert the // appropriate number separator characters. TEST(Format, separatorNumber) { EXPECT_EQ("0", sformat("{:n}", 0)); EXPECT_EQ("1", sformat("{:n}", 1)); EXPECT_EQ("123", sformat("{:n}", 123)); EXPECT_EQ("1234", sformat("{:n}", 1234)); EXPECT_EQ("12345678", sformat("{:n}", 12345678)); EXPECT_EQ("-1234", sformat("{:n}", -1234)); int64_t max_int64_t = std::numeric_limits<int64_t>::max(); int64_t min_int64_t = std::numeric_limits<int64_t>::min(); uint64_t max_uint64_t = std::numeric_limits<uint64_t>::max(); EXPECT_EQ("9223372036854775807", sformat("{:n}", max_int64_t)); EXPECT_EQ("-9223372036854775808", sformat("{:n}", min_int64_t)); EXPECT_EQ("18446744073709551615", sformat("{:n}", max_uint64_t)); EXPECT_EQ(" -1234", sformat("{: 8n}", -1234)); EXPECT_EQ("-0001234", sformat("{:08n}", -1234)); EXPECT_EQ("-000001234", sformat("{:010n}", -1234)); EXPECT_EQ(" -1234 ", sformat("{:^ 8n}", -1234)); } // insertThousandsGroupingUnsafe requires non-const params static void testGrouping(const char* a_str, const char* expected) { char str[256]; char* end_ptr = str + snprintf(str, sizeof(str), "%s", a_str); ASSERT_LT(end_ptr, str + sizeof(str)); folly::detail::insertThousandsGroupingUnsafe(str, &end_ptr); ASSERT_STREQ(expected, str); } TEST(Format, separatorUnit) { testGrouping("0", "0"); testGrouping("1", "1"); testGrouping("12", "12"); testGrouping("123", "123"); testGrouping("1234", "1,234"); testGrouping("12345", "12,345"); testGrouping("123456", "123,456"); testGrouping("1234567", "1,234,567"); testGrouping("1234567890", "1,234,567,890"); testGrouping("9223372036854775807", "9,223,372,036,854,775,807"); testGrouping("18446744073709551615", "18,446,744,073,709,551,615"); } namespace { struct KeyValue { std::string key; int value; }; } // namespace namespace folly { template <> class FormatValue<KeyValue> { public: explicit FormatValue(const KeyValue& kv) : kv_(kv) {} template <class FormatCallback> void format(FormatArg& arg, FormatCallback& cb) const { format_value::formatFormatter( folly::format("<key={}, value={}>", kv_.key, kv_.value), arg, cb); } private: const KeyValue& kv_; }; } // namespace folly TEST(Format, Custom) { KeyValue kv{"hello", 42}; EXPECT_EQ("<key=hello, value=42>", sformat("{}", kv)); EXPECT_EQ("<key=hello, value=42>", sformat("{:10}", kv)); EXPECT_EQ("<key=hello", sformat("{:.10}", kv)); EXPECT_EQ("<key=hello, value=42>XX", sformat("{:X<23}", kv)); EXPECT_EQ("XX<key=hello, value=42>", sformat("{:X>23}", kv)); EXPECT_EQ("<key=hello, value=42>", sformat("{0[0]}", &kv)); EXPECT_NE("", sformat("{}", &kv)); } namespace { struct Opaque { int k; }; } // namespace #define EXPECT_THROW_STR(code, type, str) \ do { \ bool caught = false; \ try { \ code; \ } catch (const type& e) { \ caught = true; \ EXPECT_TRUE(strstr(e.what(), (str)) != nullptr) \ << "Expected message [" << (str) << "], actual message [" \ << e.what(); \ } catch (const std::exception& e) { \ caught = true; \ ADD_FAILURE() << "Caught different exception type; expected " #type \ ", caught " \ << folly::demangle(typeid(e)); \ } catch (...) { \ caught = true; \ ADD_FAILURE() << "Caught unknown exception type; expected " #type; \ } \ if (!caught) { \ ADD_FAILURE() << "Expected exception " #type ", caught nothing"; \ } \ } while (false) #define EXPECT_FORMAT_ERROR(code, str) \ EXPECT_THROW_STR(code, folly::BadFormatArg, (str)) TEST(Format, Unformatted) { Opaque o; EXPECT_NE("", sformat("{}", &o)); EXPECT_FORMAT_ERROR( sformat("{0[0]}", &o), "No formatter available for this type"); } TEST(Format, Nested) { EXPECT_EQ("1 2 3 4", sformat("{} {} {}", 1, 2, format("{} {}", 3, 4))); // // not copyable, must hold temporary in scope instead. auto&& saved = format("{} {}", 3, 4); EXPECT_EQ("1 2 3 4", sformat("{} {} {}", 1, 2, saved)); } TEST(Format, OutOfBounds) { std::vector<int> ints{1, 2, 3, 4, 5}; EXPECT_EQ("1 3 5", sformat("{0[0]} {0[2]} {0[4]}", ints)); EXPECT_THROW(sformat("{[5]}", ints), std::out_of_range); std::map<std::string, int> map{{"hello", 0}, {"world", 1}}; EXPECT_EQ("hello = 0", sformat("hello = {[hello]}", map)); EXPECT_THROW(sformat("{[nope]}", map), std::out_of_range); EXPECT_THROW(svformat("{nope}", map), std::out_of_range); } TEST(Format, BogusFormatString) { EXPECT_FORMAT_ERROR(sformat("}"), "single '}' in format string"); EXPECT_FORMAT_ERROR(sformat("foo}bar"), "single '}' in format string"); EXPECT_FORMAT_ERROR(sformat("foo{bar"), "missing ending '}'"); EXPECT_FORMAT_ERROR(sformat("{[test]"), "missing ending '}'"); EXPECT_FORMAT_ERROR(sformat("{-1.3}"), "argument index must be non-negative"); EXPECT_FORMAT_ERROR(sformat("{1.3}", 0, 1, 2), "index not allowed"); EXPECT_FORMAT_ERROR( sformat("{0} {} {1}", 0, 1, 2), "may not have both default and explicit arg indexes"); EXPECT_FORMAT_ERROR( sformat("{:*}", 1.2), "dynamic field width argument must be integral"); EXPECT_FORMAT_ERROR( sformat("{} {:*}", "hi"), "argument index out of range, max=1"); EXPECT_FORMAT_ERROR( sformat("{:*0}", 12, "ok"), "cannot provide width arg index without value arg index"); EXPECT_FORMAT_ERROR( sformat("{0:*}", 12, "ok"), "cannot provide value arg index without width arg index"); std::vector<int> v{1, 2, 3}; EXPECT_FORMAT_ERROR( svformat("{:*}", v), "dynamic field width not supported in vformat()"); // This one fails in detail::enforceWhitespace(), which throws // std::range_error EXPECT_FORMAT_ERROR(sformat("{0[test}"), "argument index must be integer"); } template <bool containerMode, class... Args> class TestExtendingFormatter; template <bool containerMode, class... Args> class TestExtendingFormatter : public BaseFormatter< TestExtendingFormatter<containerMode, Args...>, containerMode, Args...> { private: explicit TestExtendingFormatter(StringPiece& str, Args&&... args) : BaseFormatter< TestExtendingFormatter<containerMode, Args...>, containerMode, Args...>(str, std::forward<Args>(args)...) {} template <size_t K, class Callback> void doFormatArg(FormatArg& arg, Callback& cb) const { std::string result; auto appender = [&result](StringPiece s) { result.append(s.data(), s.size()); }; this->template getFormatValue<K>().format(arg, appender); result = sformat("{{{}}}", result); cb(StringPiece(result)); } friend class BaseFormatter< TestExtendingFormatter<containerMode, Args...>, containerMode, Args...>; template <class... A> friend std::string texsformat(StringPiece fmt, A&&... arg); }; template <class... Args> std::string texsformat(StringPiece fmt, Args&&... args) { return TestExtendingFormatter<false, Args...>( fmt, std::forward<Args>(args)...) .str(); } TEST(Format, Extending) { EXPECT_EQ(texsformat("I {} brackets", "love"), "I {love} brackets"); EXPECT_EQ( texsformat("I {} nesting", sformat("really {}", "love")), "I {really love} nesting"); EXPECT_EQ( sformat("I also {} nesting", texsformat("have an {} for", "affinity")), "I also have an {affinity} for nesting"); EXPECT_EQ( texsformat( "Extending {} in {}", texsformat("a {}", "formatter"), "another formatter"), "Extending {a {formatter}} in {another formatter}"); } TEST(Format, Temporary) { constexpr StringPiece kStr = "A long string that should go on the heap"; auto fmt = format("{}", kStr.str()); // Pass a temporary std::string. EXPECT_EQ(fmt.str(), kStr); // The formatter can be reused. EXPECT_EQ(fmt.str(), kStr); } namespace { struct NoncopyableInt : MoveOnly { explicit NoncopyableInt(int v) : value(v) {} int value; }; } // namespace namespace folly { template <> class FormatValue<NoncopyableInt> { public: explicit FormatValue(const NoncopyableInt& v) : v_(v) {} template <class FormatCallback> void format(FormatArg& arg, FormatCallback& cb) const { FormatValue<int>(v_.value).format(arg, cb); } private: const NoncopyableInt& v_; }; } // namespace folly TEST(Format, NoncopyableArg) { { // Test that lvalues are held by reference. NoncopyableInt v(1); auto fmt = format("{}", v); EXPECT_EQ(fmt.str(), "1"); // The formatter can be reused. EXPECT_EQ(fmt.str(), "1"); } { // Test that rvalues are moved. auto fmt = format("{}", NoncopyableInt(1)); EXPECT_EQ(fmt.str(), "1"); } }
34.662069
80
0.574712
[ "vector" ]
4f9c44a9aea21b07e3a318dfee208f05f0a36c58
656
cpp
C++
9.STL/Vector Iterator.cpp
MainakRepositor/SRM-OOPS-Elabs-Solution
1b70b3d56ad730ce4ab02835f3302c250dc5e31b
[ "Apache-2.0" ]
27
2020-11-01T13:07:50.000Z
2022-01-07T13:26:26.000Z
9.STL/Vector Iterator.cpp
MainakRepositor/SRM-OOPD-Elabs-Solution
1b70b3d56ad730ce4ab02835f3302c250dc5e31b
[ "Apache-2.0" ]
1
2020-10-31T18:55:28.000Z
2020-10-31T18:55:28.000Z
9.STL/Vector Iterator.cpp
MainakRepositor/SRM-OOPS-Elabs-Solution
1b70b3d56ad730ce4ab02835f3302c250dc5e31b
[ "Apache-2.0" ]
null
null
null
#include <iostream> #include <vector> #include <iterator> using namespace std; int main() { int num,n; cin>>n; vector<int>MyVector; for(int i=0;i<n;i++) { cin>>num; MyVector.push_back(num); } vector<int>::iterator ptr; for (ptr = MyVector.begin(); ptr < MyVector.end(); ptr++) cout << *ptr << " "; /*for(int i=0;i<n;i++) { cout<<MyVector[i]<<" "; }*/ cout<<endl; // vector<int>::reverse_iterator; vector<int>::reverse_iterator ptr1; for (ptr1 = MyVector.rbegin(); ptr1 < MyVector.rend(); ptr1++) cout << *ptr1 << " "; /* for(int i=n-1;i>=0;i--) { cout<<MyVector[i]<<" "; }*/ return 0; }
20.5
64
0.551829
[ "vector" ]
4f9ccdbae98dc4e7ee769e1edda5f2cd50e5fc0e
12,270
cpp
C++
IndexBinaryHash.cpp
nealeaf/faiss
c6bc8c46f1decc109573978ad2b6d616b07b8eac
[ "MIT" ]
4
2019-08-27T21:10:15.000Z
2022-03-06T04:32:29.000Z
IndexBinaryHash.cpp
nealeaf/faiss
c6bc8c46f1decc109573978ad2b6d616b07b8eac
[ "MIT" ]
null
null
null
IndexBinaryHash.cpp
nealeaf/faiss
c6bc8c46f1decc109573978ad2b6d616b07b8eac
[ "MIT" ]
2
2020-05-07T02:42:46.000Z
2021-06-07T08:20:22.000Z
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ // Copyright 2004-present Facebook. All Rights Reserved // -*- c++ -*- #include <faiss/IndexBinaryHash.h> #include <cstdio> #include <memory> #include <faiss/utils/hamming.h> #include <faiss/utils/utils.h> #include <faiss/impl/AuxIndexStructures.h> #include <faiss/impl/FaissAssert.h> namespace faiss { void IndexBinaryHash::InvertedList::add ( idx_t id, size_t code_size, const uint8_t *code) { ids.push_back(id); vecs.insert(vecs.end(), code, code + code_size); } IndexBinaryHash::IndexBinaryHash(int d, int b): IndexBinary(d), b(b), nflip(0) { is_trained = true; } IndexBinaryHash::IndexBinaryHash(): b(0), nflip(0) { is_trained = true; } void IndexBinaryHash::reset() { invlists.clear(); ntotal = 0; } void IndexBinaryHash::add(idx_t n, const uint8_t *x) { add_with_ids(n, x, nullptr); } void IndexBinaryHash::add_with_ids(idx_t n, const uint8_t *x, const idx_t *xids) { uint64_t mask = ((uint64_t)1 << b) - 1; // simplistic add function. Cannot really be parallelized. for (idx_t i = 0; i < n; i++) { idx_t id = xids ? xids[i] : ntotal + i; const uint8_t * xi = x + i * code_size; idx_t hash = *((uint64_t*)xi) & mask; invlists[hash].add(id, code_size, xi); } ntotal += n; } namespace { /** Enumerate all bit vectors of size nbit with up to maxflip 1s * test in P127257851 P127258235 */ struct FlipEnumerator { int nbit, nflip, maxflip; uint64_t mask, x; FlipEnumerator (int nbit, int maxflip): nbit(nbit), maxflip(maxflip) { nflip = 0; mask = 0; x = 0; } bool next() { if (x == mask) { if (nflip == maxflip) { return false; } // increase Hamming radius nflip++; mask = (((uint64_t)1 << nflip) - 1); x = mask << (nbit - nflip); return true; } int i = __builtin_ctzll(x); if (i > 0) { x ^= (uint64_t)3 << (i - 1); } else { // nb of LSB 1s int n1 = __builtin_ctzll(~x); // clear them x &= ((uint64_t)(-1) << n1); int n2 = __builtin_ctzll(x); x ^= (((uint64_t)1 << (n1 + 2)) - 1) << (n2 - n1 - 1); } return true; } }; using idx_t = Index::idx_t; struct RangeSearchResults { int radius; RangeQueryResult &qres; inline void add (float dis, idx_t id) { if (dis < radius) { qres.add (dis, id); } } }; struct KnnSearchResults { // heap params idx_t k; int32_t * heap_sim; idx_t * heap_ids; using C = CMax<int, idx_t>; inline void add (float dis, idx_t id) { if (dis < heap_sim[0]) { heap_pop<C> (k, heap_sim, heap_ids); heap_push<C> (k, heap_sim, heap_ids, dis, id); } } }; template<class HammingComputer, class SearchResults> void search_single_query_template(const IndexBinaryHash & index, const uint8_t *q, SearchResults &res, size_t &n0, size_t &nlist, size_t &ndis) { size_t code_size = index.code_size; uint64_t mask = ((uint64_t)1 << index.b) - 1; uint64_t qhash = *((uint64_t*)q) & mask; HammingComputer hc (q, code_size); FlipEnumerator fe(index.b, index.nflip); // loop over neighbors that are at most at nflip bits do { uint64_t hash = qhash ^ fe.x; auto it = index.invlists.find (hash); if (it == index.invlists.end()) { continue; } const IndexBinaryHash::InvertedList &il = it->second; size_t nv = il.ids.size(); if (nv == 0) { n0++; } else { const uint8_t *codes = il.vecs.data(); for (size_t i = 0; i < nv; i++) { int dis = hc.hamming (codes); res.add(dis, il.ids[i]); codes += code_size; } ndis += nv; nlist++; } } while(fe.next()); } template<class SearchResults> void search_single_query(const IndexBinaryHash & index, const uint8_t *q, SearchResults &res, size_t &n0, size_t &nlist, size_t &ndis) { #define HC(name) search_single_query_template<name>(index, q, res, n0, nlist, ndis); switch(index.code_size) { case 4: HC(HammingComputer4); break; case 8: HC(HammingComputer8); break; case 16: HC(HammingComputer16); break; case 20: HC(HammingComputer20); break; case 32: HC(HammingComputer32); break; default: if (index.code_size % 8 == 0) { HC(HammingComputerM8); } else { HC(HammingComputerDefault); } } #undef HC } } // anonymous namespace void IndexBinaryHash::range_search(idx_t n, const uint8_t *x, int radius, RangeSearchResult *result) const { size_t nlist = 0, ndis = 0, n0 = 0; #pragma omp parallel if(n > 100) reduction(+: ndis, n0, nlist) { RangeSearchPartialResult pres (result); #pragma omp for for (size_t i = 0; i < n; i++) { // loop queries RangeQueryResult & qres = pres.new_result (i); RangeSearchResults res = {radius, qres}; const uint8_t *q = x + i * code_size; search_single_query (*this, q, res, n0, nlist, ndis); } pres.finalize (); } indexBinaryHash_stats.nq += n; indexBinaryHash_stats.n0 += n0; indexBinaryHash_stats.nlist += nlist; indexBinaryHash_stats.ndis += ndis; } void IndexBinaryHash::search(idx_t n, const uint8_t *x, idx_t k, int32_t *distances, idx_t *labels) const { using HeapForL2 = CMax<int32_t, idx_t>; size_t nlist = 0, ndis = 0, n0 = 0; #pragma omp parallel for if(n > 100) reduction(+: nlist, ndis, n0) for (size_t i = 0; i < n; i++) { int32_t * simi = distances + k * i; idx_t * idxi = labels + k * i; heap_heapify<HeapForL2> (k, simi, idxi); KnnSearchResults res = {k, simi, idxi}; const uint8_t *q = x + i * code_size; search_single_query (*this, q, res, n0, nlist, ndis); } indexBinaryHash_stats.nq += n; indexBinaryHash_stats.n0 += n0; indexBinaryHash_stats.nlist += nlist; indexBinaryHash_stats.ndis += ndis; } size_t IndexBinaryHash::hashtable_size() const { return invlists.size(); } void IndexBinaryHash::display() const { for (auto it = invlists.begin(); it != invlists.end(); ++it) { printf("%ld: [", it->first); const std::vector<idx_t> & v = it->second.ids; for (auto x: v) { printf("%ld ", 0 + x); } printf("]\n"); } } void IndexBinaryHashStats::reset() { memset ((void*)this, 0, sizeof (*this)); } IndexBinaryHashStats indexBinaryHash_stats; /******************************************************* * IndexBinaryMultiHash implementation ******************************************************/ IndexBinaryMultiHash::IndexBinaryMultiHash(int d, int nhash, int b): IndexBinary(d), storage(new IndexBinaryFlat(d)), own_fields(true), maps(nhash), nhash(nhash), b(b), nflip(0) { FAISS_THROW_IF_NOT(nhash * b <= d); } IndexBinaryMultiHash::IndexBinaryMultiHash(): storage(nullptr), own_fields(true), nhash(0), b(0), nflip(0) {} IndexBinaryMultiHash::~IndexBinaryMultiHash() { if (own_fields) { delete storage; } } void IndexBinaryMultiHash::reset() { storage->reset(); ntotal = 0; for(auto map: maps) { map.clear(); } } void IndexBinaryMultiHash::add(idx_t n, const uint8_t *x) { storage->add(n, x); // populate maps uint64_t mask = ((uint64_t)1 << b) - 1; for(idx_t i = 0; i < n; i++) { const uint8_t *xi = x + i * code_size; int ho = 0; for(int h = 0; h < nhash; h++) { uint64_t hash = *(uint64_t*)(xi + (ho >> 3)) >> (ho & 7); hash &= mask; maps[h][hash].push_back(i + ntotal); ho += b; } } ntotal += n; } namespace { template <class HammingComputer, class SearchResults> static void verify_shortlist( const IndexBinaryFlat & index, const uint8_t * q, const std::unordered_set<Index::idx_t> & shortlist, SearchResults &res) { size_t code_size = index.code_size; size_t nlist = 0, ndis = 0, n0 = 0; HammingComputer hc (q, code_size); const uint8_t *codes = index.xb.data(); for (auto i: shortlist) { int dis = hc.hamming (codes + i * code_size); res.add(dis, i); } } template<class SearchResults> void search_1_query_multihash(const IndexBinaryMultiHash & index, const uint8_t *xi, SearchResults &res, size_t &n0, size_t &nlist, size_t &ndis) { std::unordered_set<idx_t> shortlist; int b = index.b; uint64_t mask = ((uint64_t)1 << b) - 1; int ho = 0; for(int h = 0; h < index.nhash; h++) { uint64_t qhash = *(uint64_t*)(xi + (ho >> 3)) >> (ho & 7); qhash &= mask; const IndexBinaryMultiHash::Map & map = index.maps[h]; FlipEnumerator fe(index.b, index.nflip); // loop over neighbors that are at most at nflip bits do { uint64_t hash = qhash ^ fe.x; auto it = map.find (hash); if (it != map.end()) { const std::vector<idx_t> & v = it->second; for (auto i: v) { shortlist.insert(i); } nlist++; } else { n0++; } } while(fe.next()); ho += b; } ndis += shortlist.size(); // verify shortlist #define HC(name) verify_shortlist<name> (*index.storage, xi, shortlist, res) switch(index.code_size) { case 4: HC(HammingComputer4); break; case 8: HC(HammingComputer8); break; case 16: HC(HammingComputer16); break; case 20: HC(HammingComputer20); break; case 32: HC(HammingComputer32); break; default: if (index.code_size % 8 == 0) { HC(HammingComputerM8); } else { HC(HammingComputerDefault); } } #undef HC } } // anonymous namespace void IndexBinaryMultiHash::range_search(idx_t n, const uint8_t *x, int radius, RangeSearchResult *result) const { size_t nlist = 0, ndis = 0, n0 = 0; #pragma omp parallel if(n > 100) reduction(+: ndis, n0, nlist) { RangeSearchPartialResult pres (result); #pragma omp for for (size_t i = 0; i < n; i++) { // loop queries RangeQueryResult & qres = pres.new_result (i); RangeSearchResults res = {radius, qres}; const uint8_t *q = x + i * code_size; search_1_query_multihash (*this, q, res, n0, nlist, ndis); } pres.finalize (); } indexBinaryHash_stats.nq += n; indexBinaryHash_stats.n0 += n0; indexBinaryHash_stats.nlist += nlist; indexBinaryHash_stats.ndis += ndis; } void IndexBinaryMultiHash::search(idx_t n, const uint8_t *x, idx_t k, int32_t *distances, idx_t *labels) const { using HeapForL2 = CMax<int32_t, idx_t>; size_t nlist = 0, ndis = 0, n0 = 0; #pragma omp parallel for if(n > 100) reduction(+: nlist, ndis, n0) for (size_t i = 0; i < n; i++) { int32_t * simi = distances + k * i; idx_t * idxi = labels + k * i; heap_heapify<HeapForL2> (k, simi, idxi); KnnSearchResults res = {k, simi, idxi}; const uint8_t *q = x + i * code_size; search_1_query_multihash (*this, q, res, n0, nlist, ndis); } indexBinaryHash_stats.nq += n; indexBinaryHash_stats.n0 += n0; indexBinaryHash_stats.nlist += nlist; indexBinaryHash_stats.ndis += ndis; } size_t IndexBinaryMultiHash::hashtable_size() const { size_t tot = 0; for (auto map: maps) { tot += map.size(); } return tot; } }
24.888438
84
0.560717
[ "vector" ]
4fa061bb01d95a0c697fd70c20c27db19012d00f
3,207
hpp
C++
third_party/concurrentqueue/tests/relacy/relacy/relacy/thread_local_ctx.hpp
tufeigunchu/orbit
407354cf7c9159ff7e3177c603a6850b95509e3a
[ "BSD-2-Clause" ]
1,847
2020-03-24T19:01:42.000Z
2022-03-31T13:18:57.000Z
third_party/concurrentqueue/tests/relacy/relacy/relacy/thread_local_ctx.hpp
tufeigunchu/orbit
407354cf7c9159ff7e3177c603a6850b95509e3a
[ "BSD-2-Clause" ]
1,100
2020-03-24T19:41:13.000Z
2022-03-31T14:27:09.000Z
third_party/concurrentqueue/tests/relacy/relacy/relacy/thread_local_ctx.hpp
tufeigunchu/orbit
407354cf7c9159ff7e3177c603a6850b95509e3a
[ "BSD-2-Clause" ]
228
2020-03-25T05:32:08.000Z
2022-03-31T11:27:39.000Z
/* Relacy Race Detector * Copyright (c) 2008-2013, Dmitry S. Vyukov * All rights reserved. * This software is provided AS-IS with no warranty, either express or implied. * This software is distributed under a license and may not be copied, * modified or distributed except as expressly authorized under the * terms of the license contained in the file LICENSE in this distribution. */ #ifndef RL_THREAD_LOCAL_CTX_HPP #define RL_THREAD_LOCAL_CTX_HPP #ifdef _MSC_VER # pragma once #endif #include "base.hpp" #include "test_params.hpp" namespace rl { struct thread_local_context_iface { virtual int thread_local_alloc (void (*dtor)(intptr_t)) = 0; virtual void thread_local_free (int index) = 0; virtual void thread_local_set (int index, intptr_t value) = 0; virtual intptr_t thread_local_get (int index) = 0; virtual ~thread_local_context_iface () {} // to calm down g++ }; template<typename base_t, thread_id_t thread_count> class thread_local_contxt_impl : protected base_t { public: thread_local_contxt_impl(thread_id_t thread_count_param, test_params& params) : base_t(thread_count_param, params) { } void iteration_begin() { base_t::iteration_begin(); for (size_t ent = 0; ent != entries_.size(); ent += 1) { for (size_t th = 0; th != thread_count; th += 1) { entries_[ent].value_[th] = 0; } } } private: struct entry { bool alive_; intptr_t value_ [thread_count]; void (*dtor_) (intptr_t); }; typename vector<entry>::type entries_; using base_t::current_thread; virtual int thread_local_alloc (void (*dtor)(intptr_t)) { int index = (int)entries_.size(); entries_.resize(index + 1); entry& ent = entries_[index]; ent.alive_ = true; ent.dtor_ = dtor; for (size_t i = 0; i != thread_count; ++i) { ent.value_[i] = 0; } return index; } virtual void thread_local_free (int index) { RL_VERIFY(index >= 0 && (size_t)index < entries_.size()); entry& ent = entries_[index]; RL_VERIFY(ent.alive_); ent.alive_ = false; if (ent.dtor_) { for (size_t i = 0; i != thread_count; ++i) { if (ent.value_[i]) { ent.dtor_(ent.value_[i]); } } } } virtual void thread_local_set (int index, intptr_t value) { RL_VERIFY(index >= 0 && (size_t)index < entries_.size()); entry& ent = entries_[index]; RL_VERIFY(ent.alive_); ent.value_[current_thread()] = value; } virtual intptr_t thread_local_get (int index) { RL_VERIFY(index >= 0 && (size_t)index < entries_.size()); entry& ent = entries_[index]; RL_VERIFY(ent.alive_); return ent.value_[current_thread()]; } }; } #endif
26.073171
84
0.560025
[ "vector" ]
4fa1bf1e84d71b3a3e6a96dbf65f71480db1b268
20,274
cpp
C++
iree/compiler/Dialect/Util/IR/UtilTypes.cpp
KyleHerndon/iree
916c6f92ee4729da21ab0cf266f086f9a4f3b80b
[ "Apache-2.0" ]
null
null
null
iree/compiler/Dialect/Util/IR/UtilTypes.cpp
KyleHerndon/iree
916c6f92ee4729da21ab0cf266f086f9a4f3b80b
[ "Apache-2.0" ]
null
null
null
iree/compiler/Dialect/Util/IR/UtilTypes.cpp
KyleHerndon/iree
916c6f92ee4729da21ab0cf266f086f9a4f3b80b
[ "Apache-2.0" ]
null
null
null
// Copyright 2020 The IREE Authors // // Licensed under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception #include "iree/compiler/Dialect/Util/IR/UtilTypes.h" #include "iree/compiler/Dialect/Util/IR/UtilDialect.h" #include "llvm/ADT/BitVector.h" #include "mlir/Dialect/StandardOps/IR/Ops.h" #include "mlir/IR/Attributes.h" #include "mlir/IR/Builders.h" #include "mlir/IR/BuiltinTypes.h" #include "mlir/IR/Diagnostics.h" #include "mlir/IR/DialectImplementation.h" #include "mlir/IR/Dominance.h" #include "mlir/IR/OpDefinition.h" #include "mlir/IR/OpImplementation.h" #include "mlir/IR/TypeSupport.h" #include "mlir/Interfaces/CastInterfaces.h" #include "mlir/Parser.h" namespace mlir { namespace iree_compiler { namespace IREE { namespace Util { //===----------------------------------------------------------------------===// // ListType //===----------------------------------------------------------------------===// namespace detail { struct ListTypeStorage : public TypeStorage { ListTypeStorage(Type elementType) : elementType(elementType) {} /// The hash key used for uniquing. using KeyTy = Type; bool operator==(const KeyTy &key) const { return key == elementType; } static ListTypeStorage *construct(TypeStorageAllocator &allocator, const KeyTy &key) { // Initialize the memory using placement new. return new (allocator.allocate<ListTypeStorage>()) ListTypeStorage(key); } Type elementType; }; } // namespace detail // static bool ListType::isCompatible(Type type) { return true; } // static bool ListType::canImplicitlyCast(Type from, Type to) { if (from.isa<VariantType>() || to.isa<VariantType>()) { return true; } else if (from.isa<TensorType>() && to.isa<TensorType>()) { return true; } return from == to; } ListType ListType::get(Type elementType) { return Base::get(elementType.getContext(), elementType); } ListType ListType::getChecked(Type elementType, Location location) { return Base::getChecked(location, elementType); } ListType ListType::getChecked(function_ref<InFlightDiagnostic()> emitError, Type elementType) { return Base::getChecked(emitError, elementType.getContext(), elementType); } Type ListType::getElementType() { return getImpl()->elementType; } //===----------------------------------------------------------------------===// // PtrType //===----------------------------------------------------------------------===// namespace detail { struct PtrTypeStorage : public TypeStorage { PtrTypeStorage(Type targetType) : targetType(targetType) {} /// The hash key used for uniquing. using KeyTy = Type; bool operator==(const KeyTy &key) const { return key == targetType; } static PtrTypeStorage *construct(TypeStorageAllocator &allocator, const KeyTy &key) { // Initialize the memory using placement new. return new (allocator.allocate<PtrTypeStorage>()) PtrTypeStorage(key); } Type targetType; }; } // namespace detail PtrType PtrType::get(Type targetType) { return Base::get(targetType.getContext(), targetType); } PtrType PtrType::getChecked(Type targetType, Location location) { return Base::getChecked(location, targetType); } PtrType PtrType::getChecked(function_ref<InFlightDiagnostic()> emitError, Type targetType) { return Base::getChecked(emitError, targetType.getContext(), targetType); } Type PtrType::getTargetType() const { return getImpl()->targetType; } //===----------------------------------------------------------------------===// // IREE::Util::TiedOpInterface //===----------------------------------------------------------------------===// llvm::Optional<unsigned> detail::getTiedResultOperandIndex( Operation *op, unsigned resultIndex) { auto storageAttr = op->getAttrOfType<ArrayAttr>(TiedOpInterface::getStorageAttrName()); if (!storageAttr) return llvm::None; auto valueAttrs = storageAttr.getValue(); if (valueAttrs.empty()) return llvm::None; auto tiedOp = cast<TiedOpInterface>(op); resultIndex -= tiedOp.getTiedResultsIndexAndLength().first; int64_t value = valueAttrs[resultIndex].cast<IntegerAttr>().getInt(); if (value == TiedOpInterface::kUntiedIndex) return llvm::None; unsigned tiedOperandsOffset = tiedOp.getTiedOperandsIndexAndLength().first; return tiedOperandsOffset + static_cast<unsigned>(value); } void detail::setTiedResultOperandIndex(Operation *op, unsigned resultIndex, llvm::Optional<unsigned> operandIndex) { auto tiedOp = cast<TiedOpInterface>(op); auto resultRange = tiedOp.getTiedResultsIndexAndLength(); resultIndex -= resultRange.first; auto indices = getTiedResultOperandIndices(op); if (indices.empty()) { indices.resize(resultRange.second, TiedOpInterface::kUntiedIndex); } else { // Well, getTiedResultOperandIndices() returns indices into the full range // of the op, but in the attribute, we expect to store ranges into the range // returned by `getTiedOperandsIndexAndLength`. unsigned tiedOperandsOffset = tiedOp.getTiedOperandsIndexAndLength().first; for (auto &index : indices) { if (index != TiedOpInterface::kUntiedIndex) index -= tiedOperandsOffset; } } indices[resultIndex] = operandIndex.hasValue() ? operandIndex.getValue() : TiedOpInterface::kUntiedIndex; op->setAttr(TiedOpInterface::getStorageAttrName(), Builder(op).getIndexArrayAttr(indices)); } SmallVector<int64_t, 4> detail::getTiedResultOperandIndices(Operation *op) { SmallVector<int64_t, 4> indices; auto storageAttr = op->getAttrOfType<ArrayAttr>(TiedOpInterface::getStorageAttrName()); if (!storageAttr) return indices; auto valueAttrs = storageAttr.getValue(); if (valueAttrs.empty()) return indices; auto tiedOp = cast<TiedOpInterface>(op); auto resultRange = tiedOp.getTiedResultsIndexAndLength(); unsigned tiedOperandsOffset = tiedOp.getTiedOperandsIndexAndLength().first; indices.resize(resultRange.second); for (unsigned i = 0; i < valueAttrs.size(); ++i) { int64_t index = valueAttrs[i].cast<IntegerAttr>().getInt(); indices[i] = index != TiedOpInterface::kUntiedIndex ? tiedOperandsOffset + index : TiedOpInterface::kUntiedIndex; } return indices; } // static Value TiedOpInterface::findTiedBaseValue(Value derivedValue) { Value baseValue = derivedValue; while (auto definingOp = dyn_cast_or_null<TiedOpInterface>(baseValue.getDefiningOp())) { auto tiedValue = definingOp.getTiedResultOperand(baseValue); if (!tiedValue) break; baseValue = tiedValue; } return baseValue; } // static bool TiedOpInterface::hasAnyTiedUses(Value value) { for (auto &use : value.getUses()) { auto tiedOp = dyn_cast<IREE::Util::TiedOpInterface>(use.getOwner()); if (!tiedOp) continue; if (tiedOp.isOperandTied(use.getOperandNumber())) return true; } return false; } bool detail::isOperandTied(Operation *op, unsigned operandIndex) { auto tiedOp = dyn_cast<TiedOpInterface>(op); if (!tiedOp) return false; auto tiedIndices = tiedOp.getTiedResultOperandIndices(); for (unsigned i = 0; i < tiedIndices.size(); ++i) { if (tiedIndices[i] == operandIndex) { return true; } } return false; } SmallVector<Value> detail::getOperandTiedResults(Operation *op, unsigned operandIndex) { auto tiedOp = dyn_cast<TiedOpInterface>(op); if (!tiedOp) return {}; auto resultRange = tiedOp.getTiedResultsIndexAndLength(); SmallVector<Value> results; auto tiedIndices = tiedOp.getTiedResultOperandIndices(); for (unsigned i = 0; i < tiedIndices.size(); ++i) { if (tiedIndices[i] == operandIndex) { results.push_back(op->getResult(resultRange.first + i)); } } return results; } LogicalResult detail::verifyTiedOp(TiedOpInterface tiedOp) { auto tiedOperandIndices = tiedOp.getTiedResultOperandIndices(); if (tiedOperandIndices.empty()) return success(); auto resultRange = tiedOp.getTiedResultsIndexAndLength(); if (tiedOperandIndices.size() != resultRange.second) { return tiedOp.emitError("op results/tied operand indices mismatch"); } return success(); } void excludeTiedOperandAndResultIndices( ArrayRef<unsigned> excludedOperandIndices, ArrayRef<unsigned> excludedResultIndices, SmallVector<int64_t, 4> &tiedOperandIndices) { SmallVector<int64_t, 4> oldTiedOperandIndices = tiedOperandIndices; tiedOperandIndices.clear(); // To adjust operand indices we need to know the how many operands to offset // the indices by - if 2 operands before operand N were removed then we know // it needs to be -2. This is nasty but that's why we have this helper // function. unsigned numBits = 1; if (!excludedOperandIndices.empty()) { numBits += *std::max_element(excludedOperandIndices.begin(), excludedOperandIndices.end()); } llvm::BitVector excludedOperands(numBits, false); for (unsigned i = 0; i < excludedOperandIndices.size(); ++i) { excludedOperands[excludedOperandIndices[i]] = true; } for (auto it : llvm::enumerate(oldTiedOperandIndices)) { unsigned resultIndex = it.index(); if (llvm::is_contained(excludedResultIndices, resultIndex)) { continue; // result removed } int64_t tiedOperandIndex = it.value(); if (tiedOperandIndex != TiedOpInterface::kUntiedIndex) { // Check whether this operand is removed. If so, untie. We need to do this // before calculating the new operand index given `excludedOperandIndices` // contains the old indices. if (llvm::is_contained(excludedOperandIndices, tiedOperandIndex)) { tiedOperandIndex = TiedOpInterface::kUntiedIndex; } // Count up the number of removed operands prior to this one. unsigned offset = 0; for (unsigned i = 0; i < tiedOperandIndex; ++i) { if (i < excludedOperands.size() && excludedOperands[i]) ++offset; } tiedOperandIndex -= offset; } tiedOperandIndices.push_back(tiedOperandIndex); } } //===----------------------------------------------------------------------===// // IREE::Util::SizeAwareTypeInterface //===----------------------------------------------------------------------===// static bool isValueUsableForOp(Value value, Block *block, Block::iterator insertionPoint) { if (block == nullptr) { // Op is not in a block; can't analyze (maybe?). return false; } auto *definingBlock = value.getParentBlock(); if (definingBlock == block) { // Defined in the same block; ensure block order. if (value.isa<BlockArgument>()) return true; if (insertionPoint == block->end()) return true; if (value.getDefiningOp()->isBeforeInBlock(&*insertionPoint)) { return true; } } else if (definingBlock->isEntryBlock()) { // Entry block always dominates - fast path for constants. return true; } else { // See if block the value is defined in dominates the forOp block. // TODO(benvanik): optimize this, it's terribly expensive to recompute. DominanceInfo dominanceInfo(block->getParentOp()); return dominanceInfo.dominates(definingBlock, block); } return false; } // static Value SizeAwareTypeInterface::findSizeValue(Value resourceValue, Block *block, Block::iterator insertionPoint) { // See if the value is produced by a size-aware op; we can just ask for the // size it has tied. Walking upward is always good as we know any size we find // dominates {|block|, |insertionPoint|}. SmallVector<Value> worklist; worklist.push_back(resourceValue); while (!worklist.empty()) { auto value = worklist.pop_back_val(); auto *definingOp = value.getDefiningOp(); if (!definingOp) continue; if (auto sizeAwareOp = llvm::dyn_cast<IREE::Util::SizeAwareOpInterface>(definingOp)) { return sizeAwareOp.getResultSizeFromValue(value); } if (auto tiedOp = llvm::dyn_cast<IREE::Util::TiedOpInterface>(definingOp)) { auto tiedOperand = tiedOp.getTiedResultOperand(value); if (tiedOperand) worklist.push_back(tiedOperand); } } // Walk the users to see if any can report the size. worklist.push_back(resourceValue); while (!worklist.empty()) { auto value = worklist.pop_back_val(); for (auto &use : value.getUses()) { if (auto sizeAwareOp = llvm::dyn_cast<IREE::Util::SizeAwareOpInterface>( use.getOwner())) { auto sizeValue = sizeAwareOp.getOperandSize(use.getOperandNumber()); if (sizeValue) { if (isValueUsableForOp(sizeValue, block, insertionPoint)) return sizeValue; } } if (auto tiedOp = llvm::dyn_cast<IREE::Util::TiedOpInterface>(use.getOwner())) { worklist.append(tiedOp.getOperandTiedResults(use.getOperandNumber())); } } } return {}; } // static Value SizeAwareTypeInterface::queryValueSize(Location loc, Value resourceValue, OpBuilder &builder) { auto sizeAwareType = resourceValue.getType().dyn_cast<IREE::Util::SizeAwareTypeInterface>(); if (!sizeAwareType) { return {}; // Not a sized type. } if (!builder.getInsertionPoint().getNodePtr()->isKnownSentinel()) { auto sizeValue = sizeAwareType.findSizeValue( resourceValue, builder.getBlock(), builder.getInsertionPoint()); if (sizeValue) { return sizeValue; // Found in IR. } } // TODO(benvanik): make this cleaner. auto *definingOp = resourceValue.getDefiningOp(); if (auto sizeAwareOp = llvm::dyn_cast_or_null<IREE::Util::SizeAwareOpInterface>( definingOp)) { return sizeAwareOp.getResultSizeFromValue(resourceValue); } else if (auto inferSizeType = resourceValue.getType() .dyn_cast<IREE::Util::InferTypeSizeInterface>()) { return inferSizeType.inferSizeFromValue(loc, resourceValue, builder); } return {}; } //===----------------------------------------------------------------------===// // IREE::Util::ShapeAware* //===----------------------------------------------------------------------===// ValueRange findVariadicDynamicDims(unsigned idx, ValueRange values, ValueRange dynamicDims) { auto value = values[idx]; auto shapedType = value.getType().dyn_cast<ShapedType>(); if (!shapedType) return ValueRange{}; // Bail immediately if the shape is static. if (shapedType.hasStaticShape()) return ValueRange{}; // Find where the dynamic dims start in the flattened list. unsigned offset = 0; for (unsigned i = 0; i < idx; ++i) { if (auto type = values[i].getType().dyn_cast<ShapedType>()) { offset += type.getNumDynamicDims(); } } // Return the subrange of dynamic dims for the value being queried. return dynamicDims.slice(offset, shapedType.getNumDynamicDims()); } Optional<ValueRange> findDynamicDims(Value shapedValue, Block *block, Block::iterator insertionPoint) { // Look up the use-def chain: always safe, as any value we reach dominates // {|block|, |insertionPoint|} implicitly. SmallVector<Value> worklist; worklist.push_back(shapedValue); while (!worklist.empty()) { auto workValue = worklist.pop_back_val(); if (auto shapeAwareOp = dyn_cast_or_null<ShapeAwareOpInterface>( workValue.getDefiningOp())) { return shapeAwareOp.getResultDynamicDimsFromValue(workValue); } if (auto tiedOp = dyn_cast_or_null<TiedOpInterface>(workValue.getDefiningOp())) { auto tiedValue = tiedOp.getTiedResultOperand(workValue); if (tiedValue) worklist.push_back(tiedValue); } } // Look down the use-def chain: not safe at some point because we'll move past // where {|block|, |insertionPoint|} is dominated. This is often fine for a // bit, though, as {|block|, |insertionPoint|} may be a user of |shapedValue| // and be able to provide the shape itself. for (auto &use : shapedValue.getUses()) { if (auto shapeAwareOp = dyn_cast<ShapeAwareOpInterface>(use.getOwner())) { auto dynamicDims = shapeAwareOp.getOperandDynamicDims(use.getOperandNumber()); if (llvm::all_of(dynamicDims, [&](Value dim) { return isValueUsableForOp(dim, block, insertionPoint); })) { return dynamicDims; } } } return None; } //===----------------------------------------------------------------------===// // IREE::Util::UtilDialect //===----------------------------------------------------------------------===// // At the end so it can use functions above: #include "iree/compiler/Dialect/Util/IR/UtilOpInterfaces.cpp.inc" #include "iree/compiler/Dialect/Util/IR/UtilTypeInterfaces.cpp.inc" void UtilDialect::registerTypes() { addTypes<IREE::Util::ByteBufferType, IREE::Util::ListType, IREE::Util::MutableByteBufferType, IREE::Util::PtrType, IREE::Util::VariantType>(); } //===----------------------------------------------------------------------===// // Type printing and parsing //===----------------------------------------------------------------------===// Type UtilDialect::parseType(DialectAsmParser &parser) const { Location loc = parser.getEncodedSourceLoc(parser.getNameLoc()); llvm::StringRef spec = parser.getFullSymbolSpec(); if (spec == "variant") { return IREE::Util::VariantType::get(getContext()); } else if (spec.consume_front("ptr")) { if (!spec.consume_front("<") || !spec.consume_back(">")) { parser.emitError(parser.getCurrentLocation()) << "malformed ptr type '" << parser.getFullSymbolSpec() << "'"; return Type(); } auto variableType = mlir::parseType(spec, getContext()); if (!variableType) { parser.emitError(parser.getCurrentLocation()) << "invalid ptr object type specification: '" << parser.getFullSymbolSpec() << "'"; return Type(); } return IREE::Util::PtrType::getChecked(variableType, loc); } else if (spec == "byte_buffer") { return IREE::Util::ByteBufferType::get(getContext()); } else if (spec == "mutable_byte_buffer") { return IREE::Util::MutableByteBufferType::get(getContext()); } else if (spec.consume_front("list")) { if (!spec.consume_front("<") || !spec.consume_back(">")) { parser.emitError(parser.getCurrentLocation()) << "malformed list type '" << parser.getFullSymbolSpec() << "'"; return Type(); } Type elementType; if (spec == "?") { elementType = IREE::Util::VariantType::get(getContext()); } else { elementType = mlir::parseType(spec, getContext()); } if (!elementType) { parser.emitError(parser.getCurrentLocation()) << "invalid list element type specification: '" << parser.getFullSymbolSpec() << "'"; return Type(); } return IREE::Util::ListType::getChecked(elementType, loc); } emitError(loc, "unknown IREE type: ") << spec; return Type(); } void UtilDialect::printType(Type type, DialectAsmPrinter &os) const { if (type.isa<IREE::Util::VariantType>()) { os << "variant"; } else if (auto ptrType = type.dyn_cast<IREE::Util::PtrType>()) { os << "ptr<" << ptrType.getTargetType() << ">"; } else if (type.isa<IREE::Util::ByteBufferType>()) { os << "byte_buffer"; } else if (type.isa<IREE::Util::MutableByteBufferType>()) { os << "mutable_byte_buffer"; } else if (auto listType = type.dyn_cast<IREE::Util::ListType>()) { os << "list<"; if (listType.getElementType().isa<IREE::Util::VariantType>()) { os << "?"; } else { os << listType.getElementType(); } os << ">"; } else { llvm_unreachable("unhandled IREE type"); } } } // namespace Util } // namespace IREE } // namespace iree_compiler } // namespace mlir
36.861818
80
0.640673
[ "object", "shape" ]
4fa2eb6c6ec700ba17b1d5e8b457e63d761b79a3
2,454
cxx
C++
Modules/Core/SpatialObjects/src/itkArrowSpatialObject.cxx
nalinimsingh/ITK_4D
95a2eacaeaffe572889832ef0894239f89e3f303
[ "Apache-2.0" ]
3
2018-10-01T20:46:17.000Z
2019-12-17T19:39:50.000Z
Modules/Core/SpatialObjects/src/itkArrowSpatialObject.cxx
nalinimsingh/ITK_4D
95a2eacaeaffe572889832ef0894239f89e3f303
[ "Apache-2.0" ]
null
null
null
Modules/Core/SpatialObjects/src/itkArrowSpatialObject.cxx
nalinimsingh/ITK_4D
95a2eacaeaffe572889832ef0894239f89e3f303
[ "Apache-2.0" ]
4
2018-05-17T16:34:54.000Z
2020-09-24T02:12:40.000Z
/*========================================================================= * * Copyright Insight Software Consortium * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0.txt * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * *=========================================================================*/ #include "itkArrowSpatialObject.h" namespace itk { // This is the 3D implementation of the ArrowSpatialObject. /** Update the local transform from the position and the direction */ // Parial specialization for TDimension = 3 template< > void ArrowSpatialObject< 3 > ::UpdateTransform() { VectorType offset; for ( unsigned int i = 0; i < 3; i++ ) { offset[i] = m_Position[i]; } this->GetObjectToParentTransform()->SetOffset(offset); // If the given direction is not normalized we set the length of the vector // as the length of the arrow m_Length = m_Direction.GetSquaredNorm(); if ( m_Length != 0.0 ) { m_Length = std::sqrt(m_Length); } else { this->Modified(); return; } m_Direction.Normalize(); double anglez = 0; if ( m_Direction[0] == 0.0 ) { if ( m_Direction[1] > 0.0 ) { anglez = itk::Math::pi / 2; } else if ( m_Direction[1] < 0.0 ) { anglez = -itk::Math::pi / 2; } //NOTE: else if m_Direction[1] == 0, anglez = 0; } else { if ( m_Direction[0] < 0.0 ) { anglez = itk::Math::pi + std::atan(m_Direction[1] / m_Direction[0]); } else { anglez = std::atan(m_Direction[1] / m_Direction[0]); } } const double angley = -asin(m_Direction[2]); typedef itk::Euler3DTransform< double > EulerTransformType; EulerTransformType::Pointer euler = EulerTransformType::New(); euler->SetRotation(0, angley, anglez); this->GetObjectToParentTransform()->SetMatrix( euler->GetMatrix() ); this->Modified(); } }
27.266667
78
0.580685
[ "vector", "transform", "3d" ]
4fa437c2e6d4e77f551b2bdeda426cc188fe03a8
43,362
cc
C++
filesystems/grabfs/windowfs.cc
bispawel/macfuse
9f5773372ec7e9a8ab35c865eda7180a95edcdab
[ "AML" ]
7
2017-11-25T18:56:43.000Z
2020-10-22T21:17:33.000Z
filesystems/grabfs/windowfs.cc
bispawel/macfuse
9f5773372ec7e9a8ab35c865eda7180a95edcdab
[ "AML" ]
null
null
null
filesystems/grabfs/windowfs.cc
bispawel/macfuse
9f5773372ec7e9a8ab35c865eda7180a95edcdab
[ "AML" ]
1
2022-02-12T11:31:50.000Z
2022-02-12T11:31:50.000Z
/* * windowfs as a MacFUSE file system for Mac OS X * * Copyright Amit Singh. All Rights Reserved. * http://osxbook.com * */ #define MACFUSE_WINDOWFS_VERSION "1.0" #define FUSE_USE_VERSION 26 __attribute__((used)) static const char* copyright = "(C) Amit Singh <osxbook.com>, 2007-2008. All Rights Reserved."; #include <dirent.h> #include <errno.h> #include <fcntl.h> #include <getopt.h> #include <pthread.h> #include <stdio.h> #include <string.h> #include <sys/sysctl.h> #include <grp.h> #include <pwd.h> #include <mach/mach.h> #include <mach/mach_vm.h> #include <mach/vm_region.h> #include <mach/vm_statistics.h> #include <Carbon/Carbon.h> #include <CoreFoundation/CoreFoundation.h> #include <IOKit/IOKitLib.h> #include <cassert> #include <vector> #include <pcrecpp.h> #include <fuse.h> #include "GetPID.h" #include "windowfs_windows.h" static int total_file_patterns = 0; static int total_directory_patterns = 0; static int total_link_patterns = 0; #define WINDOWFS_NAME "GrabFS" #define WINDOWFS_MNTPOINT "/Volumes/" WINDOWFS_NAME #define WINDOWFS_ROOTDIR_PATTERN ".+ \\((\\d+)\\)" static pcrecpp::RE *valid_process_pattern = new pcrecpp::RE(WINDOWFS_ROOTDIR_PATTERN); struct windowfs_dispatcher_entry; typedef struct windowfs_dispatcher_entry * windowfs_dispatcher_entry_t; typedef int (*windowfs_open_handler_t)(windowfs_dispatcher_entry_t e, const char *argv[], const char *path, struct fuse_file_info *fi); typedef int (*windowfs_release_handler_t)(windowfs_dispatcher_entry_t e, const char *argv[], const char *path, struct fuse_file_info *fi); typedef int (*windowfs_opendir_handler_t)(windowfs_dispatcher_entry_t e, const char *argv[], const char *path, struct fuse_file_info *fi); typedef int (*windowfs_releasedir_handler_t)(windowfs_dispatcher_entry_t e, const char *argv[], const char *path, struct fuse_file_info *fi); typedef int (*windowfs_getattr_handler_t)(windowfs_dispatcher_entry_t e, const char *argv[], struct stat *stbuf); typedef int (*windowfs_read_handler_t)(windowfs_dispatcher_entry_t e, const char *argv[], char *buf, size_t size, off_t offset, struct fuse_file_info *fi); typedef int (*windowfs_readdir_handler_t)(windowfs_dispatcher_entry_t e, const char *argv[], void *buf, fuse_fill_dir_t filler, off_t offset, struct fuse_file_info *fi); typedef int (*windowfs_readlink_handler_t)(windowfs_dispatcher_entry_t e, const char *argv[], char *buf, size_t size); typedef struct windowfs_dispatcher_entry { int flag; char *pattern; pcrecpp::RE *compiled_pattern; int argc; windowfs_open_handler_t open; windowfs_release_handler_t release; windowfs_opendir_handler_t opendir; windowfs_releasedir_handler_t releasedir; windowfs_getattr_handler_t getattr; windowfs_read_handler_t read; windowfs_readdir_handler_t readdir; windowfs_readlink_handler_t readlink; const char *content_files[32]; const char *content_directories[32]; }; #define WINDOWFS_MAX_ARGS 3 #define OPEN_HANDLER(handler) \ int \ windowfs_open_##handler(windowfs_dispatcher_entry_t e, \ const char *argv[], \ const char *path, \ struct fuse_file_info *fi) \ #define RELEASE_HANDLER(handler) \ int \ windowfs_release_##handler(windowfs_dispatcher_entry_t e, \ const char *argv[], \ const char *path, \ struct fuse_file_info *fi) \ #define OPENDIR_HANDLER(handler) \ int \ windowfs_opendir_##handler(windowfs_dispatcher_entry_t e, \ const char *argv[], \ const char *path, \ struct fuse_file_info *fi) \ #define RELEASEDIR_HANDLER(handler) \ int \ windowfs_releasedir_##handler(windowfs_dispatcher_entry_t e, \ const char *argv[], \ const char *path, \ struct fuse_file_info *fi) \ #define GETATTR_HANDLER(handler) \ int \ windowfs_getattr_##handler(windowfs_dispatcher_entry_t e, \ const char *argv[], \ struct stat *stbuf) \ #define READ_HANDLER(handler) \ int \ windowfs_read_##handler(windowfs_dispatcher_entry_t e, \ const char *argv[], \ char *buf, \ size_t size, \ off_t offset, \ struct fuse_file_info *fi) \ #define READDIR_HANDLER(handler) \ int \ windowfs_readdir_##handler(windowfs_dispatcher_entry_t e, \ const char *argv[], \ void *buf, \ fuse_fill_dir_t filler, \ off_t offset, \ struct fuse_file_info *fi) \ #define READLINK_HANDLER(handler) \ int \ windowfs_readlink_##handler(windowfs_dispatcher_entry_t e, \ const char *argv[], \ char *buf, \ size_t size) \ #define PROTO_OPEN_HANDLER(handler) OPEN_HANDLER(handler) #define PROTO_RELEASE_HANDLER(handler) RELEASE_HANDLER(handler) #define PROTO_OPENDIR_HANDLER(handler) OPENDIR_HANDLER(handler) #define PROTO_RELEASEDIR_HANDLER(handler) RELEASEDIR_HANDLER(handler) #define PROTO_READ_HANDLER(handler) READ_HANDLER(handler) #define PROTO_READDIR_HANDLER(handler) READDIR_HANDLER(handler) #define PROTO_READLINK_HANDLER(handler) READLINK_HANDLER(handler) #define PROTO_GETATTR_HANDLER(handler) GETATTR_HANDLER(handler) #define DECL_FILE(pattern, argc, openp, releasep, getattrp, readp) \ { \ 0, \ pattern, \ new pcrecpp::RE(pattern), \ argc, \ windowfs_open_##openp, \ windowfs_release_##releasep, \ windowfs_opendir_enotdir, \ windowfs_releasedir_enotdir, \ windowfs_getattr_##getattrp, \ windowfs_read_##readp, \ windowfs_readdir_enotdir, \ windowfs_readlink_einval, \ { NULL }, \ { NULL } \ }, #define DECL_FILE_WITHFLAGS(flag, pattern, argc, openp, releasep, getattrp, readp) \ { \ flag, \ pattern, \ new pcrecpp::RE(pattern), \ argc, \ windowfs_open_##openp, \ windowfs_release_##releasep, \ windowfs_opendir_enotdir, \ windowfs_releasedir_enotdir, \ windowfs_getattr_##getattrp, \ windowfs_read_##readp, \ windowfs_readdir_enotdir, \ windowfs_readlink_einval, \ { NULL }, \ { NULL } \ }, #define DECL_DIRECTORY(pattern, argc, opendirp, releasedirp, getattrp, readdirp, contents, ...) \ { \ 0, \ pattern, \ new pcrecpp::RE(pattern), \ argc, \ windowfs_open_eisdir, \ windowfs_release_eisdir, \ windowfs_opendir_##opendirp, \ windowfs_releasedir_##releasedirp, \ windowfs_getattr_##getattrp, \ windowfs_read_eisdir, \ windowfs_readdir_##readdirp, \ windowfs_readlink_einval, \ contents, \ __VA_ARGS__ \ }, #define DECL_DIRECTORY_COMPACT(pattern, contents, ...) \ { \ 0, \ pattern, \ new pcrecpp::RE(pattern), \ 0, \ windowfs_open_eisdir, \ windowfs_release_eisdir, \ windowfs_opendir_default_directory, \ windowfs_releasedir_default_directory, \ windowfs_getattr_default_directory, \ windowfs_read_eisdir, \ windowfs_readdir_default, \ windowfs_readlink_einval, \ contents, \ ##__VA_ARGS__ \ }, #define DECL_LINK(pattern, argc, openp, releasep, getattrp, readlinkp) \ { \ 0, \ pattern, \ new pcrecpp::RE(pattern), \ argc, \ windowfs_open_##openp, \ windowfs_release_##releasep, \ windowfs_opendir_enotdir, \ windowfs_releasedir_enotdir, \ windowfs_getattr_##getattrp, \ windowfs_read_einval, \ windowfs_readdir_enotdir, \ windowfs_readlink_##readlinkp, \ { NULL }, \ { NULL } \ }, #define DECL_LINK_COMPACT(pattern, argc, readlinkp) \ { \ 0, \ pattern, \ new pcrecpp::RE(pattern), \ argc, \ windowfs_open_default_file, \ windowfs_release_default_file, \ windowfs_opendir_enotdir, \ windowfs_releasedir_enotdir, \ windowfs_getattr_default_link, \ windowfs_read_einval, \ windowfs_readdir_enotdir, \ windowfs_readlink_##readlinkp, \ { NULL }, \ { NULL } \ }, PROTO_OPEN_HANDLER(default_file); PROTO_OPEN_HANDLER(eisdir); PROTO_OPEN_HANDLER(proc__window); PROTO_RELEASE_HANDLER(default_file); PROTO_RELEASE_HANDLER(eisdir); PROTO_RELEASE_HANDLER(proc__window); PROTO_OPENDIR_HANDLER(default_directory); PROTO_OPENDIR_HANDLER(enotdir); PROTO_RELEASEDIR_HANDLER(default_directory); PROTO_RELEASEDIR_HANDLER(enotdir); PROTO_GETATTR_HANDLER(default_file); PROTO_GETATTR_HANDLER(default_directory); PROTO_GETATTR_HANDLER(default_link); PROTO_GETATTR_HANDLER(proc); PROTO_GETATTR_HANDLER(proc__window); PROTO_READ_HANDLER(einval); PROTO_READ_HANDLER(eisdir); PROTO_READ_HANDLER(zero); PROTO_READ_HANDLER(proc__window); PROTO_READDIR_HANDLER(default); PROTO_READDIR_HANDLER(enotdir); PROTO_READDIR_HANDLER(root); PROTO_READDIR_HANDLER(proc); PROTO_READLINK_HANDLER(einval); static struct windowfs_dispatcher_entry windowfs_link_table[] = { }; static struct windowfs_dispatcher_entry windowfs_file_table[] = { DECL_FILE( WINDOWFS_ROOTDIR_PATTERN "/([a-f\\d]+).tiff", 2, proc__window, proc__window, proc__window, proc__window ) DECL_FILE( "/\\.metadata_never_index", 0, default_file, default_file, default_file, zero ) }; static struct windowfs_dispatcher_entry windowfs_directory_table[] = { DECL_DIRECTORY( "/", 0, default_directory, default_directory, default_directory, root, { ".metadata_never_index", NULL }, { NULL }, ) DECL_DIRECTORY( //"/(\\d+) \\(.+\\)", WINDOWFS_ROOTDIR_PATTERN, 1, default_directory, default_directory, proc, proc, { NULL }, { NULL }, ) }; // BEGIN: OPEN/OPENDIR // // int // windowfs_open/opendir_<handler>(windowfs_dispatcher_entry_t e, // const char *argv[], // const char *path, // struct fuse_file_info *fi) OPEN_HANDLER(default_file) { return 0; } OPEN_HANDLER(eisdir) { return -EISDIR; } OPEN_HANDLER(proc__window) { if (fi->fh != 0) { /* XXX: need locking */ return 0; } pid_t pid = strtol(argv[0], NULL, 10); CGWindowID target = strtol(argv[1], NULL, 16); WindowListData data = { 0, 0, { 0 } }; data.pid = pid; int ret = WINDOWFS_GetWindowList(&data); if (ret <= 0) { return -ENOENT; } int i = 0; for (i = 0; i < data.windowCount; i++) { if (data.windowIDs[i] == target) { goto doread; } } return -ENOENT; doread: CFMutableDataRef window_tiff = (CFMutableDataRef)0; ret = WINDOWFS_GetTIFFForWindowAtIndex(target, &window_tiff); if (ret == -1) { return -EIO; } struct WINDOWFSWindowData *pwd = (struct WINDOWFSWindowData *)malloc(sizeof(struct WINDOWFSWindowData)); if (!pwd) { CFRelease(window_tiff); } pwd->window_tiff = window_tiff; pwd->max_len = WINDOWFS_GetTIFFSizeForWindowAtIndex(target); pwd->len = (size_t)CFDataGetLength(window_tiff); fi->fh = (uint64_t)pwd; return 0; } OPENDIR_HANDLER(default_directory) { return 0; } OPENDIR_HANDLER(enotdir) { return -ENOTDIR; } // END: OPEN/OPENDIR // BEGIN: RELEASE/RELEASEDIR // // int // windowfs_release/releasedir_<handler>(windowfs_dispatcher_entry_t e, // const char *argv[], // const char *path, // struct fuse_file_info *fi) RELEASE_HANDLER(default_file) { return 0; } RELEASE_HANDLER(eisdir) { return -EISDIR; } RELEASE_HANDLER(proc__window) { if (fi->fh) { struct WINDOWFSWindowData *pwd = (struct WINDOWFSWindowData *)(fi->fh); CFRelease((CFMutableDataRef)(pwd->window_tiff)); free((void *)pwd); fi->fh = 0; } return 0; } RELEASEDIR_HANDLER(default_directory) { return 0; } RELEASEDIR_HANDLER(enotdir) { return -ENOTDIR; } // END: RELEASE/RELEASEDIR // BEGIN: GETATTR // // int // windowfs_getattr_<handler>(windowfs_dispatcher_entry_t e, // const char *argv[], // struct stat *stbuf) GETATTR_HANDLER(default_file) { time_t current_time = time(NULL); stbuf->st_mode = S_IFREG | 0444; stbuf->st_nlink = 1; stbuf->st_size = 0; stbuf->st_atime = stbuf->st_ctime = stbuf->st_mtime = current_time; return 0; } GETATTR_HANDLER(default_directory) { time_t current_time = time(NULL); stbuf->st_mode = S_IFDIR | 0755; stbuf->st_nlink = 1; stbuf->st_size = 0; stbuf->st_atime = stbuf->st_ctime = stbuf->st_mtime = current_time; return 0; } GETATTR_HANDLER(default_link) { stbuf->st_mode = S_IFLNK | 0755; stbuf->st_nlink = 1; stbuf->st_size = 0; return 0; } GETATTR_HANDLER(proc) { pid_t pid = strtol(argv[0], NULL, 10); if (pid == getpid()) { return -ENOENT; } time_t current_time = time(NULL); stbuf->st_mode = S_IFDIR | 0755; stbuf->st_nlink = 1; stbuf->st_size = 0; stbuf->st_atime = stbuf->st_ctime = stbuf->st_mtime = current_time; return 0; } GETATTR_HANDLER(proc__window) { pid_t pid = strtol(argv[0], NULL, 10); CGWindowID target = strtol(argv[1], NULL, 16); WindowListData data = { 0, 0, { 0 } }; data.pid = pid; int ret = WINDOWFS_GetWindowList(&data); if (ret <= 0) { return -ENOENT; } int i = 0; for (i = 0; i < data.windowCount; i++) { if (data.windowIDs[i] == target) { time_t current_time = time(NULL); stbuf->st_mode = S_IFREG | 0644; stbuf->st_nlink = 1; stbuf->st_atime = stbuf->st_ctime = stbuf->st_mtime = current_time; stbuf->st_size = WINDOWFS_GetTIFFSizeForWindowAtIndex(data.windowIDs[i]); return 0; } } return -ENOENT; } // END: GETATTR // BEGIN: READ // int // windowfs_read_<handler>(windowfs_dispatcher_entry_t e, // const char *argv[], // void *buf, // size_t size, // off_t offset, // struct fuse_file_info *fi) READ_HANDLER(einval) { return -EINVAL; } READ_HANDLER(eisdir) { return -EISDIR; } READ_HANDLER(zero) { return 0; } READ_HANDLER(proc__window) { if (fi->fh == 0) { return 0; } struct WINDOWFSWindowData *pwd = (struct WINDOWFSWindowData *)fi->fh; CFMutableDataRef window_tiff = pwd->window_tiff; size_t max_len = pwd->max_len; size_t len = pwd->len; if (len > max_len) { return -EIO; } CFDataSetLength(window_tiff, max_len); len = max_len; const UInt8 *tmpbuf = CFDataGetBytePtr(window_tiff); if (len < 0) { return -EIO; } if (offset < len) { if (offset + size > len) size = len - offset; memcpy(buf, tmpbuf + offset, size); } else size = 0; return size; } // END: READ // BEGIN: READDIR // int // windowfs_readdir_<handler>(windowfs_dispatcher_entry_t *e, // const char *argv[], // void *buf, // fuse_fill_dir_t filler, // off_t offset, // struct fuse_file_info *fi) int windowfs_populate_directory(const char **content_files, const char **content_directories, void *buf, fuse_fill_dir_t filler, off_t offset, struct fuse_file_info *fi) { int bufferfull = 0; struct stat dir_stat; struct stat file_stat; const char **name; memset(&dir_stat, 0, sizeof(dir_stat)); dir_stat.st_mode = S_IFDIR | 0755; dir_stat.st_size = 0; memset(&file_stat, 0, sizeof(file_stat)); dir_stat.st_mode = S_IFREG | 0644; dir_stat.st_size = 0; if (filler(buf, ".", NULL, 0)) { bufferfull = 1; goto out; } if (filler(buf, "..", NULL, 0)) { bufferfull = 1; goto out; } if (!content_files && !content_directories) { goto out; } name = content_directories; if (name) { for (; *name; name++) { if (filler(buf, *name, &dir_stat, 0)) { bufferfull = 1; goto out; } } } name = content_files; if (name) { for (; *name; name++) { if (filler(buf, *name, &file_stat, 0)) { bufferfull = 1; goto out; } } } out: return bufferfull; } READDIR_HANDLER(default) { return 0; } READDIR_HANDLER(enotdir) { return -ENOTDIR; } READDIR_HANDLER(proc) { int i; pid_t pid = strtol(argv[0], NULL, 10); struct stat dir_stat; char the_name[MAXNAMLEN + 1]; memset(&dir_stat, 0, sizeof(dir_stat)); dir_stat.st_mode = S_IFDIR | 0755; dir_stat.st_size = 0; WindowListData data = { 0, 0, { 0 } }; data.pid = pid; int ret = WINDOWFS_GetWindowList(&data); if (ret < 0) { return -EIO; } if (data.windowCount == 0) { return 0; } for (i = 0; i < data.windowCount; i++) { snprintf(the_name, MAXNAMLEN, "%x.tiff", data.windowIDs[i]); dir_stat.st_mode = S_IFREG | 0644; dir_stat.st_size = WINDOWFS_GetTIFFSizeForWindowAtIndex(data.windowIDs[i]); if (filler(buf, the_name, &dir_stat, 0)) { break; } } return 0; } READDIR_HANDLER(root) { char the_name_app[MAXNAMLEN + 1]; char the_name[MAXNAMLEN + 1]; Boolean strstatus = false; struct stat the_stat; ProcessSerialNumber psn; OSErr osErr = noErr; OSStatus status; CFStringRef Pname; pid_t Pid; psn.highLongOfPSN = kNoProcess; psn.lowLongOfPSN = kNoProcess; memset(&the_stat, 0, sizeof(the_stat)); while ((osErr = GetNextProcess(&psn)) != procNotFound) { status = GetProcessPID(&psn, &Pid); if (status != noErr) { continue; } if (Pid == getpid()) { continue; } Pname = (CFStringRef)0; status = CopyProcessName(&psn, &Pname); if (status != noErr) { if (Pname) { CFRelease(Pname); Pname = (CFStringRef)0; } continue; } the_stat.st_mode = S_IFDIR | 0755; the_stat.st_nlink = 1; the_stat.st_size = 0; strstatus = CFStringGetCString(Pname, the_name_app, MAXNAMLEN, kCFStringEncodingASCII); if (strstatus == false) { CFRelease(Pname); Pname = (CFStringRef)0; continue; } snprintf(the_name, MAXNAMLEN, "%s (%d)", the_name_app, Pid); if (filler(buf, the_name, &the_stat, 0)) { CFRelease(Pname); break; } CFRelease(Pname); } Pid = GetPIDForProcessName("WindowServer"); if (Pid != -1) { the_stat.st_mode = S_IFDIR | 0755; the_stat.st_nlink = 1; the_stat.st_size = 0; snprintf(the_name, MAXNAMLEN, "WindowServer (%d)", Pid); (void)filler(buf, the_name, &the_stat, 0); } return 0; } // END: READDIR // BEGIN: READLINK // int // windowfs_readlink_<handler>(windowfs_dispatcher_entry_t e, // const char *argv[], // char *buf, // size_t size) READLINK_HANDLER(einval) { return -EINVAL; } // END: READLINK static void * windowfs_init(struct fuse_conn_info *conn) { total_file_patterns = sizeof(windowfs_file_table)/sizeof(struct windowfs_dispatcher_entry); total_directory_patterns = sizeof(windowfs_directory_table)/sizeof(struct windowfs_dispatcher_entry); total_link_patterns = sizeof(windowfs_link_table)/sizeof(struct windowfs_dispatcher_entry); return NULL; } static void windowfs_destroy(void *arg) { } #define WINDOWFS_OPEN_RELEASE_COMMON() \ int i; \ windowfs_dispatcher_entry_t e; \ string arg1, arg2, arg3; \ const char *real_argv[WINDOWFS_MAX_ARGS]; \ \ if (valid_process_pattern->PartialMatch(path, &arg1)) { \ pid_t check_pid = atoi(arg1.c_str()); \ if (getpgid(check_pid) == -1) { \ return -ENOENT; \ } \ } \ \ for (i = 0; i < WINDOWFS_MAX_ARGS; i++) { \ real_argv[i] = (char *)0; \ } \ \ for (i = 0; i < total_file_patterns; i++) { \ e = &windowfs_file_table[i]; \ switch (e->argc) { \ case 0: \ if (e->compiled_pattern->FullMatch(path)) { \ goto out; \ } \ break; \ \ case 1: \ if (e->compiled_pattern->FullMatch(path, &arg1)) { \ real_argv[0] = arg1.c_str(); \ goto out; \ } \ break; \ \ case 2: \ if (e->compiled_pattern->FullMatch(path, &arg1, &arg2)) { \ real_argv[0] = arg1.c_str(); \ real_argv[1] = arg2.c_str(); \ goto out; \ } \ break; \ \ case 3: \ if (e->compiled_pattern->FullMatch(path, &arg1, &arg2, &arg3)) { \ real_argv[0] = arg1.c_str(); \ real_argv[1] = arg2.c_str(); \ real_argv[2] = arg3.c_str(); \ goto out; \ } \ break; \ \ default: \ break; \ } \ } \ \ for (i = 0; i < total_link_patterns; i++) { \ e = &windowfs_link_table[i]; \ switch (e->argc) { \ case 0: \ if (e->compiled_pattern->FullMatch(path)) { \ goto out; \ } \ break; \ \ case 1: \ if (e->compiled_pattern->FullMatch(path, &arg1)) { \ real_argv[0] = arg1.c_str(); \ goto out; \ } \ break; \ \ case 2: \ if (e->compiled_pattern->FullMatch(path, &arg1, &arg2)) { \ real_argv[0] = arg1.c_str(); \ real_argv[1] = arg2.c_str(); \ goto out; \ } \ break; \ \ case 3: \ if (e->compiled_pattern->FullMatch(path, &arg1, &arg2, &arg3)) { \ real_argv[0] = arg1.c_str(); \ real_argv[1] = arg2.c_str(); \ real_argv[2] = arg3.c_str(); \ goto out; \ } \ break; \ \ default: \ break; \ } \ } \ \ return -ENOENT; \ \ out: \ static int windowfs_open(const char *path, struct fuse_file_info *fi) { WINDOWFS_OPEN_RELEASE_COMMON() return e->open(e, real_argv, path, fi); } static int windowfs_release(const char *path, struct fuse_file_info *fi) { WINDOWFS_OPEN_RELEASE_COMMON() return e->release(e, real_argv, path, fi); } static int windowfs_opendir(const char *path, struct fuse_file_info *fi) { return 0; } static int windowfs_releasedir(const char *path, struct fuse_file_info *fi) { return 0; } static int windowfs_getattr(const char *path, struct stat *stbuf) { int i; windowfs_dispatcher_entry_t e; string arg1, arg2, arg3; const char *real_argv[WINDOWFS_MAX_ARGS]; if (valid_process_pattern->PartialMatch(path, &arg1)) { pid_t check_pid = atoi(arg1.c_str()); if (getpgid(check_pid) == -1) { return -ENOENT; } } for (i = 0; i < WINDOWFS_MAX_ARGS; i++) { real_argv[i] = (char *)0; } for (i = 0; i < total_directory_patterns; i++) { e = &windowfs_directory_table[i]; switch (e->argc) { case 0: if (e->compiled_pattern->FullMatch(path)) { goto out; } break; case 1: if (e->compiled_pattern->FullMatch(path, &arg1)) { real_argv[0] = arg1.c_str(); goto out; } break; case 2: if (e->compiled_pattern->FullMatch(path, &arg1, &arg2)) { real_argv[0] = arg1.c_str(); real_argv[1] = arg2.c_str(); goto out; } break; case 3: if (e->compiled_pattern->FullMatch(path, &arg1, &arg2, &arg3)) { real_argv[0] = arg1.c_str(); real_argv[1] = arg2.c_str(); real_argv[2] = arg3.c_str(); goto out; } break; default: break; } } for (i = 0; i < total_file_patterns; i++) { e = &windowfs_file_table[i]; switch (e->argc) { case 0: if (e->compiled_pattern->FullMatch(path)) { goto out; } break; case 1: if (e->compiled_pattern->FullMatch(path, &arg1)) { real_argv[0] = arg1.c_str(); goto out; } break; case 2: if (e->compiled_pattern->FullMatch(path, &arg1, &arg2)) { real_argv[0] = arg1.c_str(); real_argv[1] = arg2.c_str(); goto out; } break; case 3: if (e->compiled_pattern->FullMatch(path, &arg1, &arg2, &arg3)) { real_argv[0] = arg1.c_str(); real_argv[1] = arg2.c_str(); real_argv[2] = arg3.c_str(); goto out; } break; default: break; } } for (i = 0; i < total_link_patterns; i++) { e = &windowfs_link_table[i]; switch (e->argc) { case 0: if (e->compiled_pattern->FullMatch(path)) { goto out; } break; case 1: if (e->compiled_pattern->FullMatch(path, &arg1)) { real_argv[0] = arg1.c_str(); goto out; } break; case 2: if (e->compiled_pattern->FullMatch(path, &arg1, &arg2)) { real_argv[0] = arg1.c_str(); real_argv[1] = arg2.c_str(); goto out; } break; case 3: if (e->compiled_pattern->FullMatch(path, &arg1, &arg2, &arg3)) { real_argv[0] = arg1.c_str(); real_argv[1] = arg2.c_str(); real_argv[2] = arg3.c_str(); goto out; } break; default: break; } } return -ENOENT; out: return e->getattr(e, real_argv, stbuf); } static int windowfs_readdir(const char *path, void *buf, fuse_fill_dir_t filler, off_t offset, struct fuse_file_info *fi) { int i; windowfs_dispatcher_entry_t e; string arg1, arg2, arg3; const char *real_argv[WINDOWFS_MAX_ARGS]; if (valid_process_pattern->PartialMatch(path, &arg1)) { pid_t check_pid = atoi(arg1.c_str()); if (getpgid(check_pid) == -1) { return -ENOENT; } } for (i = 0; i < WINDOWFS_MAX_ARGS; i++) { real_argv[i] = (char *)0; } for (i = 0; i < total_directory_patterns; i++) { e = &windowfs_directory_table[i]; switch (e->argc) { case 0: if (e->compiled_pattern->FullMatch(path)) { goto out; } break; case 1: if (e->compiled_pattern->FullMatch(path, &arg1)) { real_argv[0] = arg1.c_str(); goto out; } break; case 2: if (e->compiled_pattern->FullMatch(path, &arg1, &arg2)) { real_argv[0] = arg1.c_str(); real_argv[1] = arg2.c_str(); goto out; } break; case 3: if (e->compiled_pattern->FullMatch(path, &arg1, &arg2, &arg3)) { real_argv[0] = arg1.c_str(); real_argv[1] = arg2.c_str(); real_argv[2] = arg3.c_str(); goto out; } break; default: return -ENOENT; } } return -ENOENT; out: (void)e->readdir(e, real_argv, buf, filler, offset, fi); (void)windowfs_populate_directory(e->content_files, e->content_directories, buf, filler, offset, fi); return 0; } static int windowfs_readlink(const char *path, char *buf, size_t size) { int i; windowfs_dispatcher_entry_t e; string arg1, arg2, arg3; const char *real_argv[WINDOWFS_MAX_ARGS]; for (i = 0; i < WINDOWFS_MAX_ARGS; i++) { real_argv[i] = (char *)0; } for (i = 0; i < total_link_patterns; i++) { e = &windowfs_link_table[i]; switch (e->argc) { case 0: if (e->compiled_pattern->FullMatch(path)) { goto out; } break; case 1: if (e->compiled_pattern->FullMatch(path, &arg1)) { real_argv[0] = arg1.c_str(); goto out; } break; case 2: if (e->compiled_pattern->FullMatch(path, &arg1, &arg2)) { real_argv[0] = arg1.c_str(); real_argv[1] = arg2.c_str(); goto out; } break; } } return -ENOENT; out: return e->readlink(e, real_argv, buf, size); } static int windowfs_read(const char *path, char *buf, size_t size, off_t offset, struct fuse_file_info *fi) { int i; windowfs_dispatcher_entry_t e; string arg1, arg2, arg3; const char *real_argv[WINDOWFS_MAX_ARGS]; for (i = 0; i < WINDOWFS_MAX_ARGS; i++) { real_argv[i] = (char *)0; } for (i = 0; i < total_file_patterns; i++) { e = &windowfs_file_table[i]; switch (e->argc) { case 0: if (e->compiled_pattern->FullMatch(path)) { goto out; } break; case 1: if (e->compiled_pattern->FullMatch(path, &arg1)) { real_argv[0] = arg1.c_str(); goto out; } break; case 2: if (e->compiled_pattern->FullMatch(path, &arg1, &arg2)) { real_argv[0] = arg1.c_str(); real_argv[1] = arg2.c_str(); goto out; } break; case 3: if (e->compiled_pattern->FullMatch(path, &arg1, &arg2, &arg3)) { real_argv[0] = arg1.c_str(); real_argv[1] = arg2.c_str(); real_argv[2] = arg3.c_str(); goto out; } break; default: return -EIO; } } return -EIO; out: return e->read(e, real_argv, buf, size, offset, fi); } static int windowfs_statfs(const char *path, struct statvfs *buf) { (void)path; buf->f_namemax = 255; buf->f_bsize = 2097152; buf->f_frsize = 2097152; buf->f_blocks = 1000ULL * 1024 * 1024 * 1024 / buf->f_frsize; buf->f_bfree = buf->f_bavail = 0; buf->f_files = 1000000000; buf->f_ffree = 0; return 0; } static struct fuse_operations windowfs_oper; static void windowfs_oper_populate(struct fuse_operations *oper) { oper->init = windowfs_init; oper->destroy = windowfs_destroy; oper->statfs = windowfs_statfs; oper->open = windowfs_open; oper->release = windowfs_release; oper->opendir = windowfs_opendir; oper->releasedir = windowfs_releasedir; oper->getattr = windowfs_getattr; oper->read = windowfs_read; oper->readdir = windowfs_readdir; oper->readlink = windowfs_readlink; } static char *def_opts = "-odirect_io,iosize=2097152,local,noappledouble,nolocalcaches,ro,fsname=GrabFS,volname=GrabFS Volume"; int main(int argc, char *argv[]) { int i; char **new_argv; char *extra_opts = def_opts; argc += 3; new_argv = (char **)malloc(sizeof(char *) * argc); new_argv[0] = argv[0]; new_argv[1] = WINDOWFS_MNTPOINT; new_argv[2] = extra_opts; new_argv[3] = "-f"; for (i = 1; i < (argc - 3); i++) { new_argv[i + 3] = argv[i]; } errno = 0; int ret = mkdir(WINDOWFS_MNTPOINT, 0755); if (ret && (errno != EEXIST)) { perror("mkdir"); exit(ret); } windowfs_oper_populate(&windowfs_oper); { /* Make Carbon & Co. Happy */ pid_t Pid; ProcessSerialNumber psn = { kNoProcess, kNoProcess }; (void)GetNextProcess(&psn); (void)GetProcessPID(&psn, &Pid); } return fuse_main(argc, new_argv, &windowfs_oper, NULL); }
30.709632
126
0.433444
[ "vector" ]
4fa5ad77d9053078ebb34ed8dca3f2a3ad32f7a0
36,659
cpp
C++
src/core/qgsdistancearea.cpp
dyna-mis/Hilabeling
cb7d5d4be29624a20c8a367162dbc6fd779b2b52
[ "MIT" ]
null
null
null
src/core/qgsdistancearea.cpp
dyna-mis/Hilabeling
cb7d5d4be29624a20c8a367162dbc6fd779b2b52
[ "MIT" ]
null
null
null
src/core/qgsdistancearea.cpp
dyna-mis/Hilabeling
cb7d5d4be29624a20c8a367162dbc6fd779b2b52
[ "MIT" ]
1
2021-12-25T08:40:30.000Z
2021-12-25T08:40:30.000Z
/*************************************************************************** qgsdistancearea.cpp - Distance and area calculations on the ellipsoid --------------------------------------------------------------------------- Date : September 2005 Copyright : (C) 2005 by Martin Dobias email : won.der at centrum.sk *************************************************************************** * * * 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; either version 2 of the License, or * * (at your option) any later version. * * * ***************************************************************************/ #include <cmath> #include <QString> #include <QObject> #include "qgsdistancearea.h" #include "qgis.h" #include "qgspointxy.h" #include "qgscoordinatetransform.h" #include "qgscoordinatereferencesystem.h" #include "qgsgeometry.h" #include "qgsgeometrycollection.h" #include "qgslogger.h" #include "qgsmessagelog.h" #include "qgsmultisurface.h" #include "qgswkbptr.h" #include "qgslinestring.h" #include "qgspolygon.h" #include "qgssurface.h" #include "qgsunittypes.h" #include "qgsexception.h" #include "qgsmultilinestring.h" #include <geodesic.h> #define DEG2RAD(x) ((x)*M_PI/180) #define RAD2DEG(r) (180.0 * (r) / M_PI) #define POW2(x) ((x)*(x)) QgsDistanceArea::QgsDistanceArea() { // init with default settings mSemiMajor = -1.0; mSemiMinor = -1.0; mInvFlattening = -1.0; QgsCoordinateTransformContext context; // this is ok - by default we have a source/dest of WGS84, so no reprojection takes place setSourceCrs( QgsCoordinateReferenceSystem::fromSrsId( GEOCRS_ID ), context ); // WGS 84 setEllipsoid( GEO_NONE ); } bool QgsDistanceArea::willUseEllipsoid() const { return mEllipsoid != GEO_NONE; } void QgsDistanceArea::setSourceCrs( const QgsCoordinateReferenceSystem &srcCRS, const QgsCoordinateTransformContext &context ) { mCoordTransform.setContext( context ); mCoordTransform.setSourceCrs( srcCRS ); } bool QgsDistanceArea::setEllipsoid( const QString &ellipsoid ) { // Shortcut if ellipsoid is none. if ( ellipsoid == GEO_NONE ) { mEllipsoid = GEO_NONE; return true; } QgsEllipsoidUtils::EllipsoidParameters params = QgsEllipsoidUtils::ellipsoidParameters( ellipsoid ); if ( !params.valid ) { return false; } else { mEllipsoid = ellipsoid; setFromParams( params ); return true; } } // Inverse flattening is calculated with invf = a/(a-b) // Also, b = a-(a/invf) bool QgsDistanceArea::setEllipsoid( double semiMajor, double semiMinor ) { mEllipsoid = QStringLiteral( "PARAMETER:%1:%2" ).arg( qgsDoubleToString( semiMajor ), qgsDoubleToString( semiMinor ) ); mSemiMajor = semiMajor; mSemiMinor = semiMinor; mInvFlattening = mSemiMajor / ( mSemiMajor - mSemiMinor ); computeAreaInit(); return true; } double QgsDistanceArea::measure( const QgsAbstractGeometry *geomV2, MeasureType type ) const { if ( !geomV2 ) { return 0.0; } int geomDimension = geomV2->dimension(); if ( geomDimension <= 0 ) { return 0.0; } MeasureType measureType = type; if ( measureType == Default ) { measureType = ( geomDimension == 1 ? Length : Area ); } if ( !willUseEllipsoid() ) { //no transform required if ( measureType == Length ) { return geomV2->length(); } else { return geomV2->area(); } } else { //multigeom is sum of measured parts const QgsGeometryCollection *collection = qgsgeometry_cast<const QgsGeometryCollection *>( geomV2 ); if ( collection ) { double sum = 0; for ( int i = 0; i < collection->numGeometries(); ++i ) { sum += measure( collection->geometryN( i ), measureType ); } return sum; } if ( measureType == Length ) { const QgsCurve *curve = qgsgeometry_cast<const QgsCurve *>( geomV2 ); if ( !curve ) { return 0.0; } QgsLineString *lineString = curve->curveToLine(); double length = measureLine( lineString ); delete lineString; return length; } else { const QgsSurface *surface = qgsgeometry_cast<const QgsSurface *>( geomV2 ); if ( !surface ) return 0.0; QgsPolygon *polygon = surface->surfaceToPolygon(); double area = 0; const QgsCurve *outerRing = polygon->exteriorRing(); area += measurePolygon( outerRing ); for ( int i = 0; i < polygon->numInteriorRings(); ++i ) { const QgsCurve *innerRing = polygon->interiorRing( i ); area -= measurePolygon( innerRing ); } delete polygon; return area; } } } double QgsDistanceArea::measureArea( const QgsGeometry &geometry ) const { if ( geometry.isNull() ) return 0.0; const QgsAbstractGeometry *geomV2 = geometry.constGet(); return measure( geomV2, Area ); } double QgsDistanceArea::measureLength( const QgsGeometry &geometry ) const { if ( geometry.isNull() ) return 0.0; const QgsAbstractGeometry *geomV2 = geometry.constGet(); return measure( geomV2, Length ); } double QgsDistanceArea::measurePerimeter( const QgsGeometry &geometry ) const { if ( geometry.isNull() ) return 0.0; const QgsAbstractGeometry *geomV2 = geometry.constGet(); if ( !geomV2 || geomV2->dimension() < 2 ) { return 0.0; } if ( !willUseEllipsoid() ) { return geomV2->perimeter(); } //create list with (single) surfaces QVector< const QgsSurface * > surfaces; const QgsSurface *surf = qgsgeometry_cast<const QgsSurface *>( geomV2 ); if ( surf ) { surfaces.append( surf ); } const QgsMultiSurface *multiSurf = qgsgeometry_cast<const QgsMultiSurface *>( geomV2 ); if ( multiSurf ) { surfaces.reserve( ( surf ? 1 : 0 ) + multiSurf->numGeometries() ); for ( int i = 0; i < multiSurf->numGeometries(); ++i ) { surfaces.append( static_cast<const QgsSurface *>( multiSurf->geometryN( i ) ) ); } } double length = 0; QVector<const QgsSurface *>::const_iterator surfaceIt = surfaces.constBegin(); for ( ; surfaceIt != surfaces.constEnd(); ++surfaceIt ) { if ( !*surfaceIt ) { continue; } QgsPolygon *poly = ( *surfaceIt )->surfaceToPolygon(); const QgsCurve *outerRing = poly->exteriorRing(); if ( outerRing ) { length += measure( outerRing ); } int nInnerRings = poly->numInteriorRings(); for ( int i = 0; i < nInnerRings; ++i ) { length += measure( poly->interiorRing( i ) ); } delete poly; } return length; } double QgsDistanceArea::measureLine( const QgsCurve *curve ) const { if ( !curve ) { return 0.0; } QgsPointSequence linePointsV2; QVector<QgsPointXY> linePoints; curve->points( linePointsV2 ); QgsGeometry::convertPointList( linePointsV2, linePoints ); return measureLine( linePoints ); } double QgsDistanceArea::measureLine( const QVector<QgsPointXY> &points ) const { if ( points.size() < 2 ) return 0; double total = 0; QgsPointXY p1, p2; try { if ( willUseEllipsoid() ) p1 = mCoordTransform.transform( points[0] ); else p1 = points[0]; for ( QVector<QgsPointXY>::const_iterator i = points.constBegin(); i != points.constEnd(); ++i ) { if ( willUseEllipsoid() ) { p2 = mCoordTransform.transform( *i ); total += computeDistanceBearing( p1, p2 ); } else { p2 = *i; total += measureLine( p1, p2 ); } p1 = p2; } return total; } catch ( QgsCsException &cse ) { Q_UNUSED( cse ); QgsMessageLog::logMessage( QObject::tr( "Caught a coordinate system exception while trying to transform a point. Unable to calculate line length." ) ); return 0.0; } } double QgsDistanceArea::measureLine( const QgsPointXY &p1, const QgsPointXY &p2 ) const { double result; try { QgsPointXY pp1 = p1, pp2 = p2; QgsDebugMsgLevel( QStringLiteral( "Measuring from %1 to %2" ).arg( p1.toString( 4 ), p2.toString( 4 ) ), 3 ); if ( willUseEllipsoid() ) { QgsDebugMsgLevel( QStringLiteral( "Ellipsoidal calculations is enabled, using ellipsoid %1" ).arg( mEllipsoid ), 4 ); QgsDebugMsgLevel( QStringLiteral( "From proj4 : %1" ).arg( mCoordTransform.sourceCrs().toProj4() ), 4 ); QgsDebugMsgLevel( QStringLiteral( "To proj4 : %1" ).arg( mCoordTransform.destinationCrs().toProj4() ), 4 ); pp1 = mCoordTransform.transform( p1 ); pp2 = mCoordTransform.transform( p2 ); QgsDebugMsgLevel( QStringLiteral( "New points are %1 and %2, calculating..." ).arg( pp1.toString( 4 ), pp2.toString( 4 ) ), 4 ); result = computeDistanceBearing( pp1, pp2 ); } else { QgsDebugMsgLevel( QStringLiteral( "Cartesian calculation on canvas coordinates" ), 4 ); result = p2.distance( p1 ); } } catch ( QgsCsException &cse ) { Q_UNUSED( cse ); QgsMessageLog::logMessage( QObject::tr( "Caught a coordinate system exception while trying to transform a point. Unable to calculate line length." ) ); result = 0.0; } QgsDebugMsgLevel( QStringLiteral( "The result was %1" ).arg( result ), 3 ); return result; } double QgsDistanceArea::measureLineProjected( const QgsPointXY &p1, double distance, double azimuth, QgsPointXY *projectedPoint ) const { double result = 0.0; QgsPointXY p2; if ( mCoordTransform.sourceCrs().isGeographic() && willUseEllipsoid() ) { p2 = computeSpheroidProject( p1, distance, azimuth ); result = p1.distance( p2 ); } else // Cartesian coordinates { result = distance; // Avoid rounding errors when using meters [return as sent] if ( sourceCrs().mapUnits() != QgsUnitTypes::DistanceMeters ) { distance = ( distance * QgsUnitTypes::fromUnitToUnitFactor( QgsUnitTypes::DistanceMeters, sourceCrs().mapUnits() ) ); result = p1.distance( p2 ); } p2 = p1.project( distance, azimuth ); } QgsDebugMsgLevel( QStringLiteral( "Converted distance of %1 %2 to %3 distance %4 %5, using azimuth[%6] from point[%7] to point[%8] sourceCrs[%9] mEllipsoid[%10] isGeographic[%11] [%12]" ) .arg( QString::number( distance, 'f', 7 ), QgsUnitTypes::toString( QgsUnitTypes::DistanceMeters ), QString::number( result, 'f', 7 ), mCoordTransform.sourceCrs().isGeographic() ? QStringLiteral( "Geographic" ) : QStringLiteral( "Cartesian" ), QgsUnitTypes::toString( sourceCrs().mapUnits() ) ) .arg( azimuth ) .arg( p1.asWkt(), p2.asWkt(), sourceCrs().description(), mEllipsoid ) .arg( sourceCrs().isGeographic() ) .arg( QStringLiteral( "SemiMajor[%1] SemiMinor[%2] InvFlattening[%3] " ).arg( QString::number( mSemiMajor, 'f', 7 ), QString::number( mSemiMinor, 'f', 7 ), QString::number( mInvFlattening, 'f', 7 ) ) ), 4 ); if ( projectedPoint ) { *projectedPoint = QgsPointXY( p2 ); } return result; } /* * From original rttopo documentation: * Tested against: * http://mascot.gdbc.gov.bc.ca/mascot/util1b.html * and * http://www.ga.gov.au/nmd/geodesy/datums/vincenty_direct.jsp */ QgsPointXY QgsDistanceArea::computeSpheroidProject( const QgsPointXY &p1, double distance, double azimuth ) const { // ellipsoid double a = mSemiMajor; double b = mSemiMinor; double f = 1 / mInvFlattening; if ( ( ( a < 0 ) && ( b < 0 ) ) || ( ( p1.x() < -180.0 ) || ( p1.x() > 180.0 ) || ( p1.y() < -85.05115 ) || ( p1.y() > 85.05115 ) ) ) { // latitudes outside these bounds cause the calculations to become unstable and can return invalid results return QgsPoint( 0, 0 ); } double radians_lat = DEG2RAD( p1.y() ); double radians_long = DEG2RAD( p1.x() ); double b2 = POW2( b ); // spheroid_mu2 double omf = 1 - f; double tan_u1 = omf * std::tan( radians_lat ); double u1 = std::atan( tan_u1 ); double sigma, last_sigma, delta_sigma, two_sigma_m; double sigma1, sin_alpha, alpha, cos_alphasq; double u2, A, B; double lat2, lambda, lambda2, C, omega; int i = 0; if ( azimuth < 0.0 ) { azimuth = azimuth + M_PI * 2.0; } if ( azimuth > ( M_PI * 2.0 ) ) { azimuth = azimuth - M_PI * 2.0; } sigma1 = std::atan2( tan_u1, std::cos( azimuth ) ); sin_alpha = std::cos( u1 ) * std::sin( azimuth ); alpha = std::asin( sin_alpha ); cos_alphasq = 1.0 - POW2( sin_alpha ); u2 = POW2( std::cos( alpha ) ) * ( POW2( a ) - b2 ) / b2; // spheroid_mu2 A = 1.0 + ( u2 / 16384.0 ) * ( 4096.0 + u2 * ( -768.0 + u2 * ( 320.0 - 175.0 * u2 ) ) ); B = ( u2 / 1024.0 ) * ( 256.0 + u2 * ( -128.0 + u2 * ( 74.0 - 47.0 * u2 ) ) ); sigma = ( distance / ( b * A ) ); do { two_sigma_m = 2.0 * sigma1 + sigma; delta_sigma = B * std::sin( sigma ) * ( std::cos( two_sigma_m ) + ( B / 4.0 ) * ( std::cos( sigma ) * ( -1.0 + 2.0 * POW2( std::cos( two_sigma_m ) ) - ( B / 6.0 ) * std::cos( two_sigma_m ) * ( -3.0 + 4.0 * POW2( std::sin( sigma ) ) ) * ( -3.0 + 4.0 * POW2( std::cos( two_sigma_m ) ) ) ) ) ); last_sigma = sigma; sigma = ( distance / ( b * A ) ) + delta_sigma; i++; } while ( i < 999 && std::fabs( ( last_sigma - sigma ) / sigma ) > 1.0e-9 ); lat2 = std::atan2( ( std::sin( u1 ) * std::cos( sigma ) + std::cos( u1 ) * std::sin( sigma ) * std::cos( azimuth ) ), ( omf * std::sqrt( POW2( sin_alpha ) + POW2( std::sin( u1 ) * std::sin( sigma ) - std::cos( u1 ) * std::cos( sigma ) * std::cos( azimuth ) ) ) ) ); lambda = std::atan2( ( std::sin( sigma ) * std::sin( azimuth ) ), ( std::cos( u1 ) * std::cos( sigma ) - std::sin( u1 ) * std::sin( sigma ) * std::cos( azimuth ) ) ); C = ( f / 16.0 ) * cos_alphasq * ( 4.0 + f * ( 4.0 - 3.0 * cos_alphasq ) ); omega = lambda - ( 1.0 - C ) * f * sin_alpha * ( sigma + C * std::sin( sigma ) * ( std::cos( two_sigma_m ) + C * std::cos( sigma ) * ( -1.0 + 2.0 * POW2( std::cos( two_sigma_m ) ) ) ) ); lambda2 = radians_long + omega; return QgsPointXY( RAD2DEG( lambda2 ), RAD2DEG( lat2 ) ); } double QgsDistanceArea::latitudeGeodesicCrossesAntimeridian( const QgsPointXY &pp1, const QgsPointXY &pp2, double &fractionAlongLine ) const { QgsPointXY p1 = pp1; QgsPointXY p2 = pp2; if ( p1.x() < -120 ) p1.setX( p1.x() + 360 ); if ( p2.x() < -120 ) p2.setX( p2.x() + 360 ); // we need p2.x() > 180 and p1.x() < 180 double p1x = p1.x() < 180 ? p1.x() : p2.x(); double p1y = p1.x() < 180 ? p1.y() : p2.y(); double p2x = p1.x() < 180 ? p2.x() : p1.x(); double p2y = p1.x() < 180 ? p2.y() : p1.y(); // lat/lon are our candidate intersection position - we want this to get as close to 180 as possible // the first candidate is p2 double lat = p2y; double lon = p2x; if ( mEllipsoid == GEO_NONE ) { fractionAlongLine = ( 180 - p1x ) / ( p2x - p1x ); if ( p1.x() >= 180 ) fractionAlongLine = 1 - fractionAlongLine; return p1y + ( 180 - p1x ) / ( p2x - p1x ) * ( p2y - p1y ); } geod_geodesic geod; geod_init( &geod, mSemiMajor, 1 / mInvFlattening ); geod_geodesicline line; geod_inverseline( &line, &geod, p1y, p1x, p2y, p2x, GEOD_ALL ); const double totalDist = line.s13; double intersectionDist = line.s13; int iterations = 0; double t = 0; // iterate until our intersection candidate is within ~1 mm of the antimeridian (or too many iterations happened) while ( std::fabs( lon - 180.0 ) > 0.00000001 && iterations < 100 ) { if ( iterations > 0 && std::fabs( p2x - p1x ) > 5 ) { // if we have too large a range of longitudes, we use a binary search to narrow the window -- this ensures we will converge if ( lon < 180 ) { p1x = lon; p1y = lat; } else { p2x = lon; p2y = lat; } QgsDebugMsgLevel( QStringLiteral( "Narrowed window to %1, %2 - %3, %4" ).arg( p1x ).arg( p1y ).arg( p2x ).arg( p2y ), 4 ); geod_inverseline( &line, &geod, p1y, p1x, p2y, p2x, GEOD_ALL ); intersectionDist = line.s13 * 0.5; } else { // we have a sufficiently narrow window -- use Newton's method // adjust intersection distance by fraction of how close the previous candidate was to 180 degrees longitude - // this helps us close in to the correct longitude quickly intersectionDist *= ( 180.0 - p1x ) / ( lon - p1x ); } // now work out the point on the geodesic this far from p1 - this becomes our new candidate for crossing the antimeridian geod_position( &line, intersectionDist, &lat, &lon, &t ); // we don't want to wrap longitudes > 180 around) if ( lon < 0 ) lon += 360; iterations++; QgsDebugMsgLevel( QStringLiteral( "After %1 iterations lon is %2, lat is %3, dist from p1: %4" ).arg( iterations ).arg( lon ).arg( lat ).arg( intersectionDist ), 4 ); } fractionAlongLine = intersectionDist / totalDist; if ( p1.x() >= 180 ) fractionAlongLine = 1 - fractionAlongLine; // either converged on 180 longitude or hit too many iterations return lat; } QgsGeometry QgsDistanceArea::splitGeometryAtAntimeridian( const QgsGeometry &geometry ) const { if ( QgsWkbTypes::geometryType( geometry.wkbType() ) != QgsWkbTypes::LineGeometry ) return geometry; QgsGeometry g = geometry; // TODO - avoid segmentization of curved geometries (if this is even possible!) if ( QgsWkbTypes::isCurvedType( g.wkbType() ) ) g.convertToStraightSegment(); std::unique_ptr< QgsMultiLineString > res = qgis::make_unique< QgsMultiLineString >(); for ( auto part = g.const_parts_begin(); part != g.const_parts_end(); ++part ) { const QgsLineString *line = qgsgeometry_cast< const QgsLineString * >( *part ); if ( !line ) continue; if ( line->isEmpty() ) { continue; } std::unique_ptr< QgsLineString > l = qgis::make_unique< QgsLineString >(); try { double x = 0; double y = 0; double z = 0; double m = 0; QVector< QgsPoint > newPoints; newPoints.reserve( line->numPoints() ); double prevLon = 0; double prevLat = 0; double lon = 0; double lat = 0; double prevZ = 0; double prevM = 0; for ( int i = 0; i < line->numPoints(); i++ ) { QgsPoint p = line->pointN( i ); x = p.x(); if ( mCoordTransform.sourceCrs().isGeographic() ) { x = std::fmod( x, 360.0 ); if ( x > 180 ) x -= 360; p.setX( x ); } y = p.y(); lon = x; lat = y; mCoordTransform.transformInPlace( lon, lat, z ); //test if we crossed the antimeridian in this segment if ( i > 0 && ( ( prevLon < -120 && lon > 120 ) || ( prevLon > 120 && lon < -120 ) ) ) { // we did! // when crossing the antimeridian, we need to calculate the latitude // at which the geodesic intersects the antimeridian double fract = 0; double lat180 = latitudeGeodesicCrossesAntimeridian( QgsPointXY( prevLon, prevLat ), QgsPointXY( lon, lat ), fract ); if ( line->is3D() ) { z = prevZ + ( p.z() - prevZ ) * fract; } if ( line->isMeasure() ) { m = prevM + ( p.m() - prevM ) * fract; } QgsPointXY antiMeridianPoint; if ( prevLon < -120 ) antiMeridianPoint = mCoordTransform.transform( QgsPointXY( -180, lat180 ), QgsCoordinateTransform::ReverseTransform ); else antiMeridianPoint = mCoordTransform.transform( QgsPointXY( 180, lat180 ), QgsCoordinateTransform::ReverseTransform ); QgsPoint newPoint( antiMeridianPoint ); if ( line->is3D() ) newPoint.addZValue( z ); if ( line->isMeasure() ) newPoint.addMValue( m ); if ( std::isfinite( newPoint.x() ) && std::isfinite( newPoint.y() ) ) { newPoints << newPoint; } res->addGeometry( new QgsLineString( newPoints ) ); newPoints.clear(); newPoints.reserve( line->numPoints() - i + 1 ); if ( lon < -120 ) antiMeridianPoint = mCoordTransform.transform( QgsPointXY( -180, lat180 ), QgsCoordinateTransform::ReverseTransform ); else antiMeridianPoint = mCoordTransform.transform( QgsPointXY( 180, lat180 ), QgsCoordinateTransform::ReverseTransform ); if ( std::isfinite( antiMeridianPoint.x() ) && std::isfinite( antiMeridianPoint.y() ) ) { // we want to keep the previously calculated z/m value for newPoint, if present. They're the same each // of the antimeridian split newPoint.setX( antiMeridianPoint.x() ); newPoint.setY( antiMeridianPoint.y() ); newPoints << newPoint; } } newPoints << p; prevLon = lon; prevLat = lat; if ( line->is3D() ) prevZ = p.z(); if ( line->isMeasure() ) prevM = p.m(); } res->addGeometry( new QgsLineString( newPoints ) ); } catch ( QgsCsException & ) { QgsMessageLog::logMessage( QObject::tr( "Caught a coordinate system exception while trying to transform linestring. Unable to calculate break point." ) ); res->addGeometry( line->clone() ); break; } } return QgsGeometry( std::move( res ) ); } QVector< QVector<QgsPointXY> > QgsDistanceArea::geodesicLine( const QgsPointXY &p1, const QgsPointXY &p2, const double interval, const bool breakLine ) const { if ( !willUseEllipsoid() ) { return QVector< QVector< QgsPointXY > >() << ( QVector< QgsPointXY >() << p1 << p2 ); } geod_geodesic geod; geod_init( &geod, mSemiMajor, 1 / mInvFlattening ); QgsPointXY pp1, pp2; try { pp1 = mCoordTransform.transform( p1 ); pp2 = mCoordTransform.transform( p2 ); } catch ( QgsCsException & ) { QgsMessageLog::logMessage( QObject::tr( "Caught a coordinate system exception while trying to transform a point. Unable to calculate geodesic line." ) ); return QVector< QVector< QgsPointXY > >(); } geod_geodesicline line; geod_inverseline( &line, &geod, pp1.y(), pp1.x(), pp2.y(), pp2.x(), GEOD_ALL ); const double totalDist = line.s13; QVector< QVector< QgsPointXY > > res; QVector< QgsPointXY > currentPart; currentPart << p1; double d = interval; double prevLon = pp1.x(); double prevLat = pp1.y(); bool lastRun = false; double t = 0; while ( true ) { double lat, lon; if ( lastRun ) { lat = pp2.y(); lon = pp2.x(); if ( lon > 180 ) lon -= 360; } else { geod_position( &line, d, &lat, &lon, &t ); } if ( breakLine && ( ( prevLon < -120 && lon > 120 ) || ( prevLon > 120 && lon < -120 ) ) ) { // when breaking the geodesic at the antimeridian, we need to calculate the latitude // at which the geodesic intersects the antimeridian, and add points to both line segments at this latitude // on the antimeridian. double fraction; double lat180 = latitudeGeodesicCrossesAntimeridian( QgsPointXY( prevLon, prevLat ), QgsPointXY( lon, lat ), fraction ); try { QgsPointXY p; if ( prevLon < -120 ) p = mCoordTransform.transform( QgsPointXY( -180, lat180 ), QgsCoordinateTransform::ReverseTransform ); else p = mCoordTransform.transform( QgsPointXY( 180, lat180 ), QgsCoordinateTransform::ReverseTransform ); if ( std::isfinite( p.x() ) && std::isfinite( p.y() ) ) currentPart << p; } catch ( QgsCsException & ) { QgsMessageLog::logMessage( QObject::tr( "Caught a coordinate system exception while trying to transform a point." ) ); } res << currentPart; currentPart.clear(); try { QgsPointXY p; if ( lon < -120 ) p = mCoordTransform.transform( QgsPointXY( -180, lat180 ), QgsCoordinateTransform::ReverseTransform ); else p = mCoordTransform.transform( QgsPointXY( 180, lat180 ), QgsCoordinateTransform::ReverseTransform ); if ( std::isfinite( p.x() ) && std::isfinite( p.y() ) ) currentPart << p; } catch ( QgsCsException & ) { QgsMessageLog::logMessage( QObject::tr( "Caught a coordinate system exception while trying to transform a point." ) ); } } prevLon = lon; prevLat = lat; try { currentPart << mCoordTransform.transform( QgsPointXY( lon, lat ), QgsCoordinateTransform::ReverseTransform ); } catch ( QgsCsException & ) { QgsMessageLog::logMessage( QObject::tr( "Caught a coordinate system exception while trying to transform a point." ) ); } if ( lastRun ) break; d += interval; if ( d >= totalDist ) lastRun = true; } res << currentPart; return res; } QgsUnitTypes::DistanceUnit QgsDistanceArea::lengthUnits() const { return willUseEllipsoid() ? QgsUnitTypes::DistanceMeters : mCoordTransform.sourceCrs().mapUnits(); } QgsUnitTypes::AreaUnit QgsDistanceArea::areaUnits() const { return willUseEllipsoid() ? QgsUnitTypes::AreaSquareMeters : QgsUnitTypes::distanceToAreaUnit( mCoordTransform.sourceCrs().mapUnits() ); } double QgsDistanceArea::measurePolygon( const QgsCurve *curve ) const { if ( !curve ) { return 0.0; } QgsPointSequence linePointsV2; curve->points( linePointsV2 ); QVector<QgsPointXY> linePoints; QgsGeometry::convertPointList( linePointsV2, linePoints ); return measurePolygon( linePoints ); } double QgsDistanceArea::measurePolygon( const QVector<QgsPointXY> &points ) const { try { if ( willUseEllipsoid() ) { QVector<QgsPointXY> pts; for ( QVector<QgsPointXY>::const_iterator i = points.constBegin(); i != points.constEnd(); ++i ) { pts.append( mCoordTransform.transform( *i ) ); } return computePolygonArea( pts ); } else { return computePolygonArea( points ); } } catch ( QgsCsException &cse ) { Q_UNUSED( cse ); QgsMessageLog::logMessage( QObject::tr( "Caught a coordinate system exception while trying to transform a point. Unable to calculate polygon area." ) ); return 0.0; } } double QgsDistanceArea::bearing( const QgsPointXY &p1, const QgsPointXY &p2 ) const { QgsPointXY pp1 = p1, pp2 = p2; double bearing; if ( willUseEllipsoid() ) { pp1 = mCoordTransform.transform( p1 ); pp2 = mCoordTransform.transform( p2 ); computeDistanceBearing( pp1, pp2, &bearing ); } else //compute simple planar azimuth { double dx = p2.x() - p1.x(); double dy = p2.y() - p1.y(); bearing = std::atan2( dx, dy ); } return bearing; } /////////////////////////////////////////////////////////// // distance calculation double QgsDistanceArea::computeDistanceBearing( const QgsPointXY &p1, const QgsPointXY &p2, double *course1, double *course2 ) const { if ( qgsDoubleNear( p1.x(), p2.x() ) && qgsDoubleNear( p1.y(), p2.y() ) ) return 0; // ellipsoid double a = mSemiMajor; double b = mSemiMinor; double f = 1 / mInvFlattening; double p1_lat = DEG2RAD( p1.y() ), p1_lon = DEG2RAD( p1.x() ); double p2_lat = DEG2RAD( p2.y() ), p2_lon = DEG2RAD( p2.x() ); double L = p2_lon - p1_lon; double U1 = std::atan( ( 1 - f ) * std::tan( p1_lat ) ); double U2 = std::atan( ( 1 - f ) * std::tan( p2_lat ) ); double sinU1 = std::sin( U1 ), cosU1 = std::cos( U1 ); double sinU2 = std::sin( U2 ), cosU2 = std::cos( U2 ); double lambda = L; double lambdaP = 2 * M_PI; double sinLambda = 0; double cosLambda = 0; double sinSigma = 0; double cosSigma = 0; double sigma = 0; double alpha = 0; double cosSqAlpha = 0; double cos2SigmaM = 0; double C = 0; double tu1 = 0; double tu2 = 0; int iterLimit = 20; while ( std::fabs( lambda - lambdaP ) > 1e-12 && --iterLimit > 0 ) { sinLambda = std::sin( lambda ); cosLambda = std::cos( lambda ); tu1 = ( cosU2 * sinLambda ); tu2 = ( cosU1 * sinU2 - sinU1 * cosU2 * cosLambda ); sinSigma = std::sqrt( tu1 * tu1 + tu2 * tu2 ); cosSigma = sinU1 * sinU2 + cosU1 * cosU2 * cosLambda; sigma = std::atan2( sinSigma, cosSigma ); alpha = std::asin( cosU1 * cosU2 * sinLambda / sinSigma ); cosSqAlpha = std::cos( alpha ) * std::cos( alpha ); cos2SigmaM = cosSigma - 2 * sinU1 * sinU2 / cosSqAlpha; C = f / 16 * cosSqAlpha * ( 4 + f * ( 4 - 3 * cosSqAlpha ) ); lambdaP = lambda; lambda = L + ( 1 - C ) * f * std::sin( alpha ) * ( sigma + C * sinSigma * ( cos2SigmaM + C * cosSigma * ( -1 + 2 * cos2SigmaM * cos2SigmaM ) ) ); } if ( iterLimit == 0 ) return -1; // formula failed to converge double uSq = cosSqAlpha * ( a * a - b * b ) / ( b * b ); double A = 1 + uSq / 16384 * ( 4096 + uSq * ( -768 + uSq * ( 320 - 175 * uSq ) ) ); double B = uSq / 1024 * ( 256 + uSq * ( -128 + uSq * ( 74 - 47 * uSq ) ) ); double deltaSigma = B * sinSigma * ( cos2SigmaM + B / 4 * ( cosSigma * ( -1 + 2 * cos2SigmaM * cos2SigmaM ) - B / 6 * cos2SigmaM * ( -3 + 4 * sinSigma * sinSigma ) * ( -3 + 4 * cos2SigmaM * cos2SigmaM ) ) ); double s = b * A * ( sigma - deltaSigma ); if ( course1 ) { *course1 = std::atan2( tu1, tu2 ); } if ( course2 ) { // PI is added to return azimuth from P2 to P1 *course2 = std::atan2( cosU1 * sinLambda, -sinU1 * cosU2 + cosU1 * sinU2 * cosLambda ) + M_PI; } return s; } /////////////////////////////////////////////////////////// // stuff for measuring areas - copied from GRASS // don't know how does it work, but it's working .) // see G_begin_ellipsoid_polygon_area() in area_poly1.c double QgsDistanceArea::getQ( double x ) const { double sinx, sinx2; sinx = std::sin( x ); sinx2 = sinx * sinx; return sinx * ( 1 + sinx2 * ( m_QA + sinx2 * ( m_QB + sinx2 * m_QC ) ) ); } double QgsDistanceArea::getQbar( double x ) const { double cosx, cosx2; cosx = std::cos( x ); cosx2 = cosx * cosx; return cosx * ( m_QbarA + cosx2 * ( m_QbarB + cosx2 * ( m_QbarC + cosx2 * m_QbarD ) ) ); } void QgsDistanceArea::computeAreaInit() { //don't try to perform calculations if no ellipsoid if ( mEllipsoid == GEO_NONE ) { return; } double a2 = ( mSemiMajor * mSemiMajor ); double e2 = 1 - ( ( mSemiMinor * mSemiMinor ) / a2 ); double e4, e6; m_TwoPI = M_PI + M_PI; e4 = e2 * e2; e6 = e4 * e2; m_AE = a2 * ( 1 - e2 ); m_QA = ( 2.0 / 3.0 ) * e2; m_QB = ( 3.0 / 5.0 ) * e4; m_QC = ( 4.0 / 7.0 ) * e6; m_QbarA = -1.0 - ( 2.0 / 3.0 ) * e2 - ( 3.0 / 5.0 ) * e4 - ( 4.0 / 7.0 ) * e6; m_QbarB = ( 2.0 / 9.0 ) * e2 + ( 2.0 / 5.0 ) * e4 + ( 4.0 / 7.0 ) * e6; m_QbarC = - ( 3.0 / 25.0 ) * e4 - ( 12.0 / 35.0 ) * e6; m_QbarD = ( 4.0 / 49.0 ) * e6; m_Qp = getQ( M_PI_2 ); m_E = 4 * M_PI * m_Qp * m_AE; if ( m_E < 0.0 ) m_E = -m_E; } void QgsDistanceArea::setFromParams( const QgsEllipsoidUtils::EllipsoidParameters &params ) { if ( params.useCustomParameters ) { setEllipsoid( params.semiMajor, params.semiMinor ); } else { mSemiMajor = params.semiMajor; mSemiMinor = params.semiMinor; mInvFlattening = params.inverseFlattening; mCoordTransform.setDestinationCrs( params.crs ); // precalculate some values for area calculations computeAreaInit(); } } double QgsDistanceArea::computePolygonArea( const QVector<QgsPointXY> &points ) const { if ( points.isEmpty() ) { return 0; } // IMPORTANT // don't change anything here without reporting the changes to upstream (GRASS) // let's all be good opensource citizens and share the improvements! double x1, y1, x2, y2, dx, dy; double Qbar1, Qbar2; double area; /* GRASS comment: threshold for dy, should be between 1e-4 and 1e-7 * See relevant discussion at https://trac.osgeo.org/grass/ticket/3369 */ const double thresh = 1e-6; QgsDebugMsgLevel( "Ellipsoid: " + mEllipsoid, 3 ); if ( !willUseEllipsoid() ) { return computePolygonFlatArea( points ); } int n = points.size(); x2 = DEG2RAD( points[n - 1].x() ); y2 = DEG2RAD( points[n - 1].y() ); Qbar2 = getQbar( y2 ); area = 0.0; for ( int i = 0; i < n; i++ ) { x1 = x2; y1 = y2; Qbar1 = Qbar2; x2 = DEG2RAD( points[i].x() ); y2 = DEG2RAD( points[i].y() ); Qbar2 = getQbar( y2 ); if ( x1 > x2 ) while ( x1 - x2 > M_PI ) x2 += m_TwoPI; else if ( x2 > x1 ) while ( x2 - x1 > M_PI ) x1 += m_TwoPI; dx = x2 - x1; dy = y2 - y1; if ( std::fabs( dy ) > thresh ) { /* account for different latitudes y1, y2 */ area += dx * ( m_Qp - ( Qbar2 - Qbar1 ) / dy ); } else { /* latitudes y1, y2 are (nearly) identical */ /* if y2 becomes similar to y1, i.e. y2 -> y1 * Qbar2 - Qbar1 -> 0 and dy -> 0 * (Qbar2 - Qbar1) / dy -> ? * (Qbar2 - Qbar1) / dy should approach Q((y1 + y2) / 2) * Metz 2017 */ area += dx * ( m_Qp - getQ( ( y1 + y2 ) / 2.0 ) ); /* original: * area += dx * getQ( y2 ) - ( dx / dy ) * ( Qbar2 - Qbar1 ); */ } } if ( ( area *= m_AE ) < 0.0 ) area = -area; /* kludge - if polygon circles the south pole the area will be * computed as if it cirlced the north pole. The correction is * the difference between total surface area of the earth and * the "north pole" area. */ if ( area > m_E ) area = m_E; if ( area > m_E / 2 ) area = m_E - area; return area; } double QgsDistanceArea::computePolygonFlatArea( const QVector<QgsPointXY> &points ) const { // Normal plane area calculations. double area = 0.0; int i, size; size = points.size(); // QgsDebugMsg("New area calc, nr of points: " + QString::number(size)); for ( i = 0; i < size; i++ ) { // QgsDebugMsg("Area from point: " + (points[i]).toString(2)); // Using '% size', so that we always end with the starting point // and thus close the polygon. area = area + points[i].x() * points[( i + 1 ) % size].y() - points[( i + 1 ) % size].x() * points[i].y(); } // QgsDebugMsg("Area from point: " + (points[i % size]).toString(2)); area = area / 2.0; return std::fabs( area ); // All areas are positive! } QString QgsDistanceArea::formatDistance( double distance, int decimals, QgsUnitTypes::DistanceUnit unit, bool keepBaseUnit ) { return QgsUnitTypes::formatDistance( distance, decimals, unit, keepBaseUnit ); } QString QgsDistanceArea::formatArea( double area, int decimals, QgsUnitTypes::AreaUnit unit, bool keepBaseUnit ) { return QgsUnitTypes::formatArea( area, decimals, unit, keepBaseUnit ); } double QgsDistanceArea::convertLengthMeasurement( double length, QgsUnitTypes::DistanceUnit toUnits ) const { // get the conversion factor between the specified units QgsUnitTypes::DistanceUnit measureUnits = lengthUnits(); double factorUnits = QgsUnitTypes::fromUnitToUnitFactor( measureUnits, toUnits ); double result = length * factorUnits; QgsDebugMsgLevel( QStringLiteral( "Converted length of %1 %2 to %3 %4" ).arg( length ) .arg( QgsUnitTypes::toString( measureUnits ) ) .arg( result ) .arg( QgsUnitTypes::toString( toUnits ) ), 3 ); return result; } double QgsDistanceArea::convertAreaMeasurement( double area, QgsUnitTypes::AreaUnit toUnits ) const { // get the conversion factor between the specified units QgsUnitTypes::AreaUnit measureUnits = areaUnits(); double factorUnits = QgsUnitTypes::fromUnitToUnitFactor( measureUnits, toUnits ); double result = area * factorUnits; QgsDebugMsgLevel( QStringLiteral( "Converted area of %1 %2 to %3 %4" ).arg( area ) .arg( QgsUnitTypes::toString( measureUnits ) ) .arg( result ) .arg( QgsUnitTypes::toString( toUnits ) ), 3 ); return result; }
31.359281
295
0.594015
[ "geometry", "transform" ]
4faa1155bb9c14536cdff9ba0a390fbb07d32f5a
24,158
cpp
C++
services/winremote/winremote.cpp
emuharemagic/HPCC-Platform
bbd5423b25f6ba2d675521c8917f9ecfa97dace5
[ "Apache-2.0" ]
1
2020-08-01T19:54:56.000Z
2020-08-01T19:54:56.000Z
services/winremote/winremote.cpp
emuharemagic/HPCC-Platform
bbd5423b25f6ba2d675521c8917f9ecfa97dace5
[ "Apache-2.0" ]
null
null
null
services/winremote/winremote.cpp
emuharemagic/HPCC-Platform
bbd5423b25f6ba2d675521c8917f9ecfa97dace5
[ "Apache-2.0" ]
null
null
null
/*############################################################################## HPCC SYSTEMS software Copyright (C) 2012 HPCC Systems. 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. ############################################################################## */ #ifdef _WIN32 // Just to shut up any code-checkers on linux side #pragma warning(disable:4786) #include "win32.hpp" #include "winprocess.hpp" #include "winremote.hpp" #include "jiface.hpp" #include "jstring.hpp" #include "jexcept.hpp" #include "jiter.ipp" #include "jpqueue.hpp" #include "service/svcmsg.hpp" #include "psexec.rh" #include <functional> #include <algorithm> #include <vector> #include "Lm.h" using namespace win32; class StdOutputStream: public CInterface, implements IRemoteOutput { public: IMPLEMENT_IINTERFACE; virtual void write(const char* ip,const char* data) { StringBuffer buf(ip); buf.append(" > "); buf.append(data); fputs(buf.str(),stdout); } } stdOut; extern "C" WINREMOTE_API IRemoteOutput* queryStdout() { return &stdOut; } class StdErrorStream: public CInterface, implements IRemoteOutput { public: IMPLEMENT_IINTERFACE; virtual void write(const char* ip,const char* data) { StringBuffer buf(ip); buf.append(" ! "); buf.append(data); fputs(buf.str(),stderr); } } stdErr; extern "C" WINREMOTE_API IRemoteOutput* queryStderr() { return &stdErr; } class ServiceTask: public CInterface, implements ITask { public: IMPLEMENT_IINTERFACE; ServiceTask(const char* _remote,const char* _user, const char* _pwd): remote(_remote), user(_user), pwd(_pwd), stopped(false) { } int run() { try { checkStopped(); SharePoint ipc(remote,"IPC$",user,pwd); checkStopped(); SharePoint admin(remote,"ADMIN$",user,pwd); remoteConnected(); StringBuffer pipename; pipename.appendf("\\\\%s\\Pipe\\"PSEXECPIPE,remote); File pipe; for(int retry=5;;retry--) { checkStopped(); if(retry<=0) throw Error("Unable to connect/start service"); if(!::WaitNamedPipe(pipename.str(),500)) { DWORD err=::GetLastError(); if(err==ERROR_FILE_NOT_FOUND) { if(!CopySvcExeToRemoteMachine() || !InstallAndStartRemoteService()) { if(!stopped) ::Sleep(500); continue; } } else throw SystemError("Wait pipe failed"); } if(pipe.Open(pipename.str(),GENERIC_READ|GENERIC_WRITE,0,OPEN_EXISTING,FILE_FLAG_WRITE_THROUGH)) { pipe.SetPipeMode(PIPE_READMODE_MESSAGE); break; } else if(::GetLastError()!=ERROR_FILE_NOT_FOUND) throw SystemError("Open pipe failed"); } serviceConnected(pipe); } catch(const Error& e) { reportError(e.GetCode(),e.GetMessage()); } return 0; } bool stop() { stopped=true; return true; } void checkStopped() { if(stopped) throw Error("Cancelled"); } protected: virtual void remoteConnected() {} virtual void serviceConnected(File& pipe) {} virtual void reportError(int code,const char* error) {} bool CopySvcExeToRemoteMachine() { HMODULE hInstance = ::GetModuleHandle("winremote.dll"); // Find the binary file in resources HRSRC hSvcExecutableRes = ::FindResource(hInstance, MAKEINTRESOURCE(IDR_PSEXEC),RT_RCDATA); HGLOBAL hSvcExecutable = ::LoadResource(hInstance, hSvcExecutableRes); LPVOID pSvcExecutable = ::LockResource(hSvcExecutable); if (!pSvcExecutable) throw win32::SystemError("Could not find service executable"); DWORD executableSize = ::SizeofResource(hInstance, hSvcExecutableRes); CHAR targetpath[_MAX_PATH]; _snprintf(targetpath,arraysize(targetpath),"\\\\%s\\ADMIN$\\System32\\%s", remote, PSEXECSVCEXE); targetpath[_MAX_PATH-1]=0; // Copy binary file from resources to \\remote\ADMIN$\System32 File svc(targetpath, GENERIC_WRITE, 0, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL|FILE_FLAG_WRITE_THROUGH); if(!svc) switch(::GetLastError()) { case ERROR_SHARING_VIOLATION: { // NetSessionDel(server,client,NULL); return false; } default: throw win32::SystemError("Could not open service executable"); } checkStopped(); DWORD bytes=svc.Write(pSvcExecutable, executableSize); if(bytes!=executableSize) throw win32::SystemError("Could not copy service executable %d",bytes); ::FlushFileBuffers(svc); return true; } struct ScmHandle { ScmHandle(SC_HANDLE h): handle(h) {} ~ScmHandle() { ::CloseServiceHandle(handle); } operator SC_HANDLE() { return handle; } SC_HANDLE handle; }; struct TempService: public ScmHandle { TempService(SC_HANDLE h): ScmHandle(h) {} ~TempService() { ::DeleteService(handle); } SC_HANDLE operator = (SC_HANDLE h) { if(handle) ::CloseServiceHandle(handle); return handle=h; } }; bool InstallAndStartRemoteService() { checkStopped(); ScmHandle scm(::OpenSCManager(remote, NULL, SC_MANAGER_ALL_ACCESS)); if(!scm) throw win32::SystemError("Could not open remote SCM %s",remote); checkStopped(); // Maybe it's already there and installed, let's try to run TempService svc(::OpenService(scm, SERVICENAME, SERVICE_ALL_ACCESS)); if(!svc && !(svc=::CreateService(scm, SERVICENAME, SERVICEDISPLAYNAME, SERVICE_ALL_ACCESS, SERVICE_WIN32_OWN_PROCESS, SERVICE_DEMAND_START, SERVICE_ERROR_NORMAL, TEXT("%SystemRoot%\\system32\\")PSEXECSVCEXE, NULL, NULL, NULL, NULL, NULL))) { throw win32::SystemError("Could not create remote service %s",remote); } for(;;) { checkStopped(); SERVICE_STATUS status; if(!::QueryServiceStatus(svc,&status)) throw win32::SystemError("Could not query service status"); switch(status.dwCurrentState) { case SERVICE_RUNNING: return true; case SERVICE_STOPPED: if (!::StartService(svc, 0, NULL)) { SystemError e("Could not start remote service %s",remote); throw win32::SystemError(e); } case SERVICE_START_PENDING: ::Sleep(100); continue; case SERVICE_STOP_PENDING: return false; default: throw win32::SystemError("Service state is %d",status.dwCurrentState); } } return false; } StringAttr remote,user,pwd; volatile bool stopped; struct SharePoint { SharePoint(const char* _remote, const char* _share, const char * _user, const char * _pwd) { remote.appendf("\\\\%s\\%s",_remote,_share); NETRESOURCE nr; nr.dwType = RESOURCETYPE_ANY; nr.lpLocalName = NULL; nr.lpRemoteName = (char*)remote.str(); nr.lpProvider = NULL; for(;;) { //Establish connection (using username/pwd) DWORD rc = ::WNetAddConnection2(&nr, _pwd, _user, FALSE); if(rc==NO_ERROR) break; win32::SystemError e("Could not connect"); if(rc==ERROR_SESSION_CREDENTIAL_CONFLICT && ::WNetCancelConnection2((char*)remote.str(), 0, FALSE)==NO_ERROR) continue; throw e; } } ~SharePoint() { ::WNetCancelConnection2((char*)remote.str(), 0, FALSE); } StringBuffer remote; }; }; //typedef WaitQueue<Linked<ServiceTask> > ConnectQueueType; struct RemoteCommand: public CInterface, implements IRemoteCommand { public: IMPLEMENT_IINTERFACE; RemoteCommand(): copyFile(0), priority(NORMAL_PRIORITY_CLASS), session(0), async(true), status(0), pid(0), network(false) { } virtual void setCommand(const char * _command) { command.set(_command); } virtual void setPriority(int _priority) { priority=_priority; } virtual void setCopyFile(bool overwrite) { copyFile= overwrite ? 2 : 1; } virtual void setWorkDirectory(const char * _dir) { dir.set(_dir); } virtual void setSession(int _session) { session=_session; } virtual void setOutputStream(IRemoteOutput * _out) { out.set(_out); async=false; } virtual void setErrorStream(IRemoteOutput * _err) { err.set(_err); } virtual int getErrorStatus() const { return status; } virtual int getPid() const { return pid; } virtual void setNetworkLogon(bool set) { network=set; } StringAttr command, dir; int priority; int copyFile; int session; bool async; bool network; Linked<IRemoteOutput> out,err; int status; int pid; }; interface ITaskListener { virtual void startIO(const char* machine,DWORD pid,HANDLE in,IRemoteOutput* out,IRemoteOutput* err)=0; }; class ConnectTask: public ServiceTask { public: ConnectTask(const char* _remote,const char* _user, const char* _pwd,RemoteCommand* _cmd,ITaskListener* _tl): ServiceTask(_remote, _user, _pwd), cmd(_cmd), tl(_tl) { } protected: virtual void remoteConnected() { if(cmd->copyFile) copy(cmd->command,cmd->copyFile>1); } virtual void serviceConnected(File& pipe) { CmdMessage cmdmsg("EXEC",cmd->network ? user : NULL,cmd->network ? pwd : NULL); if(pipe.Write(&cmdmsg,sizeof(cmdmsg))!=sizeof(cmdmsg)) throw win32::SystemError("Could not talk to the server"); ExecMessage msg(cmd->command,cmd->dir,cmd->async ? ExecMessage::NoWait : 0, cmd->priority,cmd->session); ExecResult ret; if(pipe.Transact(&msg,sizeof(msg),&ret,sizeof(ret))!=sizeof(ret)) throw win32::SystemError("Could not talk to the server"); if(ret.err!=ERROR_SUCCESS) throw win32::Error("Server returned error %d",ret.err); checkStopped(); if(msg.IsNoWait()) { cmd->pid=ret.pid; } else { CHAR buf[MAX_PATH]; File pipeout(cmdmsg.GetStdout(buf,arraysize(buf),remote),GENERIC_READ,0,OPEN_EXISTING,FILE_FLAG_OVERLAPPED); if(!pipeout) throw win32::SystemError("Could not connect to STDOUT"); File pipeerr(cmdmsg.GetStderr(buf,arraysize(buf),remote),GENERIC_READ,0,OPEN_EXISTING,FILE_FLAG_OVERLAPPED); if(!pipeerr) throw win32::SystemError("Could not connect to STERR"); File pipein(cmdmsg.GetStdin(buf,arraysize(buf),remote),GENERIC_WRITE,0,OPEN_EXISTING,FILE_FLAG_WRITE_THROUGH); if(!pipein) throw win32::SystemError("Could not connect to STDIN"); DWORD status=ERROR_SUCCESS; if(pipe.Transact(&status,sizeof(status),&ret,sizeof(ret))!=sizeof(ret)) throw win32::SystemError("Could not talk to the server"); if(ret.err!=ERROR_SUCCESS) throw win32::SystemError("Server returned error %d",ret.err); cmd->pid=ret.pid; if(tl) { if(cmd->out) tl->startIO(remote,ret.pid,pipeout.get(),cmd->out,cmd->err); if(cmd->err) tl->startIO(remote,ret.pid,pipeerr.get(),cmd->err,cmd->err); } } } virtual void reportError(int code,const char* error) { if(!cmd) return; cmd->status=code; if(cmd->err) { cmd->err->write(remote,error); } } void copy(const char* cmd,bool overwrite) { #ifdef _UNICODE LPWSTR * wcmd=cmd; #else size32_t cmdsize=strlen(cmd)+1; LPWSTR wcmd=(LPWSTR)_alloca(sizeof(WCHAR)*cmdsize); mbstowcs(wcmd,cmd,cmdsize); #endif WCHAR imagepath[_MAX_PATH]={0}; int numargs=0; LPWSTR * args=::CommandLineToArgvW(wcmd,&numargs); if(args) { if(numargs>0) { ::SearchPathW(NULL,args[0],L".exe",arraysize(imagepath),imagepath,NULL); } ::GlobalFree(args); } if(!*imagepath) throw win32::SystemError("Could not find file %s",cmd); WCHAR drive[_MAX_DRIVE]; WCHAR dir[_MAX_DIR]; WCHAR fname[_MAX_FNAME]; WCHAR ext[_MAX_EXT]; // Gets the file name and extension _wsplitpath(imagepath, drive, dir, fname, ext); WCHAR targetpath[_MAX_PATH]; _snwprintf(targetpath,arraysize(targetpath),L"\\\\%S\\ADMIN$\\System32\\%s%s", remote, fname, ext); targetpath[_MAX_PATH-1]=0; // Copy the Command's exe file to \\remote\ADMIN$\System32 if(!::CopyFileW(imagepath, targetpath, overwrite ? FALSE:TRUE) && ::GetLastError()!=ERROR_FILE_EXISTS) throw win32::SystemError("Could not copy file %S to %S",imagepath,targetpath); } private: Linked<RemoteCommand> cmd; ITaskListener* tl; }; interface ITaskOutput { virtual void write(const char* machine,const char* data,size32_t len)=0; }; class OutputTask: public CInterface, implements ITask { public: IMPLEMENT_IINTERFACE; OutputTask(const char* _remote,HANDLE _input,IRemoteOutput* _output,IRemoteOutput* _err): remote(_remote), output(_output), err(_err) { input.set(_input); } int run() { thread=Handle(::GetCurrentThread(),THREAD_ALL_ACCESS).get(); try { StringBuffer sb; char buf[4096]; for(;input;) { OVERLAPPED ovl={0}; if(!input.Read(buf,sizeof(buf),&ovl)) { switch(::GetLastError()) { case ERROR_IO_PENDING: break; case ERROR_HANDLE_EOF: case ERROR_BROKEN_PIPE: case ERROR_OPERATION_ABORTED: input.Close(); continue; default: throw win32::SystemError("Read pipe"); } } DWORD ret=input.Wait(INFINITE,true); switch(ret) { case WAIT_OBJECT_0: { size32_t count=input.GetResult(&ovl,false); if(count) { char *b; char *endl; for(b=buf;endl=(char*)memchr(b,'\n',count-(b-buf));b=endl+1) { size32_t sz=endl-b+1; print("%s%.*s",sb.str(),sz,b); sb.clear(); } sb.append(count-(b-buf),b); } else { switch(::GetLastError()) { case ERROR_IO_PENDING: continue; case ERROR_HANDLE_EOF: case ERROR_BROKEN_PIPE: case ERROR_OPERATION_ABORTED: input.Close(); continue; default: throw win32::SystemError("Read pipe"); } } break; } case WAIT_IO_COMPLETION: input.Close(); continue; default: throw win32::SystemError("Wait"); } } if(sb.length()) print("%s\n",sb.str()); } catch(win32::Error& e) { if(err) err->write(remote,e.GetMessage()); } catch(...) { if(err) err->write(remote,"Unknown Error"); } return 0; } bool stop() { return ::QueueUserAPC(StopProc,thread,(ULONG_PTR)(HANDLE)input)!=0; } protected: void print(const char* format,...) __attribute__((format(printf, 2, 3))) { if(!output) return; StringBuffer buf; va_list marker; va_start(marker,format); buf.valist_appendf(format,marker); va_end(marker); output->write(remote,buf.str()); } StringAttr remote; File input; Linked<IRemoteOutput> output,err; HANDLE thread; static VOID CALLBACK StopProc(ULONG_PTR param) { HANDLE h=(HANDLE)param; ::CancelIo(h); ::CloseHandle(h); } }; interface IProcessList { virtual void add(const char* machine,int pid,int parent,int session,const wchar_t* app,const wchar_t* cmd,const wchar_t* dir)=0; }; class ListTask: public ServiceTask { public: ListTask(const char* _remote,const char* _user, const char* _pwd,const char* _path,IProcessList* _pl,IRemoteOutput* _err): ServiceTask(_remote, _user, _pwd), path(_path), pl(_pl), err(_err) { } virtual void serviceConnected(File& pipe) { CmdMessage cmdmsg("LIST",user,pwd); if(pipe.Write(&cmdmsg,sizeof(cmdmsg))!=sizeof(cmdmsg)) throw win32::SystemError("Could not talk to the server"); ListMessage msg(path); if(pipe.Write(&msg,sizeof(msg))!=sizeof(msg)) throw win32::SystemError("Could not talk to the server"); for(;;) { ListResult ret; if(pipe.Read(&ret,sizeof(ret))==sizeof(ret)) { if(pl) { pl->add(remote,ret.GetPid(),ret.GetParent(),ret.GetSession(),ret.GetAppName(),ret.GetCommandLine(),ret.GetWorkingDir()); } } else { break; } } } virtual void reportError(int code,const char* error) { if(err) err->write(remote,error); } private: StringAttr path; IProcessList* pl; Linked<IRemoteOutput> err; }; class CProcess: public CInterface, implements IRemoteProcess { public: IMPLEMENT_IINTERFACE; CProcess(const char* _machine,int _pid,int _parent,int _session,const wchar_t* _app,const wchar_t* _cmd,const wchar_t* _dir): remote(_machine), pid(_pid), parent(_parent), session(_session) { wcstombs(app,_app,arraysize(app)); wcstombs(cmd,_cmd,arraysize(cmd)); wcstombs(dir,_dir,arraysize(dir)); } virtual int getPid() const { return pid; } virtual int getParent() const { return parent; } virtual int getSession() const { return session; } virtual IStringVal& getMachine(IStringVal & val) const { val.set(remote); return val; } virtual IStringVal& getApplicationName(IStringVal& val) const { val.set(app); return val; } virtual IStringVal& getCommandLine(IStringVal& val) const { val.set(cmd); return val; } virtual IStringVal& getCurrentDirectory(IStringVal& val) const { val.set(dir); return val; } private: StringAttr remote; int pid, parent, session; char app[MAX_PATH], cmd[MAX_COMMAND], dir[MAX_PATH]; }; class CProcessArray: public Array, implements IProcessList { virtual void add(const char* machine,int pid,int parent,int session,const wchar_t* app,const wchar_t* cmd,const wchar_t* dir) { CProcess* proc=new CProcess(machine,pid,parent,session,app,cmd,dir); synchronized block(mutex); append(*proc); } Mutex mutex; }; class CProcessIterator: public CArrayIteratorOf<IRemoteProcess,IRemoteProcessIterator> { public: CProcessIterator(CProcessArray *_values) : CArrayIteratorOf<IRemoteProcess,IRemoteProcessIterator>(*_values,0), values(_values) {} ~CProcessIterator() { delete values; } CProcessArray* values; }; class RemoteAgent: public CInterface, implements IRemoteAgent, implements ITaskListener { public: IMPLEMENT_IINTERFACE; RemoteAgent(): connect(20), io(400) { } virtual void addMachine(const char * machine, const char * user, const char * pwd) { machines.push_back(MachineInfo(machine,user,pwd)); } virtual void startCommand(IRemoteCommand * _cmd) { RemoteCommand* cmd=dynamic_cast<RemoteCommand*>(_cmd); if(!cmd) return; //more for(Machines it=machines.begin();it!=machines.end();it++) { connect.put(new ConnectTask(it->machine,it->user,it->password,cmd,this)); } } virtual IRemoteProcessIterator * getProcessList(const char * path, IRemoteOutput* _err) { TaskQueue list(20); CProcessArray* a=new CProcessArray(); for(Machines it=machines.begin();it!=machines.end();it++) { list.put(new ListTask(it->machine,it->user,it->password,path,a,_err)); } return new CProcessIterator(a); } virtual void stop() { connect.stop(); io.stop(); } virtual void wait() { connect.join(); io.join(); } virtual void startIO(const char* machine,DWORD pid,HANDLE in,IRemoteOutput* out,IRemoteOutput* err) { io.put(new OutputTask(machine,in,out,err)); } struct MachineInfo { MachineInfo(const char* _machine,const char* _user,const char* _password): machine(_machine), user(_user), password(_password) {} StringAttr machine,user,password; }; std::list<MachineInfo> machines; typedef std::list<MachineInfo>::iterator Machines; TaskQueue connect, io; }; extern "C" WINREMOTE_API IRemoteCommand* createRemoteCommand() { return new RemoteCommand(); } extern "C" WINREMOTE_API IRemoteAgent* createRemoteAgent() { return new RemoteAgent(); } BOOL APIENTRY DllMain(HANDLE,DWORD,LPVOID) { return TRUE; } #endif
26.902004
157
0.548638
[ "vector" ]
4fae1d6ee95e3cc3a54deca24f3b420f6644b172
157,796
cpp
C++
mp/src/game/server/sceneentity.cpp
Code4Cookie/Atomic-Secobmod
9738d91bc37f8d9e9fb63d4a444ecbeaa0e0cf70
[ "Unlicense" ]
3
2016-06-23T16:09:35.000Z
2017-02-22T21:57:56.000Z
mp/src/game/server/sceneentity.cpp
Code4Cookie/Atomic-Secobmod
9738d91bc37f8d9e9fb63d4a444ecbeaa0e0cf70
[ "Unlicense" ]
null
null
null
mp/src/game/server/sceneentity.cpp
Code4Cookie/Atomic-Secobmod
9738d91bc37f8d9e9fb63d4a444ecbeaa0e0cf70
[ "Unlicense" ]
2
2018-04-17T22:57:35.000Z
2021-07-07T14:26:19.000Z
//========= Copyright Valve Corporation, All rights reserved. ============// // // Purpose: // //=============================================================================// #include "cbase.h" #include <stdarg.h> #include "baseflex.h" #include "entitylist.h" #include "choreoevent.h" #include "choreoactor.h" #include "choreochannel.h" #include "choreoscene.h" #include "studio.h" #include "networkstringtable_gamedll.h" #include "ai_basenpc.h" #include "engine/IEngineSound.h" #include "ai_navigator.h" #include "saverestore_utlvector.h" #include "ai_baseactor.h" #include "AI_Criteria.h" #include "tier1/strtools.h" #include "checksum_crc.h" #include "SoundEmitterSystem/isoundemittersystembase.h" #include "utlbuffer.h" #include "tier0/icommandline.h" #include "sceneentity.h" #include "datacache/idatacache.h" #include "dt_utlvector_send.h" #include "ichoreoeventcallback.h" #include "scenefilecache/ISceneFileCache.h" #include "SceneCache.h" #include "scripted.h" #include "env_debughistory.h" #ifdef HL2_EPISODIC #include "npc_alyx_episodic.h" #endif // HL2_EPISODIC // memdbgon must be the last include file in a .cpp file!!! #include "tier0/memdbgon.h" extern ISoundEmitterSystemBase *soundemitterbase; extern ISceneFileCache *scenefilecache; class CSceneEntity; class CBaseFlex; // VCDS are loaded from their compiled/binary format (much faster) // Requies vcds be saved as compiled assets //#define COMPILED_VCDS 1 static ConVar scene_forcecombined( "scene_forcecombined", "0", 0, "When playing back, force use of combined .wav files even in english." ); static ConVar scene_maxcaptionradius( "scene_maxcaptionradius", "1200", 0, "Only show closed captions if recipient is within this many units of speaking actor (0==disabled)." ); // Assume sound system is 100 msec lagged (only used if we can't find snd_mixahead cvar!) #define SOUND_SYSTEM_LATENCY_DEFAULT ( 0.1f ) // Think every 50 msec (FIXME: Try 10hz?) #define SCENE_THINK_INTERVAL 0.001 // FIXME: make scene's think in concert with their npc's #define FINDNAMEDENTITY_MAX_ENTITIES 32 // max number of entities to be considered for random entity selection in FindNamedEntity // List of the last 5 lines of speech from NPCs for bug reports static recentNPCSpeech_t speechListSounds[ SPEECH_LIST_MAX_SOUNDS ] = { { 0, "", "" }, { 0, "", "" }, { 0, "", "" }, { 0, "", "" }, { 0, "", "" } }; static int speechListIndex = 0; // Only allow scenes to change their pitch within a range of values #define SCENE_MIN_PITCH 0.25f #define SCENE_MAX_PITCH 2.5f //=========================================================================================================== // SCENE LIST MANAGER //=========================================================================================================== #define SCENE_LIST_MANAGER_MAX_SCENES 16 //----------------------------------------------------------------------------- // Purpose: Entity that manages a list of scenes //----------------------------------------------------------------------------- class CSceneListManager : public CLogicalEntity { DECLARE_CLASS( CSceneListManager, CLogicalEntity ); public: DECLARE_DATADESC(); virtual void Activate( void ); void ShutdownList( void ); void SceneStarted( CBaseEntity *pSceneOrManager ); void AddListManager( CSceneListManager *pManager ); void RemoveScene( int iIndex ); // Inputs void InputShutdown( inputdata_t &inputdata ); private: CUtlVector< CHandle< CSceneListManager > > m_hListManagers; string_t m_iszScenes[SCENE_LIST_MANAGER_MAX_SCENES]; EHANDLE m_hScenes[SCENE_LIST_MANAGER_MAX_SCENES]; }; //----------------------------------------------------------------------------- // Purpose: This class exists solely to call think on all scene entities in a deterministic order //----------------------------------------------------------------------------- class CSceneManager : public CBaseEntity { DECLARE_CLASS( CSceneManager, CBaseEntity ); DECLARE_DATADESC(); public: virtual void Spawn() { BaseClass::Spawn(); SetNextThink( gpGlobals->curtime ); } virtual int ObjectCaps( void ) { return BaseClass::ObjectCaps() | FCAP_DONT_SAVE; } virtual void Think(); void ClearAllScenes(); void AddSceneEntity( CSceneEntity *scene ); void RemoveSceneEntity( CSceneEntity *scene ); void QueueRestoredSound( CBaseFlex *actor, char const *soundname, soundlevel_t soundlevel, float time_in_past ); void OnClientActive( CBasePlayer *player ); void RemoveActorFromScenes( CBaseFlex *pActor, bool bInstancedOnly, bool bNonIdleOnly, const char *pszThisSceneOnly ); void RemoveScenesInvolvingActor( CBaseFlex *pActor ); void PauseActorsScenes( CBaseFlex *pActor, bool bInstancedOnly ); bool IsInInterruptableScenes( CBaseFlex *pActor ); void ResumeActorsScenes( CBaseFlex *pActor, bool bInstancedOnly ); void QueueActorsScenesToResume( CBaseFlex *pActor, bool bInstancedOnly ); bool IsRunningScriptedScene( CBaseFlex *pActor, bool bIgnoreInstancedScenes ); bool IsRunningScriptedSceneAndNotPaused( CBaseFlex *pActor, bool bIgnoreInstancedScenes ); bool IsRunningScriptedSceneWithSpeech( CBaseFlex *pActor, bool bIgnoreInstancedScenes ); bool IsRunningScriptedSceneWithSpeechAndNotPaused( CBaseFlex *pActor, bool bIgnoreInstancedScenes ); private: struct CRestoreSceneSound { CRestoreSceneSound() { actor = NULL; soundname[ 0 ] = NULL; soundlevel = SNDLVL_NORM; time_in_past = 0.0f; } CHandle< CBaseFlex > actor; char soundname[ 128 ]; soundlevel_t soundlevel; float time_in_past; }; CUtlVector< CHandle< CSceneEntity > > m_ActiveScenes; CUtlVector< CRestoreSceneSound > m_QueuedSceneSounds; }; //--------------------------------------------------------- // Save/Restore //--------------------------------------------------------- BEGIN_DATADESC( CSceneManager ) DEFINE_UTLVECTOR( m_ActiveScenes, FIELD_EHANDLE ), // DEFINE_FIELD( m_QueuedSceneSounds, CUtlVector < CRestoreSceneSound > ), // Don't save/restore this, it's created and used by OnRestore only END_DATADESC() #ifdef DISABLE_DEBUG_HISTORY #define LocalScene_Printf Scene_Printf #else //----------------------------------------------------------------------------- // Purpose: // Input : *pFormat - // ... - // Output : static void //----------------------------------------------------------------------------- void LocalScene_Printf( const char *pFormat, ... ) { va_list marker; char msg[8192]; va_start(marker, pFormat); Q_vsnprintf(msg, sizeof(msg), pFormat, marker); va_end(marker); Scene_Printf( "%s", msg ); ADD_DEBUG_HISTORY( HISTORY_SCENE_PRINT, UTIL_VarArgs( "(%0.2f) %s", gpGlobals->curtime, msg ) ); } #endif //----------------------------------------------------------------------------- // Purpose: // Input : *filename - // **buffer - // Output : Returns true on success, false on failure. //----------------------------------------------------------------------------- bool CopySceneFileIntoMemory( char const *pFilename, void **pBuffer, int *pSize ) { size_t bufSize = scenefilecache->GetSceneBufferSize( pFilename ); if ( bufSize > 0 ) { *pBuffer = new byte[bufSize]; *pSize = bufSize; return scenefilecache->GetSceneData( pFilename, (byte *)(*pBuffer), bufSize ); } *pBuffer = 0; *pSize = 0; return false; } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void FreeSceneFileMemory( void *buffer ) { delete[] (byte*) buffer; } //----------------------------------------------------------------------------- // Binary compiled VCDs get their strings from a pool //----------------------------------------------------------------------------- class CChoreoStringPool : public IChoreoStringPool { public: short FindOrAddString( const char *pString ) { // huh?, no compilation at run time, only fetches Assert( 0 ); return -1; } bool GetString( short stringId, char *buff, int buffSize ) { // fetch from compiled pool const char *pString = scenefilecache->GetSceneString( stringId ); if ( !pString ) { V_strncpy( buff, "", buffSize ); return false; } V_strncpy( buff, pString, buffSize ); return true; } }; CChoreoStringPool g_ChoreoStringPool; //----------------------------------------------------------------------------- // Purpose: Singleton scene manager. Created by first placed scene or recreated it it's deleted for some unknown reason // Output : CSceneManager //----------------------------------------------------------------------------- CSceneManager *GetSceneManager() { // Create it if it doesn't exist static CHandle< CSceneManager > s_SceneManager; if ( s_SceneManager == NULL ) { s_SceneManager = ( CSceneManager * )CreateEntityByName( "scene_manager" ); Assert( s_SceneManager ); if ( s_SceneManager ) { s_SceneManager->Spawn(); } } Assert( s_SceneManager ); return s_SceneManager; } //----------------------------------------------------------------------------- // Purpose: // Input : *player - //----------------------------------------------------------------------------- void SceneManager_ClientActive( CBasePlayer *player ) { Assert( GetSceneManager() ); if ( GetSceneManager() ) { GetSceneManager()->OnClientActive( player ); } } //----------------------------------------------------------------------------- // Purpose: FIXME, need to deal with save/restore //----------------------------------------------------------------------------- class CSceneEntity : public CPointEntity, public IChoreoEventCallback { friend class CInstancedSceneEntity; public: enum { SCENE_ACTION_UNKNOWN = 0, SCENE_ACTION_CANCEL, SCENE_ACTION_RESUME, }; enum { SCENE_BUSYACTOR_DEFAULT = 0, SCENE_BUSYACTOR_WAIT, SCENE_BUSYACTOR_INTERRUPT, SCENE_BUSYACTOR_INTERRUPT_CANCEL, }; DECLARE_CLASS( CSceneEntity, CPointEntity ); DECLARE_SERVERCLASS(); CSceneEntity( void ); ~CSceneEntity( void ); // From IChoreoEventCallback virtual void StartEvent( float currenttime, CChoreoScene *scene, CChoreoEvent *event ); virtual void EndEvent( float currenttime, CChoreoScene *scene, CChoreoEvent *event ); virtual void ProcessEvent( float currenttime, CChoreoScene *scene, CChoreoEvent *event ); virtual bool CheckEvent( float currenttime, CChoreoScene *scene, CChoreoEvent *event ); virtual int UpdateTransmitState(); virtual int ShouldTransmit( const CCheckTransmitInfo *pInfo ); void SetRecipientFilter( IRecipientFilter *filter ); virtual void Activate(); virtual void Precache( void ); virtual void Spawn( void ); virtual void UpdateOnRemove( void ); virtual void OnRestore(); virtual void OnLoaded(); DECLARE_DATADESC(); virtual void OnSceneFinished( bool canceled, bool fireoutput ); virtual void DoThink( float frametime ); virtual void PauseThink( void ); bool IsPlayingBack() const { return m_bIsPlayingBack; } bool IsPaused() const { return m_bPaused; } bool IsMultiplayer() const { return m_bMultiplayer; } bool IsInterruptable(); virtual void ClearInterrupt(); virtual void CheckInterruptCompletion(); virtual bool InterruptThisScene( CSceneEntity *otherScene ); void RequestCompletionNotification( CSceneEntity *otherScene ); virtual void NotifyOfCompletion( CSceneEntity *interruptor ); void AddListManager( CSceneListManager *pManager ); void ClearActivatorTargets( void ); void SetBreakOnNonIdle( bool bBreakOnNonIdle ) { m_bBreakOnNonIdle = bBreakOnNonIdle; } bool ShouldBreakOnNonIdle( void ) { return m_bBreakOnNonIdle; } // Inputs void InputStartPlayback( inputdata_t &inputdata ); void InputPausePlayback( inputdata_t &inputdata ); void InputResumePlayback( inputdata_t &inputdata ); void InputCancelPlayback( inputdata_t &inputdata ); void InputCancelAtNextInterrupt( inputdata_t &inputdata ); void InputPitchShiftPlayback( inputdata_t &inputdata ); void InputTriggerEvent( inputdata_t &inputdata ); // If the scene is playing, finds an actor in the scene who can respond to the specified concept token void InputInterjectResponse( inputdata_t &inputdata ); // If this scene is waiting on an actor, give up and quit trying. void InputStopWaitingForActor( inputdata_t &inputdata ); virtual void StartPlayback( void ); virtual void PausePlayback( void ); virtual void ResumePlayback( void ); virtual void CancelPlayback( void ); virtual void PitchShiftPlayback( float fPitch ); virtual void QueueResumePlayback( void ); bool ValidScene() const; // Scene load/unload static CChoreoScene *LoadScene( const char *filename, IChoreoEventCallback *pCallback ); void UnloadScene( void ); struct SpeakEventSound_t { CUtlSymbol m_Symbol; float m_flStartTime; }; static bool SpeakEventSoundLessFunc( const SpeakEventSound_t& lhs, const SpeakEventSound_t& rhs ); bool GetSoundNameForPlayer( CChoreoEvent *event, CBasePlayer *player, char *buf, size_t buflen, CBaseEntity *pActor ); void BuildSortedSpeakEventSoundsPrefetchList( CChoreoScene *scene, CUtlSymbolTable& table, CUtlRBTree< SpeakEventSound_t >& soundnames, float timeOffset ); void PrefetchSpeakEventSounds( CUtlSymbolTable& table, CUtlRBTree< SpeakEventSound_t >& soundnames ); // Event handlers virtual void DispatchStartExpression( CChoreoScene *scene, CBaseFlex *actor, CChoreoEvent *event ); virtual void DispatchEndExpression( CChoreoScene *scene, CBaseFlex *actor, CChoreoEvent *event ); virtual void DispatchStartFlexAnimation( CChoreoScene *scene, CBaseFlex *actor, CChoreoEvent *event ); virtual void DispatchEndFlexAnimation( CChoreoScene *scene, CBaseFlex *actor, CChoreoEvent *event ); virtual void DispatchStartGesture( CChoreoScene *scene, CBaseFlex *actor, CChoreoEvent *event ); virtual void DispatchEndGesture( CChoreoScene *scene, CBaseFlex *actor, CChoreoEvent *event ); virtual void DispatchStartLookAt( CChoreoScene *scene, CBaseFlex *actor, CBaseEntity *actor2, CChoreoEvent *event ); virtual void DispatchEndLookAt( CChoreoScene *scene, CBaseFlex *actor, CChoreoEvent *event ); virtual void DispatchStartMoveTo( CChoreoScene *scene, CBaseFlex *actor, CBaseEntity *actor2, CChoreoEvent *event ); virtual void DispatchEndMoveTo( CChoreoScene *scene, CBaseFlex *actor, CChoreoEvent *event ); virtual void DispatchStartSpeak( CChoreoScene *scene, CBaseFlex *actor, CChoreoEvent *event, soundlevel_t iSoundlevel ); virtual void DispatchEndSpeak( CChoreoScene *scene, CBaseFlex *actor, CChoreoEvent *event ); virtual void DispatchStartFace( CChoreoScene *scene, CBaseFlex *actor, CBaseEntity *actor2, CChoreoEvent *event ); virtual void DispatchEndFace( CChoreoScene *scene, CBaseFlex *actor, CChoreoEvent *event ); virtual void DispatchStartSequence( CChoreoScene *scene, CBaseFlex *actor, CChoreoEvent *event ); virtual void DispatchEndSequence( CChoreoScene *scene, CBaseFlex *actor, CChoreoEvent *event ); virtual void DispatchStartSubScene( CChoreoScene *scene, CBaseFlex *actor, CChoreoEvent *event ); virtual void DispatchStartInterrupt( CChoreoScene *scene, CChoreoEvent *event ); virtual void DispatchEndInterrupt( CChoreoScene *scene, CChoreoEvent *event ); virtual void DispatchStartGeneric( CChoreoScene *scene, CBaseFlex *actor, CChoreoEvent *event ); virtual void DispatchEndGeneric( CChoreoScene *scene, CBaseFlex *actor, CChoreoEvent *event ); // NPC can play interstitial vcds (such as responding to the player doing something during a scene) virtual void DispatchStartPermitResponses( CChoreoScene *scene, CBaseFlex *actor, CChoreoEvent *event ); virtual void DispatchEndPermitResponses( CChoreoScene *scene, CBaseFlex *actor, CChoreoEvent *event ); // Global events virtual void DispatchProcessLoop( CChoreoScene *scene, CChoreoEvent *event ); virtual void DispatchPauseScene( CChoreoScene *scene, const char *parameters ); virtual void DispatchStopPoint( CChoreoScene *scene, const char *parameters ); virtual float EstimateLength( void ); void CancelIfSceneInvolvesActor( CBaseEntity *pActor ); bool InvolvesActor( CBaseEntity *pActor ); // NOTE: returns false if scene hasn't loaded yet void GenerateSoundScene( CBaseFlex *pActor, const char *soundname ); virtual float GetPostSpeakDelay() { return 1.0; } bool HasUnplayedSpeech( void ); bool HasFlexAnimation( void ); void SetCurrentTime( float t, bool forceClientSync ); void InputScriptPlayerDeath( inputdata_t &inputdata ); // Data public: string_t m_iszSceneFile; string_t m_iszResumeSceneFile; EHANDLE m_hWaitingForThisResumeScene; bool m_bWaitingForResumeScene; string_t m_iszTarget1; string_t m_iszTarget2; string_t m_iszTarget3; string_t m_iszTarget4; string_t m_iszTarget5; string_t m_iszTarget6; string_t m_iszTarget7; string_t m_iszTarget8; EHANDLE m_hTarget1; EHANDLE m_hTarget2; EHANDLE m_hTarget3; EHANDLE m_hTarget4; EHANDLE m_hTarget5; EHANDLE m_hTarget6; EHANDLE m_hTarget7; EHANDLE m_hTarget8; CNetworkVar( bool, m_bIsPlayingBack ); CNetworkVar( bool, m_bPaused ); CNetworkVar( bool, m_bMultiplayer ); CNetworkVar( float, m_flForceClientTime ); float m_flCurrentTime; float m_flFrameTime; bool m_bCancelAtNextInterrupt; float m_fPitch; bool m_bAutomated; int m_nAutomatedAction; float m_flAutomationDelay; float m_flAutomationTime; // A pause from an input requires another input to unpause (it's a hard pause) bool m_bPausedViaInput; // Waiting for the actor to be able to speak. bool m_bWaitingForActor; // Waiting for a point at which we can interrupt our actors bool m_bWaitingForInterrupt; bool m_bInterruptedActorsScenes; bool m_bBreakOnNonIdle; public: virtual CBaseFlex *FindNamedActor( int index ); virtual CBaseFlex *FindNamedActor( CChoreoActor *pChoreoActor ); virtual CBaseFlex *FindNamedActor( const char *name ); virtual CBaseEntity *FindNamedEntity( const char *name, CBaseEntity *pActor = NULL, bool bBaseFlexOnly = false, bool bUseClear = false ); CBaseEntity *FindNamedTarget( string_t iszTarget, bool bBaseFlexOnly = false ); virtual CBaseEntity *FindNamedEntityClosest( const char *name, CBaseEntity *pActor = NULL, bool bBaseFlexOnly = false, bool bUseClear = false, const char *pszSecondary = NULL ); private: CUtlVector< CHandle< CBaseFlex > > m_hActorList; CUtlVector< CHandle< CBaseEntity > > m_hRemoveActorList; private: inline void SetRestoring( bool bRestoring ); // Prevent derived classed from using this! virtual void Think( void ) {}; void ClearSceneEvents( CChoreoScene *scene, bool canceled ); void ClearSchedules( CChoreoScene *scene ); float GetSoundSystemLatency( void ); void PrecacheScene( CChoreoScene *scene ); CChoreoScene *GenerateSceneForSound( CBaseFlex *pFlexActor, const char *soundname ); bool CheckActors(); void PrefetchAnimBlocks( CChoreoScene *scene ); bool ShouldNetwork() const; // Set if we tried to async the scene but the FS returned that the data was not loadable bool m_bSceneMissing; CChoreoScene *m_pScene; CNetworkVar( int, m_nSceneStringIndex ); static const ConVar *m_pcvSndMixahead; COutputEvent m_OnStart; COutputEvent m_OnCompletion; COutputEvent m_OnCanceled; COutputEvent m_OnTrigger1; COutputEvent m_OnTrigger2; COutputEvent m_OnTrigger3; COutputEvent m_OnTrigger4; COutputEvent m_OnTrigger5; COutputEvent m_OnTrigger6; COutputEvent m_OnTrigger7; COutputEvent m_OnTrigger8; COutputEvent m_OnTrigger9; COutputEvent m_OnTrigger10; COutputEvent m_OnTrigger11; COutputEvent m_OnTrigger12; COutputEvent m_OnTrigger13; COutputEvent m_OnTrigger14; COutputEvent m_OnTrigger15; COutputEvent m_OnTrigger16; int m_nInterruptCount; bool m_bInterrupted; CHandle< CSceneEntity > m_hInterruptScene; bool m_bCompletedEarly; bool m_bInterruptSceneFinished; CUtlVector< CHandle< CSceneEntity > > m_hNotifySceneCompletion; CUtlVector< CHandle< CSceneListManager > > m_hListManagers; bool m_bRestoring; bool m_bGenerated; string_t m_iszSoundName; CHandle< CBaseFlex > m_hActor; EHANDLE m_hActivator; int m_BusyActor; int m_iPlayerDeathBehavior; CRecipientFilter *m_pRecipientFilter; public: void SetBackground( bool bIsBackground ); bool IsBackground( void ); }; LINK_ENTITY_TO_CLASS( logic_choreographed_scene, CSceneEntity ); LINK_ENTITY_TO_CLASS( scripted_scene, CSceneEntity ); IMPLEMENT_SERVERCLASS_ST_NOBASE( CSceneEntity, DT_SceneEntity ) SendPropInt(SENDINFO(m_nSceneStringIndex),MAX_CHOREO_SCENES_STRING_BITS,SPROP_UNSIGNED), SendPropBool(SENDINFO(m_bIsPlayingBack)), SendPropBool(SENDINFO(m_bPaused)), SendPropBool(SENDINFO(m_bMultiplayer)), SendPropFloat(SENDINFO(m_flForceClientTime)), SendPropUtlVector( SENDINFO_UTLVECTOR( m_hActorList ), MAX_ACTORS_IN_SCENE, // max elements SendPropEHandle( NULL, 0 ) ), END_SEND_TABLE() BEGIN_DATADESC( CSceneEntity ) // Keys DEFINE_KEYFIELD( m_iszSceneFile, FIELD_STRING, "SceneFile" ), DEFINE_KEYFIELD( m_iszResumeSceneFile, FIELD_STRING, "ResumeSceneFile" ), DEFINE_FIELD( m_hWaitingForThisResumeScene, FIELD_EHANDLE ), DEFINE_FIELD( m_bWaitingForResumeScene, FIELD_BOOLEAN ), DEFINE_KEYFIELD( m_iszTarget1, FIELD_STRING, "target1" ), DEFINE_KEYFIELD( m_iszTarget2, FIELD_STRING, "target2" ), DEFINE_KEYFIELD( m_iszTarget3, FIELD_STRING, "target3" ), DEFINE_KEYFIELD( m_iszTarget4, FIELD_STRING, "target4" ), DEFINE_KEYFIELD( m_iszTarget5, FIELD_STRING, "target5" ), DEFINE_KEYFIELD( m_iszTarget6, FIELD_STRING, "target6" ), DEFINE_KEYFIELD( m_iszTarget7, FIELD_STRING, "target7" ), DEFINE_KEYFIELD( m_iszTarget8, FIELD_STRING, "target8" ), DEFINE_KEYFIELD( m_BusyActor, FIELD_INTEGER, "busyactor" ), DEFINE_FIELD( m_hTarget1, FIELD_EHANDLE ), DEFINE_FIELD( m_hTarget2, FIELD_EHANDLE ), DEFINE_FIELD( m_hTarget3, FIELD_EHANDLE ), DEFINE_FIELD( m_hTarget4, FIELD_EHANDLE ), DEFINE_FIELD( m_hTarget5, FIELD_EHANDLE ), DEFINE_FIELD( m_hTarget6, FIELD_EHANDLE ), DEFINE_FIELD( m_hTarget7, FIELD_EHANDLE ), DEFINE_FIELD( m_hTarget8, FIELD_EHANDLE ), DEFINE_FIELD( m_bIsPlayingBack, FIELD_BOOLEAN ), DEFINE_FIELD( m_bPaused, FIELD_BOOLEAN ), DEFINE_FIELD( m_flCurrentTime, FIELD_FLOAT ), // relative, not absolute time DEFINE_FIELD( m_flForceClientTime, FIELD_FLOAT ), DEFINE_FIELD( m_flFrameTime, FIELD_FLOAT ), // last frametime DEFINE_FIELD( m_bCancelAtNextInterrupt, FIELD_BOOLEAN ), DEFINE_FIELD( m_fPitch, FIELD_FLOAT ), DEFINE_FIELD( m_bAutomated, FIELD_BOOLEAN ), DEFINE_FIELD( m_nAutomatedAction, FIELD_INTEGER ), DEFINE_FIELD( m_flAutomationDelay, FIELD_FLOAT ), DEFINE_FIELD( m_flAutomationTime, FIELD_FLOAT ), // relative, not absolute time DEFINE_FIELD( m_bPausedViaInput, FIELD_BOOLEAN ), DEFINE_FIELD( m_bWaitingForActor, FIELD_BOOLEAN ), DEFINE_FIELD( m_bWaitingForInterrupt, FIELD_BOOLEAN ), DEFINE_FIELD( m_bInterruptedActorsScenes, FIELD_BOOLEAN ), DEFINE_FIELD( m_bBreakOnNonIdle, FIELD_BOOLEAN ), DEFINE_UTLVECTOR( m_hActorList, FIELD_EHANDLE ), DEFINE_UTLVECTOR( m_hRemoveActorList, FIELD_EHANDLE ), // DEFINE_FIELD( m_pScene, FIELD_XXXX ) // Special processing used for this // These are set up in the constructor // DEFINE_FIELD( m_pcvSndMixahead, FIELD_XXXXX ), // DEFINE_FIELD( m_bRestoring, FIELD_BOOLEAN ), DEFINE_FIELD( m_nInterruptCount, FIELD_INTEGER ), DEFINE_FIELD( m_bInterrupted, FIELD_BOOLEAN ), DEFINE_FIELD( m_hInterruptScene, FIELD_EHANDLE ), DEFINE_FIELD( m_bCompletedEarly, FIELD_BOOLEAN ), DEFINE_FIELD( m_bInterruptSceneFinished, FIELD_BOOLEAN ), DEFINE_FIELD( m_bGenerated, FIELD_BOOLEAN ), DEFINE_FIELD( m_iszSoundName, FIELD_STRING ), DEFINE_FIELD( m_hActor, FIELD_EHANDLE ), DEFINE_FIELD( m_hActivator, FIELD_EHANDLE ), // DEFINE_FIELD( m_bSceneMissing, FIELD_BOOLEAN ), DEFINE_UTLVECTOR( m_hNotifySceneCompletion, FIELD_EHANDLE ), DEFINE_UTLVECTOR( m_hListManagers, FIELD_EHANDLE ), DEFINE_FIELD( m_bMultiplayer, FIELD_BOOLEAN ), // DEFINE_FIELD( m_nSceneStringIndex, FIELD_INTEGER ), // DEFINE_FIELD( m_pRecipientFilter, IRecipientFilter* ), // Multiplayer only // Inputs DEFINE_INPUTFUNC( FIELD_VOID, "Start", InputStartPlayback ), DEFINE_INPUTFUNC( FIELD_VOID, "Pause", InputPausePlayback ), DEFINE_INPUTFUNC( FIELD_VOID, "Resume", InputResumePlayback ), DEFINE_INPUTFUNC( FIELD_VOID, "Cancel", InputCancelPlayback ), DEFINE_INPUTFUNC( FIELD_VOID, "CancelAtNextInterrupt", InputCancelAtNextInterrupt ), DEFINE_INPUTFUNC( FIELD_FLOAT, "PitchShift", InputPitchShiftPlayback ), DEFINE_INPUTFUNC( FIELD_STRING, "InterjectResponse", InputInterjectResponse ), DEFINE_INPUTFUNC( FIELD_VOID, "StopWaitingForActor", InputStopWaitingForActor ), DEFINE_INPUTFUNC( FIELD_INTEGER, "Trigger", InputTriggerEvent ), DEFINE_KEYFIELD( m_iPlayerDeathBehavior, FIELD_INTEGER, "onplayerdeath" ), DEFINE_INPUTFUNC( FIELD_VOID, "ScriptPlayerDeath", InputScriptPlayerDeath ), // Outputs DEFINE_OUTPUT( m_OnStart, "OnStart"), DEFINE_OUTPUT( m_OnCompletion, "OnCompletion"), DEFINE_OUTPUT( m_OnCanceled, "OnCanceled"), DEFINE_OUTPUT( m_OnTrigger1, "OnTrigger1"), DEFINE_OUTPUT( m_OnTrigger2, "OnTrigger2"), DEFINE_OUTPUT( m_OnTrigger3, "OnTrigger3"), DEFINE_OUTPUT( m_OnTrigger4, "OnTrigger4"), DEFINE_OUTPUT( m_OnTrigger5, "OnTrigger5"), DEFINE_OUTPUT( m_OnTrigger6, "OnTrigger6"), DEFINE_OUTPUT( m_OnTrigger7, "OnTrigger7"), DEFINE_OUTPUT( m_OnTrigger8, "OnTrigger8"), DEFINE_OUTPUT( m_OnTrigger9, "OnTrigger9"), DEFINE_OUTPUT( m_OnTrigger10, "OnTrigger10"), DEFINE_OUTPUT( m_OnTrigger11, "OnTrigger11"), DEFINE_OUTPUT( m_OnTrigger12, "OnTrigger12"), DEFINE_OUTPUT( m_OnTrigger13, "OnTrigger13"), DEFINE_OUTPUT( m_OnTrigger14, "OnTrigger14"), DEFINE_OUTPUT( m_OnTrigger15, "OnTrigger15"), DEFINE_OUTPUT( m_OnTrigger16, "OnTrigger16"), END_DATADESC() const ConVar *CSceneEntity::m_pcvSndMixahead = NULL; //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- CSceneEntity::CSceneEntity( void ) { m_bWaitingForActor = false; m_bWaitingForInterrupt = false; m_bInterruptedActorsScenes = false; m_bIsPlayingBack = false; m_bPaused = false; m_bMultiplayer = false; m_fPitch = 1.0f; m_iszSceneFile = NULL_STRING; m_iszResumeSceneFile = NULL_STRING; m_hWaitingForThisResumeScene = NULL; m_bWaitingForResumeScene = false; SetCurrentTime( 0.0f, false ); m_bCancelAtNextInterrupt = false; m_bAutomated = false; m_nAutomatedAction = SCENE_ACTION_UNKNOWN; m_flAutomationDelay = 0.0f; m_flAutomationTime = 0.0f; m_bPausedViaInput = false; ClearInterrupt(); m_pScene = NULL; m_bCompletedEarly = false; if ( !m_pcvSndMixahead ) m_pcvSndMixahead = cvar->FindVar( "snd_mixahead" ); m_BusyActor = SCENE_BUSYACTOR_DEFAULT; } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- CSceneEntity::~CSceneEntity( void ) { delete m_pRecipientFilter; m_pRecipientFilter = NULL; } //----------------------------------------------------------------------------- // Purpose: Resets time such that the client version of the .vcd is also updated, if appropriate // Input : t - // forceClientSync - forces new timestamp down to client .dll via networking //----------------------------------------------------------------------------- void CSceneEntity::SetCurrentTime( float t, bool bForceClientSync ) { m_flCurrentTime = t; if ( gpGlobals->maxClients == 1 || bForceClientSync ) { m_flForceClientTime = t; } } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CSceneEntity::UpdateOnRemove( void ) { UnloadScene(); BaseClass::UpdateOnRemove(); if ( GetSceneManager() ) { GetSceneManager()->RemoveSceneEntity( this ); } } //----------------------------------------------------------------------------- // Purpose: // Input : *actor - // *soundname - // Output : CChoreoScene //----------------------------------------------------------------------------- CChoreoScene *CSceneEntity::GenerateSceneForSound( CBaseFlex *pFlexActor, const char *soundname ) { float duration = CBaseEntity::GetSoundDuration( soundname, pFlexActor ? STRING( pFlexActor->GetModelName() ) : NULL ); if( duration <= 0.0f ) { Warning( "CSceneEntity::GenerateSceneForSound: Couldn't determine duration of %s\n", soundname ); return NULL; } CChoreoScene *scene = new CChoreoScene( this ); if ( !scene ) { Warning( "CSceneEntity::GenerateSceneForSound: Failed to allocated new scene!!!\n" ); } else { scene->SetPrintFunc( LocalScene_Printf ); CChoreoActor *actor = scene->AllocActor(); CChoreoChannel *channel = scene->AllocChannel(); CChoreoEvent *event = scene->AllocEvent(); Assert( actor ); Assert( channel ); Assert( event ); if ( !actor || !channel || !event ) { Warning( "CSceneEntity::GenerateSceneForSound: Alloc of actor, channel, or event failed!!!\n" ); delete scene; return NULL; } // Set us up the actorz actor->SetName( "!self" ); // Could be pFlexActor->GetName()? actor->SetActive( true ); // Set us up the channelz channel->SetName( STRING( m_iszSceneFile ) ); channel->SetActor( actor ); // Add to actor actor->AddChannel( channel ); // Set us up the eventz event->SetType( CChoreoEvent::SPEAK ); event->SetName( soundname ); event->SetParameters( soundname ); event->SetStartTime( 0.0f ); event->SetUsingRelativeTag( false ); event->SetEndTime( duration ); event->SnapTimes(); // Add to channel channel->AddEvent( event ); // Point back to our owners event->SetChannel( channel ); event->SetActor( actor ); } return scene; } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CSceneEntity::Activate() { if ( m_bGenerated && !m_pScene ) { m_pScene = GenerateSceneForSound( m_hActor, STRING( m_iszSoundName ) ); } BaseClass::Activate(); if ( GetSceneManager() ) { GetSceneManager()->AddSceneEntity( this ); } } //----------------------------------------------------------------------------- // Purpose: // Output : float //----------------------------------------------------------------------------- float CSceneEntity::GetSoundSystemLatency( void ) { if ( m_pcvSndMixahead ) { return m_pcvSndMixahead->GetFloat(); } // Assume 100 msec sound system latency return SOUND_SYSTEM_LATENCY_DEFAULT; } //----------------------------------------------------------------------------- // Purpose: // Input : *scene - //----------------------------------------------------------------------------- void CSceneEntity::PrecacheScene( CChoreoScene *scene ) { Assert( scene ); // Iterate events and precache necessary resources for ( int i = 0; i < scene->GetNumEvents(); i++ ) { CChoreoEvent *event = scene->GetEvent( i ); if ( !event ) continue; // load any necessary data switch (event->GetType() ) { default: break; case CChoreoEvent::SPEAK: { // Defined in SoundEmitterSystem.cpp // NOTE: The script entries associated with .vcds are forced to preload to avoid // loading hitches during triggering PrecacheScriptSound( event->GetParameters() ); if ( event->GetCloseCaptionType() == CChoreoEvent::CC_MASTER && event->GetNumSlaves() > 0 ) { char tok[ CChoreoEvent::MAX_CCTOKEN_STRING ]; if ( event->GetPlaybackCloseCaptionToken( tok, sizeof( tok ) ) ) { PrecacheScriptSound( tok ); } } } break; case CChoreoEvent::SUBSCENE: { // Only allow a single level of subscenes for now if ( !scene->IsSubScene() ) { CChoreoScene *subscene = event->GetSubScene(); if ( !subscene ) { subscene = LoadScene( event->GetParameters(), this ); subscene->SetSubScene( true ); event->SetSubScene( subscene ); // Now precache it's resources, if any PrecacheScene( subscene ); } } } break; } } } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CSceneEntity::Precache( void ) { if ( m_bGenerated ) return; if ( m_iszSceneFile == NULL_STRING ) return; if ( m_iszResumeSceneFile != NULL_STRING ) { PrecacheInstancedScene( STRING( m_iszResumeSceneFile ) ); } PrecacheInstancedScene( STRING( m_iszSceneFile ) ); } //----------------------------------------------------------------------------- // Purpose: // Input : *pActor - // *soundname - //----------------------------------------------------------------------------- void CSceneEntity::GenerateSoundScene( CBaseFlex *pActor, const char *soundname ) { m_bGenerated = true; m_iszSoundName = MAKE_STRING( soundname ); m_hActor = pActor; } //----------------------------------------------------------------------------- // Purpose: // Output : Returns true on success, false on failure. //----------------------------------------------------------------------------- bool CSceneEntity::HasUnplayedSpeech( void ) { if ( m_pScene ) return m_pScene->HasUnplayedSpeech(); return false; } //----------------------------------------------------------------------------- // Purpose: // Output : Returns true on success, false on failure. //----------------------------------------------------------------------------- bool CSceneEntity::HasFlexAnimation( void ) { if ( m_pScene ) return m_pScene->HasFlexAnimation(); return false; } //----------------------------------------------------------------------------- // Purpose: // Output : //----------------------------------------------------------------------------- void CSceneEntity::SetBackground( bool bIsBackground ) { if ( m_pScene ) { m_pScene->SetBackground( bIsBackground ); } } //----------------------------------------------------------------------------- // Purpose: // Output : Returns true on success, false on failure. //----------------------------------------------------------------------------- bool CSceneEntity::IsBackground( void ) { if ( m_pScene ) return m_pScene->IsBackground( ); return false; } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CSceneEntity::OnRestore() { BaseClass::OnRestore(); // Fix saved games that have their pitch set to zero if ( m_fPitch < SCENE_MIN_PITCH || m_fPitch > SCENE_MAX_PITCH ) m_fPitch = 1.0f; if ( !m_bIsPlayingBack ) return; if ( !m_pScene ) { m_pScene = LoadScene( STRING( m_iszSceneFile ), this ); if ( !m_pScene ) { m_bSceneMissing = true; return; } OnLoaded(); if ( ShouldNetwork() ) { m_nSceneStringIndex = g_pStringTableClientSideChoreoScenes->AddString( CBaseEntity::IsServer(), STRING( m_iszSceneFile ) ); } UpdateTransmitState(); } m_bSceneMissing = false; int i; for ( i = 0 ; i < m_pScene->GetNumActors(); i++ ) { CBaseFlex *pTestActor = FindNamedActor( i ); if ( !pTestActor ) continue; if ( !pTestActor->MyCombatCharacterPointer() ) continue; // Needed? //if ( !pTestActor->MyCombatCharacterPointer()->IsAlive() ) // return; pTestActor->StartChoreoScene( m_pScene ); } float dt = SCENE_THINK_INTERVAL; bool paused = m_bPaused; m_bPaused = false; // roll back slightly so that pause events still trigger m_pScene->ResetSimulation( true, m_flCurrentTime - SCENE_THINK_INTERVAL, m_flCurrentTime ); m_pScene->SetTime( m_flCurrentTime - SCENE_THINK_INTERVAL ); SetCurrentTime( m_flCurrentTime, true ); // Robin: This causes a miscount of any interrupt events in the scene. // All the variables are saved/restored properly, so we can safely leave them alone. //ClearInterrupt(); SetRestoring( true ); DoThink( dt ); SetRestoring( false ); if ( paused ) { PausePlayback(); } NetworkProp()->NetworkStateForceUpdate(); } //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- void CSceneEntity::SetRestoring( bool bRestoring ) { m_bRestoring = bRestoring; if ( m_pScene ) { m_pScene->SetRestoring( bRestoring ); } } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CSceneEntity::Spawn( void ) { Precache(); } void CSceneEntity::PauseThink( void ) { if ( !m_pScene ) return; // Stay paused if pause occurred from interrupt if ( m_bInterrupted ) return; // If entity I/O paused the scene, then it'll have to resume/cancel the scene... if ( m_bPausedViaInput ) { // If we're waiting for a resume scene to finish, continue when it's done if ( m_bWaitingForResumeScene && !m_hWaitingForThisResumeScene ) { // Resume scene has finished, stop waiting for it m_bWaitingForResumeScene = false; } else { return; } } if ( !m_bAutomated ) { // FIXME: Game code should check for AI waiting conditions being met, etc. // // // bool bAllFinished = m_pScene->CheckEventCompletion( ); if ( bAllFinished ) { // Perform action switch ( m_nAutomatedAction ) { case SCENE_ACTION_RESUME: ResumePlayback(); break; case SCENE_ACTION_CANCEL: LocalScene_Printf( "%s : PauseThink canceling playback\n", STRING( m_iszSceneFile ) ); CancelPlayback(); break; default: ResumePlayback(); break; } // Reset m_bAutomated = false; m_nAutomatedAction = SCENE_ACTION_UNKNOWN; m_flAutomationTime = 0.0f; m_flAutomationDelay = 0.0f; m_bPausedViaInput = false; } return; } // Otherwise, see if resume/cancel is automatic and act accordingly if enough time // has passed m_flAutomationTime += (gpGlobals->frametime); if ( m_flAutomationDelay > 0.0f && m_flAutomationTime < m_flAutomationDelay ) return; // Perform action switch ( m_nAutomatedAction ) { case SCENE_ACTION_RESUME: LocalScene_Printf( "%s : Automatically resuming playback\n", STRING( m_iszSceneFile ) ); ResumePlayback(); break; case SCENE_ACTION_CANCEL: LocalScene_Printf( "%s : Automatically canceling playback\n", STRING( m_iszSceneFile ) ); CancelPlayback(); break; default: LocalScene_Printf( "%s : Unknown action %i, automatically resuming playback\n", STRING( m_iszSceneFile ), m_nAutomatedAction ); ResumePlayback(); break; } // Reset m_bAutomated = false; m_nAutomatedAction = SCENE_ACTION_UNKNOWN; m_flAutomationTime = 0.0f; m_flAutomationDelay = 0.0f; m_bPausedViaInput = false; } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CSceneEntity::DispatchPauseScene( CChoreoScene *scene, const char *parameters ) { // Don't pause during restore, since we'll be restoring the pause state already if ( m_bRestoring ) return; // FIXME: Hook this up to AI, etc. somehow, perhaps poll each actor for conditions using // scene resume condition iterator PausePlayback(); char token[1024]; m_bPausedViaInput = false; m_bAutomated = false; m_nAutomatedAction = SCENE_ACTION_UNKNOWN; m_flAutomationDelay = 0.0f; m_flAutomationTime = 0.0f; // Check for auto resume/cancel const char *buffer = parameters; buffer = engine->ParseFile( buffer, token, sizeof( token ) ); if ( !stricmp( token, "automate" ) ) { buffer = engine->ParseFile( buffer, token, sizeof( token ) ); if ( !stricmp( token, "Cancel" ) ) { m_nAutomatedAction = SCENE_ACTION_CANCEL; } else if ( !stricmp( token, "Resume" ) ) { m_nAutomatedAction = SCENE_ACTION_RESUME; } if ( m_nAutomatedAction != SCENE_ACTION_UNKNOWN ) { buffer = engine->ParseFile( buffer, token, sizeof( token ) ); m_flAutomationDelay = (float)atof( token ); if ( m_flAutomationDelay > 0.0f ) { // Success m_bAutomated = true; m_flAutomationTime = 0.0f; } } } } //----------------------------------------------------------------------------- // Purpose: // Input : *scene - // *event - //----------------------------------------------------------------------------- void CSceneEntity::DispatchProcessLoop( CChoreoScene *scene, CChoreoEvent *event ) { // Don't restore this event since it's implied in the current "state" of the scene timer, etc. if ( m_bRestoring ) return; Assert( scene ); Assert( event->GetType() == CChoreoEvent::LOOP ); float backtime = (float)atof( event->GetParameters() ); bool process = true; int counter = event->GetLoopCount(); if ( counter != -1 ) { int remaining = event->GetNumLoopsRemaining(); if ( remaining <= 0 ) { process = false; } else { event->SetNumLoopsRemaining( --remaining ); } } if ( !process ) return; scene->LoopToTime( backtime ); SetCurrentTime( backtime, true ); } //----------------------------------------------------------------------------- // Purpose: Flag the scene as already "completed" // Input : *scene - // *parameters - //----------------------------------------------------------------------------- void CSceneEntity::DispatchStopPoint( CChoreoScene *scene, const char *parameters ) { if ( m_bCompletedEarly ) { Assert( 0 ); Warning( "Scene '%s' with two stop point events!\n", STRING( m_iszSceneFile ) ); return; } // Fire completion trigger early m_bCompletedEarly = true; m_OnCompletion.FireOutput( this, this, 0 ); } //----------------------------------------------------------------------------- // Purpose: // Output : Returns true on success, false on failure. //----------------------------------------------------------------------------- bool CSceneEntity::IsInterruptable() { return ( m_nInterruptCount > 0 ) ? true : false; } //----------------------------------------------------------------------------- // Purpose: // Input : *scene - // *actor - // *event - //----------------------------------------------------------------------------- void CSceneEntity::DispatchStartInterrupt( CChoreoScene *scene, CChoreoEvent *event ) { // Don't re-interrupt during restore if ( m_bRestoring ) return; // If we're supposed to cancel at our next interrupt point, cancel now if ( m_bCancelAtNextInterrupt ) { m_bCancelAtNextInterrupt = false; LocalScene_Printf( "%s : cancelled via interrupt\n", STRING( m_iszSceneFile ) ); CancelPlayback(); return; } ++m_nInterruptCount; } //----------------------------------------------------------------------------- // Purpose: // Input : *scene - // *actor - // *event - //----------------------------------------------------------------------------- void CSceneEntity::DispatchEndInterrupt( CChoreoScene *scene, CChoreoEvent *event ) { // Don't re-interrupt during restore if ( m_bRestoring ) return; --m_nInterruptCount; if ( m_nInterruptCount < 0 ) { m_nInterruptCount = 0; } } //----------------------------------------------------------------------------- // Purpose: // Input : *actor - // *event - //----------------------------------------------------------------------------- void CSceneEntity::DispatchStartExpression( CChoreoScene *scene, CBaseFlex *actor, CChoreoEvent *event ) { actor->AddSceneEvent( scene, event ); } //----------------------------------------------------------------------------- // Purpose: // Input : *actor - // *event - //----------------------------------------------------------------------------- void CSceneEntity::DispatchEndExpression( CChoreoScene *scene, CBaseFlex *actor, CChoreoEvent *event ) { actor->RemoveSceneEvent( scene, event, false ); } //----------------------------------------------------------------------------- // Purpose: // Input : *actor - // *event - //----------------------------------------------------------------------------- void CSceneEntity::DispatchStartFlexAnimation( CChoreoScene *scene, CBaseFlex *actor, CChoreoEvent *event ) { actor->AddSceneEvent( scene, event ); } //----------------------------------------------------------------------------- // Purpose: // Input : *actor - // *event - //----------------------------------------------------------------------------- void CSceneEntity::DispatchEndFlexAnimation( CChoreoScene *scene, CBaseFlex *actor, CChoreoEvent *event ) { actor->RemoveSceneEvent( scene, event, false ); } //----------------------------------------------------------------------------- // Purpose: // Input : *actor - // *parameters - //----------------------------------------------------------------------------- void CSceneEntity::DispatchStartGesture( CChoreoScene *scene, CBaseFlex *actor, CChoreoEvent *event ) { // Ingore null gestures if ( !Q_stricmp( event->GetName(), "NULL" ) ) return; actor->AddSceneEvent( scene, event); } //----------------------------------------------------------------------------- // Purpose: // Input : *actor - // *parameters - //----------------------------------------------------------------------------- void CSceneEntity::DispatchEndGesture( CChoreoScene *scene, CBaseFlex *actor, CChoreoEvent *event ) { // Ingore null gestures if ( !Q_stricmp( event->GetName(), "NULL" ) ) return; actor->RemoveSceneEvent( scene, event, m_bRestoring ); } //----------------------------------------------------------------------------- // Purpose: // Input : *actor - // *parameters - //----------------------------------------------------------------------------- void CSceneEntity::DispatchStartGeneric( CChoreoScene *scene, CBaseFlex *actor, CChoreoEvent *event ) { CBaseEntity *pTarget = FindNamedEntity( event->GetParameters2( ) ); actor->AddSceneEvent( scene, event, pTarget ); } //----------------------------------------------------------------------------- // Purpose: // Input : *actor - // *parameters - //----------------------------------------------------------------------------- void CSceneEntity::DispatchEndGeneric( CChoreoScene *scene, CBaseFlex *actor, CChoreoEvent *event ) { actor->RemoveSceneEvent( scene, event, m_bRestoring ); } //----------------------------------------------------------------------------- // Purpose: // Input : *actor - // *actor2 - //----------------------------------------------------------------------------- void CSceneEntity::DispatchStartLookAt( CChoreoScene *scene, CBaseFlex *actor, CBaseEntity *actor2, CChoreoEvent *event ) { actor->AddSceneEvent( scene, event, actor2 ); } void CSceneEntity::DispatchEndLookAt( CChoreoScene *scene, CBaseFlex *actor, CChoreoEvent *event ) { actor->RemoveSceneEvent( scene, event, m_bRestoring ); } //----------------------------------------------------------------------------- // Purpose: Move to spot/actor // FIXME: Need to allow this to take arbitrary amount of time and pause playback // while waiting for actor to move into position // Input : *actor - // *parameters - //----------------------------------------------------------------------------- void CSceneEntity::DispatchStartMoveTo( CChoreoScene *scene, CBaseFlex *actor, CBaseEntity *actor2, CChoreoEvent *event ) { actor->AddSceneEvent( scene, event, actor2 ); } void CSceneEntity::DispatchEndMoveTo( CChoreoScene *scene, CBaseFlex *actor, CChoreoEvent *event ) { actor->RemoveSceneEvent( scene, event, m_bRestoring ); } //----------------------------------------------------------------------------- // Purpose: // Input : *token - // listener - // soundorigins - // Output : Returns true on success, false on failure. //----------------------------------------------------------------------------- bool AttenuateCaption( const char *token, const Vector& listener, CUtlVector< Vector >& soundorigins ) { if ( scene_maxcaptionradius.GetFloat() <= 0.0f ) { return false; } int c = soundorigins.Count(); if ( c <= 0 ) { return false; } float maxdistSqr = scene_maxcaptionradius.GetFloat() * scene_maxcaptionradius.GetFloat(); for ( int i = 0; i < c; ++i ) { const Vector& org = soundorigins[ i ]; float distSqr = ( org - listener ).LengthSqr(); if ( distSqr <= maxdistSqr ) { return false; } } // All sound sources too far, don't show caption... return true; } //----------------------------------------------------------------------------- // Purpose: // Input : *event - which event // player - which recipient // buf, buflen: where to put the data // Output : Returns true if the sound should be played/prefetched //----------------------------------------------------------------------------- bool CSceneEntity::GetSoundNameForPlayer( CChoreoEvent *event, CBasePlayer *player, char *buf, size_t buflen, CBaseEntity *pActor ) { Assert( event ); Assert( player ); Assert( buf ); Assert( buflen > 0 ); bool ismasterevent = true; char tok[ CChoreoEvent::MAX_CCTOKEN_STRING ]; bool validtoken = false; tok[ 0 ] = 0; if ( event->GetCloseCaptionType() == CChoreoEvent::CC_SLAVE || event->GetCloseCaptionType() == CChoreoEvent::CC_DISABLED ) { ismasterevent = false; } else { validtoken = event->GetPlaybackCloseCaptionToken( tok, sizeof( tok ) ); } const char* pchToken = ""; if ( pActor && pActor->IsPlayer() ) { pchToken = dynamic_cast< CBasePlayer* >( pActor )->GetSceneSoundToken(); } // Copy the sound name CopySoundNameWithModifierToken( buf, event->GetParameters(), buflen, pchToken ); bool usingEnglish = true; if ( !IsXbox() ) { char const *cvarvalue = engine->GetClientConVarValue( player->entindex(), "english" ); if ( cvarvalue && *cvarvalue && Q_atoi( cvarvalue ) != 1 ) { usingEnglish = false; } } // This makes it like they are running in another language if ( scene_forcecombined.GetBool() ) { usingEnglish = false; } if ( usingEnglish ) { // English sounds always play return true; } if ( ismasterevent ) { // Master event sounds always play too (master will be the combined .wav) if ( validtoken ) { Q_strncpy( buf, tok, buflen ); } return true; } // Slave events don't play any sound... return false; } //----------------------------------------------------------------------------- // Purpose: Playback sound file that contains phonemes // Input : *actor - // *parameters - //----------------------------------------------------------------------------- void CSceneEntity::DispatchStartSpeak( CChoreoScene *scene, CBaseFlex *actor, CChoreoEvent *event, soundlevel_t iSoundlevel ) { // Emit sound if ( actor ) { CPASAttenuationFilter filter( actor ); if ( m_pRecipientFilter ) { int filterCount = filter.GetRecipientCount(); int recipientPlayerCount = m_pRecipientFilter->GetRecipientCount(); for ( int i = filterCount-1; i >= 0; --i ) { int playerindex = filter.GetRecipientIndex( i ); bool bFound = false; for ( int j = 0; j < recipientPlayerCount; ++j ) { if ( m_pRecipientFilter->GetRecipientIndex(j) == playerindex ) { bFound = true; break; } } if ( !bFound ) { filter.RemoveRecipientByPlayerIndex( playerindex ); } } } float time_in_past = m_flCurrentTime - event->GetStartTime() ; float soundtime = gpGlobals->curtime - time_in_past; if ( m_bRestoring ) { // Need to queue sounds on restore because the player has not yet connected GetSceneManager()->QueueRestoredSound( actor, event->GetParameters(), iSoundlevel, time_in_past ); return; } // Add padding to prevent any other talker talking right after I'm done, because I might // be continuing speaking with another scene. float flDuration = event->GetDuration() - time_in_past; CAI_BaseActor *pBaseActor = dynamic_cast<CAI_BaseActor*>(actor); if ( pBaseActor ) { pBaseActor->NoteSpeaking( flDuration, GetPostSpeakDelay() ); } else if ( actor->IsNPC() ) { GetSpeechSemaphore( actor->MyNPCPointer() )->Acquire( flDuration + GetPostSpeakDelay(), actor ); } EmitSound_t es; es.m_nChannel = CHAN_VOICE; es.m_flVolume = 1; es.m_SoundLevel = iSoundlevel; // Only specify exact delay in single player es.m_flSoundTime = ( gpGlobals->maxClients == 1 ) ? soundtime : 0.0f; if ( scene->ShouldIgnorePhonemes() ) { es.m_nFlags |= SND_IGNORE_PHONEMES; } if ( actor->GetSpecialDSP() != 0 ) { es.m_nSpecialDSP = actor->GetSpecialDSP(); } // No CC since we do it manually // FIXME: This will change es.m_bEmitCloseCaption = false; int c = filter.GetRecipientCount(); for ( int i = 0; i < c; ++i ) { int playerindex = filter.GetRecipientIndex( i ); CBasePlayer *player = UTIL_PlayerByIndex( playerindex ); if ( !player ) continue; CSingleUserRecipientFilter filter2( player ); char soundname[ 512 ]; if ( !GetSoundNameForPlayer( event, player, soundname, sizeof( soundname ), actor ) ) { continue; } es.m_pSoundName = soundname; // keep track of the last few sounds played for bug reports speechListSounds[ speechListIndex ].time = gpGlobals->curtime; Q_strncpy( speechListSounds[ speechListIndex ].name, soundname, sizeof( speechListSounds[ 0 ].name ) ); Q_strncpy( speechListSounds[ speechListIndex ].sceneName, ( scene ) ? scene->GetFilename() : "", sizeof( speechListSounds[ 0 ].sceneName ) ); speechListIndex++; if ( speechListIndex >= SPEECH_LIST_MAX_SOUNDS ) { speechListIndex = 0; } // Warning( "Speak %s\n", soundname ); if ( m_fPitch != 1.0f ) { if ( es.m_nPitch ) es.m_nPitch = static_cast<float>( es.m_nPitch ) * m_fPitch; else es.m_nPitch = 100.0f * m_fPitch; es.m_nFlags |= SND_CHANGE_PITCH; } EmitSound( filter2, actor->entindex(), es ); actor->AddSceneEvent( scene, event ); } // Close captioning only on master token no matter what... if ( event->GetCloseCaptionType() == CChoreoEvent::CC_MASTER ) { char tok[ CChoreoEvent::MAX_CCTOKEN_STRING ]; bool validtoken = event->GetPlaybackCloseCaptionToken( tok, sizeof( tok ) ); if ( validtoken ) { char lowercase[ 256 ]; Q_strncpy( lowercase, tok, sizeof( lowercase ) ); Q_strlower( lowercase ); // Remove any players who don't want close captions CBaseEntity::RemoveRecipientsIfNotCloseCaptioning( filter ); // Certain events are marked "don't attenuate", (breencast), skip those here if ( !event->IsSuppressingCaptionAttenuation() && ( filter.GetRecipientCount() > 0 ) ) { int c = filter.GetRecipientCount(); for ( int i = c - 1 ; i >= 0; --i ) { CBasePlayer *player = UTIL_PlayerByIndex( filter.GetRecipientIndex( i ) ); if ( !player ) continue; Vector playerOrigin = player->GetAbsOrigin(); if ( AttenuateCaption( lowercase, playerOrigin, es.m_UtlVecSoundOrigin ) ) { // If the player has a view entity, measure the distance to that if ( !player->GetViewEntity() || AttenuateCaption( lowercase, player->GetViewEntity()->GetAbsOrigin(), es.m_UtlVecSoundOrigin ) ) { filter.RemoveRecipient( player ); } } } } // Anyone left? if ( filter.GetRecipientCount() > 0 ) { float endtime = event->GetLastSlaveEndTime(); float durationShort = event->GetDuration(); float durationLong = endtime - event->GetStartTime(); float duration = MAX( durationShort, durationLong ); byte byteflags = CLOSE_CAPTION_WARNIFMISSING; // warnifmissing /* // Never for .vcds... if ( fromplayer ) { byteflags |= CLOSE_CAPTION_FROMPLAYER; } */ char const *pszActorModel = STRING( actor->GetModelName() ); gender_t gender = soundemitterbase->GetActorGender( pszActorModel ); if ( gender == GENDER_MALE ) { byteflags |= CLOSE_CAPTION_GENDER_MALE; } else if ( gender == GENDER_FEMALE ) { byteflags |= CLOSE_CAPTION_GENDER_FEMALE; } // Send caption and duration hint down to client UserMessageBegin( filter, "CloseCaption" ); WRITE_STRING( lowercase ); WRITE_SHORT( MIN( 255, (int)( duration * 10.0f ) ) ); WRITE_BYTE( byteflags ); // warn on missing MessageEnd(); } } } } } void CSceneEntity::DispatchEndSpeak( CChoreoScene *scene, CBaseFlex *actor, CChoreoEvent *event ) { actor->RemoveSceneEvent( scene, event, m_bRestoring ); } //----------------------------------------------------------------------------- // Purpose: // Input : *actor - // *actor2 - //----------------------------------------------------------------------------- void CSceneEntity::DispatchStartFace( CChoreoScene *scene, CBaseFlex *actor, CBaseEntity *actor2, CChoreoEvent *event ) { actor->AddSceneEvent( scene, event, actor2 ); } //----------------------------------------------------------------------------- // Purpose: // Input : *actor - // *actor2 - //----------------------------------------------------------------------------- void CSceneEntity::DispatchEndFace( CChoreoScene *scene, CBaseFlex *actor, CChoreoEvent *event ) { actor->RemoveSceneEvent( scene, event, m_bRestoring ); } //----------------------------------------------------------------------------- // Purpose: // Input : *actor - //----------------------------------------------------------------------------- void CSceneEntity::DispatchStartSequence( CChoreoScene *scene, CBaseFlex *actor, CChoreoEvent *event ) { actor->AddSceneEvent( scene, event ); } //----------------------------------------------------------------------------- // Purpose: // Input : *actor - //----------------------------------------------------------------------------- void CSceneEntity::DispatchEndSequence( CChoreoScene *scene, CBaseFlex *actor, CChoreoEvent *event ) { actor->RemoveSceneEvent( scene, event, m_bRestoring ); } //----------------------------------------------------------------------------- // Purpose: NPC can play interstitial vcds (such as responding to the player doing something during a scene) // Input : *scene - // *actor - // *event - //----------------------------------------------------------------------------- void CSceneEntity::DispatchStartPermitResponses( CChoreoScene *scene, CBaseFlex *actor, CChoreoEvent *event ) { actor->SetPermitResponse( gpGlobals->curtime + event->GetDuration() ); } //----------------------------------------------------------------------------- // Purpose: // Input : *scene - // *actor - // *event - //----------------------------------------------------------------------------- void CSceneEntity::DispatchEndPermitResponses( CChoreoScene *scene, CBaseFlex *actor, CChoreoEvent *event ) { actor->SetPermitResponse( 0 ); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- float CSceneEntity::EstimateLength( void ) { if ( !m_pScene ) { return GetSceneDuration( STRING( m_iszSceneFile ) ); } return m_pScene->FindStopTime(); } //----------------------------------------------------------------------------- // Purpose: // NOTE: returns false if scene hasn't loaded yet //----------------------------------------------------------------------------- void CSceneEntity::CancelIfSceneInvolvesActor( CBaseEntity *pActor ) { if ( InvolvesActor( pActor ) ) { LocalScene_Printf( "%s : cancelled for '%s'\n", STRING( m_iszSceneFile ), pActor->GetDebugName() ); CancelPlayback(); } } //----------------------------------------------------------------------------- // Purpose: // NOTE: returns false if scene hasn't loaded yet //----------------------------------------------------------------------------- bool CSceneEntity::InvolvesActor( CBaseEntity *pActor ) { if ( !m_pScene ) return false; int i; for ( i = 0 ; i < m_pScene->GetNumActors(); i++ ) { CBaseFlex *pTestActor = FindNamedActor( i ); if ( !pTestActor ) continue; if ( pTestActor == pActor ) return true; } return false; } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CSceneEntity::DoThink( float frametime ) { CheckInterruptCompletion(); if ( m_bWaitingForActor || m_bWaitingForInterrupt ) { // Try to start playback. StartPlayback(); } if ( !m_pScene ) return; if ( !m_bIsPlayingBack ) return; // catch bad pitch shifting from old save games Assert( m_fPitch >= SCENE_MIN_PITCH && m_fPitch <= SCENE_MAX_PITCH ); m_fPitch = clamp( m_fPitch, SCENE_MIN_PITCH, SCENE_MAX_PITCH ); if ( m_bPaused ) { PauseThink(); return; } // Msg("%.2f %s\n", gpGlobals->curtime, STRING( m_iszSceneFile ) ); //Msg( "SV: %d, %f for %s\n", gpGlobals->tickcount, m_flCurrentTime, m_pScene->GetFilename() ); m_flFrameTime = frametime; m_pScene->SetSoundFileStartupLatency( GetSoundSystemLatency() ); // Tell scene to go m_pScene->Think( m_flCurrentTime ); // Did we get to the end if ( !m_bPaused ) { // Drive simulation time for scene SetCurrentTime( m_flCurrentTime + m_flFrameTime * m_fPitch, false ); if ( m_pScene->SimulationFinished() ) { OnSceneFinished( false, true ); // Stop them from doing anything special ClearSchedules( m_pScene ); } } else { // Drive simulation time for scene SetCurrentTime( m_pScene->GetTime(), true ); } } //----------------------------------------------------------------------------- // Purpose: Input handlers //----------------------------------------------------------------------------- void CSceneEntity::InputStartPlayback( inputdata_t &inputdata ) { // Already playing, ignore if ( m_bIsPlayingBack ) return; // Already waiting on someone. if ( m_bWaitingForActor || m_bWaitingForInterrupt ) return; ClearActivatorTargets(); m_hActivator = inputdata.pActivator; StartPlayback(); } void CSceneEntity::InputPausePlayback( inputdata_t &inputdata ) { PausePlayback(); m_bPausedViaInput = true; } void CSceneEntity::InputResumePlayback( inputdata_t &inputdata ) { ResumePlayback(); } void CSceneEntity::InputCancelPlayback( inputdata_t &inputdata ) { LocalScene_Printf( "%s : cancelled via input\n", STRING( m_iszSceneFile ) ); CancelPlayback(); } void CSceneEntity::InputScriptPlayerDeath( inputdata_t &inputdata ) { if ( m_iPlayerDeathBehavior == SCRIPT_CANCEL ) { LocalScene_Printf( "%s : cancelled via player death\n", STRING( m_iszSceneFile ) ); CancelPlayback(); } } void CSceneEntity::InputCancelAtNextInterrupt( inputdata_t &inputdata ) { // If we're currently in an interruptable point, interrupt immediately if ( IsInterruptable() ) { LocalScene_Printf( "%s : cancelled via input at interrupt point\n", STRING( m_iszSceneFile ) ); CancelPlayback(); return; } // Otherwise, cancel when we next hit an interrupt point m_bCancelAtNextInterrupt = true; } void CSceneEntity::InputPitchShiftPlayback( inputdata_t &inputdata ) { PitchShiftPlayback( inputdata.value.Float() ); } void CSceneEntity::InputTriggerEvent( inputdata_t &inputdata ) { CBaseEntity *pActivator = this; // at some point, find this from the inputdata switch ( inputdata.value.Int() ) { case 1: m_OnTrigger1.FireOutput( pActivator, this, 0 ); break; case 2: m_OnTrigger2.FireOutput( pActivator, this, 0 ); break; case 3: m_OnTrigger3.FireOutput( pActivator, this, 0 ); break; case 4: m_OnTrigger4.FireOutput( pActivator, this, 0 ); break; case 5: m_OnTrigger5.FireOutput( pActivator, this, 0 ); break; case 6: m_OnTrigger6.FireOutput( pActivator, this, 0 ); break; case 7: m_OnTrigger7.FireOutput( pActivator, this, 0 ); break; case 8: m_OnTrigger8.FireOutput( pActivator, this, 0 ); break; case 9: m_OnTrigger9.FireOutput( pActivator, this, 0 ); break; case 10: m_OnTrigger10.FireOutput( pActivator, this, 0 ); break; case 11: m_OnTrigger11.FireOutput( pActivator, this, 0 ); break; case 12: m_OnTrigger12.FireOutput( pActivator, this, 0 ); break; case 13: m_OnTrigger13.FireOutput( pActivator, this, 0 ); break; case 14: m_OnTrigger14.FireOutput( pActivator, this, 0 ); break; case 15: m_OnTrigger15.FireOutput( pActivator, this, 0 ); break; case 16: m_OnTrigger16.FireOutput( pActivator, this, 0 ); break; } } //----------------------------------------------------------------------------- // Purpose: // Input : &inputdata - //----------------------------------------------------------------------------- void CSceneEntity::InputInterjectResponse( inputdata_t &inputdata ) { // Not currently playing a scene if ( !m_pScene ) return; CUtlVector<CAI_BaseActor *> candidates; for ( int i = 0 ; i < m_pScene->GetNumActors(); i++ ) { CBaseFlex *pTestActor = FindNamedActor( i ); if ( !pTestActor ) continue; CAI_BaseActor *pBaseActor = dynamic_cast<CAI_BaseActor *>(pTestActor); if ( !pBaseActor || !pBaseActor->IsAlive() ) continue; candidates.AddToTail( pBaseActor ); } int c = candidates.Count(); if ( !c ) return; if ( !m_bIsPlayingBack ) { // Use any actor if not playing a scene // int useIndex = RandomInt( 0, c - 1 ); Assert( !"m_bIsPlayBack is false and this code does nothing. Should it?"); } else { CUtlString modifiers("scene:"); modifiers += STRING( GetEntityName() ); while (candidates.Count() > 0) { // Pick a random slot in the candidates array. int slot = RandomInt( 0, candidates.Count() - 1 ); CAI_BaseActor *npc = candidates[ slot ]; // Try to find the response for this slot. AI_Response response; bool result = npc->SpeakFindResponse( response, inputdata.value.String(), modifiers.Get() ); if ( result ) { float duration = npc->GetResponseDuration( response ); if ( ( duration > 0.0f ) && npc->PermitResponse( duration ) ) { // If we could look it up, dispatch it and bail. npc->SpeakDispatchResponse( inputdata.value.String(), response ); return; } } // Remove this entry and look for another one. candidates.FastRemove(slot); } } } //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- void CSceneEntity::InputStopWaitingForActor( inputdata_t &inputdata ) { if( m_bIsPlayingBack ) { // Already started. return; } m_bWaitingForActor = false; } bool CSceneEntity::CheckActors() { Assert( m_pScene ); if ( !m_pScene ) return false; int i; for ( i = 0 ; i < m_pScene->GetNumActors(); i++ ) { CBaseFlex *pTestActor = FindNamedActor( i ); if ( !pTestActor ) continue; if ( !pTestActor->MyCombatCharacterPointer() ) continue; if ( !pTestActor->MyCombatCharacterPointer()->IsAlive() ) return false; if ( m_BusyActor == SCENE_BUSYACTOR_WAIT ) { CAI_BaseNPC *pActor = pTestActor->MyNPCPointer(); if ( pActor ) { bool bShouldWait = false; if ( hl2_episodic.GetBool() ) { // Episodic waits until the NPC is fully finished with any .vcd with speech in it if ( IsRunningScriptedSceneWithSpeech( pActor ) ) { bShouldWait = true; } #ifdef HL2_EPISODIC // HACK: Alyx cannot play scenes when she's in the middle of transitioning if ( pActor->IsInAVehicle() ) { CNPC_Alyx *pAlyx = dynamic_cast<CNPC_Alyx *>(pActor); if ( pAlyx != NULL && ( pAlyx->GetPassengerState() == PASSENGER_STATE_ENTERING || pAlyx->GetPassengerState() == PASSENGER_STATE_EXITING ) ) { bShouldWait = true; } } #endif // HL2_EPISODIC } if ( pActor->GetExpresser() && pActor->GetExpresser()->IsSpeaking() ) { bShouldWait = true; } if ( bShouldWait ) { // One of the actors for this scene is talking already. // Try again next think. m_bWaitingForActor = true; return false; } } } else if ( m_BusyActor == SCENE_BUSYACTOR_INTERRUPT || m_BusyActor == SCENE_BUSYACTOR_INTERRUPT_CANCEL ) { CBaseCombatCharacter *pActor = pTestActor->MyCombatCharacterPointer(); if ( pActor && !IsInInterruptableScenes( pActor ) ) { // One of the actors is in a scene that's not at an interrupt point. // Wait until the scene finishes or an interrupt point is reached. m_bWaitingForInterrupt = true; return false; } if ( m_BusyActor == SCENE_BUSYACTOR_INTERRUPT_CANCEL ) { // Cancel existing scenes RemoveActorFromScriptedScenes( pActor, false ); } else { // Pause existing scenes PauseActorsScriptedScenes( pActor, false ); m_bInterruptedActorsScenes = true; } } pTestActor->StartChoreoScene( m_pScene ); } return true; } #if !defined( _RETAIL ) static ConVar scene_async_prefetch_spew( "scene_async_prefetch_spew", "0", 0, "Display async .ani file loading info." ); #endif void CSceneEntity::PrefetchAnimBlocks( CChoreoScene *scene ) { Assert( scene ); // Build a fast lookup, too CUtlMap< CChoreoActor *, CBaseFlex *> actorMap( 0, 0, DefLessFunc( CChoreoActor * ) ); int spew = #if !defined( _RETAIL ) scene_async_prefetch_spew.GetInt(); #else 0; #endif int resident = 0; int checked = 0; // Iterate events and precache necessary resources for ( int i = 0; i < scene->GetNumEvents(); i++ ) { CChoreoEvent *event = scene->GetEvent( i ); if ( !event ) continue; // load any necessary data switch ( event->GetType() ) { default: break; case CChoreoEvent::SEQUENCE: case CChoreoEvent::GESTURE: { CChoreoActor *actor = event->GetActor(); if ( actor ) { CBaseFlex *pActor = NULL; int idx = actorMap.Find( actor ); if ( idx == actorMap.InvalidIndex() ) { pActor = FindNamedActor( actor ); idx = actorMap.Insert( actor, pActor ); } else { pActor = actorMap[ idx ]; } if ( pActor ) { int seq = pActor->LookupSequence( event->GetParameters() ); if ( seq >= 0 ) { CStudioHdr *pStudioHdr = pActor->GetModelPtr(); if ( pStudioHdr ) { // Now look up the animblock mstudioseqdesc_t &seqdesc = pStudioHdr->pSeqdesc( seq ); for ( int i = 0 ; i < seqdesc.groupsize[ 0 ] ; ++i ) { for ( int j = 0; j < seqdesc.groupsize[ 1 ]; ++j ) { int animation = seqdesc.anim( i, j ); int baseanimation = pStudioHdr->iRelativeAnim( seq, animation ); mstudioanimdesc_t &animdesc = pStudioHdr->pAnimdesc( baseanimation ); ++checked; if ( spew != 0 ) { Msg( "%s checking block %d\n", pStudioHdr->pszName(), animdesc.animblock ); } // Async load the animation int iFrame = 0; const mstudioanim_t *panim = animdesc.pAnim( &iFrame ); if ( panim ) { ++resident; if ( spew > 1 ) { Msg( "%s:%s[%i:%i] was resident\n", pStudioHdr->pszName(), animdesc.pszName(), i, j ); } } else { if ( spew != 0 ) { Msg( "%s:%s[%i:%i] async load\n", pStudioHdr->pszName(), animdesc.pszName(), i, j ); } } } } } } } } } break; } } if ( !spew || checked <= 0 ) return; Msg( "%d of %d animations resident\n", resident, checked ); } void CSceneEntity::OnLoaded() { // Nothing } //----------------------------------------------------------------------------- // Purpose: Initiate scene playback //----------------------------------------------------------------------------- void CSceneEntity::StartPlayback( void ) { if ( !m_pScene ) { if ( m_bSceneMissing ) return; m_pScene = LoadScene( STRING( m_iszSceneFile ), this ); if ( !m_pScene ) { DevMsg( "%s missing from scenes.image\n", STRING( m_iszSceneFile ) ); m_bSceneMissing = true; return; } OnLoaded(); if ( ShouldNetwork() ) { m_nSceneStringIndex = g_pStringTableClientSideChoreoScenes->AddString( CBaseEntity::IsServer(), STRING( m_iszSceneFile ) ); } UpdateTransmitState(); } if ( m_bIsPlayingBack ) return; // Make sure actors are alive and able to handle this scene now, otherwise // we'll wait for them to show up if ( !CheckActors() ) { return; } m_bCompletedEarly = false; m_bWaitingForActor = false; m_bWaitingForInterrupt = false; m_bIsPlayingBack = true; NetworkProp()->NetworkStateForceUpdate(); m_bPaused = false; SetCurrentTime( 0.0f, true ); m_pScene->ResetSimulation(); ClearInterrupt(); // Put face back in neutral pose ClearSceneEvents( m_pScene, false ); m_OnStart.FireOutput( this, this, 0 ); // Aysnchronously load speak sounds CUtlSymbolTable prefetchSoundSymbolTable; CUtlRBTree< SpeakEventSound_t > soundnames( 0, 0, SpeakEventSoundLessFunc ); BuildSortedSpeakEventSoundsPrefetchList( m_pScene, prefetchSoundSymbolTable, soundnames, 0.0f ); PrefetchSpeakEventSounds( prefetchSoundSymbolTable, soundnames ); // Tell any managers we're within that we've started int c = m_hListManagers.Count(); for ( int i = 0; i < c; i++ ) { if ( m_hListManagers[i] ) { m_hListManagers[i]->SceneStarted( this ); } } PrefetchAnimBlocks( m_pScene ); } //----------------------------------------------------------------------------- // Purpose: Static method used to sort by event start time //----------------------------------------------------------------------------- bool CSceneEntity::SpeakEventSoundLessFunc( const SpeakEventSound_t& lhs, const SpeakEventSound_t& rhs ) { return lhs.m_flStartTime < rhs.m_flStartTime; } //----------------------------------------------------------------------------- // Purpose: Prefetches the list of sounds build by BuildSortedSpeakEventSoundsPrefetchList //----------------------------------------------------------------------------- void CSceneEntity::PrefetchSpeakEventSounds( CUtlSymbolTable& table, CUtlRBTree< SpeakEventSound_t >& soundnames ) { for ( int i = soundnames.FirstInorder(); i != soundnames.InvalidIndex() ; i = soundnames.NextInorder( i ) ) { SpeakEventSound_t& sound = soundnames[ i ]; // Look it up in the string table char const *soundname = table.String( sound.m_Symbol ); // Warning( "Prefetch %s\n", soundname ); PrefetchScriptSound( soundname ); } } //----------------------------------------------------------------------------- // Purpose: Builds list of sounds sorted by start time for prefetching //----------------------------------------------------------------------------- void CSceneEntity::BuildSortedSpeakEventSoundsPrefetchList( CChoreoScene *scene, CUtlSymbolTable& table, CUtlRBTree< SpeakEventSound_t >& soundnames, float timeOffset ) { Assert( scene ); // Iterate events and precache necessary resources for ( int i = 0; i < scene->GetNumEvents(); i++ ) { CChoreoEvent *event = scene->GetEvent( i ); if ( !event ) continue; // load any necessary data switch (event->GetType() ) { default: break; case CChoreoEvent::SPEAK: { // NOTE: The script entries associated with .vcds are forced to preload to avoid // loading hitches during triggering char soundname[ CChoreoEvent::MAX_CCTOKEN_STRING ]; Q_strncpy( soundname, event->GetParameters(), sizeof( soundname ) ); if ( event->GetCloseCaptionType() == CChoreoEvent::CC_MASTER ) { event->GetPlaybackCloseCaptionToken( soundname, sizeof( soundname ) ); } // In single player, try to use the combined or regular .wav files as needed if ( gpGlobals->maxClients == 1 ) { CBasePlayer *player = UTIL_GetLocalPlayer(); if ( player && !GetSoundNameForPlayer( event, player, soundname, sizeof( soundname ), player ) ) { // Skip to next event continue; } } /* else { // UNDONE: Probably need some other solution in multiplayer... (not sure how to "prefetch" on certain players // with one sound, but not prefetch the same sound for others...) } */ SpeakEventSound_t ses; ses.m_Symbol = table.AddString( soundname ); ses.m_flStartTime = timeOffset + event->GetStartTime(); soundnames.Insert( ses ); } break; case CChoreoEvent::SUBSCENE: { // Only allow a single level of subscenes for now if ( !scene->IsSubScene() ) { CChoreoScene *subscene = event->GetSubScene(); if ( !subscene ) { subscene = LoadScene( event->GetParameters(), this ); subscene->SetSubScene( true ); event->SetSubScene( subscene ); // Now precache it's resources, if any BuildSortedSpeakEventSoundsPrefetchList( subscene, table, soundnames, event->GetStartTime() ); } } } break; } } } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CSceneEntity::PausePlayback( void ) { if ( !m_bIsPlayingBack ) return; if ( m_bPaused ) return; m_bPaused = true; } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CSceneEntity::ResumePlayback( void ) { if ( !m_bIsPlayingBack ) return; if ( !m_bPaused ) return; Assert( m_pScene ); if ( !m_pScene ) { // This should never happen!!!! return; } // FIXME: Iterate using m_pScene->IterateResumeConditionEvents and // only resume if the event conditions have all been satisfied // FIXME: Just resume for now m_pScene->ResumeSimulation(); m_bPaused = false; m_bPausedViaInput = false; } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CSceneEntity::CancelPlayback( void ) { if ( !m_bIsPlayingBack ) return; m_bIsPlayingBack = false; m_bPaused = false; m_OnCanceled.FireOutput( this, this, 0 ); LocalScene_Printf( "%s : %8.2f: canceled\n", STRING( m_iszSceneFile ), m_flCurrentTime ); OnSceneFinished( true, false ); } void CSceneEntity::PitchShiftPlayback( float fPitch ) { fPitch = clamp( fPitch, SCENE_MIN_PITCH, SCENE_MAX_PITCH ); m_fPitch = fPitch; if ( !m_pScene ) return; for ( int iActor = 0 ; iActor < m_pScene->GetNumActors(); ++iActor ) { CBaseFlex *pTestActor = FindNamedActor( iActor ); if ( !pTestActor ) continue; char szBuff[ 256 ]; if ( m_pScene->GetPlayingSoundName( szBuff, sizeof( szBuff ) ) ) { CPASAttenuationFilter filter( pTestActor ); EmitSound_t params; params.m_pSoundName = szBuff; params.m_nPitch = 100.0f * fPitch; params.m_nFlags = SND_CHANGE_PITCH; pTestActor->EmitSound( filter, pTestActor->entindex(), params ); } } } //----------------------------------------------------------------------------- // Purpose: Start a resume scene, if we have one, and resume playing when it finishes //----------------------------------------------------------------------------- void CSceneEntity::QueueResumePlayback( void ) { // Do we have a resume scene? if ( m_iszResumeSceneFile != NULL_STRING ) { bool bStartedScene = false; // If it has ".vcd" somewhere in the string, try using it as a scene file first if ( Q_stristr( STRING(m_iszResumeSceneFile), ".vcd" ) ) { bStartedScene = InstancedScriptedScene( NULL, STRING(m_iszResumeSceneFile), &m_hWaitingForThisResumeScene, 0, false ) != 0; } // HACKHACK: For now, get the first target, and see if we can find a response for him if ( !bStartedScene ) { CBaseFlex *pActor = FindNamedActor( 0 ); if ( pActor ) { CAI_BaseActor *pBaseActor = dynamic_cast<CAI_BaseActor*>(pActor); if ( pBaseActor ) { AI_Response response; bool result = pBaseActor->SpeakFindResponse( response, STRING(m_iszResumeSceneFile), NULL ); if ( result ) { const char *szResponse = response.GetResponsePtr(); bStartedScene = InstancedScriptedScene( NULL, szResponse, &m_hWaitingForThisResumeScene, 0, false ) != 0; } } } } // If we started a scene/response, wait for it to finish if ( bStartedScene ) { m_bWaitingForResumeScene = true; } else { // Failed to create the scene. Resume immediately. ResumePlayback(); } } else { // No resume scene, so just resume immediately ResumePlayback(); } } //----------------------------------------------------------------------------- // Purpose: Query whether the scene actually loaded. Only meaninful after Spawn() //----------------------------------------------------------------------------- bool CSceneEntity::ValidScene() const { return ( m_pScene != NULL ); } //----------------------------------------------------------------------------- // Purpose: // Input : *pActor - // *scene - // *event - //----------------------------------------------------------------------------- void CSceneEntity::DispatchStartSubScene( CChoreoScene *scene, CBaseFlex *pActor, CChoreoEvent *event) { if ( !scene->IsSubScene() ) { CChoreoScene *subscene = event->GetSubScene(); if ( !subscene ) { Assert( 0 ); /* subscene = LoadScene( event->GetParameters() ); subscene->SetSubScene( true ); event->SetSubScene( subscene ); */ } if ( subscene ) { subscene->ResetSimulation(); } } } //----------------------------------------------------------------------------- // Purpose: All events are leading edge triggered // Input : currenttime - // *event - //----------------------------------------------------------------------------- void CSceneEntity::StartEvent( float currenttime, CChoreoScene *scene, CChoreoEvent *event ) { Assert( event ); if ( !Q_stricmp( event->GetName(), "NULL" ) ) { LocalScene_Printf( "%s : %8.2f: ignored %s\n", STRING( m_iszSceneFile ), currenttime, event->GetDescription() ); return; } CBaseFlex *pActor = NULL; CChoreoActor *actor = event->GetActor(); if ( actor ) { pActor = FindNamedActor( actor ); if (pActor == NULL) { Warning( "CSceneEntity %s unable to find actor named \"%s\"\n", STRING(GetEntityName()), actor->GetName() ); return; } } LocalScene_Printf( "%s : %8.2f: start %s\n", STRING( m_iszSceneFile ), currenttime, event->GetDescription() ); switch ( event->GetType() ) { case CChoreoEvent::SUBSCENE: { if ( pActor && !IsMultiplayer() ) { DispatchStartSubScene( scene, pActor, event ); } } break; case CChoreoEvent::EXPRESSION: { if ( pActor && !IsMultiplayer() ) { DispatchStartExpression( scene, pActor, event ); } } break; case CChoreoEvent::FLEXANIMATION: { if ( pActor && !IsMultiplayer() ) { DispatchStartFlexAnimation( scene, pActor, event ); } } break; case CChoreoEvent::LOOKAT: { if ( pActor && !IsMultiplayer() ) { CBaseEntity *pActor2 = FindNamedEntity( event->GetParameters( ), pActor ); if ( pActor2 ) { // Huh? DispatchStartLookAt( scene, pActor, pActor2, event ); } else { Warning( "CSceneEntity %s unable to find actor named \"%s\"\n", STRING(GetEntityName()), event->GetParameters() ); } } } break; case CChoreoEvent::SPEAK: { if ( pActor ) { // Speaking is edge triggered // FIXME: dB hack. soundlevel needs to be moved into inside of wav? soundlevel_t iSoundlevel = SNDLVL_TALKING; if (event->GetParameters2()) { iSoundlevel = (soundlevel_t)atoi( event->GetParameters2() ); if (iSoundlevel == SNDLVL_NONE) iSoundlevel = SNDLVL_TALKING; } DispatchStartSpeak( scene, pActor, event, iSoundlevel ); } } break; case CChoreoEvent::MOVETO: { // FIXME: make sure moveto's aren't edge triggered if ( !event->HasEndTime() ) { event->SetEndTime( event->GetStartTime() + 1.0 ); } if ( pActor && !IsMultiplayer() ) { CBaseEntity *pActor2 = NULL; if ( event->GetParameters3( ) && strlen( event->GetParameters3( ) ) > 0 ) { pActor2 = FindNamedEntityClosest( event->GetParameters( ), pActor, false, true, event->GetParameters3( ) ); } else { pActor2 = FindNamedEntity( event->GetParameters( ), pActor, false, true ); } if ( pActor2 ) { DispatchStartMoveTo( scene, pActor, pActor2, event ); } else { Warning( "CSceneEntity %s unable to find actor named \"%s\"\n", STRING(GetEntityName()), event->GetParameters() ); } } } break; case CChoreoEvent::FACE: { if ( pActor && !IsMultiplayer() ) { CBaseEntity *pActor2 = FindNamedEntity( event->GetParameters( ), pActor ); if ( pActor2 ) { DispatchStartFace( scene, pActor, pActor2, event ); } else { Warning( "CSceneEntity %s unable to find actor named \"%s\"\n", STRING(GetEntityName()), event->GetParameters() ); } } } break; case CChoreoEvent::GESTURE: { if ( pActor ) { DispatchStartGesture( scene, pActor, event ); } } break; case CChoreoEvent::GENERIC: { // If the first token in the parameters is "debugtext", print the rest of the text if ( event->GetParameters() && !Q_strncmp( event->GetParameters(), "debugtext", 9 ) ) { const char *pszText = event->GetParameters() + 10; hudtextparms_s tTextParam; tTextParam.x = -1; tTextParam.y = 0.65; tTextParam.effect = 0; tTextParam.r1 = 255; tTextParam.g1 = 170; tTextParam.b1 = 0; tTextParam.a1 = 255; tTextParam.r2 = 255; tTextParam.g2 = 170; tTextParam.b2 = 0; tTextParam.a2 = 255; tTextParam.fadeinTime = 0; tTextParam.fadeoutTime = 0; tTextParam.holdTime = 3.1; tTextParam.fxTime = 0; tTextParam.channel = 1; UTIL_HudMessageAll( tTextParam, pszText ); break; } if ( pActor ) { DispatchStartGeneric( scene, pActor, event ); } } break; case CChoreoEvent::FIRETRIGGER: { if ( IsMultiplayer() ) break; // Don't re-fire triggers during restore, the entities should already reflect all such state... if ( m_bRestoring ) { break; } CBaseEntity *pActivator = pActor; if (!pActivator) { pActivator = this; } // FIXME: how do I decide who fired it?? switch( atoi( event->GetParameters() ) ) { case 1: m_OnTrigger1.FireOutput( pActivator, this, 0 ); break; case 2: m_OnTrigger2.FireOutput( pActivator, this, 0 ); break; case 3: m_OnTrigger3.FireOutput( pActivator, this, 0 ); break; case 4: m_OnTrigger4.FireOutput( pActivator, this, 0 ); break; case 5: m_OnTrigger5.FireOutput( pActivator, this, 0 ); break; case 6: m_OnTrigger6.FireOutput( pActivator, this, 0 ); break; case 7: m_OnTrigger7.FireOutput( pActivator, this, 0 ); break; case 8: m_OnTrigger8.FireOutput( pActivator, this, 0 ); break; case 9: m_OnTrigger9.FireOutput( pActivator, this, 0 ); break; case 10: m_OnTrigger10.FireOutput( pActivator, this, 0 ); break; case 11: m_OnTrigger11.FireOutput( pActivator, this, 0 ); break; case 12: m_OnTrigger12.FireOutput( pActivator, this, 0 ); break; case 13: m_OnTrigger13.FireOutput( pActivator, this, 0 ); break; case 14: m_OnTrigger14.FireOutput( pActivator, this, 0 ); break; case 15: m_OnTrigger15.FireOutput( pActivator, this, 0 ); break; case 16: m_OnTrigger16.FireOutput( pActivator, this, 0 ); break; } } break; case CChoreoEvent::SEQUENCE: { if ( pActor ) { DispatchStartSequence( scene, pActor, event ); } } break; case CChoreoEvent::SECTION: { if ( IsMultiplayer() ) break; // Pauses scene playback DispatchPauseScene( scene, event->GetParameters() ); } break; case CChoreoEvent::LOOP: { DispatchProcessLoop( scene, event ); } break; case CChoreoEvent::INTERRUPT: { if ( IsMultiplayer() ) break; DispatchStartInterrupt( scene, event ); } break; case CChoreoEvent::STOPPOINT: { if ( IsMultiplayer() ) break; DispatchStopPoint( scene, event->GetParameters() ); } break; case CChoreoEvent::PERMIT_RESPONSES: { if ( IsMultiplayer() ) break; DispatchStartPermitResponses( scene, pActor, event ); } break; default: { // FIXME: Unhandeled event // Assert(0); } break; } } //----------------------------------------------------------------------------- // Purpose: // Input : currenttime - // *event - //----------------------------------------------------------------------------- void CSceneEntity::EndEvent( float currenttime, CChoreoScene *scene, CChoreoEvent *event ) { Assert( event ); if ( !Q_stricmp( event->GetName(), "NULL" ) ) { return; } CBaseFlex *pActor = NULL; CChoreoActor *actor = event->GetActor(); if ( actor ) { pActor = FindNamedActor( actor ); } LocalScene_Printf( "%s : %8.2f: finish %s\n", STRING( m_iszSceneFile ), currenttime, event->GetDescription() ); switch ( event->GetType() ) { case CChoreoEvent::EXPRESSION: { if ( pActor && !IsMultiplayer() ) { DispatchEndExpression( scene, pActor, event ); } } break; case CChoreoEvent::SPEAK: { if ( pActor ) { DispatchEndSpeak( scene, pActor, event ); } } break; case CChoreoEvent::FLEXANIMATION: { if ( pActor && !IsMultiplayer() ) { DispatchEndFlexAnimation( scene, pActor, event ); } } break; case CChoreoEvent::LOOKAT: { if ( pActor && !IsMultiplayer() ) { DispatchEndLookAt( scene, pActor, event ); } } break; case CChoreoEvent::GESTURE: { if ( pActor ) { DispatchEndGesture( scene, pActor, event ); } } break; case CChoreoEvent::GENERIC: { // If the first token in the parameters is "debugtext", we printed it and we're done if ( event->GetParameters() && !Q_strncmp( event->GetParameters(), "debugtext", 9 ) ) break; if ( pActor ) { DispatchEndGeneric( scene, pActor, event ); } } break; case CChoreoEvent::SEQUENCE: { if ( pActor ) { DispatchEndSequence( scene, pActor, event ); } } break; case CChoreoEvent::FACE: { if ( pActor && !IsMultiplayer() ) { DispatchEndFace( scene, pActor, event ); } } break; case CChoreoEvent::MOVETO: { if ( pActor && !IsMultiplayer() ) { DispatchEndMoveTo( scene, pActor, event ); } } break; case CChoreoEvent::SUBSCENE: { if ( IsMultiplayer() ) break; CChoreoScene *subscene = event->GetSubScene(); if ( subscene ) { subscene->ResetSimulation(); } } break; case CChoreoEvent::INTERRUPT: { if ( IsMultiplayer() ) break; DispatchEndInterrupt( scene, event ); } break; case CChoreoEvent::PERMIT_RESPONSES: { if ( IsMultiplayer() ) break; DispatchEndPermitResponses( scene, pActor, event ); } break; default: break; } } //----------------------------------------------------------------------------- // Purpose: Only spew one time per missing scene!!! // Input : *scenename - //----------------------------------------------------------------------------- void MissingSceneWarning( char const *scenename ) { static CUtlSymbolTable missing; // Make sure we only show the message once if ( UTL_INVAL_SYMBOL == missing.Find( scenename ) ) { missing.AddString( scenename ); Warning( "Scene '%s' missing!\n", scenename ); } } bool CSceneEntity::ShouldNetwork() const { if ( m_bMultiplayer ) { if ( m_pScene && ( m_pScene->HasEventsOfType( CChoreoEvent::FLEXANIMATION ) || m_pScene->HasEventsOfType( CChoreoEvent::EXPRESSION )|| m_pScene->HasEventsOfType( CChoreoEvent::GESTURE ) || m_pScene->HasEventsOfType( CChoreoEvent::SEQUENCE ) ) ) { return true; } } else { if ( m_pScene && ( m_pScene->HasEventsOfType( CChoreoEvent::FLEXANIMATION ) || m_pScene->HasEventsOfType( CChoreoEvent::EXPRESSION ) ) ) { return true; } } return false; } CChoreoScene *CSceneEntity::LoadScene( const char *filename, IChoreoEventCallback *pCallback ) { DevMsg( 2, "Blocking load of scene from '%s'\n", filename ); char loadfile[MAX_PATH]; Q_strncpy( loadfile, filename, sizeof( loadfile ) ); Q_SetExtension( loadfile, ".vcd", sizeof( loadfile ) ); Q_FixSlashes( loadfile ); // binary compiled vcd void *pBuffer; int fileSize; if ( !CopySceneFileIntoMemory( loadfile, &pBuffer, &fileSize ) ) { MissingSceneWarning( loadfile ); return NULL; } CChoreoScene *pScene = new CChoreoScene( NULL ); CUtlBuffer buf( pBuffer, fileSize, CUtlBuffer::READ_ONLY ); if ( !pScene->RestoreFromBinaryBuffer( buf, loadfile, &g_ChoreoStringPool ) ) { Warning( "CSceneEntity::LoadScene: Unable to load binary scene '%s'\n", loadfile ); delete pScene; pScene = NULL; } else { pScene->SetPrintFunc( LocalScene_Printf ); pScene->SetEventCallbackInterface( pCallback ); } FreeSceneFileMemory( pBuffer ); return pScene; } CChoreoScene *BlockingLoadScene( const char *filename ) { return CSceneEntity::LoadScene( filename, NULL ); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CSceneEntity::UnloadScene( void ) { if ( m_pScene ) { ClearSceneEvents( m_pScene, false ); for ( int i = 0 ; i < m_pScene->GetNumActors(); i++ ) { CBaseFlex *pTestActor = FindNamedActor( i ); if ( !pTestActor ) continue; pTestActor->RemoveChoreoScene( m_pScene ); } } delete m_pScene; m_pScene = NULL; } //----------------------------------------------------------------------------- // Purpose: Called every frame that an event is active (Start/EndEvent as also // called) // Input : *event - // Output : Returns true on success, false on failure. //----------------------------------------------------------------------------- void CSceneEntity::ProcessEvent( float currenttime, CChoreoScene *scene, CChoreoEvent *event ) { switch ( event->GetType() ) { case CChoreoEvent::SUBSCENE: { Assert( event->GetType() == CChoreoEvent::SUBSCENE ); CChoreoScene *subscene = event->GetSubScene(); if ( !subscene ) return; if ( subscene->SimulationFinished() ) return; // Have subscenes think for appropriate time subscene->Think( m_flFrameTime ); } break; default: break; } return; } //----------------------------------------------------------------------------- // Purpose: Called for events that are part of a pause condition // Input : *event - // Output : Returns true on event completed, false on non-completion. //----------------------------------------------------------------------------- bool CSceneEntity::CheckEvent( float currenttime, CChoreoScene *scene, CChoreoEvent *event ) { switch ( event->GetType() ) { case CChoreoEvent::SUBSCENE: { } break; default: { CBaseFlex *pActor = NULL; CChoreoActor *actor = event->GetActor(); if ( actor ) { pActor = FindNamedActor( actor ); if (pActor == NULL) { Warning( "CSceneEntity %s unable to find actor \"%s\"\n", STRING(GetEntityName()), actor->GetName() ); return true; } } if (pActor) { return pActor->CheckSceneEvent( currenttime, scene, event ); } } break; } return true; } //----------------------------------------------------------------------------- // Purpose: Get a sticky version of a named actor // Input : CChoreoActor // Output : CBaseFlex //----------------------------------------------------------------------------- CBaseFlex *CSceneEntity::FindNamedActor( int index ) { if (m_hActorList.Count() == 0) { m_hActorList.SetCount( m_pScene->GetNumActors() ); NetworkProp()->NetworkStateForceUpdate(); } if ( !m_hActorList.IsValidIndex( index ) ) { DevWarning( "Scene %s has %d actors, but scene entity only has %d actors\n", m_pScene->GetFilename(), m_pScene->GetNumActors(), m_hActorList.Size() ); return NULL; } CBaseFlex *pActor = m_hActorList[ index ]; if (pActor == NULL || !pActor->IsAlive() ) { CChoreoActor *pChoreoActor = m_pScene->GetActor( index ); if ( !pChoreoActor ) return NULL; pActor = FindNamedActor( pChoreoActor->GetName() ); if (pActor) { // save who we found so we'll use them again m_hActorList[ index ] = pActor; NetworkProp()->NetworkStateForceUpdate(); } } return pActor; } //----------------------------------------------------------------------------- // Purpose: Get a sticky version of a named actor // Input : CChoreoActor // Output : CBaseFlex //----------------------------------------------------------------------------- CBaseFlex *CSceneEntity::FindNamedActor( CChoreoActor *pChoreoActor ) { int index = m_pScene->FindActorIndex( pChoreoActor ); if (index >= 0) { return FindNamedActor( index ); } return NULL; } //----------------------------------------------------------------------------- // Purpose: Search for an actor by name, make sure it can do face poses // Input : *name - // Output : CBaseFlex //----------------------------------------------------------------------------- CBaseFlex *CSceneEntity::FindNamedActor( const char *name ) { CBaseEntity *entity = FindNamedEntity( name, NULL, true ); if ( !entity ) { // Couldn't find actor! return NULL; } // Make sure it can actually do facial animation, etc. CBaseFlex *flexEntity = dynamic_cast< CBaseFlex * >( entity ); if ( !flexEntity ) { // That actor was not a CBaseFlex! return NULL; } return flexEntity; } //----------------------------------------------------------------------------- // Purpose: Find an entity specified by a target name // Input : *name - // Output : CBaseEntity //----------------------------------------------------------------------------- CBaseEntity *CSceneEntity::FindNamedTarget( string_t iszTarget, bool bBaseFlexOnly ) { if ( !stricmp( STRING(iszTarget), "!activator" ) ) return m_hActivator; // If we don't have a wildcard in the target, just return the first entity found if ( !strchr( STRING(iszTarget), '*' ) ) return gEntList.FindEntityByName( NULL, iszTarget ); CBaseEntity *pTarget = NULL; while ( (pTarget = gEntList.FindEntityByName( pTarget, iszTarget )) != NULL ) { if ( bBaseFlexOnly ) { // Make sure it can actually do facial animation, etc. if ( dynamic_cast< CBaseFlex * >( pTarget ) ) return pTarget; } else { return pTarget; } } // Failed to find one return NULL; } //----------------------------------------------------------------------------- // Purpose: Filters entities only if they're clear //----------------------------------------------------------------------------- class CSceneFindMarkFilter : public IEntityFindFilter { public: void SetActor( CBaseEntity *pActor ) { m_hActor = pActor; } bool ShouldFindEntity( CBaseEntity *pEntity ) { if ( !m_hActor ) return true; // If we find no truly valid marks, we'll just use the first. if ( !m_hEntityFound.Get() ) { m_hEntityFound = pEntity; } // We only want marks that are clear trace_t tr; Vector vecOrigin = pEntity->GetAbsOrigin(); AI_TraceHull( vecOrigin, vecOrigin, m_hActor->WorldAlignMins(), m_hActor->WorldAlignMaxs(), MASK_SOLID, m_hActor, COLLISION_GROUP_NONE, &tr ); if ( tr.startsolid ) { return false; } m_hEntityFound = pEntity; return true; } CBaseEntity *GetFilterResult( void ) { return m_hEntityFound; } private: EHANDLE m_hActor; // To maintain backwards compatability, store off the first mark // we find. If we find no truly valid marks, we'll just use the first. EHANDLE m_hEntityFound; }; //----------------------------------------------------------------------------- // Purpose: Finds the entity nearest to both entities, and is clear //----------------------------------------------------------------------------- class CSceneFindNearestMarkFilter : public IEntityFindFilter { public: CSceneFindNearestMarkFilter( const CBaseEntity *pActor, const Vector &vecPos2, float flMaxRadius = MAX_TRACE_LENGTH ) { m_vecPos2 = vecPos2; m_flMaxSegmentDistance = flMaxRadius; m_flNearestToTarget = flMaxRadius; m_pNearestToTarget = NULL; m_flNearestToActor = flMaxRadius; m_pNearestToActor = NULL; m_hActor = pActor; if (pActor) { m_vecPos1 = pActor->GetAbsOrigin(); m_flMaxSegmentDistance = MIN( flMaxRadius, (m_vecPos1 - m_vecPos2).Length() + 1.0 ); if (m_flMaxSegmentDistance <= 1.0) { // must be closest to self m_flMaxSegmentDistance = MIN( flMaxRadius, MAX_TRACE_LENGTH ); } } } bool ShouldFindEntity( CBaseEntity *pEntity ) { if ( !m_hActor ) return true; // If we find no truly valid marks, we'll just use the first. if ( m_pNearestToActor == NULL ) { m_pNearestToActor = pEntity; } // We only want marks that are clear trace_t tr; Vector vecOrigin = pEntity->GetAbsOrigin(); AI_TraceHull( vecOrigin, vecOrigin, m_hActor->WorldAlignMins(), m_hActor->WorldAlignMaxs(), MASK_SOLID, m_hActor, COLLISION_GROUP_NONE, &tr ); if ( !tr.startsolid || tr.m_pEnt == m_hActor) { float dist1 = (m_vecPos1 - pEntity->GetAbsOrigin()).Length(); float dist2 = (m_vecPos2 - pEntity->GetAbsOrigin()).Length(); /* char text[256]; Q_snprintf( text, sizeof( text ), "%.0f : %.0f", dist1, dist2 ); NDebugOverlay::Text( pEntity->GetAbsOrigin() + Vector( 0, 0, 8 ), text, false, 5.0f ); */ // find the point closest to the actor if (dist1 <= m_flNearestToActor) { m_pNearestToActor = pEntity; m_flNearestToActor = dist2; } // find that node that's closest to both, but the distance to it from the actor isn't farther than // the distance to the second node. This should keep the actor from walking past their point of interest if (dist1 <= m_flMaxSegmentDistance && dist2 <= m_flMaxSegmentDistance && dist2 < m_flNearestToTarget) { m_pNearestToTarget = pEntity; m_flNearestToTarget = dist2; } } return false; } CBaseEntity *GetFilterResult( void ) { if (m_pNearestToTarget) return m_pNearestToTarget; return m_pNearestToActor; } private: EHANDLE m_hActor; Vector m_vecPos1; Vector m_vecPos2; float m_flMaxSegmentDistance; float m_flNearestToTarget; CBaseEntity *m_pNearestToTarget; float m_flNearestToActor; CBaseEntity *m_pNearestToActor; }; //----------------------------------------------------------------------------- // Purpose: Search for an actor by name, make sure it can do face poses // Input : *name - // Output : CBaseFlex //----------------------------------------------------------------------------- CBaseEntity *CSceneEntity::FindNamedEntity( const char *name, CBaseEntity *pActor, bool bBaseFlexOnly, bool bUseClear ) { CBaseEntity *entity = NULL; if ( !stricmp( name, "Player" ) || !stricmp( name, "!player" )) { #ifdef SecobMod__Enable_Fixed_Multiplayer_AI entity = UTIL_GetNearestPlayer(GetAbsOrigin()); #else entity = ( gpGlobals->maxClients == 1 ) ? ( CBaseEntity * )UTIL_GetLocalPlayer() : NULL; #endif //SecobMod__Enable_Fixed_Multiplayer_AI } else if ( !stricmp( name, "!target1" ) ) { if (m_hTarget1 == NULL) { m_hTarget1 = FindNamedTarget( m_iszTarget1, bBaseFlexOnly ); } return m_hTarget1; } else if ( !stricmp( name, "!target2" ) ) { if (m_hTarget2 == NULL) { m_hTarget2 = FindNamedTarget( m_iszTarget2, bBaseFlexOnly ); } return m_hTarget2; } else if ( !stricmp( name, "!target3" ) ) { if (m_hTarget3 == NULL) { m_hTarget3 = FindNamedTarget( m_iszTarget3, bBaseFlexOnly ); } return m_hTarget3; } else if ( !stricmp( name, "!target4" ) ) { if (m_hTarget4 == NULL) { m_hTarget4 = FindNamedTarget( m_iszTarget4, bBaseFlexOnly ); } return m_hTarget4; } else if ( !stricmp( name, "!target5" ) ) { if (m_hTarget5 == NULL) { m_hTarget5 = FindNamedTarget( m_iszTarget5, bBaseFlexOnly ); } return m_hTarget5; } else if ( !stricmp( name, "!target6" ) ) { if (m_hTarget6 == NULL) { m_hTarget6 = FindNamedTarget( m_iszTarget6, bBaseFlexOnly ); } return m_hTarget6; } else if ( !stricmp( name, "!target7" ) ) { if (m_hTarget7 == NULL) { m_hTarget7 = FindNamedTarget( m_iszTarget7, bBaseFlexOnly ); } return m_hTarget7; } else if ( !stricmp( name, "!target8" ) ) { if (m_hTarget8 == NULL) { m_hTarget8 = FindNamedTarget( m_iszTarget8, bBaseFlexOnly ); } return m_hTarget8; } else if (pActor && pActor->MyNPCPointer()) { CSceneFindMarkFilter *pFilter = NULL; if ( bUseClear ) { pFilter = new CSceneFindMarkFilter(); pFilter->SetActor( pActor ); } entity = pActor->MyNPCPointer()->FindNamedEntity( name, pFilter ); if ( !entity && pFilter ) { entity = pFilter->GetFilterResult(); } } else { // search for up to 32 entities with the same name and choose one randomly CBaseEntity *entityList[ FINDNAMEDENTITY_MAX_ENTITIES ]; int iCount; entity = NULL; for( iCount = 0; iCount < FINDNAMEDENTITY_MAX_ENTITIES; iCount++ ) { entity = gEntList.FindEntityByName( entity, name, NULL, pActor ); if ( !entity ) { break; } entityList[ iCount ] = entity; } if ( iCount > 0 ) { entity = entityList[ RandomInt( 0, iCount - 1 ) ]; } else { entity = NULL; } } return entity; } //----------------------------------------------------------------------------- // Purpose: Search for an actor by name, make sure it can do face poses // Input : *name - // Output : CBaseFlex //----------------------------------------------------------------------------- CBaseEntity *CSceneEntity::FindNamedEntityClosest( const char *name, CBaseEntity *pActor, bool bBaseFlexOnly, bool bUseClear, const char *pszSecondary ) { CBaseEntity *entity = NULL; if ( !stricmp( name, "!activator" ) ) { return m_hActivator; } else if ( !stricmp( name, "Player" ) || !stricmp( name, "!player" )) { #ifdef SecobMod__Enable_Fixed_Multiplayer_AI entity = UTIL_GetNearestPlayer(GetAbsOrigin()); #else entity = ( gpGlobals->maxClients == 1 ) ? ( CBaseEntity * )UTIL_GetLocalPlayer() : NULL; #endif //SecobMod__Enable_Fixed_Multiplayer_AI return entity; } else if ( !stricmp( name, "!target1" ) ) { name = STRING( m_iszTarget1 ); } else if ( !stricmp( name, "!target2" ) ) { name = STRING( m_iszTarget2 ); } else if ( !stricmp( name, "!target3" ) ) { name = STRING( m_iszTarget3 ); } else if ( !stricmp( name, "!target4" ) ) { name = STRING( m_iszTarget4 ); } else if ( !stricmp( name, "!target5" ) ) { name = STRING( m_iszTarget5 ); } else if ( !stricmp( name, "!target6" ) ) { name = STRING( m_iszTarget6 ); } else if ( !stricmp( name, "!target7" ) ) { name = STRING( m_iszTarget7 ); } if (pActor && pActor->MyNPCPointer()) { if (pszSecondary && strlen( pszSecondary ) > 0) { CBaseEntity *pActor2 = FindNamedEntityClosest( pszSecondary, pActor, false, false, NULL ); if (pActor2) { CSceneFindNearestMarkFilter *pFilter = new CSceneFindNearestMarkFilter( pActor, pActor2->GetAbsOrigin() ); entity = pActor->MyNPCPointer()->FindNamedEntity( name, pFilter ); if (!entity && pFilter) { entity = pFilter->GetFilterResult(); } } } if (!entity) { CSceneFindMarkFilter *pFilter = NULL; if ( bUseClear ) { pFilter = new CSceneFindMarkFilter(); pFilter->SetActor( pActor ); } entity = pActor->MyNPCPointer()->FindNamedEntity( name, pFilter ); if (!entity && pFilter) { entity = pFilter->GetFilterResult(); } } } else { // search for up to 32 entities with the same name and choose one randomly int iCount; entity = NULL; CBaseEntity *current = NULL; for( iCount = 0; iCount < FINDNAMEDENTITY_MAX_ENTITIES; iCount++ ) { current = gEntList.FindEntityByName( current, name, NULL, pActor ); if ( current ) { if (RandomInt( 0, iCount ) == 0) entity = current; } } entity = NULL; } return entity; } //----------------------------------------------------------------------------- // Purpose: Remove all "scene" expressions from all actors in this scene //----------------------------------------------------------------------------- void CSceneEntity::ClearSceneEvents( CChoreoScene *scene, bool canceled ) { if ( !m_pScene ) return; LocalScene_Printf( "%s : %8.2f: clearing events\n", STRING( m_iszSceneFile ), m_flCurrentTime ); int i; for ( i = 0 ; i < m_pScene->GetNumActors(); i++ ) { CBaseFlex *pActor = FindNamedActor( i ); if ( !pActor ) continue; // Clear any existing expressions pActor->ClearSceneEvents( scene, canceled ); } // Iterate events and precache necessary resources for ( i = 0; i < scene->GetNumEvents(); i++ ) { CChoreoEvent *event = scene->GetEvent( i ); if ( !event ) continue; // load any necessary data switch (event->GetType() ) { default: break; case CChoreoEvent::SUBSCENE: { // Only allow a single level of subscenes for now if ( !scene->IsSubScene() ) { CChoreoScene *subscene = event->GetSubScene(); if ( subscene ) { ClearSceneEvents( subscene, canceled ); } } } break; } } } //----------------------------------------------------------------------------- // Purpose: Remove all imposed schedules from all actors in this scene //----------------------------------------------------------------------------- void CSceneEntity::ClearSchedules( CChoreoScene *scene ) { if ( !m_pScene ) return; int i; for ( i = 0 ; i < m_pScene->GetNumActors(); i++ ) { CBaseFlex *pActor = FindNamedActor( i ); if ( !pActor ) continue; CAI_BaseNPC *pNPC = pActor->MyNPCPointer(); if ( pNPC ) { /* if ( pNPC->IsCurSchedule( SCHED_SCENE_GENERIC ) ) pNPC->ClearSchedule( "Scene entity clearing all actor schedules" ); */ } else { pActor->ResetSequence( pActor->SelectWeightedSequence( ACT_IDLE ) ); pActor->SetCycle( 0 ); } // Clear any existing expressions } // Iterate events and precache necessary resources for ( i = 0; i < scene->GetNumEvents(); i++ ) { CChoreoEvent *event = scene->GetEvent( i ); if ( !event ) continue; // load any necessary data switch (event->GetType() ) { default: break; case CChoreoEvent::SUBSCENE: { // Only allow a single level of subscenes for now if ( !scene->IsSubScene() ) { CChoreoScene *subscene = event->GetSubScene(); if ( subscene ) { ClearSchedules( subscene ); } } } break; } } } //----------------------------------------------------------------------------- // Purpose: If we are currently interruptable, pause this scene and wait for the other // scene to finish // Input : *otherScene - //----------------------------------------------------------------------------- bool CSceneEntity::InterruptThisScene( CSceneEntity *otherScene ) { Assert( otherScene ); if ( !IsInterruptable() ) { return false; } // Already interrupted if ( m_bInterrupted ) { return false; } m_bInterrupted = true; m_hInterruptScene = otherScene; // Ask other scene to tell us when it's finished or canceled otherScene->RequestCompletionNotification( this ); PausePlayback(); return true; } /* void scene_interrupt( const CCommand &args ) { if ( args.ArgC() != 3 ) return; const char *scene1 = args[1]; const char *scene2 = args[2]; CSceneEntity *s1 = dynamic_cast< CSceneEntity * >( gEntList.FindEntityByName( NULL, scene1 ) ); CSceneEntity *s2 = dynamic_cast< CSceneEntity * >( gEntList.FindEntityByName( NULL, scene2 ) ); if ( !s1 || !s2 ) return; if ( s1->InterruptThisScene( s2 ) ) { s2->StartPlayback(); } } static ConCommand interruptscene( "int", scene_interrupt, "interrupt scene 1 with scene 2.", FCVAR_CHEAT ); */ //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CSceneEntity::CheckInterruptCompletion() { if ( !m_bInterrupted ) return; // If the interruptor goes away it's the same as having that scene finish up... if ( m_hInterruptScene != NULL && !m_bInterruptSceneFinished ) { return; } m_bInterrupted = false; m_hInterruptScene = NULL; ResumePlayback(); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CSceneEntity::ClearInterrupt() { m_nInterruptCount = 0; m_bInterrupted = false; m_hInterruptScene = NULL; } //----------------------------------------------------------------------------- // Purpose: Another scene is asking us to notify upon completion // Input : *notify - //----------------------------------------------------------------------------- void CSceneEntity::RequestCompletionNotification( CSceneEntity *notify ) { CHandle< CSceneEntity > h; h = notify; // Only add it once if ( m_hNotifySceneCompletion.Find( h ) == m_hNotifySceneCompletion.InvalidIndex() ) { m_hNotifySceneCompletion.AddToTail( h ); } } //----------------------------------------------------------------------------- // Purpose: An interrupt scene has finished or been canceled, we can resume once we pick up this state in CheckInterruptCompletion // Input : *interruptor - //----------------------------------------------------------------------------- void CSceneEntity::NotifyOfCompletion( CSceneEntity *interruptor ) { Assert( m_bInterrupted ); Assert( m_hInterruptScene == interruptor ); m_bInterruptSceneFinished = true; CheckInterruptCompletion(); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CSceneEntity::AddListManager( CSceneListManager *pManager ) { CHandle< CSceneListManager > h; h = pManager; // Only add it once if ( m_hListManagers.Find( h ) == m_hListManagers.InvalidIndex() ) { m_hListManagers.AddToTail( h ); } } //----------------------------------------------------------------------------- // Purpose: Clear any targets that a referencing !activator //----------------------------------------------------------------------------- void CSceneEntity::ClearActivatorTargets( void ) { if ( !stricmp( STRING(m_iszTarget1), "!activator" ) ) { // We need to clear out actors so they're re-evaluated m_hActorList.Purge(); NetworkProp()->NetworkStateForceUpdate(); m_hTarget1 = NULL; } if ( !stricmp( STRING(m_iszTarget2), "!activator" ) ) { // We need to clear out actors so they're re-evaluated m_hActorList.Purge(); NetworkProp()->NetworkStateForceUpdate(); m_hTarget2 = NULL; } if ( !stricmp( STRING(m_iszTarget3), "!activator" ) ) { // We need to clear out actors so they're re-evaluated m_hActorList.Purge(); NetworkProp()->NetworkStateForceUpdate(); m_hTarget3 = NULL; } if ( !stricmp( STRING(m_iszTarget4), "!activator" ) ) { // We need to clear out actors so they're re-evaluated m_hActorList.Purge(); NetworkProp()->NetworkStateForceUpdate(); m_hTarget4 = NULL; } if ( !stricmp( STRING(m_iszTarget5), "!activator" ) ) { // We need to clear out actors so they're re-evaluated m_hActorList.Purge(); NetworkProp()->NetworkStateForceUpdate(); m_hTarget5 = NULL; } if ( !stricmp( STRING(m_iszTarget6), "!activator" ) ) { // We need to clear out actors so they're re-evaluated m_hActorList.Purge(); NetworkProp()->NetworkStateForceUpdate(); m_hTarget6 = NULL; } if ( !stricmp( STRING(m_iszTarget7), "!activator" ) ) { // We need to clear out actors so they're re-evaluated m_hActorList.Purge(); NetworkProp()->NetworkStateForceUpdate(); m_hTarget7 = NULL; } if ( !stricmp( STRING(m_iszTarget8), "!activator" ) ) { // We need to clear out actors so they're re-evaluated m_hActorList.Purge(); NetworkProp()->NetworkStateForceUpdate(); m_hTarget8 = NULL; } } //----------------------------------------------------------------------------- // Purpose: Called when a scene is completed or canceled //----------------------------------------------------------------------------- void CSceneEntity::OnSceneFinished( bool canceled, bool fireoutput ) { if ( !m_pScene ) return; LocalScene_Printf( "%s : %8.2f: finished\n", STRING( m_iszSceneFile ), m_flCurrentTime ); // Notify any listeners int c = m_hNotifySceneCompletion.Count(); int i; for ( i = 0; i < c; i++ ) { CSceneEntity *ent = m_hNotifySceneCompletion[ i ].Get(); if ( !ent ) continue; ent->NotifyOfCompletion( this ); } m_hNotifySceneCompletion.RemoveAll(); // Clear simulation m_pScene->ResetSimulation(); m_bIsPlayingBack = false; m_bPaused = false; SetCurrentTime( 0.0f, false ); // Clear interrupt state if we were interrupted for some reason ClearInterrupt(); if ( fireoutput && !m_bCompletedEarly) { m_OnCompletion.FireOutput( this, this, 0 ); } // Put face back in neutral pose ClearSceneEvents( m_pScene, canceled ); for ( i = 0 ; i < m_pScene->GetNumActors(); i++ ) { CBaseFlex *pTestActor = FindNamedActor( i ); if ( !pTestActor ) continue; pTestActor->RemoveChoreoScene( m_pScene, canceled ); // If we interrupted the actor's previous scenes, resume them if ( m_bInterruptedActorsScenes ) { QueueActorsScriptedScenesToResume( pTestActor, false ); } } } //----------------------------------------------------------------------------- // Should we transmit it to the client? //----------------------------------------------------------------------------- int CSceneEntity::UpdateTransmitState() { if ( !ShouldNetwork() ) { return SetTransmitState( FL_EDICT_DONTSEND ); } if ( m_pRecipientFilter ) { return SetTransmitState( FL_EDICT_FULLCHECK ); } return SetTransmitState( FL_EDICT_ALWAYS ); } //----------------------------------------------------------------------------- // Purpose: Which clients should we be transmitting to? //----------------------------------------------------------------------------- int CSceneEntity::ShouldTransmit( const CCheckTransmitInfo *pInfo ) { int result = BaseClass::ShouldTransmit( pInfo ); // if we have excluded them via our recipient filter, don't send if ( m_pRecipientFilter && result != FL_EDICT_DONTSEND ) { bool bFound = false; // If we can't find them in the recipient list, exclude int i; for ( i=0; i<m_pRecipientFilter->GetRecipientCount();i++ ) { int iRecipient = m_pRecipientFilter->GetRecipientIndex(i); CBasePlayer *player = static_cast< CBasePlayer * >( CBaseEntity::Instance( iRecipient ) ); if ( player && player->edict() == pInfo->m_pClientEnt ) { bFound = true; break; } } if ( !bFound ) { result = FL_EDICT_DONTSEND; } } return result; } void CSceneEntity::SetRecipientFilter( IRecipientFilter *filter ) { // create a copy of this filter if ( filter ) { m_pRecipientFilter = new CRecipientFilter(); m_pRecipientFilter->CopyFrom( (CRecipientFilter &)( *filter ) ); } } //----------------------------------------------------------------------------- // Purpose: // Input : // Output : //----------------------------------------------------------------------------- class CInstancedSceneEntity : public CSceneEntity { DECLARE_DATADESC(); DECLARE_CLASS( CInstancedSceneEntity, CSceneEntity ); public: EHANDLE m_hOwner; bool m_bHadOwner; float m_flPostSpeakDelay; float m_flPreDelay; char m_szInstanceFilename[ CChoreoScene::MAX_SCENE_FILENAME ]; bool m_bIsBackground; virtual void StartPlayback( void ); virtual void DoThink( float frametime ); virtual CBaseFlex *FindNamedActor( const char *name ); virtual CBaseEntity *FindNamedEntity( const char *name ); virtual float GetPostSpeakDelay() { return m_flPostSpeakDelay; } virtual void SetPostSpeakDelay( float flDelay ) { m_flPostSpeakDelay = flDelay; } virtual float GetPreDelay() { return m_flPreDelay; } virtual void SetPreDelay( float flDelay ) { m_flPreDelay = flDelay; } virtual void OnLoaded(); virtual void DispatchStartMoveTo( CChoreoScene *scene, CBaseFlex *actor, CBaseEntity *actor2, CChoreoEvent *event ) { if (PassThrough( actor )) BaseClass::DispatchStartMoveTo( scene, actor, actor2, event ); }; virtual void DispatchEndMoveTo( CChoreoScene *scene, CBaseFlex *actor, CChoreoEvent *event ) { if (PassThrough( actor )) BaseClass::DispatchEndMoveTo( scene, actor, event ); }; virtual void DispatchStartFace( CChoreoScene *scene, CBaseFlex *actor, CBaseEntity *actor2, CChoreoEvent *event ) { if (PassThrough( actor )) BaseClass::DispatchStartFace( scene, actor, actor2, event ); }; virtual void DispatchEndFace( CChoreoScene *scene, CBaseFlex *actor, CChoreoEvent *event ) { if (PassThrough( actor )) BaseClass::DispatchEndFace( scene, actor, event ); }; virtual void DispatchStartSequence( CChoreoScene *scene, CBaseFlex *actor, CChoreoEvent *event ) { if ( IsMultiplayer() ) { BaseClass::DispatchStartSequence( scene, actor, event ); } }; virtual void DispatchEndSequence( CChoreoScene *scene, CBaseFlex *actor, CChoreoEvent *event ) { if ( IsMultiplayer() ) { BaseClass::DispatchEndSequence( scene, actor, event ); } }; virtual void DispatchPauseScene( CChoreoScene *scene, const char *parameters ) { /* suppress */ }; void OnRestore(); virtual float EstimateLength( void ); private: bool PassThrough( CBaseFlex *actor ); }; LINK_ENTITY_TO_CLASS( instanced_scripted_scene, CInstancedSceneEntity ); //--------------------------------------------------------- // Save/Restore //--------------------------------------------------------- BEGIN_DATADESC( CInstancedSceneEntity ) DEFINE_FIELD( m_hOwner, FIELD_EHANDLE ), DEFINE_FIELD( m_bHadOwner, FIELD_BOOLEAN ), DEFINE_FIELD( m_flPostSpeakDelay, FIELD_FLOAT ), DEFINE_FIELD( m_flPreDelay, FIELD_FLOAT ), DEFINE_AUTO_ARRAY( m_szInstanceFilename, FIELD_CHARACTER ), DEFINE_FIELD( m_bIsBackground, FIELD_BOOLEAN ), END_DATADESC() //----------------------------------------------------------------------------- // Purpose: create a one-shot scene, no movement, sequences, etc. // Input : // Output : //----------------------------------------------------------------------------- float InstancedScriptedScene( CBaseFlex *pActor, const char *pszScene, EHANDLE *phSceneEnt, float flPostDelay, bool bIsBackground, AI_Response *response, bool bMultiplayer, IRecipientFilter *filter /* = NULL */ ) { VPROF( "InstancedScriptedScene" ); CInstancedSceneEntity *pScene = (CInstancedSceneEntity *)CBaseEntity::CreateNoSpawn( "instanced_scripted_scene", vec3_origin, vec3_angle ); // This code expands any $gender tags into male or female tags based on the gender of the actor (based on his/her .mdl) if ( pActor ) { pActor->GenderExpandString( pszScene, pScene->m_szInstanceFilename, sizeof( pScene->m_szInstanceFilename ) ); } else { Q_strncpy( pScene->m_szInstanceFilename, pszScene, sizeof( pScene->m_szInstanceFilename ) ); } pScene->m_iszSceneFile = MAKE_STRING( pScene->m_szInstanceFilename ); // FIXME: I should set my output to fire something that kills me.... // FIXME: add a proper initialization function pScene->m_hOwner = pActor; pScene->m_bHadOwner = pActor != NULL; pScene->m_bMultiplayer = bMultiplayer; pScene->SetPostSpeakDelay( flPostDelay ); DispatchSpawn( pScene ); pScene->Activate(); pScene->m_bIsBackground = bIsBackground; pScene->SetBackground( bIsBackground ); pScene->SetRecipientFilter( filter ); if ( response ) { float flPreDelay = response->GetPreDelay(); if ( flPreDelay ) { pScene->SetPreDelay( flPreDelay ); } } pScene->StartPlayback(); if ( response ) { // If the response wants us to abort on NPC state switch, remember that pScene->SetBreakOnNonIdle( response->ShouldBreakOnNonIdle() ); } if ( phSceneEnt ) { *phSceneEnt = pScene; } return pScene->EstimateLength(); } //----------------------------------------------------------------------------- // Purpose: // Input : *pActor - // *soundnmame - // *phSceneEnt - // Output : float //----------------------------------------------------------------------------- float InstancedAutoGeneratedSoundScene( CBaseFlex *pActor, char const *soundname, EHANDLE *phSceneEnt /*= NULL*/ ) { if ( !pActor ) { Warning( "InstancedAutoGeneratedSoundScene: Expecting non-NULL pActor for sound %s\n", soundname ); return 0; } CInstancedSceneEntity *pScene = (CInstancedSceneEntity *)CBaseEntity::CreateNoSpawn( "instanced_scripted_scene", vec3_origin, vec3_angle ); Q_strncpy( pScene->m_szInstanceFilename, UTIL_VarArgs( "AutoGenerated(%s)", soundname ), sizeof( pScene->m_szInstanceFilename ) ); pScene->m_iszSceneFile = MAKE_STRING( pScene->m_szInstanceFilename ); pScene->m_hOwner = pActor; pScene->m_bHadOwner = pActor != NULL; pScene->GenerateSoundScene( pActor, soundname ); pScene->Spawn(); pScene->Activate(); pScene->StartPlayback(); if ( phSceneEnt ) { *phSceneEnt = pScene; } return pScene->EstimateLength(); } //----------------------------------------------------------------------------- void StopScriptedScene( CBaseFlex *pActor, EHANDLE hSceneEnt ) { CBaseEntity *pEntity = hSceneEnt; CSceneEntity *pScene = dynamic_cast<CSceneEntity *>(pEntity); if ( pScene ) { LocalScene_Printf( "%s : stop scripted scene\n", STRING( pScene->m_iszSceneFile ) ); pScene->CancelPlayback(); } } //----------------------------------------------------------------------------- // Purpose: // Input : *pszScene - // Output : float //----------------------------------------------------------------------------- float GetSceneDuration( char const *pszScene ) { unsigned int msecs = 0; SceneCachedData_t cachedData; if ( scenefilecache->GetSceneCachedData( pszScene, &cachedData ) ) { msecs = cachedData.msecs; } return (float)msecs * 0.001f; } //----------------------------------------------------------------------------- // Purpose: // Input : *pszScene - // Output : int //----------------------------------------------------------------------------- int GetSceneSpeechCount( char const *pszScene ) { SceneCachedData_t cachedData; if ( scenefilecache->GetSceneCachedData( pszScene, &cachedData ) ) { return cachedData.numSounds; } return 0; } //----------------------------------------------------------------------------- // Purpose: Used for precaching instanced scenes // Input : *pszScene - //----------------------------------------------------------------------------- void PrecacheInstancedScene( char const *pszScene ) { static int nMakingReslists = -1; if ( nMakingReslists == -1 ) { nMakingReslists = CommandLine()->FindParm( "-makereslists" ) > 0 ? 1 : 0; } if ( nMakingReslists == 1 ) { // Just stat the file to add to reslist g_pFullFileSystem->Size( pszScene ); } // verify existence, cache is pre-populated, should be there SceneCachedData_t sceneData; if ( !scenefilecache->GetSceneCachedData( pszScene, &sceneData ) ) { // Scenes are sloppy and don't always exist. // A scene that is not in the pre-built cache image, but on disk, is a true error. if ( developer.GetInt() && ( IsX360() && ( g_pFullFileSystem->GetDVDMode() != DVDMODE_STRICT ) && g_pFullFileSystem->FileExists( pszScene, "GAME" ) ) ) { Warning( "PrecacheInstancedScene: Missing scene '%s' from scene image cache.\nRebuild scene image cache!\n", pszScene ); } } else { for ( int i = 0; i < sceneData.numSounds; ++i ) { short stringId = scenefilecache->GetSceneCachedSound( sceneData.sceneId, i ); CBaseEntity::PrecacheScriptSound( scenefilecache->GetSceneString( stringId ) ); } } g_pStringTableClientSideChoreoScenes->AddString( CBaseEntity::IsServer(), pszScene ); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CInstancedSceneEntity::StartPlayback( void ) { // Wait until our pre delay is over if ( GetPreDelay() ) return; BaseClass::StartPlayback(); } //----------------------------------------------------------------------------- // Purpose: // Input : // Output : //----------------------------------------------------------------------------- void CInstancedSceneEntity::DoThink( float frametime ) { CheckInterruptCompletion(); if ( m_flPreDelay > 0 ) { m_flPreDelay = MAX( 0, m_flPreDelay - frametime ); StartPlayback(); if ( !m_bIsPlayingBack ) return; } if ( !m_pScene || !m_bIsPlayingBack || ( m_bHadOwner && m_hOwner == NULL ) ) { UTIL_Remove( this ); return; } // catch bad pitch shifting from old save games Assert( m_fPitch >= SCENE_MIN_PITCH && m_fPitch <= SCENE_MAX_PITCH ); m_fPitch = clamp( m_fPitch, SCENE_MIN_PITCH, SCENE_MAX_PITCH ); if ( m_bPaused ) { PauseThink(); return; } float dt = frametime; m_pScene->SetSoundFileStartupLatency( GetSoundSystemLatency() ); // Tell scene to go m_pScene->Think( m_flCurrentTime ); // Drive simulation time for scene SetCurrentTime( m_flCurrentTime + dt * m_fPitch, false ); // Did we get to the end if ( m_pScene->SimulationFinished() ) { OnSceneFinished( false, false ); UTIL_Remove( this ); } } //----------------------------------------------------------------------------- // Purpose: Search for an actor by name, make sure it can do face poses // Input : *name - // Output : CBaseFlex //----------------------------------------------------------------------------- CBaseFlex *CInstancedSceneEntity::FindNamedActor( const char *name ) { if ( m_pScene->GetNumActors() == 1 || stricmp( name, "!self" ) == 0 ) { if ( m_hOwner != NULL ) { CBaseCombatCharacter *pCharacter = m_hOwner->MyCombatCharacterPointer(); if ( pCharacter ) { return pCharacter; } } } return BaseClass::FindNamedActor( name ); } //----------------------------------------------------------------------------- // Purpose: Search for an actor by name, make sure it can do face poses // Input : *name - // Output : CBaseFlex //----------------------------------------------------------------------------- CBaseEntity *CInstancedSceneEntity::FindNamedEntity( const char *name ) { CBaseEntity *pOther = NULL; if (m_hOwner != NULL) { CAI_BaseNPC *npc = m_hOwner->MyNPCPointer(); if (npc) { pOther = npc->FindNamedEntity( name ); } else if ( m_hOwner->MyCombatCharacterPointer() ) { pOther = m_hOwner; } } if (!pOther) { pOther = BaseClass::FindNamedEntity( name ); } return pOther; } //----------------------------------------------------------------------------- // Purpose: Suppress certain events when it's instanced since they're can cause odd problems // Input : actor // Output : true - the event should happen, false - it shouldn't //----------------------------------------------------------------------------- bool CInstancedSceneEntity::PassThrough( CBaseFlex *actor ) { if (!actor) return false; CAI_BaseNPC *myNpc = actor->MyNPCPointer( ); if (!myNpc) return false; if (myNpc->IsCurSchedule( SCHED_SCENE_GENERIC )) { return true; } if (myNpc->GetCurSchedule()) { CAI_ScheduleBits testBits; myNpc->GetCurSchedule()->GetInterruptMask( &testBits ); if (testBits.IsBitSet( COND_IDLE_INTERRUPT )) { return true; } } LocalScene_Printf( "%s : event suppressed\n", STRING( m_iszSceneFile ) ); return false; } //----------------------------------------------------------------------------- void CInstancedSceneEntity::OnRestore() { if ( m_bHadOwner && !m_hOwner ) { // probably just came back from a level transition UTIL_Remove( this ); return; } // reset background state if ( m_pScene ) { m_pScene->SetBackground( m_bIsBackground ); } BaseClass::OnRestore(); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- float CInstancedSceneEntity::EstimateLength( void ) { return (BaseClass::EstimateLength() + GetPreDelay()); } void CInstancedSceneEntity::OnLoaded() { BaseClass::OnLoaded(); SetBackground( m_bIsBackground ); } bool g_bClientFlex = true; LINK_ENTITY_TO_CLASS( scene_manager, CSceneManager ); //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CSceneManager::Think() { // Latch this only once per frame... g_bClientFlex = scene_clientflex.GetBool(); // The manager is always thinking at 20 hz SetNextThink( gpGlobals->curtime + SCENE_THINK_INTERVAL ); float frameTime = ( gpGlobals->curtime - GetLastThink() ); frameTime = MIN( 0.1, frameTime ); // stop if AI is diabled if (CAI_BaseNPC::m_nDebugBits & bits_debugDisableAI) return; bool needCleanupPass = false; int c = m_ActiveScenes.Count(); for ( int i = 0; i < c; i++ ) { CSceneEntity *scene = m_ActiveScenes[ i ].Get(); if ( !scene ) { needCleanupPass = true; continue; } scene->DoThink( frameTime ); if ( m_ActiveScenes.Count() < c ) { // Scene removed self while thinking. Adjust iteration. c = m_ActiveScenes.Count(); i--; } } // Now delete any invalid ones if ( needCleanupPass ) { for ( int i = c - 1; i >= 0; i-- ) { CSceneEntity *scene = m_ActiveScenes[ i ].Get(); if ( scene ) continue; m_ActiveScenes.Remove( i ); } } } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CSceneManager::ClearAllScenes() { m_ActiveScenes.RemoveAll(); } //----------------------------------------------------------------------------- // Purpose: // Input : *scene - //----------------------------------------------------------------------------- void CSceneManager::AddSceneEntity( CSceneEntity *scene ) { CHandle< CSceneEntity > h; h = scene; // Already added/activated if ( m_ActiveScenes.Find( h ) != m_ActiveScenes.InvalidIndex() ) { return; } m_ActiveScenes.AddToTail( h ); } //----------------------------------------------------------------------------- // Purpose: // Input : *scene - //----------------------------------------------------------------------------- void CSceneManager::RemoveSceneEntity( CSceneEntity *scene ) { CHandle< CSceneEntity > h; h = scene; m_ActiveScenes.FindAndRemove( h ); } //----------------------------------------------------------------------------- // Purpose: // Input : *player - //----------------------------------------------------------------------------- void CSceneManager::OnClientActive( CBasePlayer *player ) { int c = m_QueuedSceneSounds.Count(); for ( int i = 0; i < c; i++ ) { CRestoreSceneSound *sound = &m_QueuedSceneSounds[ i ]; if ( sound->actor == NULL ) continue; // Blow off sounds too far in past to encode over networking layer if ( fabs( 1000.0f * sound->time_in_past ) > MAX_SOUND_DELAY_MSEC ) continue; CPASAttenuationFilter filter( sound->actor ); EmitSound_t es; es.m_nChannel = CHAN_VOICE; es.m_flVolume = 1; es.m_pSoundName = sound->soundname; es.m_SoundLevel = sound->soundlevel; es.m_flSoundTime = gpGlobals->curtime - sound->time_in_past; EmitSound( filter, sound->actor->entindex(), es ); } m_QueuedSceneSounds.RemoveAll(); } //----------------------------------------------------------------------------- // Purpose: Deletes scenes involving the specified actor //----------------------------------------------------------------------------- void CSceneManager::RemoveScenesInvolvingActor( CBaseFlex *pActor ) { if ( !pActor ) return; // This loop can remove items from m_ActiveScenes array, so loop through backwards. int c = m_ActiveScenes.Count(); for ( int i = c - 1 ; i >= 0; --i ) { CSceneEntity *pScene = m_ActiveScenes[ i ].Get(); if ( !pScene ) { continue; } if ( pScene->InvolvesActor( pActor ) ) // NOTE: returns false if scene hasn't loaded yet { LocalScene_Printf( "%s : removed for '%s'\n", STRING( pScene->m_iszSceneFile ), pActor ? pActor->GetDebugName() : "NULL" ); pScene->CancelPlayback(); } else { CInstancedSceneEntity *pInstancedScene = dynamic_cast< CInstancedSceneEntity * >( pScene ); if ( pInstancedScene && pInstancedScene->m_hOwner ) { if ( pInstancedScene->m_hOwner == pActor ) { if ( pInstancedScene->m_bIsPlayingBack ) { pInstancedScene->OnSceneFinished( true, false ); } LocalScene_Printf( "%s : removed for '%s'\n", STRING( pInstancedScene->m_iszSceneFile ), pActor ? pActor->GetDebugName() : "NULL" ); UTIL_Remove( pInstancedScene ); } } } } } //----------------------------------------------------------------------------- // Purpose: Stops scenes involving the specified actor //----------------------------------------------------------------------------- void CSceneManager::RemoveActorFromScenes( CBaseFlex *pActor, bool bInstancedOnly, bool bNonIdleOnly, const char *pszThisSceneOnly ) { int c = m_ActiveScenes.Count(); for ( int i = 0; i < c; i++ ) { CSceneEntity *pScene = m_ActiveScenes[ i ].Get(); if ( !pScene ) { continue; } // If only stopping instanced scenes, then skip it if it can't cast to an instanced scene if ( bInstancedOnly && ( dynamic_cast< CInstancedSceneEntity * >( pScene ) == NULL ) ) { continue; } if ( bNonIdleOnly && !pScene->ShouldBreakOnNonIdle() ) continue; if ( pScene->InvolvesActor( pActor ) ) { if ( pszThisSceneOnly && pszThisSceneOnly[0] ) { if ( Q_strcmp( pszThisSceneOnly, STRING(pScene->m_iszSceneFile) ) ) continue; } LocalScene_Printf( "%s : removed for '%s'\n", STRING( pScene->m_iszSceneFile ), pActor ? pActor->GetDebugName() : "NULL" ); pScene->CancelPlayback(); } } } //----------------------------------------------------------------------------- // Purpose: Pause scenes involving the specified actor //----------------------------------------------------------------------------- void CSceneManager::PauseActorsScenes( CBaseFlex *pActor, bool bInstancedOnly ) { int c = m_ActiveScenes.Count(); for ( int i = 0; i < c; i++ ) { CSceneEntity *pScene = m_ActiveScenes[ i ].Get(); if ( !pScene ) { continue; } // If only stopping instanced scenes, then skip it if it can't cast to an instanced scene if ( bInstancedOnly && ( dynamic_cast< CInstancedSceneEntity * >( pScene ) == NULL ) ) { continue; } if ( pScene->InvolvesActor( pActor ) && pScene->IsPlayingBack() ) { LocalScene_Printf( "Pausing actor %s scripted scene: %s\n", pActor->GetDebugName(), STRING(pScene->m_iszSceneFile) ); variant_t emptyVariant; pScene->AcceptInput( "Pause", pScene, pScene, emptyVariant, 0 ); } } } //----------------------------------------------------------------------------- // Purpose: Return true if this Actor is only in scenes that are interruptable right now //----------------------------------------------------------------------------- bool CSceneManager::IsInInterruptableScenes( CBaseFlex *pActor ) { int c = m_ActiveScenes.Count(); for ( int i = 0; i < c; i++ ) { CSceneEntity *pScene = m_ActiveScenes[ i ].Get(); if ( !pScene ) continue; //Ignore background scenes since they're harmless. if ( pScene->IsBackground() == true ) continue; if ( pScene->InvolvesActor( pActor ) && pScene->IsPlayingBack() ) { if ( pScene->IsInterruptable() == false ) return false; } } return true; } //----------------------------------------------------------------------------- // Purpose: Resume any paused scenes involving the specified actor //----------------------------------------------------------------------------- void CSceneManager::ResumeActorsScenes( CBaseFlex *pActor, bool bInstancedOnly ) { int c = m_ActiveScenes.Count(); for ( int i = 0; i < c; i++ ) { CSceneEntity *pScene = m_ActiveScenes[ i ].Get(); if ( !pScene ) { continue; } // If only stopping instanced scenes, then skip it if it can't cast to an instanced scene if ( bInstancedOnly && ( dynamic_cast< CInstancedSceneEntity * >( pScene ) == NULL ) ) { continue; } if ( pScene->InvolvesActor( pActor ) && pScene->IsPlayingBack() ) { LocalScene_Printf( "Resuming actor %s scripted scene: %s\n", pActor->GetDebugName(), STRING(pScene->m_iszSceneFile) ); variant_t emptyVariant; pScene->AcceptInput( "Resume", pScene, pScene, emptyVariant, 0 ); } } } //----------------------------------------------------------------------------- // Purpose: Set all paused, in-playback scenes to resume when the actor is ready //----------------------------------------------------------------------------- void CSceneManager::QueueActorsScenesToResume( CBaseFlex *pActor, bool bInstancedOnly ) { int c = m_ActiveScenes.Count(); for ( int i = 0; i < c; i++ ) { CSceneEntity *pScene = m_ActiveScenes[ i ].Get(); if ( !pScene ) { continue; } // If only stopping instanced scenes, then skip it if it can't cast to an instanced scene if ( bInstancedOnly && ( dynamic_cast< CInstancedSceneEntity * >( pScene ) == NULL ) ) { continue; } if ( pScene->InvolvesActor( pActor ) && pScene->IsPlayingBack() && pScene->IsPaused() ) { pScene->QueueResumePlayback(); } } } //----------------------------------------------------------------------------- // Purpose: returns if there are scenes involving the specified actor //----------------------------------------------------------------------------- bool CSceneManager::IsRunningScriptedScene( CBaseFlex *pActor, bool bIgnoreInstancedScenes ) { int c = m_ActiveScenes.Count(); for ( int i = 0; i < c; i++ ) { CSceneEntity *pScene = m_ActiveScenes[ i ].Get(); if ( !pScene || !pScene->IsPlayingBack() || ( bIgnoreInstancedScenes && dynamic_cast<CInstancedSceneEntity *>(pScene) != NULL ) ) { continue; } if ( pScene->InvolvesActor( pActor ) ) { return true; } } return false; } bool CSceneManager::IsRunningScriptedSceneAndNotPaused( CBaseFlex *pActor, bool bIgnoreInstancedScenes ) { int c = m_ActiveScenes.Count(); for ( int i = 0; i < c; i++ ) { CSceneEntity *pScene = m_ActiveScenes[ i ].Get(); if ( !pScene || !pScene->IsPlayingBack() || pScene->IsPaused() || ( bIgnoreInstancedScenes && dynamic_cast<CInstancedSceneEntity *>(pScene) != NULL ) ) { continue; } if ( pScene->InvolvesActor( pActor ) ) { return true; } } return false; } //----------------------------------------------------------------------------- // Purpose: // Input : *pActor - // Output : Returns true on success, false on failure. //----------------------------------------------------------------------------- bool CSceneManager::IsRunningScriptedSceneWithSpeech( CBaseFlex *pActor, bool bIgnoreInstancedScenes ) { int c = m_ActiveScenes.Count(); for ( int i = 0; i < c; i++ ) { CSceneEntity *pScene = m_ActiveScenes[ i ].Get(); if ( !pScene || !pScene->IsPlayingBack() || ( bIgnoreInstancedScenes && dynamic_cast<CInstancedSceneEntity *>(pScene) != NULL ) ) { continue; } if ( pScene->InvolvesActor( pActor ) ) { if ( pScene->HasUnplayedSpeech() ) return true; } } return false; } bool CSceneManager::IsRunningScriptedSceneWithSpeechAndNotPaused( CBaseFlex *pActor, bool bIgnoreInstancedScenes ) { int c = m_ActiveScenes.Count(); for ( int i = 0; i < c; i++ ) { CSceneEntity *pScene = m_ActiveScenes[ i ].Get(); if ( !pScene || !pScene->IsPlayingBack() || pScene->IsPaused() || ( bIgnoreInstancedScenes && dynamic_cast<CInstancedSceneEntity *>(pScene) != NULL ) ) { continue; } if ( pScene->InvolvesActor( pActor ) ) { if ( pScene->HasUnplayedSpeech() ) return true; } } return false; } //----------------------------------------------------------------------------- // Purpose: // Input : *actor - // *soundname - // soundlevel - // soundtime - //----------------------------------------------------------------------------- void CSceneManager::QueueRestoredSound( CBaseFlex *actor, char const *soundname, soundlevel_t soundlevel, float time_in_past ) { CRestoreSceneSound e; e.actor = actor; Q_strncpy( e.soundname, soundname, sizeof( e.soundname ) ); e.soundlevel = soundlevel; e.time_in_past = time_in_past; m_QueuedSceneSounds.AddToTail( e ); } //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- void RemoveActorFromScriptedScenes( CBaseFlex *pActor, bool instancedscenesonly, bool nonidlescenesonly, const char *pszThisSceneOnly ) { GetSceneManager()->RemoveActorFromScenes( pActor, instancedscenesonly, nonidlescenesonly, pszThisSceneOnly ); } //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- void RemoveAllScenesInvolvingActor( CBaseFlex *pActor ) { GetSceneManager()->RemoveScenesInvolvingActor( pActor ); } //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- void PauseActorsScriptedScenes( CBaseFlex *pActor, bool instancedscenesonly ) { GetSceneManager()->PauseActorsScenes( pActor, instancedscenesonly ); } //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- bool IsInInterruptableScenes( CBaseFlex *pActor ) { return GetSceneManager()->IsInInterruptableScenes( pActor ); } //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- void ResumeActorsScriptedScenes( CBaseFlex *pActor, bool instancedscenesonly ) { GetSceneManager()->ResumeActorsScenes( pActor, instancedscenesonly ); } //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- void QueueActorsScriptedScenesToResume( CBaseFlex *pActor, bool instancedscenesonly ) { GetSceneManager()->QueueActorsScenesToResume( pActor, instancedscenesonly ); } //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- bool IsRunningScriptedScene( CBaseFlex *pActor, bool bIgnoreInstancedScenes ) { return GetSceneManager()->IsRunningScriptedScene( pActor, bIgnoreInstancedScenes ); } bool IsRunningScriptedSceneAndNotPaused( CBaseFlex *pActor, bool bIgnoreInstancedScenes ) { return GetSceneManager()->IsRunningScriptedSceneAndNotPaused( pActor, bIgnoreInstancedScenes ); } //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- bool IsRunningScriptedSceneWithSpeech( CBaseFlex *pActor, bool bIgnoreInstancedScenes ) { return GetSceneManager()->IsRunningScriptedSceneWithSpeech( pActor, bIgnoreInstancedScenes ); } bool IsRunningScriptedSceneWithSpeechAndNotPaused( CBaseFlex *pActor, bool bIgnoreInstancedScenes ) { return GetSceneManager()->IsRunningScriptedSceneWithSpeechAndNotPaused( pActor, bIgnoreInstancedScenes ); } //=========================================================================================================== // SCENE LIST MANAGER //=========================================================================================================== LINK_ENTITY_TO_CLASS( logic_scene_list_manager, CSceneListManager ); BEGIN_DATADESC( CSceneListManager ) DEFINE_UTLVECTOR( m_hListManagers, FIELD_EHANDLE ), // Keys DEFINE_KEYFIELD( m_iszScenes[0], FIELD_STRING, "scene0" ), DEFINE_KEYFIELD( m_iszScenes[1], FIELD_STRING, "scene1" ), DEFINE_KEYFIELD( m_iszScenes[2], FIELD_STRING, "scene2" ), DEFINE_KEYFIELD( m_iszScenes[3], FIELD_STRING, "scene3" ), DEFINE_KEYFIELD( m_iszScenes[4], FIELD_STRING, "scene4" ), DEFINE_KEYFIELD( m_iszScenes[5], FIELD_STRING, "scene5" ), DEFINE_KEYFIELD( m_iszScenes[6], FIELD_STRING, "scene6" ), DEFINE_KEYFIELD( m_iszScenes[7], FIELD_STRING, "scene7" ), DEFINE_KEYFIELD( m_iszScenes[8], FIELD_STRING, "scene8" ), DEFINE_KEYFIELD( m_iszScenes[9], FIELD_STRING, "scene9" ), DEFINE_KEYFIELD( m_iszScenes[10], FIELD_STRING, "scene10" ), DEFINE_KEYFIELD( m_iszScenes[11], FIELD_STRING, "scene11" ), DEFINE_KEYFIELD( m_iszScenes[12], FIELD_STRING, "scene12" ), DEFINE_KEYFIELD( m_iszScenes[13], FIELD_STRING, "scene13" ), DEFINE_KEYFIELD( m_iszScenes[14], FIELD_STRING, "scene14" ), DEFINE_KEYFIELD( m_iszScenes[15], FIELD_STRING, "scene15" ), DEFINE_FIELD( m_hScenes[0], FIELD_EHANDLE ), DEFINE_FIELD( m_hScenes[1], FIELD_EHANDLE ), DEFINE_FIELD( m_hScenes[2], FIELD_EHANDLE ), DEFINE_FIELD( m_hScenes[3], FIELD_EHANDLE ), DEFINE_FIELD( m_hScenes[4], FIELD_EHANDLE ), DEFINE_FIELD( m_hScenes[5], FIELD_EHANDLE ), DEFINE_FIELD( m_hScenes[6], FIELD_EHANDLE ), DEFINE_FIELD( m_hScenes[7], FIELD_EHANDLE ), DEFINE_FIELD( m_hScenes[8], FIELD_EHANDLE ), DEFINE_FIELD( m_hScenes[9], FIELD_EHANDLE ), DEFINE_FIELD( m_hScenes[10], FIELD_EHANDLE ), DEFINE_FIELD( m_hScenes[11], FIELD_EHANDLE ), DEFINE_FIELD( m_hScenes[12], FIELD_EHANDLE ), DEFINE_FIELD( m_hScenes[13], FIELD_EHANDLE ), DEFINE_FIELD( m_hScenes[14], FIELD_EHANDLE ), DEFINE_FIELD( m_hScenes[15], FIELD_EHANDLE ), // Inputs DEFINE_INPUTFUNC( FIELD_VOID, "Shutdown", InputShutdown ), END_DATADESC() //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CSceneListManager::Activate( void ) { BaseClass::Activate(); // Hook up scenes, but not after loading a game because they're saved. if ( gpGlobals->eLoadType != MapLoad_LoadGame ) { for ( int i = 0; i < SCENE_LIST_MANAGER_MAX_SCENES; i++ ) { if ( m_iszScenes[i] != NULL_STRING ) { m_hScenes[i] = gEntList.FindEntityByName( NULL, STRING(m_iszScenes[i]) ); if ( m_hScenes[i] ) { CSceneEntity *pScene = dynamic_cast<CSceneEntity*>(m_hScenes[i].Get()); if ( pScene ) { pScene->AddListManager( this ); } else { CSceneListManager *pList = dynamic_cast<CSceneListManager*>(m_hScenes[i].Get()); if ( pList ) { pList->AddListManager( this ); } else { Warning( "%s(%s) found an entity that wasn't a logic_choreographed_scene or logic_scene_list_manager in slot %d, named %s\n", GetDebugName(), GetClassname(), i, STRING(m_iszScenes[i]) ); m_hScenes[i] = NULL; } } } else { Warning( "%s(%s) could not find scene %d, named %s\n", GetDebugName(), GetClassname(), i, STRING(m_iszScenes[i]) ); } } } } } //----------------------------------------------------------------------------- // Purpose: A scene or manager in our list has started playing. // Remove all scenes earlier in the list. //----------------------------------------------------------------------------- void CSceneListManager::SceneStarted( CBaseEntity *pSceneOrManager ) { // Move backwards and call remove on all scenes / managers earlier in the list to the fired one bool bFoundStart = false; for ( int i = SCENE_LIST_MANAGER_MAX_SCENES-1; i >= 0; i-- ) { if ( !m_hScenes[i] ) continue; if ( bFoundStart ) { RemoveScene( i ); } else if ( m_hScenes[i] == pSceneOrManager ) { bFoundStart = true; } } // Tell any managers we're within that we've started a scene if ( bFoundStart ) { int c = m_hListManagers.Count(); for ( int i = 0; i < c; i++ ) { if ( m_hListManagers[i] ) { m_hListManagers[i]->SceneStarted( this ); } } } } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CSceneListManager::AddListManager( CSceneListManager *pManager ) { CHandle< CSceneListManager > h; h = pManager; // Only add it once if ( m_hListManagers.Find( h ) == m_hListManagers.InvalidIndex() ) { m_hListManagers.AddToTail( h ); } } //----------------------------------------------------------------------------- // Purpose: Shut down all scenes, and then remove this entity //----------------------------------------------------------------------------- void CSceneListManager::InputShutdown( inputdata_t &inputdata ) { ShutdownList(); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CSceneListManager::ShutdownList( void ) { for ( int i = 0; i < SCENE_LIST_MANAGER_MAX_SCENES; i++ ) { if ( m_hScenes[i] ) { RemoveScene(i); } } UTIL_Remove( this ); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CSceneListManager::RemoveScene( int iIndex ) { CSceneEntity *pScene = dynamic_cast<CSceneEntity*>(m_hScenes[iIndex].Get()); if ( pScene ) { // Remove the scene UTIL_Remove( pScene ); return; } // Tell the list manager to shut down all scenes CSceneListManager *pList = dynamic_cast<CSceneListManager*>(m_hScenes[iIndex].Get()); if ( pList ) { pList->ShutdownList(); } } void ReloadSceneFromDisk( CBaseEntity *ent ) { CSceneEntity *scene = dynamic_cast< CSceneEntity * >( ent ); if ( !scene ) return; Assert( 0 ); } // Purpose: // Input : *ent - // Output : char const //----------------------------------------------------------------------------- char const *GetSceneFilename( CBaseEntity *ent ) { CSceneEntity *scene = dynamic_cast< CSceneEntity * >( ent ); if ( !scene ) return ""; return STRING( scene->m_iszSceneFile ); } //----------------------------------------------------------------------------- // Purpose: Return a list of the last 5 lines of speech from NPCs for bug reports // Input : // Output : speech - last 5 sound files played as speech // returns the number of sounds in the returned list //----------------------------------------------------------------------------- int GetRecentNPCSpeech( recentNPCSpeech_t speech[ SPEECH_LIST_MAX_SOUNDS ] ) { int i; int num; int index; // clear out the output list for( i = 0; i < SPEECH_LIST_MAX_SOUNDS; i++ ) { speech[ i ].time = 0.0f; speech[ i ].name[ 0 ] = 0; speech[ i ].sceneName[ 0 ] = 0; } // copy the sound names into the list in order they were played num = 0; index = speechListIndex; for( i = 0; i < SPEECH_LIST_MAX_SOUNDS; i++ ) { if ( speechListSounds[ index ].name[ 0 ] ) { // only copy names that are not zero length speech[ num ] = speechListSounds[ index ]; num++; } index++; if ( index >= SPEECH_LIST_MAX_SOUNDS ) { index = 0; } } return num; } //----------------------------------------------------------------------------- // Purpose: Displays a list of the last 5 lines of speech from NPCs // Input : // Output : //----------------------------------------------------------------------------- static void ListRecentNPCSpeech( void ) { if ( !UTIL_IsCommandIssuedByServerAdmin() ) return; recentNPCSpeech_t speech[ SPEECH_LIST_MAX_SOUNDS ]; int num; int i; // get any sounds that were spoken by NPCs recently num = GetRecentNPCSpeech( speech ); Msg( "Recent NPC speech:\n" ); for( i = 0; i < num; i++ ) { Msg( " time: %6.3f sound name: %s scene: %s\n", speech[ i ].time, speech[ i ].name, speech[ i ].sceneName ); } Msg( "Current time: %6.3f\n", gpGlobals->curtime ); } static ConCommand ListRecentNPCSpeechCmd( "listRecentNPCSpeech", ListRecentNPCSpeech, "Displays a list of the last 5 lines of speech from NPCs.", FCVAR_DONTRECORD|FCVAR_GAMEDLL ); CON_COMMAND( scene_flush, "Flush all .vcds from the cache and reload from disk." ) { if ( !UTIL_IsCommandIssuedByServerAdmin() ) return; Msg( "Reloading\n" ); scenefilecache->Reload(); Msg( " done\n" ); }
28.027709
193
0.589445
[ "vector" ]
4fb0b69c4899e9dd2efaa1a0d1faec58466ad31a
10,243
hpp
C++
include/seec/RuntimeErrors/ArgumentTypes.hpp
seec-team/seec
4b92456011e86b70f9d88833a95c1f655a21cf1a
[ "MIT" ]
7
2018-06-25T12:06:13.000Z
2022-01-18T09:20:13.000Z
include/seec/RuntimeErrors/ArgumentTypes.hpp
seec-team/seec
4b92456011e86b70f9d88833a95c1f655a21cf1a
[ "MIT" ]
20
2016-12-01T23:46:12.000Z
2019-08-11T02:41:04.000Z
include/seec/RuntimeErrors/ArgumentTypes.hpp
seec-team/seec
4b92456011e86b70f9d88833a95c1f655a21cf1a
[ "MIT" ]
1
2020-10-19T03:20:05.000Z
2020-10-19T03:20:05.000Z
//===- include/seec/RuntimeErrors/ArgumentTypes.hpp -----------------------===// // // SeeC // // This file is distributed under The MIT License (MIT). See LICENSE.TXT for // details. // //===----------------------------------------------------------------------===// /// /// \file /// //===----------------------------------------------------------------------===// #ifndef SEEC_RUNTIMEERRORS_ARGUMENTTYPES_HPP #define SEEC_RUNTIMEERRORS_ARGUMENTTYPES_HPP #include "seec/RuntimeErrors/FormatSelects.hpp" #include "llvm/Support/Casting.h" #include <cassert> #include <cstdint> #include <string> #include <memory> namespace seec { namespace runtime_errors { /// Enumeration of all basic runtime error argument types. enum class ArgType : uint8_t { None = 0, #define SEEC_RUNERR_ARG(TYPE) TYPE, #include "seec/RuntimeErrors/ArgumentTypes.def" }; char const *describe(ArgType Type); /// \brief Base class for all runtime error arguments. /// /// This class can not be constructed directly, but holds functionality common /// to all arguments. class Arg { ArgType Type; /// \brief Clone this Arg. /// virtual std::unique_ptr<Arg> cloneImpl() const =0; protected: Arg(ArgType Type) : Type(Type) {} // Arg objects should not be copied directly, only as part of copying a // subclass. Arg(Arg const &Other) = default; Arg &operator=(Arg const &RHS) = default; public: virtual ~Arg() = 0; /// Get the type of this argument. ArgType type() const { return Type; } /// Serialize data. virtual uint64_t data() const = 0; /// Deserialize from type and data. static std::unique_ptr<Arg> deserialize(uint8_t Type, uint64_t Data); /// Support LLVM's dynamic casting. static bool classof(Arg const *A) { return true; } /// \brief Clone this Arg. /// std::unique_ptr<Arg> clone() const { return cloneImpl(); } }; /// \brief An argument that holds a runtime address. /// class ArgAddress : public Arg { uintptr_t Address; /// \brief Clone this Arg. /// std::unique_ptr<Arg> cloneImpl() const override { return std::unique_ptr<Arg>(new ArgAddress(*this)); } public: ArgAddress(uintptr_t Address) : Arg(ArgType::Address), Address(Address) {} ArgAddress(ArgAddress const &Other) = default; virtual ~ArgAddress(); virtual uint64_t data() const override { return Address; } /// \brief Deserialize from data. static std::unique_ptr<Arg> deserialize(uint64_t Data) { return std::unique_ptr<Arg>(new ArgAddress(Data)); } /// Support LLVM's dynamic casting. /// \return true. static bool classof(ArgAddress const *A) { return true; } /// Support LLVM's dynamic casting. /// \return true iff *A is an ArgAddress. static bool classof(Arg const *A) { return A->type() == ArgType::Address; } uintptr_t address() const { return Address; } }; /// \brief An argument that represents a runtime object. /// class ArgObject : public Arg { /// \brief Clone this Arg. /// std::unique_ptr<Arg> cloneImpl() const override { return std::unique_ptr<Arg>(new ArgObject(*this)); } public: ArgObject() : Arg(ArgType::Object) {} ArgObject(ArgObject const &Other) = default; virtual ~ArgObject(); virtual uint64_t data() const override { return 0; } /// \brief Deserialize from data. static std::unique_ptr<Arg> deserialize(uint64_t Data) { return std::unique_ptr<Arg>(new ArgObject()); } /// Support LLVM's dynamic casting. /// \return true. static bool classof(ArgObject const *A) { return true; } /// Support LLVM's dynamic casting. /// \return true iff *A is an ArgObject. static bool classof(Arg const *A) { return A->type() == ArgType::Object; } }; /// \brief Base class for all ArgSelect objects. /// class ArgSelectBase : public Arg { public: ArgSelectBase() : Arg(ArgType::SelectBase) {} virtual ~ArgSelectBase(); virtual uint64_t data() const override { uint64_t Data = static_cast<uint32_t>(getSelectID()); Data <<= 32; Data |= static_cast<uint32_t>(getRawItemValue()); return Data; } /// \brief Deserialize from data. static std::unique_ptr<Arg> deserialize(uint64_t Data); /// Support LLVM's dynamic casting. /// \return true. static bool classof(ArgSelectBase const *A) { return true; } /// Support LLVM's dynamic casting. /// \return true iff A->type() is ArgType::SelectBase. static bool classof(Arg const *A) { return A->type() == ArgType::SelectBase; } /// Get the address of the format_selects::getCString() overload for the /// select type of this ArgSelect object. Used by ArgSelect to support LLVM's /// dynamic casting. virtual uintptr_t getCStringAddress() const = 0; virtual format_selects::SelectID getSelectID() const = 0; virtual uint32_t getRawItemValue() const = 0; }; /// \brief An argument that represents a selection. /// template<typename SelectType> class ArgSelect : public ArgSelectBase { SelectType Item; /// \brief Clone this Arg. /// std::unique_ptr<Arg> cloneImpl() const override { return std::unique_ptr<Arg>(new ArgSelect(*this)); } protected: static uintptr_t getCStringAddressImpl() { char const *(*func)(SelectType) = format_selects::getCString; return (uintptr_t) func; } virtual uintptr_t getCStringAddress() const override { return getCStringAddressImpl(); } public: ArgSelect(SelectType Item) : ArgSelectBase(), Item(Item) {} ArgSelect(ArgSelect<SelectType> const &Other) = default; virtual ~ArgSelect() {} static bool classof(ArgSelect<SelectType> const *A) { return true; } static bool classof(Arg const *A) { if (A->type() != ArgType::SelectBase) return false; ArgSelectBase const *Base = llvm::cast<ArgSelectBase>(A); return Base->getCStringAddress() == getCStringAddressImpl(); } virtual format_selects::SelectID getSelectID() const override { return format_selects::GetSelectID<SelectType>::value(); } virtual uint32_t getRawItemValue() const override { return static_cast<uint32_t>(Item); } }; /// std::unique_ptr<Arg> createArgSelect(format_selects::SelectID Select, uint32_t Item); /// \brief An argument that holds a size. /// class ArgSize : public Arg { uint64_t Size; /// \brief Clone this Arg. /// std::unique_ptr<Arg> cloneImpl() const override { return std::unique_ptr<Arg>(new ArgSize(*this)); } public: ArgSize(uint64_t Size) : Arg(ArgType::Size), Size(Size) {} ArgSize(ArgSize const &Other) = default; virtual ~ArgSize(); virtual uint64_t data() const override { return Size; } /// \brief Deserialize from data. static std::unique_ptr<Arg> deserialize(uint64_t Data) { return std::unique_ptr<Arg>(new ArgSize(Data)); } /// Support LLVM's dynamic casting. /// \return true. static bool classof(ArgSize const *A) { return true; } /// Support LLVM's dynamic casting. /// \return true iff *A is an ArgSize. static bool classof(Arg const *A) { return A->type() == ArgType::Size; } uint64_t size() const { return Size; } }; /// \brief An argument that holds the index of an operand of an llvm::User. /// class ArgOperand : public Arg { uint64_t Index; /// \brief Clone this Arg. /// std::unique_ptr<Arg> cloneImpl() const override { return std::unique_ptr<Arg>(new ArgOperand(*this)); } public: ArgOperand(uint64_t Index) : Arg(ArgType::Operand), Index(Index) {} ArgOperand(ArgOperand const &Other) = default; virtual ~ArgOperand(); virtual uint64_t data() const override { return Index; } /// \brief Deserialize from data. static std::unique_ptr<Arg> deserialize(uint64_t Data) { return std::unique_ptr<Arg>(new ArgOperand(Data)); } /// Support LLVM's dynamic casting. /// \return true. static bool classof(ArgOperand const *A) { return true; } /// Support LLVM's dynamic casting. /// \return true iff *A is an ArgOperand. static bool classof(Arg const *A) { return A->type() == ArgType::Operand; } uint64_t index() const { return Index; } }; /// \brief An argument that holds the index of a parameter to a function. /// class ArgParameter : public Arg { uint64_t Index; /// \brief Clone this Arg. /// std::unique_ptr<Arg> cloneImpl() const override { return std::unique_ptr<Arg>(new ArgParameter(*this)); } public: ArgParameter(uint64_t Index) : Arg(ArgType::Parameter), Index(Index) {} ArgParameter(ArgParameter const &Other) = default; virtual ~ArgParameter(); virtual uint64_t data() const override { return Index; } /// \brief Deserialize from data. static std::unique_ptr<Arg> deserialize(uint64_t Data) { return std::unique_ptr<Arg>(new ArgParameter(Data)); } /// Support LLVM's dynamic casting. /// \return true. static bool classof(ArgParameter const *A) { return true; } /// Support LLVM's dynamic casting. /// \return true iff *A is an ArgParameter. static bool classof(Arg const *A) { return A->type() == ArgType::Parameter; } uint64_t index() const { return Index; } }; /// \brief An argument that holds a single character. /// class ArgCharacter : public Arg { char Character; /// \brief Clone this Arg. /// std::unique_ptr<Arg> cloneImpl() const override { return std::unique_ptr<Arg>(new ArgCharacter(*this)); } public: ArgCharacter(char Character) : Arg(ArgType::Character), Character(Character) {} ArgCharacter(ArgCharacter const &Other) = default; virtual ~ArgCharacter(); virtual uint64_t data() const override { return Character; } /// \brief Deserialize from data. static std::unique_ptr<Arg> deserialize(uint64_t Data) { return std::unique_ptr<Arg>(new ArgCharacter(static_cast<char>(Data))); } /// Support LLVM's dynamic casting. /// \return true. static bool classof(ArgCharacter const *A) { return true; } /// Support LLVM's dynamic casting. /// \return true iff *A is an ArgCharacter. static bool classof(Arg const *A) { return A->type() == ArgType::Character; } char character() const { return Character; } }; } // namespace runtime_errors (in seec) } // namespace seec #endif // SEEC_RUNTIMEERRORS_ARGUMENTTYPES_HPP
25.105392
80
0.666504
[ "object" ]
4fb255962e0707cb728ed9a85a7583aa2360638e
131,117
cpp
C++
src/clients/meta/MetaClient.cpp
klay-test-org/nebula
8c8b2b13189a6446752fd0a55f2c7246ec8d677e
[ "Apache-2.0" ]
null
null
null
src/clients/meta/MetaClient.cpp
klay-test-org/nebula
8c8b2b13189a6446752fd0a55f2c7246ec8d677e
[ "Apache-2.0" ]
24
2021-09-15T12:42:03.000Z
2021-09-16T04:59:19.000Z
src/clients/meta/MetaClient.cpp
klay-test-org/nebula
8c8b2b13189a6446752fd0a55f2c7246ec8d677e
[ "Apache-2.0" ]
null
null
null
/* Copyright (c) 2018 vesoft inc. All rights reserved. * * This source code is licensed under Apache 2.0 License, * attached with Common Clause Condition 1.0, found in the LICENSES directory. */ #include "clients/meta/MetaClient.h" #include <folly/ScopeGuard.h> #include <folly/executors/Async.h> #include <folly/futures/Future.h> #include <folly/hash/Hash.h> #include <thrift/lib/cpp/util/EnumUtils.h> #include "clients/meta/FileBasedClusterIdMan.h" #include "common/base/Base.h" #include "common/base/MurmurHash2.h" #include "common/conf/Configuration.h" #include "common/http/HttpClient.h" #include "common/meta/NebulaSchemaProvider.h" #include "common/network/NetworkUtils.h" #include "common/stats/StatsManager.h" #include "common/time/TimeUtils.h" #include "version/Version.h" #include "webservice/Common.h" DEFINE_uint32(expired_time_factor, 5, "The factor of expired time based on heart beat interval"); DEFINE_int32(heartbeat_interval_secs, 10, "Heartbeat interval in seconds"); DEFINE_int32(meta_client_retry_times, 3, "meta client retry times, 0 means no retry"); DEFINE_int32(meta_client_retry_interval_secs, 1, "meta client sleep interval between retry"); DEFINE_int32(meta_client_timeout_ms, 60 * 1000, "meta client timeout"); DEFINE_string(cluster_id_path, "cluster.id", "file path saved clusterId"); DEFINE_int32(check_plan_killed_frequency, 8, "check plan killed every 1<<n times"); namespace nebula { namespace meta { MetaClient::MetaClient(std::shared_ptr<folly::IOThreadPoolExecutor> ioThreadPool, std::vector<HostAddr> addrs, const MetaClientOptions& options) : ioThreadPool_(ioThreadPool), addrs_(std::move(addrs)), options_(options), sessionMap_(new SessionMap{}), killedPlans_(new folly::F14FastSet<std::pair<SessionID, ExecutionPlanID>>{}) { CHECK(ioThreadPool_ != nullptr) << "IOThreadPool is required"; CHECK(!addrs_.empty()) << "No meta server address is specified or can be solved. Meta server is required"; clientsMan_ = std::make_shared<thrift::ThriftClientManager<cpp2::MetaServiceAsyncClient>>(); updateActive(); updateLeader(); bgThread_ = std::make_unique<thread::GenericWorker>(); LOG(INFO) << "Create meta client to " << active_; } MetaClient::~MetaClient() { stop(); delete sessionMap_.load(); delete killedPlans_.load(); VLOG(3) << "~MetaClient"; } bool MetaClient::isMetadReady() { auto ret = heartbeat().get(); if (!ret.ok()) { LOG(ERROR) << "Heartbeat failed, status:" << ret.status(); return ready_; } else if (options_.role_ == cpp2::HostRole::STORAGE && metaServerVersion_ != EXPECT_META_VERSION) { LOG(ERROR) << "Expect meta version is " << EXPECT_META_VERSION << ", but actual is " << metaServerVersion_; return ready_; } // ready_ will be set in loadData bool ldRet = loadData(); bool lcRet = true; if (!options_.skipConfig_) { lcRet = loadCfg(); } if (ldRet && lcRet) { localLastUpdateTime_ = metadLastUpdateTime_; } return ready_; } bool MetaClient::waitForMetadReady(int count, int retryIntervalSecs) { if (!options_.skipConfig_) { std::string gflagsJsonPath; GflagsManager::getGflagsModule(gflagsModule_); gflagsDeclared_ = GflagsManager::declareGflags(gflagsModule_); } isRunning_ = true; int tryCount = count; while (!isMetadReady() && ((count == -1) || (tryCount > 0)) && isRunning_) { LOG(INFO) << "Waiting for the metad to be ready!"; --tryCount; ::sleep(retryIntervalSecs); } // end while if (!isRunning_) { LOG(ERROR) << "Connect to the MetaServer Failed"; return false; } CHECK(bgThread_->start()); LOG(INFO) << "Register time task for heartbeat!"; size_t delayMS = FLAGS_heartbeat_interval_secs * 1000 + folly::Random::rand32(900); bgThread_->addDelayTask(delayMS, &MetaClient::heartBeatThreadFunc, this); return ready_; } void MetaClient::stop() { if (bgThread_ != nullptr) { bgThread_->stop(); bgThread_->wait(); bgThread_.reset(); } isRunning_ = false; } void MetaClient::heartBeatThreadFunc() { SCOPE_EXIT { bgThread_->addDelayTask( FLAGS_heartbeat_interval_secs * 1000, &MetaClient::heartBeatThreadFunc, this); }; auto ret = heartbeat().get(); if (!ret.ok()) { LOG(ERROR) << "Heartbeat failed, status:" << ret.status(); return; } // if MetaServer has some changes, refesh the localCache_ if (localLastUpdateTime_ < metadLastUpdateTime_) { bool ldRet = loadData(); bool lcRet = true; if (!options_.skipConfig_) { lcRet = loadCfg(); } if (ldRet && lcRet) { localLastUpdateTime_ = metadLastUpdateTime_; } } } bool MetaClient::loadUsersAndRoles() { auto userRoleRet = listUsers().get(); if (!userRoleRet.ok()) { LOG(ERROR) << "List users failed, status:" << userRoleRet.status(); return false; } decltype(userRolesMap_) userRolesMap; decltype(userPasswordMap_) userPasswordMap; for (auto& user : userRoleRet.value()) { auto rolesRet = getUserRoles(user.first).get(); if (!rolesRet.ok()) { LOG(ERROR) << "List role by user failed, user : " << user.first; return false; } userRolesMap[user.first] = rolesRet.value(); userPasswordMap[user.first] = user.second; } { folly::RWSpinLock::WriteHolder holder(localCacheLock_); userRolesMap_ = std::move(userRolesMap); userPasswordMap_ = std::move(userPasswordMap); } return true; } bool MetaClient::loadData() { if (ioThreadPool_->numThreads() <= 0) { LOG(ERROR) << "The threads number in ioThreadPool should be greater than 0"; return false; } if (!loadUsersAndRoles()) { LOG(ERROR) << "Load roles Failed"; return false; } if (!loadFulltextClients()) { LOG(ERROR) << "Load fulltext services Failed"; return false; } if (!loadFulltextIndexes()) { LOG(ERROR) << "Load fulltext indexes Failed"; return false; } if (!loadSessions()) { LOG(ERROR) << "Load sessions Failed"; return false; } auto ret = listSpaces().get(); if (!ret.ok()) { LOG(ERROR) << "List space failed, status:" << ret.status(); return false; } decltype(localCache_) cache; decltype(spaceIndexByName_) spaceIndexByName; decltype(spaceTagIndexByName_) spaceTagIndexByName; decltype(spaceEdgeIndexByName_) spaceEdgeIndexByName; decltype(spaceNewestTagVerMap_) spaceNewestTagVerMap; decltype(spaceNewestEdgeVerMap_) spaceNewestEdgeVerMap; decltype(spaceEdgeIndexByType_) spaceEdgeIndexByType; decltype(spaceTagIndexById_) spaceTagIndexById; decltype(spaceAllEdgeMap_) spaceAllEdgeMap; for (auto space : ret.value()) { auto spaceId = space.first; MetaClient::PartTerms partTerms; auto r = getPartsAlloc(spaceId, &partTerms).get(); if (!r.ok()) { LOG(ERROR) << "Get parts allocation failed for spaceId " << spaceId << ", status " << r.status(); return false; } auto spaceCache = std::make_shared<SpaceInfoCache>(); auto partsAlloc = r.value(); auto& spaceName = space.second; spaceCache->partsOnHost_ = reverse(partsAlloc); spaceCache->partsAlloc_ = std::move(partsAlloc); spaceCache->termOfPartition_ = std::move(partTerms); VLOG(2) << "Load space " << spaceId << ", parts num:" << spaceCache->partsAlloc_.size(); // loadSchemas if (!loadSchemas(spaceId, spaceCache, spaceTagIndexByName, spaceTagIndexById, spaceEdgeIndexByName, spaceEdgeIndexByType, spaceNewestTagVerMap, spaceNewestEdgeVerMap, spaceAllEdgeMap)) { LOG(ERROR) << "Load Schemas Failed"; return false; } if (!loadIndexes(spaceId, spaceCache)) { LOG(ERROR) << "Load Indexes Failed"; return false; } if (!loadListeners(spaceId, spaceCache)) { LOG(ERROR) << "Load Listeners Failed"; return false; } // get space properties auto resp = getSpace(spaceName).get(); if (!resp.ok()) { LOG(ERROR) << "Get space properties failed for space " << spaceId; return false; } auto properties = resp.value().get_properties(); spaceCache->spaceDesc_ = std::move(properties); cache.emplace(spaceId, spaceCache); spaceIndexByName.emplace(space.second, spaceId); } auto hostsRet = listHosts().get(); if (!ret.ok()) { LOG(ERROR) << "List hosts failed, status:" << hostsRet.status(); return false; } auto& hostItems = hostsRet.value(); std::vector<HostAddr> hosts(hostItems.size()); std::transform(hostItems.begin(), hostItems.end(), hosts.begin(), [](auto& hostItem) -> HostAddr { return *hostItem.hostAddr_ref(); }); loadLeader(hostItems, spaceIndexByName_); decltype(localCache_) oldCache; { folly::RWSpinLock::WriteHolder holder(localCacheLock_); oldCache = std::move(localCache_); localCache_ = std::move(cache); spaceIndexByName_ = std::move(spaceIndexByName); spaceTagIndexByName_ = std::move(spaceTagIndexByName); spaceEdgeIndexByName_ = std::move(spaceEdgeIndexByName); spaceNewestTagVerMap_ = std::move(spaceNewestTagVerMap); spaceNewestEdgeVerMap_ = std::move(spaceNewestEdgeVerMap); spaceEdgeIndexByType_ = std::move(spaceEdgeIndexByType); spaceTagIndexById_ = std::move(spaceTagIndexById); spaceAllEdgeMap_ = std::move(spaceAllEdgeMap); storageHosts_ = std::move(hosts); } diff(oldCache, localCache_); listenerDiff(oldCache, localCache_); loadRemoteListeners(); ready_ = true; return true; } bool MetaClient::loadSchemas(GraphSpaceID spaceId, std::shared_ptr<SpaceInfoCache> spaceInfoCache, SpaceTagNameIdMap& tagNameIdMap, SpaceTagIdNameMap& tagIdNameMap, SpaceEdgeNameTypeMap& edgeNameTypeMap, SpaceEdgeTypeNameMap& edgeTypeNameMap, SpaceNewestTagVerMap& newestTagVerMap, SpaceNewestEdgeVerMap& newestEdgeVerMap, SpaceAllEdgeMap& allEdgeMap) { auto tagRet = listTagSchemas(spaceId).get(); if (!tagRet.ok()) { LOG(ERROR) << "Get tag schemas failed for spaceId " << spaceId << ", " << tagRet.status(); return false; } auto edgeRet = listEdgeSchemas(spaceId).get(); if (!edgeRet.ok()) { LOG(ERROR) << "Get edge schemas failed for spaceId " << spaceId << ", " << edgeRet.status(); return false; } auto tagItemVec = tagRet.value(); auto edgeItemVec = edgeRet.value(); allEdgeMap[spaceId] = {}; TagSchemas tagSchemas; EdgeSchemas edgeSchemas; TagID lastTagId = -1; auto addSchemaField = [&spaceInfoCache](NebulaSchemaProvider* schema, const cpp2::ColumnDef& col) { bool hasDef = col.default_value_ref().has_value(); auto& colType = col.get_type(); size_t len = colType.type_length_ref().has_value() ? *colType.get_type_length() : 0; bool nullable = col.nullable_ref().has_value() ? *col.get_nullable() : false; Expression* defaultValueExpr = nullptr; if (hasDef) { auto encoded = *col.get_default_value(); defaultValueExpr = Expression::decode(&(spaceInfoCache->pool_), folly::StringPiece(encoded.data(), encoded.size())); if (defaultValueExpr == nullptr) { LOG(ERROR) << "Wrong expr default value for column name: " << col.get_name(); hasDef = false; } } schema->addField( col.get_name(), colType.get_type(), len, nullable, hasDef ? defaultValueExpr : nullptr); }; for (auto& tagIt : tagItemVec) { // meta will return the different version from new to old auto schema = std::make_shared<NebulaSchemaProvider>(tagIt.get_version()); for (const auto& colIt : tagIt.get_schema().get_columns()) { addSchemaField(schema.get(), colIt); } // handle schema property schema->setProp(tagIt.get_schema().get_schema_prop()); if (tagIt.get_tag_id() != lastTagId) { // init schema vector, since schema version is zero-based, need to add one tagSchemas[tagIt.get_tag_id()].resize(schema->getVersion() + 1); lastTagId = tagIt.get_tag_id(); } tagSchemas[tagIt.get_tag_id()][schema->getVersion()] = std::move(schema); tagNameIdMap.emplace(std::make_pair(spaceId, tagIt.get_tag_name()), tagIt.get_tag_id()); tagIdNameMap.emplace(std::make_pair(spaceId, tagIt.get_tag_id()), tagIt.get_tag_name()); // get the latest tag version auto it = newestTagVerMap.find(std::make_pair(spaceId, tagIt.get_tag_id())); if (it != newestTagVerMap.end()) { if (it->second < tagIt.get_version()) { it->second = tagIt.get_version(); } } else { newestTagVerMap.emplace(std::make_pair(spaceId, tagIt.get_tag_id()), tagIt.get_version()); } VLOG(3) << "Load Tag Schema Space " << spaceId << ", ID " << tagIt.get_tag_id() << ", Name " << tagIt.get_tag_name() << ", Version " << tagIt.get_version() << " Successfully!"; } std::unordered_set<std::pair<GraphSpaceID, EdgeType>> edges; EdgeType lastEdgeType = -1; for (auto& edgeIt : edgeItemVec) { // meta will return the different version from new to old auto schema = std::make_shared<NebulaSchemaProvider>(edgeIt.get_version()); for (const auto& col : edgeIt.get_schema().get_columns()) { addSchemaField(schema.get(), col); } // handle shcem property schema->setProp(edgeIt.get_schema().get_schema_prop()); if (edgeIt.get_edge_type() != lastEdgeType) { // init schema vector, since schema version is zero-based, need to add one edgeSchemas[edgeIt.get_edge_type()].resize(schema->getVersion() + 1); lastEdgeType = edgeIt.get_edge_type(); } edgeSchemas[edgeIt.get_edge_type()][schema->getVersion()] = std::move(schema); edgeNameTypeMap.emplace(std::make_pair(spaceId, edgeIt.get_edge_name()), edgeIt.get_edge_type()); edgeTypeNameMap.emplace(std::make_pair(spaceId, edgeIt.get_edge_type()), edgeIt.get_edge_name()); if (edges.find({spaceId, edgeIt.get_edge_type()}) != edges.cend()) { continue; } edges.emplace(spaceId, edgeIt.get_edge_type()); allEdgeMap[spaceId].emplace_back(edgeIt.get_edge_name()); // get the latest edge version auto it2 = newestEdgeVerMap.find(std::make_pair(spaceId, edgeIt.get_edge_type())); if (it2 != newestEdgeVerMap.end()) { if (it2->second < edgeIt.get_version()) { it2->second = edgeIt.get_version(); } } else { newestEdgeVerMap.emplace(std::make_pair(spaceId, edgeIt.get_edge_type()), edgeIt.get_version()); } VLOG(3) << "Load Edge Schema Space " << spaceId << ", Type " << edgeIt.get_edge_type() << ", Name " << edgeIt.get_edge_name() << ", Version " << edgeIt.get_version() << " Successfully!"; } spaceInfoCache->tagSchemas_ = std::move(tagSchemas); spaceInfoCache->edgeSchemas_ = std::move(edgeSchemas); return true; } bool MetaClient::loadIndexes(GraphSpaceID spaceId, std::shared_ptr<SpaceInfoCache> cache) { auto tagIndexesRet = listTagIndexes(spaceId).get(); if (!tagIndexesRet.ok()) { LOG(ERROR) << "Get tag indexes failed for spaceId " << spaceId << ", " << tagIndexesRet.status(); return false; } auto edgeIndexesRet = listEdgeIndexes(spaceId).get(); if (!edgeIndexesRet.ok()) { LOG(ERROR) << "Get edge indexes failed for spaceId " << spaceId << ", " << edgeIndexesRet.status(); return false; } Indexes tagIndexes; for (auto tagIndex : tagIndexesRet.value()) { auto indexName = tagIndex.get_index_name(); auto indexID = tagIndex.get_index_id(); std::pair<GraphSpaceID, std::string> pair(spaceId, indexName); tagNameIndexMap_[pair] = indexID; auto tagIndexPtr = std::make_shared<cpp2::IndexItem>(tagIndex); tagIndexes.emplace(indexID, tagIndexPtr); } cache->tagIndexes_ = std::move(tagIndexes); Indexes edgeIndexes; for (auto& edgeIndex : edgeIndexesRet.value()) { auto indexName = edgeIndex.get_index_name(); auto indexID = edgeIndex.get_index_id(); std::pair<GraphSpaceID, std::string> pair(spaceId, indexName); edgeNameIndexMap_[pair] = indexID; auto edgeIndexPtr = std::make_shared<cpp2::IndexItem>(edgeIndex); edgeIndexes.emplace(indexID, edgeIndexPtr); } cache->edgeIndexes_ = std::move(edgeIndexes); return true; } bool MetaClient::loadListeners(GraphSpaceID spaceId, std::shared_ptr<SpaceInfoCache> cache) { auto listenerRet = listListener(spaceId).get(); if (!listenerRet.ok()) { LOG(ERROR) << "Get listeners failed for spaceId " << spaceId << ", " << listenerRet.status(); return false; } Listeners listeners; for (auto& listener : listenerRet.value()) { listeners[listener.get_host()].emplace_back( std::make_pair(listener.get_part_id(), listener.get_type())); } cache->listeners_ = std::move(listeners); return true; } bool MetaClient::loadFulltextClients() { auto ftRet = listFTClients().get(); if (!ftRet.ok()) { LOG(ERROR) << "List fulltext services failed, status:" << ftRet.status(); return false; } { folly::RWSpinLock::WriteHolder holder(localCacheLock_); fulltextClientList_ = std::move(ftRet).value(); } return true; } bool MetaClient::loadFulltextIndexes() { auto ftRet = listFTIndexes().get(); if (!ftRet.ok()) { LOG(ERROR) << "List fulltext indexes failed, status:" << ftRet.status(); return false; } { folly::RWSpinLock::WriteHolder holder(localCacheLock_); fulltextIndexMap_ = std::move(ftRet).value(); } return true; } Status MetaClient::checkTagIndexed(GraphSpaceID space, IndexID indexID) { folly::RWSpinLock::ReadHolder holder(localCacheLock_); auto it = localCache_.find(space); if (it != localCache_.end()) { auto indexIt = it->second->tagIndexes_.find(indexID); if (indexIt != it->second->tagIndexes_.end()) { return Status::OK(); } else { return Status::IndexNotFound(); } } return Status::SpaceNotFound(); } Status MetaClient::checkEdgeIndexed(GraphSpaceID space, IndexID indexID) { folly::RWSpinLock::ReadHolder holder(localCacheLock_); auto it = localCache_.find(space); if (it != localCache_.end()) { auto indexIt = it->second->edgeIndexes_.find(indexID); if (indexIt != it->second->edgeIndexes_.end()) { return Status::OK(); } else { return Status::IndexNotFound(); } } return Status::SpaceNotFound(); } std::unordered_map<HostAddr, std::vector<PartitionID>> MetaClient::reverse( const PartsAlloc& parts) { std::unordered_map<HostAddr, std::vector<PartitionID>> hosts; for (auto& partHost : parts) { for (auto& h : partHost.second) { hosts[h].emplace_back(partHost.first); } } return hosts; } template <typename Request, typename RemoteFunc, typename RespGenerator, typename RpcResponse, typename Response> void MetaClient::getResponse(Request req, RemoteFunc remoteFunc, RespGenerator respGen, folly::Promise<StatusOr<Response>> pro, bool toLeader, int32_t retry, int32_t retryLimit) { auto* evb = ioThreadPool_->getEventBase(); HostAddr host; { folly::RWSpinLock::ReadHolder holder(&hostLock_); host = toLeader ? leader_ : active_; } folly::via(evb, [host, evb, req = std::move(req), remoteFunc = std::move(remoteFunc), respGen = std::move(respGen), pro = std::move(pro), toLeader, retry, retryLimit, this]() mutable { auto client = clientsMan_->client(host, evb, false, FLAGS_meta_client_timeout_ms); VLOG(1) << "Send request to meta " << host; remoteFunc(client, req) .via(evb) .then([host, req = std::move(req), remoteFunc = std::move(remoteFunc), respGen = std::move(respGen), pro = std::move(pro), toLeader, retry, retryLimit, evb, this](folly::Try<RpcResponse>&& t) mutable { // exception occurred during RPC if (t.hasException()) { if (toLeader) { updateLeader(); } else { updateActive(); } if (retry < retryLimit) { evb->runAfterDelay( [req = std::move(req), remoteFunc = std::move(remoteFunc), respGen = std::move(respGen), pro = std::move(pro), toLeader, retry, retryLimit, this]() mutable { getResponse(std::move(req), std::move(remoteFunc), std::move(respGen), std::move(pro), toLeader, retry + 1, retryLimit); }, FLAGS_meta_client_retry_interval_secs * 1000); return; } else { LOG(ERROR) << "Send request to " << host << ", exceed retry limit"; pro.setValue(Status::Error("RPC failure in MetaClient: %s", t.exception().what().c_str())); } return; } auto&& resp = t.value(); if (resp.get_code() == nebula::cpp2::ErrorCode::SUCCEEDED) { // succeeded pro.setValue(respGen(std::move(resp))); return; } else if (resp.get_code() == nebula::cpp2::ErrorCode::E_LEADER_CHANGED) { updateLeader(resp.get_leader()); if (retry < retryLimit) { evb->runAfterDelay( [req = std::move(req), remoteFunc = std::move(remoteFunc), respGen = std::move(respGen), pro = std::move(pro), toLeader, retry, retryLimit, this]() mutable { getResponse(std::move(req), std::move(remoteFunc), std::move(respGen), std::move(pro), toLeader, retry + 1, retryLimit); }, FLAGS_meta_client_retry_interval_secs * 1000); return; } } pro.setValue(this->handleResponse(resp)); }); // then }); // via } std::vector<SpaceIdName> MetaClient::toSpaceIdName(const std::vector<cpp2::IdName>& tIdNames) { std::vector<SpaceIdName> idNames; idNames.resize(tIdNames.size()); std::transform(tIdNames.begin(), tIdNames.end(), idNames.begin(), [](const auto& tin) { return SpaceIdName(tin.get_id().get_space_id(), tin.get_name()); }); return idNames; } template <typename RESP> Status MetaClient::handleResponse(const RESP& resp) { switch (resp.get_code()) { case nebula::cpp2::ErrorCode::SUCCEEDED: return Status::OK(); case nebula::cpp2::ErrorCode::E_DISCONNECTED: return Status::Error("Disconnected!"); case nebula::cpp2::ErrorCode::E_FAIL_TO_CONNECT: return Status::Error("Fail to connect!"); case nebula::cpp2::ErrorCode::E_RPC_FAILURE: return Status::Error("Rpc failure!"); case nebula::cpp2::ErrorCode::E_LEADER_CHANGED: return Status::LeaderChanged("Leader changed!"); case nebula::cpp2::ErrorCode::E_NO_HOSTS: return Status::Error("No hosts!"); case nebula::cpp2::ErrorCode::E_EXISTED: return Status::Error("Existed!"); case nebula::cpp2::ErrorCode::E_SPACE_NOT_FOUND: return Status::Error("Space not existed!"); case nebula::cpp2::ErrorCode::E_TAG_NOT_FOUND: return Status::Error("Tag not existed!"); case nebula::cpp2::ErrorCode::E_EDGE_NOT_FOUND: return Status::Error("Edge not existed!"); case nebula::cpp2::ErrorCode::E_INDEX_NOT_FOUND: return Status::Error("Index not existed!"); case nebula::cpp2::ErrorCode::E_STATS_NOT_FOUND: return Status::Error( "There is no any stats info to show, please execute " "`submit job stats' firstly!"); case nebula::cpp2::ErrorCode::E_EDGE_PROP_NOT_FOUND: return Status::Error("Edge prop not existed!"); case nebula::cpp2::ErrorCode::E_TAG_PROP_NOT_FOUND: return Status::Error("Tag prop not existed!"); case nebula::cpp2::ErrorCode::E_ROLE_NOT_FOUND: return Status::Error("Role not existed!"); case nebula::cpp2::ErrorCode::E_CONFIG_NOT_FOUND: return Status::Error("Conf not existed!"); case nebula::cpp2::ErrorCode::E_PART_NOT_FOUND: return Status::Error("Part not existed!"); case nebula::cpp2::ErrorCode::E_USER_NOT_FOUND: return Status::Error("User not existed!"); case nebula::cpp2::ErrorCode::E_GROUP_NOT_FOUND: return Status::Error("Group not existed!"); case nebula::cpp2::ErrorCode::E_ZONE_NOT_FOUND: return Status::Error("Zone not existed!"); case nebula::cpp2::ErrorCode::E_KEY_NOT_FOUND: return Status::Error("Key not existed!"); case nebula::cpp2::ErrorCode::E_INVALID_HOST: return Status::Error("Invalid host!"); case nebula::cpp2::ErrorCode::E_UNSUPPORTED: return Status::Error("Unsupported!"); case nebula::cpp2::ErrorCode::E_NOT_DROP: return Status::Error("Not allowed to drop!"); case nebula::cpp2::ErrorCode::E_BALANCER_RUNNING: return Status::Error("The balancer is running!"); case nebula::cpp2::ErrorCode::E_CONFIG_IMMUTABLE: return Status::Error("Config immutable!"); case nebula::cpp2::ErrorCode::E_CONFLICT: return Status::Error("Conflict!"); case nebula::cpp2::ErrorCode::E_INVALID_PARM: return Status::Error("Invalid parm!"); case nebula::cpp2::ErrorCode::E_WRONGCLUSTER: return Status::Error("Wrong cluster!"); case nebula::cpp2::ErrorCode::E_STORE_FAILURE: return Status::Error("Store failure!"); case nebula::cpp2::ErrorCode::E_STORE_SEGMENT_ILLEGAL: return Status::Error("Store segment illegal!"); case nebula::cpp2::ErrorCode::E_BAD_BALANCE_PLAN: return Status::Error("Bad balance plan!"); case nebula::cpp2::ErrorCode::E_BALANCED: return Status::Error("The cluster is balanced!"); case nebula::cpp2::ErrorCode::E_NO_RUNNING_BALANCE_PLAN: return Status::Error("No running balance plan!"); case nebula::cpp2::ErrorCode::E_NO_VALID_HOST: return Status::Error("No valid host hold the partition!"); case nebula::cpp2::ErrorCode::E_CORRUPTTED_BALANCE_PLAN: return Status::Error("No corrupted blance plan!"); case nebula::cpp2::ErrorCode::E_INVALID_PASSWORD: return Status::Error("Invalid password!"); case nebula::cpp2::ErrorCode::E_IMPROPER_ROLE: return Status::Error("Improper role!"); case nebula::cpp2::ErrorCode::E_INVALID_PARTITION_NUM: return Status::Error("No valid partition_num!"); case nebula::cpp2::ErrorCode::E_INVALID_REPLICA_FACTOR: return Status::Error("No valid replica_factor!"); case nebula::cpp2::ErrorCode::E_INVALID_CHARSET: return Status::Error("No valid charset!"); case nebula::cpp2::ErrorCode::E_INVALID_COLLATE: return Status::Error("No valid collate!"); case nebula::cpp2::ErrorCode::E_CHARSET_COLLATE_NOT_MATCH: return Status::Error("Charset and collate not match!"); case nebula::cpp2::ErrorCode::E_SNAPSHOT_FAILURE: return Status::Error("Snapshot failure!"); case nebula::cpp2::ErrorCode::E_BLOCK_WRITE_FAILURE: return Status::Error("Block write failure!"); case nebula::cpp2::ErrorCode::E_REBUILD_INDEX_FAILED: return Status::Error("Rebuild index failed!"); case nebula::cpp2::ErrorCode::E_INDEX_WITH_TTL: return Status::Error("Index with ttl!"); case nebula::cpp2::ErrorCode::E_ADD_JOB_FAILURE: return Status::Error("Add job failure!"); case nebula::cpp2::ErrorCode::E_STOP_JOB_FAILURE: return Status::Error("Stop job failure!"); case nebula::cpp2::ErrorCode::E_SAVE_JOB_FAILURE: return Status::Error("Save job failure!"); case nebula::cpp2::ErrorCode::E_BALANCER_FAILURE: return Status::Error("Balance failure!"); case nebula::cpp2::ErrorCode::E_NO_INVALID_BALANCE_PLAN: return Status::Error("No invalid balance plan!"); case nebula::cpp2::ErrorCode::E_JOB_NOT_FINISHED: return Status::Error("Job is not finished!"); case nebula::cpp2::ErrorCode::E_TASK_REPORT_OUT_DATE: return Status::Error("Task report is out of date!"); case nebula::cpp2::ErrorCode::E_BACKUP_FAILED: return Status::Error("Backup failure!"); case nebula::cpp2::ErrorCode::E_BACKUP_BUILDING_INDEX: return Status::Error("Backup building indexes!"); case nebula::cpp2::ErrorCode::E_BACKUP_SPACE_NOT_FOUND: return Status::Error("The space is not found when backup!"); case nebula::cpp2::ErrorCode::E_RESTORE_FAILURE: return Status::Error("Restore failure!"); case nebula::cpp2::ErrorCode::E_LIST_CLUSTER_FAILURE: return Status::Error("list cluster failure!"); case nebula::cpp2::ErrorCode::E_LIST_CLUSTER_GET_ABS_PATH_FAILURE: return Status::Error("Failed to get the absolute path!"); case nebula::cpp2::ErrorCode::E_GET_META_DIR_FAILURE: return Status::Error("Failed to get meta dir!"); case nebula::cpp2::ErrorCode::E_INVALID_JOB: return Status::Error("No valid job!"); case nebula::cpp2::ErrorCode::E_BACKUP_EMPTY_TABLE: return Status::Error("Backup empty table!"); case nebula::cpp2::ErrorCode::E_BACKUP_TABLE_FAILED: return Status::Error("Backup table failure!"); case nebula::cpp2::ErrorCode::E_SESSION_NOT_FOUND: return Status::Error("Session not existed!"); default: return Status::Error("Unknown error!"); } } PartsMap MetaClient::doGetPartsMap(const HostAddr& host, const LocalCache& localCache) { PartsMap partMap; for (auto it = localCache.begin(); it != localCache.end(); it++) { auto spaceId = it->first; auto& cache = it->second; auto partsIt = cache->partsOnHost_.find(host); if (partsIt != cache->partsOnHost_.end()) { for (auto& partId : partsIt->second) { auto partAllocIter = cache->partsAlloc_.find(partId); CHECK(partAllocIter != cache->partsAlloc_.end()); auto& partM = partMap[spaceId][partId]; partM.spaceId_ = spaceId; partM.partId_ = partId; partM.hosts_ = partAllocIter->second; } } } return partMap; } void MetaClient::diff(const LocalCache& oldCache, const LocalCache& newCache) { folly::RWSpinLock::WriteHolder holder(listenerLock_); if (listener_ == nullptr) { VLOG(3) << "Listener is null!"; return; } auto newPartsMap = doGetPartsMap(options_.localHost_, newCache); auto oldPartsMap = doGetPartsMap(options_.localHost_, oldCache); VLOG(1) << "Let's check if any new parts added/updated for " << options_.localHost_; for (auto it = newPartsMap.begin(); it != newPartsMap.end(); it++) { auto spaceId = it->first; const auto& newParts = it->second; auto oldIt = oldPartsMap.find(spaceId); if (oldIt == oldPartsMap.end()) { VLOG(1) << "SpaceId " << spaceId << " was added!"; listener_->onSpaceAdded(spaceId); for (auto partIt = newParts.begin(); partIt != newParts.end(); partIt++) { listener_->onPartAdded(partIt->second); } } else { const auto& oldParts = oldIt->second; for (auto partIt = newParts.begin(); partIt != newParts.end(); partIt++) { auto oldPartIt = oldParts.find(partIt->first); if (oldPartIt == oldParts.end()) { VLOG(1) << "SpaceId " << spaceId << ", partId " << partIt->first << " was added!"; listener_->onPartAdded(partIt->second); } else { const auto& oldPartHosts = oldPartIt->second; const auto& newPartHosts = partIt->second; if (oldPartHosts != newPartHosts) { VLOG(1) << "SpaceId " << spaceId << ", partId " << partIt->first << " was updated!"; listener_->onPartUpdated(newPartHosts); } } } } } VLOG(1) << "Let's check if any old parts removed...."; for (auto it = oldPartsMap.begin(); it != oldPartsMap.end(); it++) { auto spaceId = it->first; const auto& oldParts = it->second; auto newIt = newPartsMap.find(spaceId); if (newIt == newPartsMap.end()) { VLOG(1) << "SpaceId " << spaceId << " was removed!"; for (auto partIt = oldParts.begin(); partIt != oldParts.end(); partIt++) { listener_->onPartRemoved(spaceId, partIt->first); } listener_->onSpaceRemoved(spaceId); } else { const auto& newParts = newIt->second; for (auto partIt = oldParts.begin(); partIt != oldParts.end(); partIt++) { auto newPartIt = newParts.find(partIt->first); if (newPartIt == newParts.end()) { VLOG(1) << "SpaceId " << spaceId << ", partId " << partIt->first << " was removed!"; listener_->onPartRemoved(spaceId, partIt->first); } } } } } void MetaClient::listenerDiff(const LocalCache& oldCache, const LocalCache& newCache) { folly::RWSpinLock::WriteHolder holder(listenerLock_); if (listener_ == nullptr) { VLOG(3) << "Listener is null!"; return; } auto newMap = doGetListenersMap(options_.localHost_, newCache); auto oldMap = doGetListenersMap(options_.localHost_, oldCache); if (newMap == oldMap) { return; } VLOG(1) << "Let's check if any listeners parts added for " << options_.localHost_; for (auto& spaceEntry : newMap) { auto spaceId = spaceEntry.first; auto oldSpaceIter = oldMap.find(spaceId); if (oldSpaceIter == oldMap.end()) { // new space is added VLOG(1) << "[Listener] SpaceId " << spaceId << " was added!"; listener_->onSpaceAdded(spaceId, true); for (const auto& partEntry : spaceEntry.second) { auto partId = partEntry.first; for (const auto& info : partEntry.second) { VLOG(1) << "[Listener] SpaceId " << spaceId << ", partId " << partId << " was added!"; listener_->onListenerAdded(spaceId, partId, info); } } } else { // check if new part listener is added for (auto& partEntry : spaceEntry.second) { auto partId = partEntry.first; auto oldPartIter = oldSpaceIter->second.find(partId); if (oldPartIter == oldSpaceIter->second.end()) { for (const auto& info : partEntry.second) { VLOG(1) << "[Listener] SpaceId " << spaceId << ", partId " << partId << " was added!"; listener_->onListenerAdded(spaceId, partId, info); } } else { std::sort(partEntry.second.begin(), partEntry.second.end()); std::sort(oldPartIter->second.begin(), oldPartIter->second.end()); std::vector<ListenerHosts> diff; std::set_difference(partEntry.second.begin(), partEntry.second.end(), oldPartIter->second.begin(), oldPartIter->second.end(), std::back_inserter(diff)); for (const auto& info : diff) { VLOG(1) << "[Listener] SpaceId " << spaceId << ", partId " << partId << " was added!"; listener_->onListenerAdded(spaceId, partId, info); } } } } } VLOG(1) << "Let's check if any old listeners removed...."; for (auto& spaceEntry : oldMap) { auto spaceId = spaceEntry.first; auto newSpaceIter = newMap.find(spaceId); if (newSpaceIter == newMap.end()) { // remove old space for (const auto& partEntry : spaceEntry.second) { auto partId = partEntry.first; for (const auto& info : partEntry.second) { VLOG(1) << "SpaceId " << spaceId << ", partId " << partId << " was removed!"; listener_->onListenerRemoved(spaceId, partId, info.type_); } } listener_->onSpaceRemoved(spaceId, true); VLOG(1) << "[Listener] SpaceId " << spaceId << " was removed!"; } else { // check if part listener is removed for (auto& partEntry : spaceEntry.second) { auto partId = partEntry.first; auto newPartIter = newSpaceIter->second.find(partId); if (newPartIter == newSpaceIter->second.end()) { for (const auto& info : partEntry.second) { VLOG(1) << "[Listener] SpaceId " << spaceId << ", partId " << partId << " was removed!"; listener_->onListenerRemoved(spaceId, partId, info.type_); } } else { std::sort(partEntry.second.begin(), partEntry.second.end()); std::sort(newPartIter->second.begin(), newPartIter->second.end()); std::vector<ListenerHosts> diff; std::set_difference(partEntry.second.begin(), partEntry.second.end(), newPartIter->second.begin(), newPartIter->second.end(), std::back_inserter(diff)); for (const auto& info : diff) { VLOG(1) << "[Listener] SpaceId " << spaceId << ", partId " << partId << " was removed!"; listener_->onListenerRemoved(spaceId, partId, info.type_); } } } } } } void MetaClient::loadRemoteListeners() { folly::RWSpinLock::WriteHolder holder(listenerLock_); if (listener_ == nullptr) { VLOG(3) << "Listener is null!"; return; } auto partsMap = getPartsMapFromCache(options_.localHost_); for (const auto& spaceEntry : partsMap) { auto spaceId = spaceEntry.first; for (const auto& partEntry : spaceEntry.second) { auto partId = partEntry.first; auto listeners = getListenerHostTypeBySpacePartType(spaceId, partId); std::vector<HostAddr> remoteListeners; if (listeners.ok()) { for (const auto& listener : listeners.value()) { remoteListeners.emplace_back(listener.first); } } listener_->onCheckRemoteListeners(spaceId, partId, remoteListeners); } } } /// ================================== public methods ================================= PartitionID MetaClient::partId(int32_t numParts, const VertexID id) const { // If the length of the id is 8, we will treat it as int64_t to be compatible // with the version 1.0 uint64_t vid = 0; if (id.size() == 8) { memcpy(static_cast<void*>(&vid), id.data(), 8); } else { MurmurHash2 hash; vid = hash(id.data()); } PartitionID pId = vid % numParts + 1; CHECK_GT(pId, 0U); return pId; } folly::Future<StatusOr<cpp2::AdminJobResult>> MetaClient::submitJob( cpp2::AdminJobOp op, cpp2::AdminCmd cmd, std::vector<std::string> paras) { cpp2::AdminJobReq req; req.set_op(op); req.set_cmd(cmd); req.set_paras(std::move(paras)); folly::Promise<StatusOr<cpp2::AdminJobResult>> promise; auto future = promise.getFuture(); getResponse( std::move(req), [](auto client, auto request) { return client->future_runAdminJob(request); }, [](cpp2::AdminJobResp&& resp) -> decltype(auto) { return resp.get_result(); }, std::move(promise)); return future; } folly::Future<StatusOr<GraphSpaceID>> MetaClient::createSpace(meta::cpp2::SpaceDesc spaceDesc, bool ifNotExists) { cpp2::CreateSpaceReq req; req.set_properties(std::move(spaceDesc)); req.set_if_not_exists(ifNotExists); folly::Promise<StatusOr<GraphSpaceID>> promise; auto future = promise.getFuture(); getResponse( std::move(req), [](auto client, auto request) { return client->future_createSpace(request); }, [](cpp2::ExecResp&& resp) -> GraphSpaceID { return resp.get_id().get_space_id(); }, std::move(promise)); return future; } folly::Future<StatusOr<std::vector<SpaceIdName>>> MetaClient::listSpaces() { cpp2::ListSpacesReq req; folly::Promise<StatusOr<std::vector<SpaceIdName>>> promise; auto future = promise.getFuture(); getResponse( std::move(req), [](auto client, auto request) { return client->future_listSpaces(request); }, [this](cpp2::ListSpacesResp&& resp) -> decltype(auto) { return this->toSpaceIdName(resp.get_spaces()); }, std::move(promise)); return future; } folly::Future<StatusOr<cpp2::SpaceItem>> MetaClient::getSpace(std::string name) { cpp2::GetSpaceReq req; req.set_space_name(std::move(name)); folly::Promise<StatusOr<cpp2::SpaceItem>> promise; auto future = promise.getFuture(); getResponse( std::move(req), [](auto client, auto request) { return client->future_getSpace(request); }, [](cpp2::GetSpaceResp&& resp) -> decltype(auto) { return std::move(resp).get_item(); }, std::move(promise)); return future; } folly::Future<StatusOr<bool>> MetaClient::dropSpace(std::string name, const bool ifExists) { cpp2::DropSpaceReq req; req.set_space_name(std::move(name)); req.set_if_exists(ifExists); folly::Promise<StatusOr<bool>> promise; auto future = promise.getFuture(); getResponse( std::move(req), [](auto client, auto request) { return client->future_dropSpace(request); }, [](cpp2::ExecResp&& resp) -> bool { return resp.get_code() == nebula::cpp2::ErrorCode::SUCCEEDED; }, std::move(promise)); return future; } folly::Future<StatusOr<std::vector<cpp2::HostItem>>> MetaClient::listHosts(cpp2::ListHostType tp) { cpp2::ListHostsReq req; req.set_type(tp); folly::Promise<StatusOr<std::vector<cpp2::HostItem>>> promise; auto future = promise.getFuture(); getResponse( std::move(req), [](auto client, auto request) { return client->future_listHosts(request); }, [](cpp2::ListHostsResp&& resp) -> decltype(auto) { return resp.get_hosts(); }, std::move(promise)); return future; } folly::Future<StatusOr<std::vector<cpp2::PartItem>>> MetaClient::listParts( GraphSpaceID spaceId, std::vector<PartitionID> partIds) { cpp2::ListPartsReq req; req.set_space_id(spaceId); req.set_part_ids(std::move(partIds)); folly::Promise<StatusOr<std::vector<cpp2::PartItem>>> promise; auto future = promise.getFuture(); getResponse( std::move(req), [](auto client, auto request) { return client->future_listParts(request); }, [](cpp2::ListPartsResp&& resp) -> decltype(auto) { return resp.get_parts(); }, std::move(promise)); return future; } folly::Future<StatusOr<std::unordered_map<PartitionID, std::vector<HostAddr>>>> MetaClient::getPartsAlloc(GraphSpaceID spaceId, PartTerms* partTerms) { cpp2::GetPartsAllocReq req; req.set_space_id(spaceId); folly::Promise<StatusOr<std::unordered_map<PartitionID, std::vector<HostAddr>>>> promise; auto future = promise.getFuture(); getResponse( std::move(req), [](auto client, auto request) { return client->future_getPartsAlloc(request); }, [=](cpp2::GetPartsAllocResp&& resp) -> decltype(auto) { std::unordered_map<PartitionID, std::vector<HostAddr>> parts; for (auto it = resp.get_parts().begin(); it != resp.get_parts().end(); it++) { parts.emplace(it->first, it->second); } if (partTerms && resp.terms_ref().has_value()) { for (auto& termOfPart : resp.terms_ref().value()) { (*partTerms)[termOfPart.first] = termOfPart.second; } } return parts; }, std::move(promise)); return future; } StatusOr<GraphSpaceID> MetaClient::getSpaceIdByNameFromCache(const std::string& name) { if (!ready_) { return Status::Error("Not ready!"); } folly::RWSpinLock::ReadHolder holder(localCacheLock_); auto it = spaceIndexByName_.find(name); if (it != spaceIndexByName_.end()) { return it->second; } return Status::SpaceNotFound(); } StatusOr<std::string> MetaClient::getSpaceNameByIdFromCache(GraphSpaceID spaceId) { if (!ready_) { return Status::Error("Not ready!"); } folly::RWSpinLock::ReadHolder holder(localCacheLock_); auto spaceIt = localCache_.find(spaceId); if (spaceIt == localCache_.end()) { LOG(ERROR) << "Space " << spaceId << " not found!"; return Status::Error("Space %d not found", spaceId); } return spaceIt->second->spaceDesc_.get_space_name(); } StatusOr<TagID> MetaClient::getTagIDByNameFromCache(const GraphSpaceID& space, const std::string& name) { if (!ready_) { return Status::Error("Not ready!"); } folly::RWSpinLock::ReadHolder holder(localCacheLock_); auto it = spaceTagIndexByName_.find(std::make_pair(space, name)); if (it == spaceTagIndexByName_.end()) { return Status::Error("TagName `%s' is nonexistent", name.c_str()); } return it->second; } StatusOr<std::string> MetaClient::getTagNameByIdFromCache(const GraphSpaceID& space, const TagID& tagId) { if (!ready_) { return Status::Error("Not ready!"); } folly::RWSpinLock::ReadHolder holder(localCacheLock_); auto it = spaceTagIndexById_.find(std::make_pair(space, tagId)); if (it == spaceTagIndexById_.end()) { return Status::Error("TagID `%d' is nonexistent", tagId); } return it->second; } StatusOr<EdgeType> MetaClient::getEdgeTypeByNameFromCache(const GraphSpaceID& space, const std::string& name) { if (!ready_) { return Status::Error("Not ready!"); } folly::RWSpinLock::ReadHolder holder(localCacheLock_); auto it = spaceEdgeIndexByName_.find(std::make_pair(space, name)); if (it == spaceEdgeIndexByName_.end()) { return Status::Error("EdgeName `%s' is nonexistent", name.c_str()); } return it->second; } StatusOr<std::string> MetaClient::getEdgeNameByTypeFromCache(const GraphSpaceID& space, const EdgeType edgeType) { if (!ready_) { return Status::Error("Not ready!"); } folly::RWSpinLock::ReadHolder holder(localCacheLock_); auto it = spaceEdgeIndexByType_.find(std::make_pair(space, edgeType)); if (it == spaceEdgeIndexByType_.end()) { return Status::Error("EdgeType `%d' is nonexistent", edgeType); } return it->second; } StatusOr<std::vector<std::string>> MetaClient::getAllEdgeFromCache(const GraphSpaceID& space) { if (!ready_) { return Status::Error("Not ready!"); } folly::RWSpinLock::ReadHolder holder(localCacheLock_); auto it = spaceAllEdgeMap_.find(space); if (it == spaceAllEdgeMap_.end()) { return Status::Error("SpaceId `%d' is nonexistent", space); } return it->second; } folly::Future<StatusOr<bool>> MetaClient::multiPut( std::string segment, std::vector<std::pair<std::string, std::string>> pairs) { if (!nebula::meta::checkSegment(segment) || pairs.empty()) { return Status::Error("arguments invalid!"); } cpp2::MultiPutReq req; std::vector<nebula::KeyValue> data; for (auto& element : pairs) { data.emplace_back(std::move(element)); } req.set_segment(std::move(segment)); req.set_pairs(std::move(data)); folly::Promise<StatusOr<bool>> promise; auto future = promise.getFuture(); getResponse( std::move(req), [](auto client, auto request) { return client->future_multiPut(request); }, [](cpp2::ExecResp&& resp) -> bool { return resp.get_code() == nebula::cpp2::ErrorCode::SUCCEEDED; }, std::move(promise)); return future; } folly::Future<StatusOr<std::string>> MetaClient::get(std::string segment, std::string key) { if (!nebula::meta::checkSegment(segment) || key.empty()) { return Status::Error("arguments invalid!"); } cpp2::GetReq req; req.set_segment(std::move(segment)); req.set_key(std::move(key)); folly::Promise<StatusOr<std::string>> promise; auto future = promise.getFuture(); getResponse( std::move(req), [](auto client, auto request) { return client->future_get(request); }, [](cpp2::GetResp&& resp) -> std::string { return resp.get_value(); }, std::move(promise)); return future; } folly::Future<StatusOr<std::vector<std::string>>> MetaClient::multiGet( std::string segment, std::vector<std::string> keys) { if (!nebula::meta::checkSegment(segment) || keys.empty()) { return Status::Error("arguments invalid!"); } cpp2::MultiGetReq req; req.set_segment(std::move(segment)); req.set_keys(std::move(keys)); folly::Promise<StatusOr<std::vector<std::string>>> promise; auto future = promise.getFuture(); getResponse( std::move(req), [](auto client, auto request) { return client->future_multiGet(request); }, [](cpp2::MultiGetResp&& resp) -> std::vector<std::string> { return resp.get_values(); }, std::move(promise)); return future; } folly::Future<StatusOr<std::vector<std::string>>> MetaClient::scan(std::string segment, std::string start, std::string end) { if (!nebula::meta::checkSegment(segment) || start.empty() || end.empty()) { return Status::Error("arguments invalid!"); } cpp2::ScanReq req; req.set_segment(std::move(segment)); req.set_start(std::move(start)); req.set_end(std::move(end)); folly::Promise<StatusOr<std::vector<std::string>>> promise; auto future = promise.getFuture(); getResponse( std::move(req), [](auto client, auto request) { return client->future_scan(request); }, [](cpp2::ScanResp&& resp) -> std::vector<std::string> { return resp.get_values(); }, std::move(promise)); return future; } folly::Future<StatusOr<bool>> MetaClient::remove(std::string segment, std::string key) { if (!nebula::meta::checkSegment(segment) || key.empty()) { return Status::Error("arguments invalid!"); } cpp2::RemoveReq req; req.set_segment(std::move(segment)); req.set_key(std::move(key)); folly::Promise<StatusOr<bool>> promise; auto future = promise.getFuture(); getResponse( std::move(req), [](auto client, auto request) { return client->future_remove(request); }, [](cpp2::ExecResp&& resp) -> bool { return resp.get_code() == nebula::cpp2::ErrorCode::SUCCEEDED; }, std::move(promise)); return future; } folly::Future<StatusOr<bool>> MetaClient::removeRange(std::string segment, std::string start, std::string end) { if (!nebula::meta::checkSegment(segment) || start.empty() || end.empty()) { return Status::Error("arguments invalid!"); } cpp2::RemoveRangeReq req; req.set_segment(std::move(segment)); req.set_start(std::move(start)); req.set_end(std::move(end)); folly::Promise<StatusOr<bool>> promise; auto future = promise.getFuture(); getResponse( std::move(req), [](auto client, auto request) { return client->future_removeRange(request); }, [](cpp2::ExecResp&& resp) -> bool { return resp.get_code() == nebula::cpp2::ErrorCode::SUCCEEDED; }, std::move(promise)); return future; } PartsMap MetaClient::getPartsMapFromCache(const HostAddr& host) { folly::RWSpinLock::ReadHolder holder(localCacheLock_); return doGetPartsMap(host, localCache_); } StatusOr<PartHosts> MetaClient::getPartHostsFromCache(GraphSpaceID spaceId, PartitionID partId) { folly::RWSpinLock::ReadHolder holder(localCacheLock_); auto it = localCache_.find(spaceId); if (it == localCache_.end()) { return Status::Error("Space not found, spaceid: %d", spaceId); } auto& cache = it->second; auto partAllocIter = cache->partsAlloc_.find(partId); if (partAllocIter == cache->partsAlloc_.end()) { return Status::Error("Part not found in cache, spaceid: %d, partid: %d", spaceId, partId); } PartHosts ph; ph.spaceId_ = spaceId; ph.partId_ = partId; ph.hosts_ = partAllocIter->second; return ph; } Status MetaClient::checkPartExistInCache(const HostAddr& host, GraphSpaceID spaceId, PartitionID partId) { folly::RWSpinLock::ReadHolder holder(localCacheLock_); auto it = localCache_.find(spaceId); if (it != localCache_.end()) { auto partsIt = it->second->partsOnHost_.find(host); if (partsIt != it->second->partsOnHost_.end()) { for (auto& pId : partsIt->second) { if (pId == partId) { return Status::OK(); } } return Status::PartNotFound(); } else { return Status::HostNotFound(); } } return Status::SpaceNotFound(); } Status MetaClient::checkSpaceExistInCache(const HostAddr& host, GraphSpaceID spaceId) { folly::RWSpinLock::ReadHolder holder(localCacheLock_); auto it = localCache_.find(spaceId); if (it != localCache_.end()) { auto partsIt = it->second->partsOnHost_.find(host); if (partsIt != it->second->partsOnHost_.end() && !partsIt->second.empty()) { return Status::OK(); } else { return Status::PartNotFound(); } } return Status::SpaceNotFound(); } StatusOr<int32_t> MetaClient::partsNum(GraphSpaceID spaceId) const { folly::RWSpinLock::ReadHolder holder(localCacheLock_); auto it = localCache_.find(spaceId); if (it == localCache_.end()) { return Status::Error("Space not found, spaceid: %d", spaceId); } return it->second->partsAlloc_.size(); } folly::Future<StatusOr<TagID>> MetaClient::createTagSchema(GraphSpaceID spaceId, std::string name, cpp2::Schema schema, bool ifNotExists) { cpp2::CreateTagReq req; req.set_space_id(spaceId); req.set_tag_name(std::move(name)); req.set_schema(std::move(schema)); req.set_if_not_exists(ifNotExists); folly::Promise<StatusOr<TagID>> promise; auto future = promise.getFuture(); getResponse( std::move(req), [](auto client, auto request) { return client->future_createTag(request); }, [](cpp2::ExecResp&& resp) -> TagID { return resp.get_id().get_tag_id(); }, std::move(promise)); return future; } folly::Future<StatusOr<bool>> MetaClient::alterTagSchema(GraphSpaceID spaceId, std::string name, std::vector<cpp2::AlterSchemaItem> items, cpp2::SchemaProp schemaProp) { cpp2::AlterTagReq req; req.set_space_id(spaceId); req.set_tag_name(std::move(name)); req.set_tag_items(std::move(items)); req.set_schema_prop(std::move(schemaProp)); folly::Promise<StatusOr<bool>> promise; auto future = promise.getFuture(); getResponse( std::move(req), [](auto client, auto request) { return client->future_alterTag(request); }, [](cpp2::ExecResp&& resp) -> bool { return resp.get_code() == nebula::cpp2::ErrorCode::SUCCEEDED; }, std::move(promise)); return future; } folly::Future<StatusOr<std::vector<cpp2::TagItem>>> MetaClient::listTagSchemas( GraphSpaceID spaceId) { cpp2::ListTagsReq req; req.set_space_id(spaceId); folly::Promise<StatusOr<std::vector<cpp2::TagItem>>> promise; auto future = promise.getFuture(); getResponse( std::move(req), [](auto client, auto request) { return client->future_listTags(request); }, [](cpp2::ListTagsResp&& resp) -> decltype(auto) { return std::move(resp).get_tags(); }, std::move(promise)); return future; } folly::Future<StatusOr<bool>> MetaClient::dropTagSchema(GraphSpaceID spaceId, std::string tagName, const bool ifExists) { cpp2::DropTagReq req; req.set_space_id(spaceId); req.set_tag_name(std::move(tagName)); req.set_if_exists(ifExists); folly::Promise<StatusOr<bool>> promise; auto future = promise.getFuture(); getResponse( std::move(req), [](auto client, auto request) { return client->future_dropTag(request); }, [](cpp2::ExecResp&& resp) -> bool { return resp.get_code() == nebula::cpp2::ErrorCode::SUCCEEDED; }, std::move(promise)); return future; } folly::Future<StatusOr<cpp2::Schema>> MetaClient::getTagSchema(GraphSpaceID spaceId, std::string name, int64_t version) { cpp2::GetTagReq req; req.set_space_id(spaceId); req.set_tag_name(std::move(name)); req.set_version(version); folly::Promise<StatusOr<cpp2::Schema>> promise; auto future = promise.getFuture(); getResponse( std::move(req), [](auto client, auto request) { return client->future_getTag(request); }, [](cpp2::GetTagResp&& resp) -> cpp2::Schema { return std::move(resp).get_schema(); }, std::move(promise)); return future; } folly::Future<StatusOr<EdgeType>> MetaClient::createEdgeSchema(GraphSpaceID spaceId, std::string name, cpp2::Schema schema, bool ifNotExists) { cpp2::CreateEdgeReq req; req.set_space_id(spaceId); req.set_edge_name(std::move(name)); req.set_schema(schema); req.set_if_not_exists(ifNotExists); folly::Promise<StatusOr<EdgeType>> promise; auto future = promise.getFuture(); getResponse( std::move(req), [](auto client, auto request) { return client->future_createEdge(request); }, [](cpp2::ExecResp&& resp) -> EdgeType { return resp.get_id().get_edge_type(); }, std::move(promise)); return future; } folly::Future<StatusOr<bool>> MetaClient::alterEdgeSchema(GraphSpaceID spaceId, std::string name, std::vector<cpp2::AlterSchemaItem> items, cpp2::SchemaProp schemaProp) { cpp2::AlterEdgeReq req; req.set_space_id(spaceId); req.set_edge_name(std::move(name)); req.set_edge_items(std::move(items)); req.set_schema_prop(std::move(schemaProp)); folly::Promise<StatusOr<bool>> promise; auto future = promise.getFuture(); getResponse( std::move(req), [](auto client, auto request) { return client->future_alterEdge(request); }, [](cpp2::ExecResp&& resp) -> bool { return resp.get_code() == nebula::cpp2::ErrorCode::SUCCEEDED; }, std::move(promise)); return future; } folly::Future<StatusOr<std::vector<cpp2::EdgeItem>>> MetaClient::listEdgeSchemas( GraphSpaceID spaceId) { cpp2::ListEdgesReq req; req.set_space_id(spaceId); folly::Promise<StatusOr<std::vector<cpp2::EdgeItem>>> promise; auto future = promise.getFuture(); getResponse( std::move(req), [](auto client, auto request) { return client->future_listEdges(request); }, [](cpp2::ListEdgesResp&& resp) -> decltype(auto) { return std::move(resp).get_edges(); }, std::move(promise)); return future; } folly::Future<StatusOr<cpp2::Schema>> MetaClient::getEdgeSchema(GraphSpaceID spaceId, std::string name, SchemaVer version) { cpp2::GetEdgeReq req; req.set_space_id(spaceId); req.set_edge_name(std::move(name)); req.set_version(version); folly::Promise<StatusOr<cpp2::Schema>> promise; auto future = promise.getFuture(); getResponse( std::move(req), [](auto client, auto request) { return client->future_getEdge(request); }, [](cpp2::GetEdgeResp&& resp) -> cpp2::Schema { return std::move(resp).get_schema(); }, std::move(promise)); return future; } folly::Future<StatusOr<bool>> MetaClient::dropEdgeSchema(GraphSpaceID spaceId, std::string name, const bool ifExists) { cpp2::DropEdgeReq req; req.set_space_id(spaceId); req.set_edge_name(std::move(name)); req.set_if_exists(ifExists); folly::Promise<StatusOr<bool>> promise; auto future = promise.getFuture(); getResponse( std::move(req), [](auto client, auto request) { return client->future_dropEdge(request); }, [](cpp2::ExecResp&& resp) -> bool { return resp.get_code() == nebula::cpp2::ErrorCode::SUCCEEDED; }, std::move(promise)); return future; } folly::Future<StatusOr<IndexID>> MetaClient::createTagIndex(GraphSpaceID spaceID, std::string indexName, std::string tagName, std::vector<cpp2::IndexFieldDef> fields, bool ifNotExists, const std::string* comment) { cpp2::CreateTagIndexReq req; req.set_space_id(spaceID); req.set_index_name(std::move(indexName)); req.set_tag_name(std::move(tagName)); req.set_fields(std::move(fields)); req.set_if_not_exists(ifNotExists); if (comment != nullptr) { req.set_comment(*comment); } folly::Promise<StatusOr<IndexID>> promise; auto future = promise.getFuture(); getResponse( std::move(req), [](auto client, auto request) { return client->future_createTagIndex(request); }, [](cpp2::ExecResp&& resp) -> IndexID { return resp.get_id().get_index_id(); }, std::move(promise)); return future; } folly::Future<StatusOr<bool>> MetaClient::dropTagIndex(GraphSpaceID spaceID, std::string name, bool ifExists) { cpp2::DropTagIndexReq req; req.set_space_id(spaceID); req.set_index_name(std::move(name)); req.set_if_exists(ifExists); folly::Promise<StatusOr<bool>> promise; auto future = promise.getFuture(); getResponse( std::move(req), [](auto client, auto request) { return client->future_dropTagIndex(request); }, [](cpp2::ExecResp&& resp) -> bool { return resp.get_code() == nebula::cpp2::ErrorCode::SUCCEEDED; }, std::move(promise)); return future; } folly::Future<StatusOr<cpp2::IndexItem>> MetaClient::getTagIndex(GraphSpaceID spaceID, std::string name) { cpp2::GetTagIndexReq req; req.set_space_id(spaceID); req.set_index_name(std::move(name)); folly::Promise<StatusOr<cpp2::IndexItem>> promise; auto future = promise.getFuture(); getResponse( std::move(req), [](auto client, auto request) { return client->future_getTagIndex(request); }, [](cpp2::GetTagIndexResp&& resp) -> cpp2::IndexItem { return std::move(resp).get_item(); }, std::move(promise)); return future; } folly::Future<StatusOr<std::vector<cpp2::IndexItem>>> MetaClient::listTagIndexes( GraphSpaceID spaceId) { cpp2::ListTagIndexesReq req; req.set_space_id(spaceId); folly::Promise<StatusOr<std::vector<cpp2::IndexItem>>> promise; auto future = promise.getFuture(); getResponse( std::move(req), [](auto client, auto request) { return client->future_listTagIndexes(request); }, [](cpp2::ListTagIndexesResp&& resp) -> decltype(auto) { return std::move(resp).get_items(); }, std::move(promise)); return future; } folly::Future<StatusOr<bool>> MetaClient::rebuildTagIndex(GraphSpaceID spaceID, std::string name) { cpp2::RebuildIndexReq req; req.set_space_id(spaceID); req.set_index_name(std::move(name)); folly::Promise<StatusOr<bool>> promise; auto future = promise.getFuture(); getResponse( std::move(req), [](auto client, auto request) { return client->future_rebuildTagIndex(request); }, [](cpp2::ExecResp&& resp) -> bool { return resp.get_code() == nebula::cpp2::ErrorCode::SUCCEEDED; }, std::move(promise)); return future; } folly::Future<StatusOr<std::vector<cpp2::IndexStatus>>> MetaClient::listTagIndexStatus( GraphSpaceID spaceID) { cpp2::ListIndexStatusReq req; req.set_space_id(spaceID); folly::Promise<StatusOr<std::vector<cpp2::IndexStatus>>> promise; auto future = promise.getFuture(); getResponse( std::move(req), [](auto client, auto request) { return client->future_listTagIndexStatus(request); }, [](cpp2::ListIndexStatusResp&& resp) -> decltype(auto) { return std::move(resp).get_statuses(); }, std::move(promise)); return future; } folly::Future<StatusOr<IndexID>> MetaClient::createEdgeIndex( GraphSpaceID spaceID, std::string indexName, std::string edgeName, std::vector<cpp2::IndexFieldDef> fields, bool ifNotExists, const std::string* comment) { cpp2::CreateEdgeIndexReq req; req.set_space_id(spaceID); req.set_index_name(std::move(indexName)); req.set_edge_name(std::move(edgeName)); req.set_fields(std::move(fields)); req.set_if_not_exists(ifNotExists); if (comment != nullptr) { req.set_comment(*comment); } folly::Promise<StatusOr<IndexID>> promise; auto future = promise.getFuture(); getResponse( std::move(req), [](auto client, auto request) { return client->future_createEdgeIndex(request); }, [](cpp2::ExecResp&& resp) -> IndexID { return resp.get_id().get_index_id(); }, std::move(promise)); return future; } folly::Future<StatusOr<bool>> MetaClient::dropEdgeIndex(GraphSpaceID spaceId, std::string name, bool ifExists) { cpp2::DropEdgeIndexReq req; req.set_space_id(spaceId); req.set_index_name(std::move(name)); req.set_if_exists(ifExists); folly::Promise<StatusOr<bool>> promise; auto future = promise.getFuture(); getResponse( std::move(req), [](auto client, auto request) { return client->future_dropEdgeIndex(request); }, [](cpp2::ExecResp&& resp) -> bool { return resp.get_code() == nebula::cpp2::ErrorCode::SUCCEEDED; }, std::move(promise)); return future; } folly::Future<StatusOr<cpp2::IndexItem>> MetaClient::getEdgeIndex(GraphSpaceID spaceId, std::string name) { cpp2::GetEdgeIndexReq req; req.set_space_id(spaceId); req.set_index_name(std::move(name)); folly::Promise<StatusOr<cpp2::IndexItem>> promise; auto future = promise.getFuture(); getResponse( std::move(req), [](auto client, auto request) { return client->future_getEdgeIndex(request); }, [](cpp2::GetEdgeIndexResp&& resp) -> cpp2::IndexItem { return std::move(resp).get_item(); }, std::move(promise)); return future; } folly::Future<StatusOr<std::vector<cpp2::IndexItem>>> MetaClient::listEdgeIndexes( GraphSpaceID spaceId) { cpp2::ListEdgeIndexesReq req; req.set_space_id(spaceId); folly::Promise<StatusOr<std::vector<cpp2::IndexItem>>> promise; auto future = promise.getFuture(); getResponse( std::move(req), [](auto client, auto request) { return client->future_listEdgeIndexes(request); }, [](cpp2::ListEdgeIndexesResp&& resp) -> decltype(auto) { return std::move(resp).get_items(); }, std::move(promise)); return future; } StatusOr<int32_t> MetaClient::getSpaceVidLen(const GraphSpaceID& spaceId) { if (!ready_) { return Status::Error("Not ready!"); } folly::RWSpinLock::ReadHolder holder(localCacheLock_); auto spaceIt = localCache_.find(spaceId); if (spaceIt == localCache_.end()) { LOG(ERROR) << "Space " << spaceId << " not found!"; return Status::Error("Space %d not found", spaceId); } auto& vidType = spaceIt->second->spaceDesc_.get_vid_type(); auto vIdLen = vidType.type_length_ref().has_value() ? *vidType.get_type_length() : 0; if (vIdLen <= 0) { return Status::Error("Space %d vertexId length invalid", spaceId); } return vIdLen; } StatusOr<cpp2::PropertyType> MetaClient::getSpaceVidType(const GraphSpaceID& spaceId) { if (!ready_) { return Status::Error("Not ready!"); } folly::RWSpinLock::ReadHolder holder(localCacheLock_); auto spaceIt = localCache_.find(spaceId); if (spaceIt == localCache_.end()) { LOG(ERROR) << "Space " << spaceId << " not found!"; return Status::Error("Space %d not found", spaceId); } auto vIdType = spaceIt->second->spaceDesc_.get_vid_type().get_type(); if (vIdType != cpp2::PropertyType::INT64 && vIdType != cpp2::PropertyType::FIXED_STRING) { std::stringstream ss; ss << "Space " << spaceId << ", vertexId type invalid: " << apache::thrift::util::enumNameSafe(vIdType); return Status::Error(ss.str()); } return vIdType; } StatusOr<cpp2::SpaceDesc> MetaClient::getSpaceDesc(const GraphSpaceID& space) { if (!ready_) { return Status::Error("Not ready!"); } folly::RWSpinLock::ReadHolder holder(localCacheLock_); auto spaceIt = localCache_.find(space); if (spaceIt == localCache_.end()) { LOG(ERROR) << "Space " << space << " not found!"; return Status::Error("Space %d not found", space); } return spaceIt->second->spaceDesc_; } StatusOr<meta::cpp2::IsolationLevel> MetaClient::getIsolationLevel(GraphSpaceID spaceId) { auto spaceDescStatus = getSpaceDesc(spaceId); if (!spaceDescStatus.ok()) { return spaceDescStatus.status(); } using IsolationLevel = meta::cpp2::IsolationLevel; return spaceDescStatus.value().isolation_level_ref().value_or(IsolationLevel::DEFAULT); } StatusOr<std::shared_ptr<const NebulaSchemaProvider>> MetaClient::getTagSchemaFromCache( GraphSpaceID spaceId, TagID tagID, SchemaVer ver) { if (!ready_) { return Status::Error("Not ready!"); } folly::RWSpinLock::ReadHolder holder(localCacheLock_); auto spaceIt = localCache_.find(spaceId); if (spaceIt != localCache_.end()) { auto tagIt = spaceIt->second->tagSchemas_.find(tagID); if (tagIt != spaceIt->second->tagSchemas_.end() && !tagIt->second.empty()) { size_t vNum = tagIt->second.size(); if (static_cast<SchemaVer>(vNum) > ver) { return ver < 0 ? tagIt->second.back() : tagIt->second[ver]; } } } LOG(ERROR) << "The tag schema " << tagID << " not found in space " << spaceId; return std::shared_ptr<const NebulaSchemaProvider>(); } StatusOr<std::shared_ptr<const NebulaSchemaProvider>> MetaClient::getEdgeSchemaFromCache( GraphSpaceID spaceId, EdgeType edgeType, SchemaVer ver) { if (!ready_) { return Status::Error("Not ready!"); } folly::RWSpinLock::ReadHolder holder(localCacheLock_); auto spaceIt = localCache_.find(spaceId); if (spaceIt != localCache_.end()) { auto edgeIt = spaceIt->second->edgeSchemas_.find(edgeType); if (edgeIt != spaceIt->second->edgeSchemas_.end() && !edgeIt->second.empty()) { size_t vNum = edgeIt->second.size(); if (static_cast<SchemaVer>(vNum) > ver) { return ver < 0 ? edgeIt->second.back() : edgeIt->second[ver]; } } } LOG(ERROR) << "The edge schema " << edgeType << " not found in space " << spaceId; return std::shared_ptr<const NebulaSchemaProvider>(); } StatusOr<TagSchemas> MetaClient::getAllVerTagSchema(GraphSpaceID spaceId) { if (!ready_) { return Status::Error("Not ready!"); } folly::RWSpinLock::ReadHolder holder(localCacheLock_); auto iter = localCache_.find(spaceId); if (iter == localCache_.end()) { return Status::Error("Space %d not found", spaceId); } return iter->second->tagSchemas_; } StatusOr<TagSchema> MetaClient::getAllLatestVerTagSchema(const GraphSpaceID& spaceId) { if (!ready_) { return Status::Error("Not ready!"); } folly::RWSpinLock::ReadHolder holder(localCacheLock_); auto iter = localCache_.find(spaceId); if (iter == localCache_.end()) { return Status::Error("Space %d not found", spaceId); } TagSchema tagsSchema; tagsSchema.reserve(iter->second->tagSchemas_.size()); // fetch all tagIds for (const auto& tagSchema : iter->second->tagSchemas_) { tagsSchema.emplace(tagSchema.first, tagSchema.second.back()); } return tagsSchema; } StatusOr<EdgeSchemas> MetaClient::getAllVerEdgeSchema(GraphSpaceID spaceId) { if (!ready_) { return Status::Error("Not ready!"); } folly::RWSpinLock::ReadHolder holder(localCacheLock_); auto iter = localCache_.find(spaceId); if (iter == localCache_.end()) { return Status::Error("Space %d not found", spaceId); } return iter->second->edgeSchemas_; } StatusOr<EdgeSchema> MetaClient::getAllLatestVerEdgeSchemaFromCache(const GraphSpaceID& spaceId) { if (!ready_) { return Status::Error("Not ready!"); } folly::RWSpinLock::ReadHolder holder(localCacheLock_); auto iter = localCache_.find(spaceId); if (iter == localCache_.end()) { return Status::Error("Space %d not found", spaceId); } EdgeSchema edgesSchema; edgesSchema.reserve(iter->second->edgeSchemas_.size()); // fetch all edgeTypes for (const auto& edgeSchema : iter->second->edgeSchemas_) { edgesSchema.emplace(edgeSchema.first, edgeSchema.second.back()); } return edgesSchema; } folly::Future<StatusOr<bool>> MetaClient::rebuildEdgeIndex(GraphSpaceID spaceID, std::string name) { cpp2::RebuildIndexReq req; req.set_space_id(spaceID); req.set_index_name(std::move(name)); folly::Promise<StatusOr<bool>> promise; auto future = promise.getFuture(); getResponse( std::move(req), [](auto client, auto request) { return client->future_rebuildEdgeIndex(request); }, [](cpp2::ExecResp&& resp) -> bool { return resp.get_code() == nebula::cpp2::ErrorCode::SUCCEEDED; }, std::move(promise)); return future; } folly::Future<StatusOr<std::vector<cpp2::IndexStatus>>> MetaClient::listEdgeIndexStatus( GraphSpaceID spaceID) { cpp2::ListIndexStatusReq req; req.set_space_id(spaceID); folly::Promise<StatusOr<std::vector<cpp2::IndexStatus>>> promise; auto future = promise.getFuture(); getResponse( std::move(req), [](auto client, auto request) { return client->future_listEdgeIndexStatus(request); }, [](cpp2::ListIndexStatusResp&& resp) -> decltype(auto) { return std::move(resp).get_statuses(); }, std::move(promise)); return future; } StatusOr<std::shared_ptr<cpp2::IndexItem>> MetaClient::getTagIndexByNameFromCache( const GraphSpaceID space, const std::string& name) { if (!ready_) { return Status::Error("Not ready!"); } std::pair<GraphSpaceID, std::string> key(space, name); auto iter = tagNameIndexMap_.find(key); if (iter == tagNameIndexMap_.end()) { return Status::IndexNotFound(); } auto indexID = iter->second; auto itemStatus = getTagIndexFromCache(space, indexID); if (!itemStatus.ok()) { return itemStatus.status(); } return itemStatus.value(); } StatusOr<std::shared_ptr<cpp2::IndexItem>> MetaClient::getEdgeIndexByNameFromCache( const GraphSpaceID space, const std::string& name) { if (!ready_) { return Status::Error("Not ready!"); } std::pair<GraphSpaceID, std::string> key(space, name); auto iter = edgeNameIndexMap_.find(key); if (iter == edgeNameIndexMap_.end()) { return Status::IndexNotFound(); } auto indexID = iter->second; auto itemStatus = getEdgeIndexFromCache(space, indexID); if (!itemStatus.ok()) { return itemStatus.status(); } return itemStatus.value(); } StatusOr<std::shared_ptr<cpp2::IndexItem>> MetaClient::getTagIndexFromCache(GraphSpaceID spaceId, IndexID indexID) { if (!ready_) { return Status::Error("Not ready!"); } folly::RWSpinLock::ReadHolder holder(localCacheLock_); auto spaceIt = localCache_.find(spaceId); if (spaceIt == localCache_.end()) { VLOG(3) << "Space " << spaceId << " not found!"; return Status::SpaceNotFound(); } else { auto iter = spaceIt->second->tagIndexes_.find(indexID); if (iter == spaceIt->second->tagIndexes_.end()) { VLOG(3) << "Space " << spaceId << ", Tag Index " << indexID << " not found!"; return Status::IndexNotFound(); } else { return iter->second; } } } StatusOr<TagID> MetaClient::getRelatedTagIDByIndexNameFromCache(const GraphSpaceID space, const std::string& indexName) { if (!ready_) { return Status::Error("Not ready!"); } auto indexRet = getTagIndexByNameFromCache(space, indexName); if (!indexRet.ok()) { LOG(ERROR) << "Index " << indexName << " Not Found"; return indexRet.status(); } return indexRet.value()->get_schema_id().get_tag_id(); } StatusOr<std::shared_ptr<cpp2::IndexItem>> MetaClient::getEdgeIndexFromCache(GraphSpaceID spaceId, IndexID indexID) { if (!ready_) { return Status::Error("Not ready!"); } folly::RWSpinLock::ReadHolder holder(localCacheLock_); auto spaceIt = localCache_.find(spaceId); if (spaceIt == localCache_.end()) { VLOG(3) << "Space " << spaceId << " not found!"; return Status::SpaceNotFound(); } else { auto iter = spaceIt->second->edgeIndexes_.find(indexID); if (iter == spaceIt->second->edgeIndexes_.end()) { VLOG(3) << "Space " << spaceId << ", Edge Index " << indexID << " not found!"; return Status::IndexNotFound(); } else { return iter->second; } } } StatusOr<EdgeType> MetaClient::getRelatedEdgeTypeByIndexNameFromCache( const GraphSpaceID space, const std::string& indexName) { if (!ready_) { return Status::Error("Not ready!"); } auto indexRet = getEdgeIndexByNameFromCache(space, indexName); if (!indexRet.ok()) { LOG(ERROR) << "Index " << indexName << " Not Found"; return indexRet.status(); } return indexRet.value()->get_schema_id().get_edge_type(); } StatusOr<std::vector<std::shared_ptr<cpp2::IndexItem>>> MetaClient::getTagIndexesFromCache( GraphSpaceID spaceId) { if (!ready_) { return Status::Error("Not ready!"); } folly::RWSpinLock::ReadHolder holder(localCacheLock_); auto spaceIt = localCache_.find(spaceId); if (spaceIt == localCache_.end()) { VLOG(3) << "Space " << spaceId << " not found!"; return Status::SpaceNotFound(); } else { auto tagIndexes = spaceIt->second->tagIndexes_; auto iter = tagIndexes.begin(); std::vector<std::shared_ptr<cpp2::IndexItem>> items; while (iter != tagIndexes.end()) { items.emplace_back(iter->second); iter++; } return items; } } StatusOr<std::vector<std::shared_ptr<cpp2::IndexItem>>> MetaClient::getEdgeIndexesFromCache( GraphSpaceID spaceId) { if (!ready_) { return Status::Error("Not ready!"); } folly::RWSpinLock::ReadHolder holder(localCacheLock_); auto spaceIt = localCache_.find(spaceId); if (spaceIt == localCache_.end()) { VLOG(3) << "Space " << spaceId << " not found!"; return Status::SpaceNotFound(); } else { auto edgeIndexes = spaceIt->second->edgeIndexes_; auto iter = edgeIndexes.begin(); std::vector<std::shared_ptr<cpp2::IndexItem>> items; while (iter != edgeIndexes.end()) { items.emplace_back(iter->second); iter++; } return items; } } StatusOr<HostAddr> MetaClient::getStorageLeaderFromCache(GraphSpaceID spaceId, PartitionID partId) { if (!ready_) { return Status::Error("Not ready!"); } { folly::RWSpinLock::ReadHolder holder(leadersLock_); auto iter = leadersInfo_.leaderMap_.find({spaceId, partId}); if (iter != leadersInfo_.leaderMap_.end()) { return iter->second; } } { // no leader found, pick one in round-robin auto partHostsRet = getPartHostsFromCache(spaceId, partId); if (!partHostsRet.ok()) { return partHostsRet.status(); } auto partHosts = partHostsRet.value(); folly::RWSpinLock::WriteHolder wh(leadersLock_); VLOG(1) << "No leader exists. Choose one in round-robin."; auto index = (leadersInfo_.pickedIndex_[{spaceId, partId}] + 1) % partHosts.hosts_.size(); auto picked = partHosts.hosts_[index]; leadersInfo_.leaderMap_[{spaceId, partId}] = picked; leadersInfo_.pickedIndex_[{spaceId, partId}] = index; return picked; } } void MetaClient::updateStorageLeader(GraphSpaceID spaceId, PartitionID partId, const HostAddr& leader) { VLOG(1) << "Update the leader for [" << spaceId << ", " << partId << "] to " << leader; folly::RWSpinLock::WriteHolder holder(leadersLock_); leadersInfo_.leaderMap_[{spaceId, partId}] = leader; } void MetaClient::invalidStorageLeader(GraphSpaceID spaceId, PartitionID partId) { VLOG(1) << "Invalidate the leader for [" << spaceId << ", " << partId << "]"; folly::RWSpinLock::WriteHolder holder(leadersLock_); leadersInfo_.leaderMap_.erase({spaceId, partId}); } StatusOr<LeaderInfo> MetaClient::getLeaderInfo() { if (!ready_) { return Status::Error("Not ready!"); } folly::RWSpinLock::ReadHolder holder(leadersLock_); return leadersInfo_; } const std::vector<HostAddr>& MetaClient::getAddresses() { return addrs_; } std::vector<cpp2::RoleItem> MetaClient::getRolesByUserFromCache(const std::string& user) const { if (!ready_) { return std::vector<cpp2::RoleItem>(0); } folly::RWSpinLock::ReadHolder holder(localCacheLock_); auto iter = userRolesMap_.find(user); if (iter == userRolesMap_.end()) { return std::vector<cpp2::RoleItem>(0); } return iter->second; } bool MetaClient::authCheckFromCache(const std::string& account, const std::string& password) const { if (!ready_) { return false; } folly::RWSpinLock::ReadHolder holder(localCacheLock_); auto iter = userPasswordMap_.find(account); if (iter == userPasswordMap_.end()) { return false; } return iter->second == password; } bool MetaClient::checkShadowAccountFromCache(const std::string& account) const { if (!ready_) { return false; } folly::RWSpinLock::ReadHolder holder(localCacheLock_); auto iter = userPasswordMap_.find(account); if (iter != userPasswordMap_.end()) { return true; } return false; } TermID MetaClient::getTermFromCache(GraphSpaceID spaceId, PartitionID partId) const { static TermID notFound = -1; folly::RWSpinLock::ReadHolder holder(localCacheLock_); auto spaceInfo = localCache_.find(spaceId); if (spaceInfo == localCache_.end()) { return notFound; } auto termInfo = spaceInfo->second->termOfPartition_.find(partId); if (termInfo == spaceInfo->second->termOfPartition_.end()) { return notFound; } return termInfo->second; } StatusOr<std::vector<HostAddr>> MetaClient::getStorageHosts() const { if (!ready_) { return Status::Error("Not ready!"); } folly::RWSpinLock::ReadHolder holder(localCacheLock_); return storageHosts_; } StatusOr<SchemaVer> MetaClient::getLatestTagVersionFromCache(const GraphSpaceID& space, const TagID& tagId) { if (!ready_) { return Status::Error("Not ready!"); } folly::RWSpinLock::ReadHolder holder(localCacheLock_); auto it = spaceNewestTagVerMap_.find(std::make_pair(space, tagId)); if (it == spaceNewestTagVerMap_.end()) { return Status::TagNotFound(); } return it->second; } StatusOr<SchemaVer> MetaClient::getLatestEdgeVersionFromCache(const GraphSpaceID& space, const EdgeType& edgeType) { if (!ready_) { return Status::Error("Not ready!"); } folly::RWSpinLock::ReadHolder holder(localCacheLock_); auto it = spaceNewestEdgeVerMap_.find(std::make_pair(space, edgeType)); if (it == spaceNewestEdgeVerMap_.end()) { return Status::EdgeNotFound(); } return it->second; } folly::Future<StatusOr<bool>> MetaClient::heartbeat() { cpp2::HBReq req; req.set_host(options_.localHost_); req.set_role(options_.role_); req.set_git_info_sha(options_.gitInfoSHA_); #if defined(NEBULA_BUILD_VERSION) req.set_version(versionString(false)); #endif if (options_.role_ == cpp2::HostRole::STORAGE) { if (options_.clusterId_.load() == 0) { options_.clusterId_ = FileBasedClusterIdMan::getClusterIdFromFile(FLAGS_cluster_id_path); } req.set_cluster_id(options_.clusterId_.load()); std::unordered_map<GraphSpaceID, std::vector<cpp2::LeaderInfo>> leaderIds; if (listener_ != nullptr) { listener_->fetchLeaderInfo(leaderIds); if (leaderIds_ != leaderIds) { { folly::RWSpinLock::WriteHolder holder(leaderIdsLock_); leaderIds_.clear(); leaderIds_ = leaderIds; } } req.set_leader_partIds(std::move(leaderIds)); } else { req.set_leader_partIds(std::move(leaderIds)); } } folly::Promise<StatusOr<bool>> promise; auto future = promise.getFuture(); VLOG(1) << "Send heartbeat to " << leader_ << ", clusterId " << req.get_cluster_id(); getResponse( std::move(req), [](auto client, auto request) { return client->future_heartBeat(request); }, [this](cpp2::HBResp&& resp) -> bool { if (options_.role_ == cpp2::HostRole::STORAGE && options_.clusterId_.load() == 0) { LOG(INFO) << "Persisit the cluster Id from metad " << resp.get_cluster_id(); if (FileBasedClusterIdMan::persistInFile(resp.get_cluster_id(), FLAGS_cluster_id_path)) { options_.clusterId_.store(resp.get_cluster_id()); } else { LOG(FATAL) << "Can't persist the clusterId in file " << FLAGS_cluster_id_path; } } heartbeatTime_ = time::WallClock::fastNowInMilliSec(); metadLastUpdateTime_ = resp.get_last_update_time_in_ms(); VLOG(1) << "Metad last update time: " << metadLastUpdateTime_; metaServerVersion_ = resp.get_meta_version(); return resp.get_code() == nebula::cpp2::ErrorCode::SUCCEEDED; }, std::move(promise)); return future; } folly::Future<StatusOr<bool>> MetaClient::createUser(std::string account, std::string password, bool ifNotExists) { cpp2::CreateUserReq req; req.set_account(std::move(account)); req.set_encoded_pwd(std::move(password)); req.set_if_not_exists(ifNotExists); folly::Promise<StatusOr<bool>> promise; auto future = promise.getFuture(); getResponse( std::move(req), [](auto client, auto request) { return client->future_createUser(request); }, [](cpp2::ExecResp&& resp) -> bool { return resp.get_code() == nebula::cpp2::ErrorCode::SUCCEEDED; }, std::move(promise)); return future; } folly::Future<StatusOr<bool>> MetaClient::dropUser(std::string account, bool ifExists) { cpp2::DropUserReq req; req.set_account(std::move(account)); req.set_if_exists(ifExists); folly::Promise<StatusOr<bool>> promise; auto future = promise.getFuture(); getResponse( std::move(req), [](auto client, auto request) { return client->future_dropUser(request); }, [](cpp2::ExecResp&& resp) -> bool { return resp.get_code() == nebula::cpp2::ErrorCode::SUCCEEDED; }, std::move(promise)); return future; } folly::Future<StatusOr<bool>> MetaClient::alterUser(std::string account, std::string password) { cpp2::AlterUserReq req; req.set_account(std::move(account)); req.set_encoded_pwd(std::move(password)); folly::Promise<StatusOr<bool>> promise; auto future = promise.getFuture(); getResponse( std::move(req), [](auto client, auto request) { return client->future_alterUser(request); }, [](cpp2::ExecResp&& resp) -> bool { return resp.get_code() == nebula::cpp2::ErrorCode::SUCCEEDED; }, std::move(promise)); return future; } folly::Future<StatusOr<bool>> MetaClient::grantToUser(cpp2::RoleItem roleItem) { cpp2::GrantRoleReq req; req.set_role_item(std::move(roleItem)); folly::Promise<StatusOr<bool>> promise; auto future = promise.getFuture(); getResponse( std::move(req), [](auto client, auto request) { return client->future_grantRole(request); }, [](cpp2::ExecResp&& resp) -> bool { return resp.get_code() == nebula::cpp2::ErrorCode::SUCCEEDED; }, std::move(promise)); return future; } folly::Future<StatusOr<bool>> MetaClient::revokeFromUser(cpp2::RoleItem roleItem) { cpp2::RevokeRoleReq req; req.set_role_item(std::move(roleItem)); folly::Promise<StatusOr<bool>> promise; auto future = promise.getFuture(); getResponse( std::move(req), [](auto client, auto request) { return client->future_revokeRole(request); }, [](cpp2::ExecResp&& resp) -> bool { return resp.get_code() == nebula::cpp2::ErrorCode::SUCCEEDED; }, std::move(promise)); return future; } folly::Future<StatusOr<std::unordered_map<std::string, std::string>>> MetaClient::listUsers() { cpp2::ListUsersReq req; folly::Promise<StatusOr<std::unordered_map<std::string, std::string>>> promise; auto future = promise.getFuture(); getResponse( std::move(req), [](auto client, auto request) { return client->future_listUsers(request); }, [](cpp2::ListUsersResp&& resp) -> decltype(auto) { return std::move(resp).get_users(); }, std::move(promise)); return future; } folly::Future<StatusOr<std::vector<cpp2::RoleItem>>> MetaClient::listRoles(GraphSpaceID space) { cpp2::ListRolesReq req; req.set_space_id(std::move(space)); folly::Promise<StatusOr<std::vector<cpp2::RoleItem>>> promise; auto future = promise.getFuture(); getResponse( std::move(req), [](auto client, auto request) { return client->future_listRoles(request); }, [](cpp2::ListRolesResp&& resp) -> decltype(auto) { return std::move(resp).get_roles(); }, std::move(promise)); return future; } folly::Future<StatusOr<bool>> MetaClient::changePassword(std::string account, std::string newPwd, std::string oldPwd) { cpp2::ChangePasswordReq req; req.set_account(std::move(account)); req.set_new_encoded_pwd(std::move(newPwd)); req.set_old_encoded_pwd(std::move(oldPwd)); folly::Promise<StatusOr<bool>> promise; auto future = promise.getFuture(); getResponse( std::move(req), [](auto client, auto request) { return client->future_changePassword(request); }, [](cpp2::ExecResp&& resp) -> bool { return resp.get_code() == nebula::cpp2::ErrorCode::SUCCEEDED; }, std::move(promise)); return future; } folly::Future<StatusOr<std::vector<cpp2::RoleItem>>> MetaClient::getUserRoles(std::string account) { cpp2::GetUserRolesReq req; req.set_account(std::move(account)); folly::Promise<StatusOr<std::vector<cpp2::RoleItem>>> promise; auto future = promise.getFuture(); getResponse( std::move(req), [](auto client, auto request) { return client->future_getUserRoles(request); }, [](cpp2::ListRolesResp&& resp) -> decltype(auto) { return std::move(resp).get_roles(); }, std::move(promise)); return future; } folly::Future<StatusOr<int64_t>> MetaClient::balance(std::vector<HostAddr> hostDel, bool isStop, bool isReset) { cpp2::BalanceReq req; if (!hostDel.empty()) { req.set_host_del(std::move(hostDel)); } if (isStop) { req.set_stop(isStop); } if (isReset) { req.set_reset(isReset); } folly::Promise<StatusOr<int64_t>> promise; auto future = promise.getFuture(); getResponse( std::move(req), [](auto client, auto request) { return client->future_balance(request); }, [](cpp2::BalanceResp&& resp) -> int64_t { return resp.get_id(); }, std::move(promise)); return future; } folly::Future<StatusOr<std::vector<cpp2::BalanceTask>>> MetaClient::showBalance(int64_t balanceId) { cpp2::BalanceReq req; req.set_id(balanceId); folly::Promise<StatusOr<std::vector<cpp2::BalanceTask>>> promise; auto future = promise.getFuture(); getResponse( std::move(req), [](auto client, auto request) { return client->future_balance(request); }, [](cpp2::BalanceResp&& resp) -> std::vector<cpp2::BalanceTask> { return resp.get_tasks(); }, std::move(promise)); return future; } folly::Future<StatusOr<bool>> MetaClient::balanceLeader() { cpp2::LeaderBalanceReq req; folly::Promise<StatusOr<bool>> promise; auto future = promise.getFuture(); getResponse( std::move(req), [](auto client, auto request) { return client->future_leaderBalance(request); }, [](cpp2::ExecResp&& resp) -> bool { return resp.get_code() == nebula::cpp2::ErrorCode::SUCCEEDED; }, std::move(promise)); return future; } folly::Future<StatusOr<std::string>> MetaClient::getTagDefaultValue(GraphSpaceID spaceId, TagID tagId, const std::string& field) { cpp2::GetReq req; static std::string defaultKey = "__default__"; req.set_segment(defaultKey); std::string key; key.reserve(64); key.append(reinterpret_cast<const char*>(&spaceId), sizeof(GraphSpaceID)); key.append(reinterpret_cast<const char*>(&tagId), sizeof(TagID)); key.append(field); req.set_key(std::move(key)); folly::Promise<StatusOr<std::string>> promise; auto future = promise.getFuture(); getResponse( std::move(req), [](auto client, auto request) { return client->future_get(request); }, [](cpp2::GetResp&& resp) -> std::string { return resp.get_value(); }, std::move(promise)); return future; } folly::Future<StatusOr<std::string>> MetaClient::getEdgeDefaultValue(GraphSpaceID spaceId, EdgeType edgeType, const std::string& field) { cpp2::GetReq req; static std::string defaultKey = "__default__"; req.set_segment(defaultKey); std::string key; key.reserve(64); key.append(reinterpret_cast<const char*>(&spaceId), sizeof(GraphSpaceID)); key.append(reinterpret_cast<const char*>(&edgeType), sizeof(EdgeType)); key.append(field); req.set_key(std::move(key)); folly::Promise<StatusOr<std::string>> promise; auto future = promise.getFuture(); getResponse( std::move(req), [](auto client, auto request) { return client->future_get(request); }, [](cpp2::GetResp&& resp) -> std::string { return resp.get_value(); }, std::move(promise)); return future; } folly::Future<StatusOr<bool>> MetaClient::regConfig(const std::vector<cpp2::ConfigItem>& items) { cpp2::RegConfigReq req; req.set_items(items); folly::Promise<StatusOr<int64_t>> promise; auto future = promise.getFuture(); getResponse( std::move(req), [](auto client, auto request) { return client->future_regConfig(request); }, [](cpp2::ExecResp&& resp) -> decltype(auto) { return resp.get_code() == nebula::cpp2::ErrorCode::SUCCEEDED; }, std::move(promise)); return future; } folly::Future<StatusOr<std::vector<cpp2::ConfigItem>>> MetaClient::getConfig( const cpp2::ConfigModule& module, const std::string& name) { if (!configReady_) { return Status::Error("Not ready!"); } cpp2::ConfigItem item; item.set_module(module); item.set_name(name); cpp2::GetConfigReq req; req.set_item(item); folly::Promise<StatusOr<std::vector<cpp2::ConfigItem>>> promise; auto future = promise.getFuture(); getResponse( std::move(req), [](auto client, auto request) { return client->future_getConfig(request); }, [](cpp2::GetConfigResp&& resp) -> decltype(auto) { return std::move(resp).get_items(); }, std::move(promise)); return future; } folly::Future<StatusOr<bool>> MetaClient::setConfig(const cpp2::ConfigModule& module, const std::string& name, const Value& value) { cpp2::ConfigItem item; item.set_module(module); item.set_name(name); item.set_value(value); cpp2::SetConfigReq req; req.set_item(item); folly::Promise<StatusOr<bool>> promise; auto future = promise.getFuture(); getResponse( std::move(req), [](auto client, auto request) { return client->future_setConfig(request); }, [](cpp2::ExecResp&& resp) -> bool { return resp.get_code() == nebula::cpp2::ErrorCode::SUCCEEDED; }, std::move(promise)); return future; } folly::Future<StatusOr<std::vector<cpp2::ConfigItem>>> MetaClient::listConfigs( const cpp2::ConfigModule& module) { cpp2::ListConfigsReq req; req.set_module(module); folly::Promise<StatusOr<std::vector<cpp2::ConfigItem>>> promise; auto future = promise.getFuture(); getResponse( std::move(req), [](auto client, auto request) { return client->future_listConfigs(request); }, [](cpp2::ListConfigsResp&& resp) -> decltype(auto) { return std::move(resp).get_items(); }, std::move(promise)); return future; } folly::Future<StatusOr<bool>> MetaClient::createSnapshot() { cpp2::CreateSnapshotReq req; folly::Promise<StatusOr<bool>> promise; auto future = promise.getFuture(); getResponse( std::move(req), [](auto client, auto request) { return client->future_createSnapshot(request); }, [](cpp2::ExecResp&& resp) -> bool { return resp.get_code() == nebula::cpp2::ErrorCode::SUCCEEDED; }, std::move(promise)); return future; } folly::Future<StatusOr<bool>> MetaClient::dropSnapshot(const std::string& name) { cpp2::DropSnapshotReq req; req.set_name(name); folly::Promise<StatusOr<bool>> promise; auto future = promise.getFuture(); getResponse( std::move(req), [](auto client, auto request) { return client->future_dropSnapshot(request); }, [](cpp2::ExecResp&& resp) -> bool { return resp.get_code() == nebula::cpp2::ErrorCode::SUCCEEDED; }, std::move(promise)); return future; } folly::Future<StatusOr<std::vector<cpp2::Snapshot>>> MetaClient::listSnapshots() { cpp2::ListSnapshotsReq req; folly::Promise<StatusOr<std::vector<cpp2::Snapshot>>> promise; auto future = promise.getFuture(); getResponse( std::move(req), [](auto client, auto request) { return client->future_listSnapshots(request); }, [](cpp2::ListSnapshotsResp&& resp) -> decltype(auto) { return std::move(resp).get_snapshots(); }, std::move(promise)); return future; } folly::Future<StatusOr<bool>> MetaClient::addListener(GraphSpaceID spaceId, cpp2::ListenerType type, std::vector<HostAddr> hosts) { cpp2::AddListenerReq req; req.set_space_id(spaceId); req.set_type(type); req.set_hosts(std::move(hosts)); folly::Promise<StatusOr<bool>> promise; auto future = promise.getFuture(); getResponse( std::move(req), [](auto client, auto request) { return client->future_addListener(request); }, [](cpp2::ExecResp&& resp) -> bool { return resp.get_code() == nebula::cpp2::ErrorCode::SUCCEEDED; }, std::move(promise)); return future; } folly::Future<StatusOr<bool>> MetaClient::removeListener(GraphSpaceID spaceId, cpp2::ListenerType type) { cpp2::RemoveListenerReq req; req.set_space_id(spaceId); req.set_type(type); folly::Promise<StatusOr<bool>> promise; auto future = promise.getFuture(); getResponse( std::move(req), [](auto client, auto request) { return client->future_removeListener(request); }, [](cpp2::ExecResp&& resp) -> bool { return resp.get_code() == nebula::cpp2::ErrorCode::SUCCEEDED; }, std::move(promise)); return future; } folly::Future<StatusOr<std::vector<cpp2::ListenerInfo>>> MetaClient::listListener( GraphSpaceID spaceId) { cpp2::ListListenerReq req; req.set_space_id(spaceId); folly::Promise<StatusOr<std::vector<cpp2::ListenerInfo>>> promise; auto future = promise.getFuture(); getResponse( std::move(req), [](auto client, auto request) { return client->future_listListener(request); }, [](cpp2::ListListenerResp&& resp) -> decltype(auto) { return std::move(resp).get_listeners(); }, std::move(promise)); return future; } bool MetaClient::registerCfg() { auto ret = regConfig(gflagsDeclared_).get(); if (ret.ok()) { LOG(INFO) << "Register gflags ok " << gflagsDeclared_.size(); configReady_ = true; } return configReady_; } StatusOr<std::vector<std::pair<PartitionID, cpp2::ListenerType>>> MetaClient::getListenersBySpaceHostFromCache(GraphSpaceID spaceId, const HostAddr& host) { if (!ready_) { return Status::Error("Not ready!"); } folly::RWSpinLock::ReadHolder holder(localCacheLock_); auto spaceIt = localCache_.find(spaceId); if (spaceIt == localCache_.end()) { VLOG(3) << "Space " << spaceId << " not found!"; return Status::SpaceNotFound(); } auto iter = spaceIt->second->listeners_.find(host); if (iter == spaceIt->second->listeners_.end()) { VLOG(3) << "Space " << spaceId << ", Listener on host " << host.toString() << " not found!"; return Status::ListenerNotFound(); } else { return iter->second; } } StatusOr<ListenersMap> MetaClient::getListenersByHostFromCache(const HostAddr& host) { if (!ready_) { return Status::Error("Not ready!"); } folly::RWSpinLock::ReadHolder holder(localCacheLock_); return doGetListenersMap(host, localCache_); } ListenersMap MetaClient::doGetListenersMap(const HostAddr& host, const LocalCache& localCache) { ListenersMap listenersMap; for (const auto& space : localCache) { auto spaceId = space.first; for (const auto& listener : space.second->listeners_) { if (host != listener.first) { continue; } for (const auto& part : listener.second) { auto partId = part.first; auto type = part.second; auto partIter = space.second->partsAlloc_.find(partId); if (partIter != space.second->partsAlloc_.end()) { auto peers = partIter->second; listenersMap[spaceId][partId].emplace_back(std::move(type), std::move(peers)); } else { FLOG_WARN("%s has listener of [%d, %d], but can't find part peers", host.toString().c_str(), spaceId, partId); } } } } return listenersMap; } StatusOr<HostAddr> MetaClient::getListenerHostsBySpacePartType(GraphSpaceID spaceId, PartitionID partId, cpp2::ListenerType type) { if (!ready_) { return Status::Error("Not ready!"); } folly::RWSpinLock::ReadHolder holder(localCacheLock_); auto spaceIt = localCache_.find(spaceId); if (spaceIt == localCache_.end()) { VLOG(3) << "Space " << spaceId << " not found!"; return Status::SpaceNotFound(); } for (const auto& host : spaceIt->second->listeners_) { for (const auto& l : host.second) { if (l.first == partId && l.second == type) { return host.first; } } } return Status::ListenerNotFound(); } StatusOr<std::vector<RemoteListenerInfo>> MetaClient::getListenerHostTypeBySpacePartType( GraphSpaceID spaceId, PartitionID partId) { if (!ready_) { return Status::Error("Not ready!"); } folly::RWSpinLock::ReadHolder holder(localCacheLock_); auto spaceIt = localCache_.find(spaceId); if (spaceIt == localCache_.end()) { VLOG(3) << "Space " << spaceId << " not found!"; return Status::SpaceNotFound(); } std::vector<RemoteListenerInfo> items; for (const auto& host : spaceIt->second->listeners_) { for (const auto& l : host.second) { if (l.first == partId) { items.emplace_back(std::make_pair(host.first, l.second)); } } } if (items.empty()) { return Status::ListenerNotFound(); } return items; } bool MetaClient::loadCfg() { if (!configReady_ && !registerCfg()) { return false; } // only load current module's config is enough auto ret = listConfigs(gflagsModule_).get(); if (ret.ok()) { // if we load config from meta server successfully, update gflags and set configReady_ auto items = ret.value(); MetaConfigMap metaConfigMap; for (auto& item : items) { std::pair<cpp2::ConfigModule, std::string> key = {item.get_module(), item.get_name()}; metaConfigMap.emplace(std::move(key), std::move(item)); } { // For any configurations that is in meta, update in cache to replace previous value folly::RWSpinLock::WriteHolder holder(configCacheLock_); for (const auto& entry : metaConfigMap) { auto& key = entry.first; auto it = metaConfigMap_.find(key); if (it == metaConfigMap_.end() || metaConfigMap[key].get_value() != it->second.get_value()) { updateGflagsValue(entry.second); metaConfigMap_[key] = entry.second; } } } } else { LOG(ERROR) << "Load configs failed: " << ret.status(); return false; } return true; } void MetaClient::updateGflagsValue(const cpp2::ConfigItem& item) { if (item.get_mode() != cpp2::ConfigMode::MUTABLE) { return; } auto value = item.get_value(); std::string curValue; if (!gflags::GetCommandLineOption(item.get_name().c_str(), &curValue)) { return; } else { auto gflagValue = GflagsManager::gflagsValueToValue(value.typeName(), curValue); if (gflagValue != value) { auto valueStr = GflagsManager::ValueToGflagString(value); if (value.isMap() && value.getMap().kvs.empty()) { // Be compatible with previous configuration valueStr = "{}"; } gflags::SetCommandLineOption(item.get_name().c_str(), valueStr.c_str()); // TODO: we simply judge the rocksdb by nested type for now if (listener_ != nullptr && value.isMap()) { updateNestedGflags(value.getMap().kvs); } LOG(INFO) << "Update config " << item.get_name() << " from " << curValue << " to " << valueStr; } } } void MetaClient::updateNestedGflags(const std::unordered_map<std::string, Value>& nameValues) { std::unordered_map<std::string, std::string> optionMap; for (const auto& value : nameValues) { optionMap.emplace(value.first, value.second.toString()); } folly::RWSpinLock::ReadHolder holder(localCacheLock_); for (const auto& spaceEntry : localCache_) { listener_->onSpaceOptionUpdated(spaceEntry.first, optionMap); } } Status MetaClient::refreshCache() { auto ret = bgThread_->addTask(&MetaClient::loadData, this).get(); return ret ? Status::OK() : Status::Error("Load data failed"); } void MetaClient::loadLeader(const std::vector<cpp2::HostItem>& hostItems, const SpaceNameIdMap& spaceIndexByName) { LeaderInfo leaderInfo; for (auto& item : hostItems) { for (auto& spaceEntry : item.get_leader_parts()) { auto spaceName = spaceEntry.first; // ready_ is still false, can't read from cache auto iter = spaceIndexByName.find(spaceName); if (iter == spaceIndexByName.end()) { continue; } auto spaceId = iter->second; for (const auto& partId : spaceEntry.second) { leaderInfo.leaderMap_[{spaceId, partId}] = item.get_hostAddr(); auto partHosts = getPartHostsFromCache(spaceId, partId); size_t leaderIndex = 0; if (partHosts.ok()) { const auto& peers = partHosts.value().hosts_; for (size_t i = 0; i < peers.size(); i++) { if (peers[i] == item.get_hostAddr()) { leaderIndex = i; break; } } } leaderInfo.pickedIndex_[{spaceId, partId}] = leaderIndex; } } LOG(INFO) << "Load leader of " << item.get_hostAddr() << " in " << item.get_leader_parts().size() << " space"; } { // todo(doodle): in worst case, storage and meta isolated, so graph may get a outdate // leader info. The problem could be solved if leader term are cached as well. LOG(INFO) << "Load leader ok"; folly::RWSpinLock::WriteHolder wh(leadersLock_); leadersInfo_ = std::move(leaderInfo); } } folly::Future<StatusOr<bool>> MetaClient::addZone(std::string zoneName, std::vector<HostAddr> nodes) { cpp2::AddZoneReq req; req.set_zone_name(std::move(zoneName)); req.set_nodes(std::move(nodes)); folly::Promise<StatusOr<bool>> promise; auto future = promise.getFuture(); getResponse( std::move(req), [](auto client, auto request) { return client->future_addZone(request); }, [](cpp2::ExecResp&& resp) -> bool { return resp.get_code() == nebula::cpp2::ErrorCode::SUCCEEDED; }, std::move(promise)); return future; } folly::Future<StatusOr<bool>> MetaClient::dropZone(std::string zoneName) { cpp2::DropZoneReq req; req.set_zone_name(std::move(zoneName)); folly::Promise<StatusOr<bool>> promise; auto future = promise.getFuture(); getResponse( std::move(req), [](auto client, auto request) { return client->future_dropZone(request); }, [](cpp2::ExecResp&& resp) -> bool { return resp.get_code() == nebula::cpp2::ErrorCode::SUCCEEDED; }, std::move(promise)); return future; } folly::Future<StatusOr<bool>> MetaClient::addHostIntoZone(HostAddr node, std::string zoneName) { cpp2::AddHostIntoZoneReq req; req.set_node(node); req.set_zone_name(zoneName); folly::Promise<StatusOr<bool>> promise; auto future = promise.getFuture(); getResponse( std::move(req), [](auto client, auto request) { return client->future_addHostIntoZone(request); }, [](cpp2::ExecResp&& resp) -> bool { return resp.get_code() == nebula::cpp2::ErrorCode::SUCCEEDED; }, std::move(promise)); return future; } folly::Future<StatusOr<bool>> MetaClient::dropHostFromZone(HostAddr node, std::string zoneName) { cpp2::DropHostFromZoneReq req; req.set_node(node); req.set_zone_name(zoneName); folly::Promise<StatusOr<bool>> promise; auto future = promise.getFuture(); getResponse( std::move(req), [](auto client, auto request) { return client->future_dropHostFromZone(request); }, [](cpp2::ExecResp&& resp) -> bool { return resp.get_code() == nebula::cpp2::ErrorCode::SUCCEEDED; }, std::move(promise)); return future; } folly::Future<StatusOr<std::vector<HostAddr>>> MetaClient::getZone(std::string zoneName) { cpp2::GetZoneReq req; req.set_zone_name(std::move(zoneName)); folly::Promise<StatusOr<std::vector<HostAddr>>> promise; auto future = promise.getFuture(); getResponse( std::move(req), [](auto client, auto request) { return client->future_getZone(request); }, [](cpp2::GetZoneResp&& resp) -> decltype(auto) { return resp.get_hosts(); }, std::move(promise)); return future; } folly::Future<StatusOr<std::vector<cpp2::Zone>>> MetaClient::listZones() { cpp2::ListZonesReq req; folly::Promise<StatusOr<std::vector<cpp2::Zone>>> promise; auto future = promise.getFuture(); getResponse( std::move(req), [](auto client, auto request) { return client->future_listZones(request); }, [](cpp2::ListZonesResp&& resp) -> decltype(auto) { return resp.get_zones(); }, std::move(promise)); return future; } folly::Future<StatusOr<bool>> MetaClient::addGroup(std::string groupName, std::vector<std::string> zoneNames) { cpp2::AddGroupReq req; req.set_group_name(std::move(groupName)); req.set_zone_names(std::move(zoneNames)); folly::Promise<StatusOr<bool>> promise; auto future = promise.getFuture(); getResponse( std::move(req), [](auto client, auto request) { return client->future_addGroup(request); }, [](cpp2::ExecResp&& resp) -> bool { return resp.get_code() == nebula::cpp2::ErrorCode::SUCCEEDED; }, std::move(promise)); return future; } folly::Future<StatusOr<bool>> MetaClient::dropGroup(std::string groupName) { cpp2::DropGroupReq req; req.set_group_name(std::move(groupName)); folly::Promise<StatusOr<bool>> promise; auto future = promise.getFuture(); getResponse( std::move(req), [](auto client, auto request) { return client->future_dropGroup(request); }, [](cpp2::ExecResp&& resp) -> bool { return resp.get_code() == nebula::cpp2::ErrorCode::SUCCEEDED; }, std::move(promise)); return future; } folly::Future<StatusOr<bool>> MetaClient::addZoneIntoGroup(std::string zoneName, std::string groupName) { cpp2::AddZoneIntoGroupReq req; req.set_zone_name(zoneName); req.set_group_name(groupName); folly::Promise<StatusOr<bool>> promise; auto future = promise.getFuture(); getResponse( std::move(req), [](auto client, auto request) { return client->future_addZoneIntoGroup(request); }, [](cpp2::ExecResp&& resp) -> bool { return resp.get_code() == nebula::cpp2::ErrorCode::SUCCEEDED; }, std::move(promise)); return future; } folly::Future<StatusOr<bool>> MetaClient::dropZoneFromGroup(std::string zoneName, std::string groupName) { cpp2::DropZoneFromGroupReq req; req.set_zone_name(zoneName); req.set_group_name(groupName); folly::Promise<StatusOr<bool>> promise; auto future = promise.getFuture(); getResponse( std::move(req), [](auto client, auto request) { return client->future_dropZoneFromGroup(request); }, [](cpp2::ExecResp&& resp) -> bool { return resp.get_code() == nebula::cpp2::ErrorCode::SUCCEEDED; }, std::move(promise)); return future; } folly::Future<StatusOr<std::vector<std::string>>> MetaClient::getGroup(std::string groupName) { cpp2::GetGroupReq req; req.set_group_name(std::move(groupName)); folly::Promise<StatusOr<std::vector<std::string>>> promise; auto future = promise.getFuture(); getResponse( std::move(req), [](auto client, auto request) { return client->future_getGroup(request); }, [](cpp2::GetGroupResp&& resp) -> decltype(auto) { return resp.get_zone_names(); }, std::move(promise)); return future; } folly::Future<StatusOr<std::vector<cpp2::Group>>> MetaClient::listGroups() { cpp2::ListGroupsReq req; folly::Promise<StatusOr<std::vector<cpp2::Group>>> promise; auto future = promise.getFuture(); getResponse( std::move(req), [](auto client, auto request) { return client->future_listGroups(request); }, [](cpp2::ListGroupsResp&& resp) -> decltype(auto) { return resp.get_groups(); }, std::move(promise)); return future; } folly::Future<StatusOr<cpp2::StatsItem>> MetaClient::getStats(GraphSpaceID spaceId) { cpp2::GetStatsReq req; req.set_space_id(spaceId); folly::Promise<StatusOr<cpp2::StatsItem>> promise; auto future = promise.getFuture(); getResponse( std::move(req), [](auto client, auto request) { return client->future_getStats(request); }, [](cpp2::GetStatsResp&& resp) -> cpp2::StatsItem { return std::move(resp).get_stats(); }, std::move(promise), true); return future; } folly::Future<StatusOr<nebula::cpp2::ErrorCode>> MetaClient::reportTaskFinish( int32_t jobId, int32_t taskId, nebula::cpp2::ErrorCode taskErrCode, cpp2::StatsItem* statisticItem) { cpp2::ReportTaskReq req; req.set_code(taskErrCode); req.set_job_id(jobId); req.set_task_id(taskId); if (statisticItem) { req.set_stats(*statisticItem); } folly::Promise<StatusOr<nebula::cpp2::ErrorCode>> pro; auto fut = pro.getFuture(); getResponse( std::move(req), [](auto client, auto request) { return client->future_reportTaskFinish(request); }, [](cpp2::ExecResp&& resp) -> nebula::cpp2::ErrorCode { return resp.get_code(); }, std::move(pro), true); return fut; } folly::Future<StatusOr<bool>> MetaClient::signInFTService( cpp2::FTServiceType type, const std::vector<cpp2::FTClient>& clients) { cpp2::SignInFTServiceReq req; req.set_type(type); req.set_clients(clients); folly::Promise<StatusOr<bool>> promise; auto future = promise.getFuture(); getResponse( std::move(req), [](auto client, auto request) { return client->future_signInFTService(request); }, [](cpp2::ExecResp&& resp) -> bool { return resp.get_code() == nebula::cpp2::ErrorCode::SUCCEEDED; }, std::move(promise), true); return future; } folly::Future<StatusOr<bool>> MetaClient::signOutFTService() { cpp2::SignOutFTServiceReq req; folly::Promise<StatusOr<bool>> promise; auto future = promise.getFuture(); getResponse( std::move(req), [](auto client, auto request) { return client->future_signOutFTService(request); }, [](cpp2::ExecResp&& resp) -> bool { return resp.get_code() == nebula::cpp2::ErrorCode::SUCCEEDED; }, std::move(promise), true); return future; } folly::Future<StatusOr<std::vector<cpp2::FTClient>>> MetaClient::listFTClients() { cpp2::ListFTClientsReq req; folly::Promise<StatusOr<std::vector<cpp2::FTClient>>> promise; auto future = promise.getFuture(); getResponse( std::move(req), [](auto client, auto request) { return client->future_listFTClients(request); }, [](cpp2::ListFTClientsResp&& resp) -> decltype(auto) { return std::move(resp).get_clients(); }, std::move(promise)); return future; } StatusOr<std::vector<cpp2::FTClient>> MetaClient::getFTClientsFromCache() { if (!ready_) { return Status::Error("Not ready!"); } return fulltextClientList_; } folly::Future<StatusOr<bool>> MetaClient::createFTIndex(const std::string& name, const cpp2::FTIndex& index) { cpp2::CreateFTIndexReq req; req.set_fulltext_index_name(name); req.set_index(index); folly::Promise<StatusOr<bool>> promise; auto future = promise.getFuture(); getResponse( std::move(req), [](auto client, auto request) { return client->future_createFTIndex(request); }, [](cpp2::ExecResp&& resp) -> bool { return resp.get_code() == nebula::cpp2::ErrorCode::SUCCEEDED; }, std::move(promise), true); return future; } folly::Future<StatusOr<bool>> MetaClient::dropFTIndex(GraphSpaceID spaceId, const std::string& name) { cpp2::DropFTIndexReq req; req.set_fulltext_index_name(name); req.set_space_id(spaceId); folly::Promise<StatusOr<bool>> promise; auto future = promise.getFuture(); getResponse( std::move(req), [](auto client, auto request) { return client->future_dropFTIndex(request); }, [](cpp2::ExecResp&& resp) -> bool { return resp.get_code() == nebula::cpp2::ErrorCode::SUCCEEDED; }, std::move(promise), true); return future; } folly::Future<StatusOr<std::unordered_map<std::string, cpp2::FTIndex>>> MetaClient::listFTIndexes() { cpp2::ListFTIndexesReq req; folly::Promise<StatusOr<std::unordered_map<std::string, cpp2::FTIndex>>> promise; auto future = promise.getFuture(); getResponse( std::move(req), [](auto client, auto request) { return client->future_listFTIndexes(request); }, [](cpp2::ListFTIndexesResp&& resp) -> decltype(auto) { return std::move(resp).get_indexes(); }, std::move(promise)); return future; } StatusOr<std::unordered_map<std::string, cpp2::FTIndex>> MetaClient::getFTIndexesFromCache() { if (!ready_) { return Status::Error("Not ready!"); } folly::RWSpinLock::ReadHolder holder(localCacheLock_); return fulltextIndexMap_; } StatusOr<std::unordered_map<std::string, cpp2::FTIndex>> MetaClient::getFTIndexBySpaceFromCache( GraphSpaceID spaceId) { if (!ready_) { return Status::Error("Not ready!"); } folly::RWSpinLock::ReadHolder holder(localCacheLock_); std::unordered_map<std::string, cpp2::FTIndex> indexes; for (auto it = fulltextIndexMap_.begin(); it != fulltextIndexMap_.end(); ++it) { if (it->second.get_space_id() == spaceId) { indexes[it->first] = it->second; } } return indexes; } StatusOr<std::pair<std::string, cpp2::FTIndex>> MetaClient::getFTIndexBySpaceSchemaFromCache( GraphSpaceID spaceId, int32_t schemaId) { if (!ready_) { return Status::Error("Not ready!"); } folly::RWSpinLock::ReadHolder holder(localCacheLock_); for (auto it = fulltextIndexMap_.begin(); it != fulltextIndexMap_.end(); ++it) { auto id = it->second.get_depend_schema().getType() == nebula::cpp2::SchemaID::Type::edge_type ? it->second.get_depend_schema().get_edge_type() : it->second.get_depend_schema().get_tag_id(); if (it->second.get_space_id() == spaceId && id == schemaId) { return std::make_pair(it->first, it->second); } } return Status::IndexNotFound(); } StatusOr<cpp2::FTIndex> MetaClient::getFTIndexByNameFromCache(GraphSpaceID spaceId, const std::string& name) { if (!ready_) { return Status::Error("Not ready!"); } folly::RWSpinLock::ReadHolder holder(localCacheLock_); if (fulltextIndexMap_.find(name) != fulltextIndexMap_.end() && fulltextIndexMap_[name].get_space_id() != spaceId) { return Status::IndexNotFound(); } return fulltextIndexMap_[name]; } folly::Future<StatusOr<cpp2::CreateSessionResp>> MetaClient::createSession( const std::string& userName, const HostAddr& graphAddr, const std::string& clientIp) { cpp2::CreateSessionReq req; req.set_user(userName); req.set_graph_addr(graphAddr); req.set_client_ip(clientIp); folly::Promise<StatusOr<cpp2::CreateSessionResp>> promise; auto future = promise.getFuture(); getResponse( std::move(req), [](auto client, auto request) { return client->future_createSession(request); }, [](cpp2::CreateSessionResp&& resp) -> decltype(auto) { return std::move(resp); }, std::move(promise), true); return future; } folly::Future<StatusOr<cpp2::UpdateSessionsResp>> MetaClient::updateSessions( const std::vector<cpp2::Session>& sessions) { cpp2::UpdateSessionsReq req; req.set_sessions(sessions); folly::Promise<StatusOr<cpp2::UpdateSessionsResp>> promise; auto future = promise.getFuture(); getResponse( std::move(req), [](auto client, auto request) { return client->future_updateSessions(request); }, [](cpp2::UpdateSessionsResp&& resp) -> decltype(auto) { return std::move(resp); }, std::move(promise), true); return future; } folly::Future<StatusOr<cpp2::ListSessionsResp>> MetaClient::listSessions() { cpp2::ListSessionsReq req; folly::Promise<StatusOr<cpp2::ListSessionsResp>> promise; auto future = promise.getFuture(); getResponse( std::move(req), [](auto client, auto request) { return client->future_listSessions(request); }, [](cpp2::ListSessionsResp&& resp) -> decltype(auto) { return std::move(resp); }, std::move(promise)); return future; } folly::Future<StatusOr<cpp2::GetSessionResp>> MetaClient::getSession(SessionID sessionId) { cpp2::GetSessionReq req; req.set_session_id(sessionId); folly::Promise<StatusOr<cpp2::GetSessionResp>> promise; auto future = promise.getFuture(); getResponse( std::move(req), [](auto client, auto request) { return client->future_getSession(request); }, [](cpp2::GetSessionResp&& resp) -> decltype(auto) { return std::move(resp); }, std::move(promise)); return future; } folly::Future<StatusOr<cpp2::ExecResp>> MetaClient::removeSession(SessionID sessionId) { cpp2::RemoveSessionReq req; req.set_session_id(sessionId); folly::Promise<StatusOr<cpp2::ExecResp>> promise; auto future = promise.getFuture(); getResponse( std::move(req), [](auto client, auto request) { return client->future_removeSession(request); }, [](cpp2::ExecResp&& resp) -> decltype(auto) { return std::move(resp); }, std::move(promise), true); return future; } folly::Future<StatusOr<cpp2::ExecResp>> MetaClient::killQuery( std::unordered_map<SessionID, std::unordered_set<ExecutionPlanID>> killQueries) { cpp2::KillQueryReq req; req.set_kill_queries(std::move(killQueries)); folly::Promise<StatusOr<cpp2::ExecResp>> promise; auto future = promise.getFuture(); getResponse( std::move(req), [](auto client, auto request) { return client->future_killQuery(request); }, [](cpp2::ExecResp&& resp) -> decltype(auto) { return std::move(resp); }, std::move(promise), true); return future; } folly::Future<StatusOr<bool>> MetaClient::download(const std::string& hdfsHost, int32_t hdfsPort, const std::string& hdfsPath, GraphSpaceID spaceId) { auto url = folly::stringPrintf("http://%s:%d/download-dispatch?host=%s&port=%d&path=%s&space=%d", leader_.host.c_str(), FLAGS_ws_meta_http_port, hdfsHost.c_str(), hdfsPort, hdfsPath.c_str(), spaceId); auto func = [url] { auto result = http::HttpClient::get(url); if (result.ok() && result.value() == "SSTFile dispatch successfully") { LOG(INFO) << "Download Successfully"; return true; } else { LOG(ERROR) << "Download Failed: " << result.value(); return false; } }; return folly::async(func); } folly::Future<StatusOr<bool>> MetaClient::ingest(GraphSpaceID spaceId) { auto url = folly::stringPrintf("http://%s:%d/ingest-dispatch?space=%d", leader_.host.c_str(), FLAGS_ws_meta_http_port, spaceId); auto func = [url] { auto result = http::HttpClient::get(url); if (result.ok() && result.value() == "SSTFile ingest successfully") { LOG(INFO) << "Ingest Successfully"; return true; } else { LOG(ERROR) << "Ingest Failed"; return false; } }; return folly::async(func); } bool MetaClient::loadSessions() { auto session_list = listSessions().get(); if (!session_list.ok()) { LOG(ERROR) << "List sessions failed, status:" << session_list.status(); return false; } SessionMap* oldSessionMap = sessionMap_.load(); SessionMap* newSessionMap = new SessionMap(*oldSessionMap); auto oldKilledPlan = killedPlans_.load(); auto newKilledPlan = new folly::F14FastSet<std::pair<SessionID, ExecutionPlanID>>(*oldKilledPlan); for (auto& session : session_list.value().get_sessions()) { (*newSessionMap)[session.get_session_id()] = session; for (auto& query : session.get_queries()) { if (query.second.get_status() == cpp2::QueryStatus::KILLING) { newKilledPlan->insert({session.get_session_id(), query.first}); } } } sessionMap_.store(newSessionMap); killedPlans_.store(newKilledPlan); folly::rcu_retire(oldKilledPlan); folly::rcu_retire(oldSessionMap); return true; } StatusOr<cpp2::Session> MetaClient::getSessionFromCache(const nebula::SessionID& session_id) { if (!ready_) { return Status::Error("Not ready!"); } folly::rcu_reader guard; auto session_map = sessionMap_.load(); auto it = session_map->find(session_id); if (it != session_map->end()) { return it->second; } return Status::SessionNotFound(); } bool MetaClient::checkIsPlanKilled(SessionID sessionId, ExecutionPlanID planId) { static thread_local int check_counter = 0; // Inaccurate in a multi-threaded environment, but it is not important check_counter = (check_counter + 1) & ((1 << FLAGS_check_plan_killed_frequency) - 1); if (check_counter != 0) { return false; } folly::rcu_reader guard; return killedPlans_.load()->count({sessionId, planId}); } } // namespace meta } // namespace nebula
36.965605
100
0.63033
[ "vector", "transform" ]
4fb38d00d35c110b35287c8ba500893706eade5c
2,643
cpp
C++
src/ttauri/GUI/keyboard_bindings.cpp
PinkFlufflyLlama/ttauri
7badcfbe792932ebb912d54d1062d8fc820c40a7
[ "BSL-1.0" ]
null
null
null
src/ttauri/GUI/keyboard_bindings.cpp
PinkFlufflyLlama/ttauri
7badcfbe792932ebb912d54d1062d8fc820c40a7
[ "BSL-1.0" ]
null
null
null
src/ttauri/GUI/keyboard_bindings.cpp
PinkFlufflyLlama/ttauri
7badcfbe792932ebb912d54d1062d8fc820c40a7
[ "BSL-1.0" ]
null
null
null
// Copyright Take Vos 2020. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at https://www.boost.org/LICENSE_1_0.txt) #include "keyboard_bindings.hpp" #include "../codec/JSON.hpp" #include "../command.hpp" #include "../logger.hpp" namespace tt { [[nodiscard]] keyboard_bindings *keyboard_bindings::subsystem_init() noexcept { auto tmp = new keyboard_bindings(); try { tmp->loadSystemBindings(); } catch (std::exception const &e) { tt_log_fatal("Could not load keyboard bindings. \"{}\"", e.what()); } return tmp; } void keyboard_bindings::subsystem_deinit() noexcept { if (auto tmp = _global.exchange(nullptr)) { delete tmp; } } void keyboard_bindings::loadBindings(URL url, bool system_binding) { ttlet data = parse_JSON(url); try { tt_parse_check(data.contains("bindings"), "Missing key 'bindings' at top level."); ttlet binding_list = data["bindings"]; tt_parse_check(binding_list.is_vector(), "Expecting array value for key 'bindings' at top level."); for (auto i = binding_list.vector_begin(); i != binding_list.vector_end(); ++i) { ttlet binding = *i; tt_parse_check(binding.is_map(), "Expecting object for a binding, got {}", binding); tt_parse_check( binding.contains("key") && binding.contains("command"), "Expecting required 'key' and 'command' for a binding, got {}", binding); ttlet key_name = static_cast<std::string>(binding["key"]); ttlet key = keyboard_key(key_name); auto command_name = static_cast<std::string>(binding["command"]); // Commands starting with '-' are ignored system-bindings. bool ignored_binding = false; if (command_name.size() >= 1 && command_name[0] == '-') { ignored_binding = true; command_name = command_name.substr(1); } auto command = to_command(command_name); if (command == command::unknown) { throw parse_error("Could not parse command '{}'", command_name); } if (ignored_binding) { addIgnoredBinding(key, command); } else if (system_binding) { addSystemBinding(key, command); } else { addUserBinding(key, command); } } } catch (std::exception const &e) { throw io_error("{}: Could not load keyboard bindings.\n{}", url, e.what()); } } } // namespace tt
32.62963
107
0.594779
[ "object" ]
4fb5380fd6f648519f2dd1307914b867a2111775
2,501
hpp
C++
boost/boost/geometry/iterators/point_reverse_iterator.hpp
tonystone/geofeatures
25aca530a9140b3f259e9ee0833c93522e83a697
[ "BSL-1.0", "Apache-2.0" ]
24
2015-08-25T05:35:37.000Z
2020-10-24T14:21:59.000Z
boost/boost/geometry/iterators/point_reverse_iterator.hpp
tonystone/geofeatures
25aca530a9140b3f259e9ee0833c93522e83a697
[ "BSL-1.0", "Apache-2.0" ]
97
2015-08-25T16:11:16.000Z
2019-03-17T00:54:32.000Z
boost/boost/geometry/iterators/point_reverse_iterator.hpp
tonystone/geofeatures
25aca530a9140b3f259e9ee0833c93522e83a697
[ "BSL-1.0", "Apache-2.0" ]
9
2015-08-26T03:11:38.000Z
2018-03-21T07:16:29.000Z
// Boost.Geometry (aka GGL, Generic Geometry Library) // Copyright (c) 2014, Oracle and/or its affiliates. // Contributed and/or modified by Menelaos Karavelas, on behalf of Oracle // Licensed under the Boost Software License version 1.0. // http://www.boost.org/users/license.html #ifndef BOOST_GEOMETRY_ITERATORS_POINT_REVERSE_ITERATOR_HPP #define BOOST_GEOMETRY_ITERATORS_POINT_REVERSE_ITERATOR_HPP #include <iterator> #include <boost/mpl/assert.hpp> #include <boost/type_traits/is_convertible.hpp> #include <boost/geometry/iterators/point_iterator.hpp> namespace geofeatures_boost {} namespace boost = geofeatures_boost; namespace geofeatures_boost { namespace geometry { // MK:: need to add doc here template <typename Geometry> class point_reverse_iterator : public std::reverse_iterator<point_iterator<Geometry> > { private: typedef std::reverse_iterator<point_iterator<Geometry> > base_type; template <typename OtherGeometry> friend class point_reverse_iterator; template <typename G> friend inline point_reverse_iterator<G> points_rbegin(G&); template <typename G> friend inline point_reverse_iterator<G> points_rend(G&); inline point_reverse_iterator(base_type const& base_it) : base_type(base_it) {} public: inline point_reverse_iterator() {} template <typename OtherGeometry> inline point_reverse_iterator(point_reverse_iterator<OtherGeometry> const& other) : base_type(other.base()) { static const bool is_conv = geofeatures_boost::is_convertible < std::reverse_iterator<point_iterator<Geometry> >, std::reverse_iterator<point_iterator<OtherGeometry> > >::value; BOOST_MPL_ASSERT_MSG((is_conv), NOT_CONVERTIBLE, (point_reverse_iterator<OtherGeometry>)); } }; // MK:: need to add doc here template <typename Geometry> inline point_reverse_iterator<Geometry> points_rbegin(Geometry& geometry) { return std::reverse_iterator < point_iterator<Geometry> >(points_end(geometry)); } // MK:: need to add doc here template <typename Geometry> inline point_reverse_iterator<Geometry> points_rend(Geometry& geometry) { return std::reverse_iterator < point_iterator<Geometry> >(points_begin(geometry)); } }} // namespace geofeatures_boost::geometry #endif // BOOST_GEOMETRY_ITERATORS_POINT_REVERSE_ITERATOR_HPP
27.788889
116
0.719712
[ "geometry" ]
4fb77b8f7cf314f6006101954daf39a30e45b4bb
29,550
cc
C++
ash/display/display_controller.cc
7kbird/chrome
f56688375530f1003e34c34f441321977c5af3c3
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
1
2019-01-16T03:57:39.000Z
2019-01-16T03:57:39.000Z
ash/display/display_controller.cc
7kbird/chrome
f56688375530f1003e34c34f441321977c5af3c3
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
1
2018-02-10T21:00:08.000Z
2018-03-20T05:09:50.000Z
ash/display/display_controller.cc
aranajhonny/chromium
caf5bcb822f79b8997720e589334266551a50a13
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
1
2020-11-04T07:23:37.000Z
2020-11-04T07:23:37.000Z
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ash/display/display_controller.h" #include <algorithm> #include <cmath> #include <map> #include "ash/ash_switches.h" #include "ash/display/cursor_window_controller.h" #include "ash/display/display_layout_store.h" #include "ash/display/display_manager.h" #include "ash/display/mirror_window_controller.h" #include "ash/display/root_window_transformers.h" #include "ash/display/virtual_keyboard_window_controller.h" #include "ash/host/ash_window_tree_host.h" #include "ash/host/ash_window_tree_host_init_params.h" #include "ash/host/root_window_transformer.h" #include "ash/root_window_controller.h" #include "ash/root_window_settings.h" #include "ash/screen_util.h" #include "ash/shell.h" #include "ash/shell_delegate.h" #include "ash/wm/coordinate_conversion.h" #include "base/command_line.h" #include "base/strings/stringprintf.h" #include "base/strings/utf_string_conversions.h" #include "ui/aura/client/capture_client.h" #include "ui/aura/client/focus_client.h" #include "ui/aura/client/screen_position_client.h" #include "ui/aura/window.h" #include "ui/aura/window_event_dispatcher.h" #include "ui/aura/window_property.h" #include "ui/aura/window_tracker.h" #include "ui/aura/window_tree_host.h" #include "ui/compositor/compositor.h" #include "ui/compositor/compositor_vsync_manager.h" #include "ui/gfx/display.h" #include "ui/gfx/screen.h" #include "ui/wm/public/activation_client.h" #if defined(OS_CHROMEOS) #include "ash/display/display_configurator_animation.h" #include "base/sys_info.h" #include "base/time/time.h" #endif // defined(OS_CHROMEOS) #if defined(USE_X11) #include "ui/base/x/x11_util.h" #include "ui/gfx/x/x11_types.h" // Including this at the bottom to avoid other // potential conflict with chrome headers. #include <X11/extensions/Xrandr.h> #undef RootWindow #endif // defined(USE_X11) namespace ash { namespace { // Primary display stored in global object as it can be // accessed after Shell is deleted. A separate display instance is created // during the shutdown instead of always keeping two display instances // (one here and another one in display_manager) in sync, which is error prone. // This is initialized in the constructor, and then in CreatePrimaryHost(). int64 primary_display_id = -1; // Specifies how long the display change should have been disabled // after each display change operations. // |kCycleDisplayThrottleTimeoutMs| is set to be longer to avoid // changing the settings while the system is still configurating // displays. It will be overriden by |kAfterDisplayChangeThrottleTimeoutMs| // when the display change happens, so the actual timeout is much shorter. const int64 kAfterDisplayChangeThrottleTimeoutMs = 500; const int64 kCycleDisplayThrottleTimeoutMs = 4000; const int64 kSwapDisplayThrottleTimeoutMs = 500; DisplayManager* GetDisplayManager() { return Shell::GetInstance()->display_manager(); } void SetDisplayPropertiesOnHost(AshWindowTreeHost* ash_host, const gfx::Display& display) { DisplayInfo info = GetDisplayManager()->GetDisplayInfo(display.id()); aura::WindowTreeHost* host = ash_host->AsWindowTreeHost(); #if defined(OS_CHROMEOS) && defined(USE_X11) // Native window property (Atom in X11) that specifies the display's // rotation, scale factor and if it's internal display. They are // read and used by touchpad/mouse driver directly on X (contact // adlr@ for more details on touchpad/mouse driver side). The value // of the rotation is one of 0 (normal), 1 (90 degrees clockwise), 2 // (180 degree) or 3 (270 degrees clockwise). The value of the // scale factor is in percent (100, 140, 200 etc). const char kRotationProp[] = "_CHROME_DISPLAY_ROTATION"; const char kScaleFactorProp[] = "_CHROME_DISPLAY_SCALE_FACTOR"; const char kInternalProp[] = "_CHROME_DISPLAY_INTERNAL"; const char kCARDINAL[] = "CARDINAL"; int xrandr_rotation = RR_Rotate_0; switch (info.rotation()) { case gfx::Display::ROTATE_0: xrandr_rotation = RR_Rotate_0; break; case gfx::Display::ROTATE_90: xrandr_rotation = RR_Rotate_90; break; case gfx::Display::ROTATE_180: xrandr_rotation = RR_Rotate_180; break; case gfx::Display::ROTATE_270: xrandr_rotation = RR_Rotate_270; break; } int internal = display.IsInternal() ? 1 : 0; gfx::AcceleratedWidget xwindow = host->GetAcceleratedWidget(); ui::SetIntProperty(xwindow, kInternalProp, kCARDINAL, internal); ui::SetIntProperty(xwindow, kRotationProp, kCARDINAL, xrandr_rotation); ui::SetIntProperty(xwindow, kScaleFactorProp, kCARDINAL, 100 * display.device_scale_factor()); #endif scoped_ptr<RootWindowTransformer> transformer( CreateRootWindowTransformerForDisplay(host->window(), display)); ash_host->SetRootWindowTransformer(transformer.Pass()); DisplayMode mode; if (GetDisplayManager()->GetSelectedModeForDisplayId(display.id(), &mode) && mode.refresh_rate > 0.0f) { host->compositor()->vsync_manager()->SetAuthoritativeVSyncInterval( base::TimeDelta::FromMicroseconds( base::Time::kMicrosecondsPerSecond / mode.refresh_rate)); } } aura::Window* GetWindow(AshWindowTreeHost* ash_host) { CHECK(ash_host->AsWindowTreeHost()); return ash_host->AsWindowTreeHost()->window(); } } // namespace // A utility class to store/restore focused/active window // when the display configuration has changed. class FocusActivationStore { public: FocusActivationStore() : activation_client_(NULL), capture_client_(NULL), focus_client_(NULL), focused_(NULL), active_(NULL) { } void Store(bool clear_focus) { if (!activation_client_) { aura::Window* root = Shell::GetPrimaryRootWindow(); activation_client_ = aura::client::GetActivationClient(root); capture_client_ = aura::client::GetCaptureClient(root); focus_client_ = aura::client::GetFocusClient(root); } focused_ = focus_client_->GetFocusedWindow(); if (focused_) tracker_.Add(focused_); active_ = activation_client_->GetActiveWindow(); if (active_ && focused_ != active_) tracker_.Add(active_); // Deactivate the window to close menu / bubble windows. if (clear_focus) activation_client_->DeactivateWindow(active_); // Release capture if any. capture_client_->SetCapture(NULL); // Clear the focused window if any. This is necessary because a // window may be deleted when losing focus (fullscreen flash for // example). If the focused window is still alive after move, it'll // be re-focused below. if (clear_focus) focus_client_->FocusWindow(NULL); } void Restore() { // Restore focused or active window if it's still alive. if (focused_ && tracker_.Contains(focused_)) { focus_client_->FocusWindow(focused_); } else if (active_ && tracker_.Contains(active_)) { activation_client_->ActivateWindow(active_); } if (focused_) tracker_.Remove(focused_); if (active_) tracker_.Remove(active_); focused_ = NULL; active_ = NULL; } private: aura::client::ActivationClient* activation_client_; aura::client::CaptureClient* capture_client_; aura::client::FocusClient* focus_client_; aura::WindowTracker tracker_; aura::Window* focused_; aura::Window* active_; DISALLOW_COPY_AND_ASSIGN(FocusActivationStore); }; //////////////////////////////////////////////////////////////////////////////// // DisplayChangeLimiter DisplayController::DisplayChangeLimiter::DisplayChangeLimiter() : throttle_timeout_(base::Time::Now()) { } void DisplayController::DisplayChangeLimiter::SetThrottleTimeout( int64 throttle_ms) { throttle_timeout_ = base::Time::Now() + base::TimeDelta::FromMilliseconds(throttle_ms); } bool DisplayController::DisplayChangeLimiter::IsThrottled() const { return base::Time::Now() < throttle_timeout_; } //////////////////////////////////////////////////////////////////////////////// // DisplayController DisplayController::DisplayController() : primary_tree_host_for_replace_(NULL), focus_activation_store_(new FocusActivationStore()), cursor_window_controller_(new CursorWindowController()), mirror_window_controller_(new MirrorWindowController()), weak_ptr_factory_(this) { #if defined(OS_CHROMEOS) if (base::SysInfo::IsRunningOnChromeOS()) limiter_.reset(new DisplayChangeLimiter); #endif // Reset primary display to make sure that tests don't use // stale display info from previous tests. primary_display_id = gfx::Display::kInvalidDisplayID; } DisplayController::~DisplayController() { } void DisplayController::Start() { // Created here so that Shell has finished being created. Adds itself // as a ShellObserver. virtual_keyboard_window_controller_.reset( new VirtualKeyboardWindowController); Shell::GetScreen()->AddObserver(this); Shell::GetInstance()->display_manager()->set_delegate(this); } void DisplayController::Shutdown() { // Unset the display manager's delegate here because // DisplayManager outlives DisplayController. Shell::GetInstance()->display_manager()->set_delegate(NULL); cursor_window_controller_.reset(); mirror_window_controller_.reset(); virtual_keyboard_window_controller_.reset(); Shell::GetScreen()->RemoveObserver(this); // Delete all root window controllers, which deletes root window // from the last so that the primary root window gets deleted last. for (WindowTreeHostMap::const_reverse_iterator it = window_tree_hosts_.rbegin(); it != window_tree_hosts_.rend(); ++it) { RootWindowController* controller = GetRootWindowController(GetWindow(it->second)); DCHECK(controller); delete controller; } } void DisplayController::CreatePrimaryHost( const AshWindowTreeHostInitParams& init_params) { const gfx::Display& primary_candidate = GetDisplayManager()->GetPrimaryDisplayCandidate(); primary_display_id = primary_candidate.id(); CHECK_NE(gfx::Display::kInvalidDisplayID, primary_display_id); AddWindowTreeHostForDisplay(primary_candidate, init_params); } void DisplayController::InitDisplays() { RootWindowController::CreateForPrimaryDisplay( window_tree_hosts_[primary_display_id]); DisplayManager* display_manager = GetDisplayManager(); for (size_t i = 0; i < display_manager->GetNumDisplays(); ++i) { const gfx::Display& display = display_manager->GetDisplayAt(i); if (primary_display_id != display.id()) { AshWindowTreeHost* ash_host = AddWindowTreeHostForDisplay( display, AshWindowTreeHostInitParams()); RootWindowController::CreateForSecondaryDisplay(ash_host); } } UpdateHostWindowNames(); FOR_EACH_OBSERVER(Observer, observers_, OnDisplaysInitialized()); } void DisplayController::AddObserver(Observer* observer) { observers_.AddObserver(observer); } void DisplayController::RemoveObserver(Observer* observer) { observers_.RemoveObserver(observer); } // static int64 DisplayController::GetPrimaryDisplayId() { CHECK_NE(gfx::Display::kInvalidDisplayID, primary_display_id); return primary_display_id; } aura::Window* DisplayController::GetPrimaryRootWindow() { return GetRootWindowForDisplayId(primary_display_id); } aura::Window* DisplayController::GetRootWindowForDisplayId(int64 id) { DCHECK_EQ(1u, window_tree_hosts_.count(id)); AshWindowTreeHost* host = window_tree_hosts_[id]; CHECK(host); return GetWindow(host); } void DisplayController::CloseChildWindows() { for (WindowTreeHostMap::const_iterator it = window_tree_hosts_.begin(); it != window_tree_hosts_.end(); ++it) { aura::Window* root_window = GetWindow(it->second); RootWindowController* controller = GetRootWindowController(root_window); if (controller) { controller->CloseChildWindows(); } else { while (!root_window->children().empty()) { aura::Window* child = root_window->children()[0]; delete child; } } } } aura::Window::Windows DisplayController::GetAllRootWindows() { aura::Window::Windows windows; for (WindowTreeHostMap::const_iterator it = window_tree_hosts_.begin(); it != window_tree_hosts_.end(); ++it) { DCHECK(it->second); if (GetRootWindowController(GetWindow(it->second))) windows.push_back(GetWindow(it->second)); } return windows; } gfx::Insets DisplayController::GetOverscanInsets(int64 display_id) const { return GetDisplayManager()->GetOverscanInsets(display_id); } void DisplayController::SetOverscanInsets(int64 display_id, const gfx::Insets& insets_in_dip) { GetDisplayManager()->SetOverscanInsets(display_id, insets_in_dip); } std::vector<RootWindowController*> DisplayController::GetAllRootWindowControllers() { std::vector<RootWindowController*> controllers; for (WindowTreeHostMap::const_iterator it = window_tree_hosts_.begin(); it != window_tree_hosts_.end(); ++it) { RootWindowController* controller = GetRootWindowController(GetWindow(it->second)); if (controller) controllers.push_back(controller); } return controllers; } void DisplayController::ToggleMirrorMode() { DisplayManager* display_manager = GetDisplayManager(); if (display_manager->num_connected_displays() <= 1) return; if (limiter_) { if (limiter_->IsThrottled()) return; limiter_->SetThrottleTimeout(kCycleDisplayThrottleTimeoutMs); } #if defined(OS_CHROMEOS) Shell* shell = Shell::GetInstance(); DisplayConfiguratorAnimation* animation = shell->display_configurator_animation(); animation->StartFadeOutAnimation( base::Bind(&DisplayController::SetMirrorModeAfterAnimation, weak_ptr_factory_.GetWeakPtr(), !display_manager->IsMirrored())); #endif } void DisplayController::SwapPrimaryDisplay() { if (limiter_) { if (limiter_->IsThrottled()) return; limiter_->SetThrottleTimeout(kSwapDisplayThrottleTimeoutMs); } if (Shell::GetScreen()->GetNumDisplays() > 1) { #if defined(OS_CHROMEOS) DisplayConfiguratorAnimation* animation = Shell::GetInstance()->display_configurator_animation(); if (animation) { animation->StartFadeOutAnimation(base::Bind( &DisplayController::OnFadeOutForSwapDisplayFinished, weak_ptr_factory_.GetWeakPtr())); } else { SetPrimaryDisplay(ScreenUtil::GetSecondaryDisplay()); } #else SetPrimaryDisplay(ScreenUtil::GetSecondaryDisplay()); #endif } } void DisplayController::SetPrimaryDisplayId(int64 id) { DCHECK_NE(gfx::Display::kInvalidDisplayID, id); if (id == gfx::Display::kInvalidDisplayID || primary_display_id == id) return; const gfx::Display& display = GetDisplayManager()->GetDisplayForId(id); if (display.is_valid()) SetPrimaryDisplay(display); } void DisplayController::SetPrimaryDisplay( const gfx::Display& new_primary_display) { DisplayManager* display_manager = GetDisplayManager(); DCHECK(new_primary_display.is_valid()); DCHECK(display_manager->IsActiveDisplay(new_primary_display)); if (!new_primary_display.is_valid() || !display_manager->IsActiveDisplay(new_primary_display)) { LOG(ERROR) << "Invalid or non-existent display is requested:" << new_primary_display.ToString(); return; } if (primary_display_id == new_primary_display.id() || window_tree_hosts_.size() < 2) { return; } AshWindowTreeHost* non_primary_host = window_tree_hosts_[new_primary_display.id()]; LOG_IF(ERROR, !non_primary_host) << "Unknown display is requested in SetPrimaryDisplay: id=" << new_primary_display.id(); if (!non_primary_host) return; gfx::Display old_primary_display = Shell::GetScreen()->GetPrimaryDisplay(); // Swap root windows between current and new primary display. AshWindowTreeHost* primary_host = window_tree_hosts_[primary_display_id]; CHECK(primary_host); CHECK_NE(primary_host, non_primary_host); window_tree_hosts_[new_primary_display.id()] = primary_host; GetRootWindowSettings(GetWindow(primary_host))->display_id = new_primary_display.id(); window_tree_hosts_[old_primary_display.id()] = non_primary_host; GetRootWindowSettings(GetWindow(non_primary_host))->display_id = old_primary_display.id(); primary_display_id = new_primary_display.id(); GetDisplayManager()->layout_store()->UpdatePrimaryDisplayId( display_manager->GetCurrentDisplayIdPair(), primary_display_id); UpdateWorkAreaOfDisplayNearestWindow(GetWindow(primary_host), old_primary_display.GetWorkAreaInsets()); UpdateWorkAreaOfDisplayNearestWindow(GetWindow(non_primary_host), new_primary_display.GetWorkAreaInsets()); // Update the dispay manager with new display info. std::vector<DisplayInfo> display_info_list; display_info_list.push_back(display_manager->GetDisplayInfo( primary_display_id)); display_info_list.push_back(display_manager->GetDisplayInfo( ScreenUtil::GetSecondaryDisplay().id())); GetDisplayManager()->set_force_bounds_changed(true); GetDisplayManager()->UpdateDisplays(display_info_list); GetDisplayManager()->set_force_bounds_changed(false); } void DisplayController::EnsurePointerInDisplays() { // If the mouse is currently on a display in native location, // use the same native location. Otherwise find the display closest // to the current cursor location in screen coordinates. gfx::Point point_in_screen = Shell::GetScreen()->GetCursorScreenPoint(); gfx::Point target_location_in_native; int64 closest_distance_squared = -1; DisplayManager* display_manager = GetDisplayManager(); aura::Window* dst_root_window = NULL; for (size_t i = 0; i < display_manager->GetNumDisplays(); ++i) { const gfx::Display& display = display_manager->GetDisplayAt(i); const DisplayInfo display_info = display_manager->GetDisplayInfo(display.id()); aura::Window* root_window = GetRootWindowForDisplayId(display.id()); if (display_info.bounds_in_native().Contains( cursor_location_in_native_coords_for_restore_)) { dst_root_window = root_window; target_location_in_native = cursor_location_in_native_coords_for_restore_; break; } gfx::Point center = display.bounds().CenterPoint(); // Use the distance squared from the center of the dislay. This is not // exactly "closest" display, but good enough to pick one // appropriate (and there are at most two displays). // We don't care about actual distance, only relative to other displays, so // using the LengthSquared() is cheaper than Length(). int64 distance_squared = (center - point_in_screen).LengthSquared(); if (closest_distance_squared < 0 || closest_distance_squared > distance_squared) { aura::Window* root_window = GetRootWindowForDisplayId(display.id()); aura::client::ScreenPositionClient* client = aura::client::GetScreenPositionClient(root_window); client->ConvertPointFromScreen(root_window, &center); root_window->GetHost()->ConvertPointToNativeScreen(&center); dst_root_window = root_window; target_location_in_native = center; closest_distance_squared = distance_squared; } } dst_root_window->GetHost()->ConvertPointFromNativeScreen( &target_location_in_native); dst_root_window->MoveCursorTo(target_location_in_native); } bool DisplayController::UpdateWorkAreaOfDisplayNearestWindow( const aura::Window* window, const gfx::Insets& insets) { const aura::Window* root_window = window->GetRootWindow(); int64 id = GetRootWindowSettings(root_window)->display_id; // if id is |kInvaildDisplayID|, it's being deleted. DCHECK(id != gfx::Display::kInvalidDisplayID); return GetDisplayManager()->UpdateWorkAreaOfDisplay(id, insets); } void DisplayController::OnDisplayAdded(const gfx::Display& display) { if (primary_tree_host_for_replace_) { DCHECK(window_tree_hosts_.empty()); primary_display_id = display.id(); window_tree_hosts_[display.id()] = primary_tree_host_for_replace_; GetRootWindowSettings(GetWindow(primary_tree_host_for_replace_)) ->display_id = display.id(); primary_tree_host_for_replace_ = NULL; const DisplayInfo& display_info = GetDisplayManager()->GetDisplayInfo(display.id()); AshWindowTreeHost* ash_host = window_tree_hosts_[display.id()]; ash_host->AsWindowTreeHost()->SetBounds(display_info.bounds_in_native()); SetDisplayPropertiesOnHost(ash_host, display); } else { if (primary_display_id == gfx::Display::kInvalidDisplayID) primary_display_id = display.id(); DCHECK(!window_tree_hosts_.empty()); AshWindowTreeHost* ash_host = AddWindowTreeHostForDisplay( display, AshWindowTreeHostInitParams()); RootWindowController::CreateForSecondaryDisplay(ash_host); } } void DisplayController::OnDisplayRemoved(const gfx::Display& display) { AshWindowTreeHost* host_to_delete = window_tree_hosts_[display.id()]; CHECK(host_to_delete) << display.ToString(); // Display for root window will be deleted when the Primary RootWindow // is deleted by the Shell. window_tree_hosts_.erase(display.id()); // When the primary root window's display is removed, move the primary // root to the other display. if (primary_display_id == display.id()) { // Temporarily store the primary root window in // |primary_root_window_for_replace_| when replacing the display. if (window_tree_hosts_.size() == 0) { primary_display_id = gfx::Display::kInvalidDisplayID; primary_tree_host_for_replace_ = host_to_delete; return; } DCHECK_EQ(1U, window_tree_hosts_.size()); primary_display_id = ScreenUtil::GetSecondaryDisplay().id(); AshWindowTreeHost* primary_host = host_to_delete; // Delete the other host instead. host_to_delete = window_tree_hosts_[primary_display_id]; GetRootWindowSettings(GetWindow(host_to_delete))->display_id = display.id(); // Setup primary root. window_tree_hosts_[primary_display_id] = primary_host; GetRootWindowSettings(GetWindow(primary_host))->display_id = primary_display_id; OnDisplayMetricsChanged( GetDisplayManager()->GetDisplayForId(primary_display_id), DISPLAY_METRIC_BOUNDS); } RootWindowController* controller = GetRootWindowController(GetWindow(host_to_delete)); DCHECK(controller); controller->MoveWindowsTo(GetPrimaryRootWindow()); // Delete most of root window related objects, but don't delete // root window itself yet because the stack may be using it. controller->Shutdown(); base::MessageLoop::current()->DeleteSoon(FROM_HERE, controller); } void DisplayController::OnDisplayMetricsChanged(const gfx::Display& display, uint32_t metrics) { if (!(metrics & (DISPLAY_METRIC_BOUNDS | DISPLAY_METRIC_ROTATION | DISPLAY_METRIC_DEVICE_SCALE_FACTOR))) return; const DisplayInfo& display_info = GetDisplayManager()->GetDisplayInfo(display.id()); DCHECK(!display_info.bounds_in_native().IsEmpty()); AshWindowTreeHost* ash_host = window_tree_hosts_[display.id()]; ash_host->AsWindowTreeHost()->SetBounds(display_info.bounds_in_native()); SetDisplayPropertiesOnHost(ash_host, display); } void DisplayController::OnHostResized(const aura::WindowTreeHost* host) { gfx::Display display = Shell::GetScreen()->GetDisplayNearestWindow( const_cast<aura::Window*>(host->window())); DisplayManager* display_manager = GetDisplayManager(); if (display_manager->UpdateDisplayBounds(display.id(), host->GetBounds())) { mirror_window_controller_->UpdateWindow(); cursor_window_controller_->UpdateContainer(); } } void DisplayController::CreateOrUpdateNonDesktopDisplay( const DisplayInfo& info) { switch (GetDisplayManager()->second_display_mode()) { case DisplayManager::MIRRORING: mirror_window_controller_->UpdateWindow(info); cursor_window_controller_->UpdateContainer(); virtual_keyboard_window_controller_->Close(); break; case DisplayManager::VIRTUAL_KEYBOARD: mirror_window_controller_->Close(); cursor_window_controller_->UpdateContainer(); virtual_keyboard_window_controller_->UpdateWindow(info); break; case DisplayManager::EXTENDED: NOTREACHED(); } } void DisplayController::CloseNonDesktopDisplay() { mirror_window_controller_->Close(); cursor_window_controller_->UpdateContainer(); virtual_keyboard_window_controller_->Close(); } void DisplayController::PreDisplayConfigurationChange(bool clear_focus) { FOR_EACH_OBSERVER(Observer, observers_, OnDisplayConfigurationChanging()); focus_activation_store_->Store(clear_focus); gfx::Screen* screen = Shell::GetScreen(); gfx::Point point_in_screen = screen->GetCursorScreenPoint(); gfx::Display display = screen->GetDisplayNearestPoint(point_in_screen); aura::Window* root_window = GetRootWindowForDisplayId(display.id()); aura::client::ScreenPositionClient* client = aura::client::GetScreenPositionClient(root_window); client->ConvertPointFromScreen(root_window, &point_in_screen); root_window->GetHost()->ConvertPointToNativeScreen(&point_in_screen); cursor_location_in_native_coords_for_restore_ = point_in_screen; } void DisplayController::PostDisplayConfigurationChange() { if (limiter_) limiter_->SetThrottleTimeout(kAfterDisplayChangeThrottleTimeoutMs); focus_activation_store_->Restore(); DisplayManager* display_manager = GetDisplayManager(); DisplayLayoutStore* layout_store = display_manager->layout_store(); if (display_manager->num_connected_displays() > 1) { DisplayIdPair pair = display_manager->GetCurrentDisplayIdPair(); layout_store->UpdateMirrorStatus(pair, display_manager->IsMirrored()); DisplayLayout layout = layout_store->GetRegisteredDisplayLayout(pair); if (Shell::GetScreen()->GetNumDisplays() > 1 ) { int64 primary_id = layout.primary_id; SetPrimaryDisplayId( primary_id == gfx::Display::kInvalidDisplayID ? pair.first : primary_id); // Update the primary_id in case the above call is // ignored. Happens when a) default layout's primary id // doesn't exist, or b) the primary_id has already been // set to the same and didn't update it. layout_store->UpdatePrimaryDisplayId( pair, Shell::GetScreen()->GetPrimaryDisplay().id()); } } FOR_EACH_OBSERVER(Observer, observers_, OnDisplayConfigurationChanged()); UpdateHostWindowNames(); EnsurePointerInDisplays(); } AshWindowTreeHost* DisplayController::AddWindowTreeHostForDisplay( const gfx::Display& display, const AshWindowTreeHostInitParams& init_params) { static int host_count = 0; const DisplayInfo& display_info = GetDisplayManager()->GetDisplayInfo(display.id()); AshWindowTreeHostInitParams params_with_bounds(init_params); params_with_bounds.initial_bounds = display_info.bounds_in_native(); AshWindowTreeHost* ash_host = AshWindowTreeHost::Create(params_with_bounds); aura::WindowTreeHost* host = ash_host->AsWindowTreeHost(); host->window()->SetName(base::StringPrintf("RootWindow-%d", host_count++)); host->window()->SetTitle(base::UTF8ToUTF16(display_info.name())); host->compositor()->SetBackgroundColor(SK_ColorBLACK); // No need to remove our observer observer because the DisplayController // outlives the host. host->AddObserver(this); InitRootWindowSettings(host->window())->display_id = display.id(); host->InitHost(); window_tree_hosts_[display.id()] = ash_host; SetDisplayPropertiesOnHost(ash_host, display); #if defined(OS_CHROMEOS) static bool force_constrain_pointer_to_root = CommandLine::ForCurrentProcess()->HasSwitch( switches::kAshConstrainPointerToRoot); if (base::SysInfo::IsRunningOnChromeOS() || force_constrain_pointer_to_root) ash_host->ConfineCursorToRootWindow(); #endif return ash_host; } void DisplayController::OnFadeOutForSwapDisplayFinished() { #if defined(OS_CHROMEOS) SetPrimaryDisplay(ScreenUtil::GetSecondaryDisplay()); Shell::GetInstance()->display_configurator_animation() ->StartFadeInAnimation(); #endif } void DisplayController::SetMirrorModeAfterAnimation(bool mirror) { GetDisplayManager()->SetMirrorMode(mirror); } void DisplayController::UpdateHostWindowNames() { #if defined(USE_X11) // crbug.com/120229 - set the window title for the primary dislpay // to "aura_root_0" so gtalk can find the primary root window to broadcast. // TODO(jhorwich) Remove this once Chrome supports window-based broadcasting. aura::Window* primary = Shell::GetPrimaryRootWindow(); aura::Window::Windows root_windows = Shell::GetAllRootWindows(); for (size_t i = 0; i < root_windows.size(); ++i) { std::string name = root_windows[i] == primary ? "aura_root_0" : "aura_root_x"; gfx::AcceleratedWidget xwindow = root_windows[i]->GetHost()->GetAcceleratedWidget(); XStoreName(gfx::GetXDisplay(), xwindow, name.c_str()); } #endif } } // namespace ash
37.643312
80
0.735533
[ "object", "vector" ]
4fba5931e0e5d6338b337ee2666dd27e6d0f7e3e
4,725
cc
C++
modules/perception/lib/config_manager/config_manager_test.cc
zhuyawen/apollo
91c1811970edf0a43f2b4c3b6070c171e11e646d
[ "Apache-2.0" ]
2
2018-01-13T12:53:27.000Z
2019-04-19T09:24:01.000Z
modules/perception/lib/config_manager/config_manager_test.cc
zhuyawen/apollo
91c1811970edf0a43f2b4c3b6070c171e11e646d
[ "Apache-2.0" ]
9
2019-12-07T07:26:32.000Z
2022-02-10T18:26:18.000Z
modules/perception/lib/config_manager/config_manager_test.cc
zhuyawen/apollo
91c1811970edf0a43f2b4c3b6070c171e11e646d
[ "Apache-2.0" ]
8
2018-02-16T10:42:46.000Z
2019-08-15T09:18:17.000Z
/****************************************************************************** * Copyright 2017 The Apollo 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 "modules/perception/lib/config_manager/config_manager.h" #include <string> #include <vector> #include "gtest/gtest.h" #include "modules/perception/common/perception_gflags.h" namespace apollo { namespace perception { class ConfigManagerTest : public testing::Test { protected: ConfigManagerTest() : config_manager_(NULL) {} virtual ~ConfigManagerTest() {} virtual void SetUp() { FLAGS_work_root = "modules/perception/data"; FLAGS_config_manager_path = "./config_manager_test/config_manager.config"; config_manager_ = ConfigManager::instance(); } protected: ConfigManager* config_manager_; }; TEST_F(ConfigManagerTest, test_Init) { EXPECT_TRUE(config_manager_->Init()); EXPECT_EQ(config_manager_->NumModels(), 3u); } TEST_F(ConfigManagerTest, test_Reset) { EXPECT_TRUE(config_manager_->Reset()); std::string wrong_root = "wrong_root"; config_manager_->SetWorkRoot(wrong_root); EXPECT_FALSE(config_manager_->Reset()); config_manager_->SetWorkRoot(FLAGS_work_root); } TEST_F(ConfigManagerTest, test_GetModelConfig) { std::string model_name = "ROIFilterTest"; const ModelConfig* model_config = NULL; EXPECT_TRUE(config_manager_->GetModelConfig(model_name, &model_config)); ASSERT_TRUE(model_config != NULL); EXPECT_EQ(model_config->name(), model_name); // not exist model. model_config = NULL; EXPECT_FALSE(config_manager_->GetModelConfig("noexist", &model_config)); EXPECT_TRUE(model_config == NULL); } TEST_F(ConfigManagerTest, test_ModelConfig) { std::string model_name = "ROIFilterTest"; ASSERT_TRUE(config_manager_->Init()); ASSERT_EQ(config_manager_->NumModels(), 3u); const ModelConfig* model_config = NULL; ASSERT_TRUE(config_manager_->GetModelConfig(model_name, &model_config)); ASSERT_EQ(model_config->name(), model_name); // Check ROIFilterTest param map. int int_value = 0; EXPECT_TRUE(model_config->GetValue("threshold1", &int_value)); EXPECT_EQ(int_value, 1); EXPECT_TRUE(model_config->GetValue("threshold2", &int_value)); EXPECT_EQ(int_value, 2); std::string str_value; EXPECT_TRUE(model_config->GetValue("threshold3", &str_value)); EXPECT_EQ(str_value, "str3"); double double_value; EXPECT_TRUE(model_config->GetValue("threshold4", &double_value)); EXPECT_EQ(double_value, 4.0); float float_value; EXPECT_TRUE(model_config->GetValue("threshold5", &float_value)); EXPECT_EQ(float_value, 5.0); bool bool_value = false; EXPECT_TRUE(model_config->GetValue("bool_value_true", &bool_value)); EXPECT_EQ(bool_value, true); EXPECT_TRUE(model_config->GetValue("bool_value_false", &bool_value)); EXPECT_EQ(bool_value, false); std::vector<int> int_list; EXPECT_TRUE(model_config->GetValue("array_p1", &int_list)); EXPECT_EQ(int_list.size(), 3u); EXPECT_EQ(int_list[2], 3); std::vector<std::string> str_list; EXPECT_TRUE(model_config->GetValue("array_p2", &str_list)); EXPECT_EQ(str_list.size(), 4u); EXPECT_EQ(str_list[2], "str3"); std::vector<double> double_list; EXPECT_TRUE(model_config->GetValue("array_p4", &double_list)); EXPECT_EQ(double_list.size(), 4u); EXPECT_EQ(double_list[2], 1.3); std::vector<float> float_list; EXPECT_TRUE(model_config->GetValue("array_float", &float_list)); EXPECT_EQ(float_list.size(), 4u); EXPECT_FLOAT_EQ(float_list[2], 2.3); std::vector<bool> bool_list; EXPECT_TRUE(model_config->GetValue("array_bool", &bool_list)); EXPECT_EQ(bool_list.size(), 4u); EXPECT_EQ(bool_list[2], true); // not exist EXPECT_FALSE(model_config->GetValue("array_p3", &double_list)); EXPECT_FALSE(model_config->GetValue("array_p3", &int_list)); EXPECT_FALSE(model_config->GetValue("array_p1", &str_list)); EXPECT_FALSE(model_config->GetValue("array_p3", &double_value)); EXPECT_FALSE(model_config->GetValue("array_p3", &int_value)); EXPECT_FALSE(model_config->GetValue("array_p3", &str_value)); } } // namespace perception } // namespace apollo
34.489051
79
0.72381
[ "vector", "model" ]
4fbbe16e81785768824914d9279abe57830ebacf
1,517
hpp
C++
proton-c/bindings/cpp/include/proton/function.hpp
jdanekrh/qpid-proton-fuzz
1ff7171e006eba3f66bc7811a2c0ef56f1ed6978
[ "Apache-2.0" ]
null
null
null
proton-c/bindings/cpp/include/proton/function.hpp
jdanekrh/qpid-proton-fuzz
1ff7171e006eba3f66bc7811a2c0ef56f1ed6978
[ "Apache-2.0" ]
null
null
null
proton-c/bindings/cpp/include/proton/function.hpp
jdanekrh/qpid-proton-fuzz
1ff7171e006eba3f66bc7811a2c0ef56f1ed6978
[ "Apache-2.0" ]
null
null
null
#ifndef PROTON_FUNCTION_HPP #define PROTON_FUNCTION_HPP /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ namespace proton { /// A C++03 compatible void no-argument callback function object, used by /// container::schedule() and event_loop::inject() /// In C++11 you can use std::bind, std::function or a void-no-argument lambda instead. /// /// void_function0 is passed by reference, so instances of sub-classes do not /// have to be heap allocated. Once passed, the instance must not be deleted until /// its operator() is called or the container has stopped. /// class void_function0 { public: virtual ~void_function0() {} /// Override the call operator with your code. virtual void operator()() = 0; }; } #endif // PROTON_FUNCTION_HPP
35.27907
87
0.736981
[ "object" ]
4fbd633fcb2cf8331b9d1f35d51fca6dd754b959
3,857
cpp
C++
source/data_model/hdf5/src/dataspace.cpp
computationalgeography/lue
71993169bae67a9863d7bd7646d207405dc6f767
[ "MIT" ]
2
2021-02-26T22:45:56.000Z
2021-05-02T10:28:48.000Z
source/data_model/hdf5/src/dataspace.cpp
pcraster/lue
e64c18f78a8b6d8a602b7578a2572e9740969202
[ "MIT" ]
262
2016-08-11T10:12:02.000Z
2020-10-13T18:09:16.000Z
source/data_model/hdf5/src/dataspace.cpp
computationalgeography/lue
71993169bae67a9863d7bd7646d207405dc6f767
[ "MIT" ]
1
2020-03-11T09:49:41.000Z
2020-03-11T09:49:41.000Z
#include "lue/hdf5/dataspace.hpp" #include <cassert> #include <cstring> #include <memory> #include <stdexcept> namespace lue { namespace hdf5 { /*! @brief Construct an instance of a particular @a type @param type Dataspace type @exception std::runtime_error In case the dataspace cannot be created @sa [H5Screate](https://support.hdfgroup.org/HDF5/doc/RM/RM_H5S.html#Dataspace-Create) */ Dataspace::Dataspace( ::H5S_class_t const type): Dataspace{::H5Screate(type)} { } /*! @brief Create an instance based on a dataspace identifier @param id Identifier of created dataspace @exception std::runtime_error In case the @a id is not valid */ Dataspace::Dataspace( ::hid_t const id): Dataspace{Identifier{id, ::H5Sclose}} { } /*! @brief Create an instance based on a dataspace identifier @param id Identifier of created dataspace @exception std::runtime_error In case the @a id is not valid */ Dataspace::Dataspace( Identifier&& id): _id{std::move(id)} { if(!_id.is_valid()) { throw std::runtime_error("Dataspace is not valid"); } assert(_id.type() == H5I_DATASPACE); } /*! @brief Return the identifier */ Identifier const& Dataspace::id() const { return _id; } /*! @brief Return the number of dimensions @exception std::runtime_error In case the number of dimensions cannot be determined */ int Dataspace::nr_dimensions() const { int const nr_dimensions{::H5Sget_simple_extent_ndims(_id)}; if(nr_dimensions < 0) { throw std::runtime_error("Cannot determine number of dataspace dimensions"); } return nr_dimensions; } /*! @brief Return the dimension extents @exception std::runtime_error In case the dimension extents cannot be determined */ Shape Dataspace::dimension_extents() const { int const nr_dimensions{this->nr_dimensions()}; static_assert(std::is_same_v<Shape::value_type, ::hsize_t>); Shape extents(nr_dimensions); ::hsize_t* max_extents = nullptr; int const nr_dimensions2{::H5Sget_simple_extent_dims(_id, extents.data(), max_extents)}; if(nr_dimensions2 < 0) { throw std::runtime_error("Cannot retrieve dataspace extents"); } assert(nr_dimensions2 == nr_dimensions); return extents; } ::hssize_t Dataspace::nr_elements() const { return ::H5Sget_simple_extent_npoints(_id); } /*! @brief Create a new simple dataspace instance @param dimension_sizes Size of each dimension. This value will also be used as the upper limit on the size of each dimension @sa create_dataspace(Shape const&, Shape const&) */ Dataspace create_dataspace( Shape const& dimension_sizes) { return create_dataspace(dimension_sizes, dimension_sizes); } /*! @brief Create a new simple dataspace instance @param dimension_sizes Size of each dimension @param max_dimension_sizes Upper limit on the size of each dimension @exception std::runtime_error In case the dataspace cannot be created @sa [H5Screate_simple](https://support.hdfgroup.org/HDF5/doc/RM/RM_H5S.html#Dataspace-CreateSimple) */ Dataspace create_dataspace( Shape const& dimension_sizes, Shape const& max_dimension_sizes) { assert(dimension_sizes.size() == max_dimension_sizes.size()); Identifier dataspace_location(::H5Screate_simple(static_cast<int>( dimension_sizes.size()), dimension_sizes.data(), max_dimension_sizes.data()), H5Sclose); if(!dataspace_location.is_valid()) { throw std::runtime_error("Dataspace cannot be created"); } return Dataspace{std::move(dataspace_location)}; } } // namespace hdf5 } // namespace lue
24.411392
111
0.67721
[ "shape" ]
4fc0555b2492d0f6e1f9a9a207a545e771a365ad
2,138
cxx
C++
test/capi/capi_functions.cxx
shreyasvj25/turicreate
32e84ca16aef8d04aff3d49ae9984bd49326bffd
[ "BSD-3-Clause" ]
1
2018-12-15T20:03:51.000Z
2018-12-15T20:03:51.000Z
test/capi/capi_functions.cxx
shreyasvj25/turicreate
32e84ca16aef8d04aff3d49ae9984bd49326bffd
[ "BSD-3-Clause" ]
2
2022-01-13T04:03:55.000Z
2022-03-12T01:02:31.000Z
test/capi/capi_functions.cxx
ZeroInfinite/turicreate
dd210c2563930881abd51fd69cb73007955b33fd
[ "BSD-3-Clause" ]
1
2019-06-01T18:49:28.000Z
2019-06-01T18:49:28.000Z
/* Copyright © 2018 Apple Inc. All rights reserved. * * Use of this source code is governed by a BSD-3-clause license that can * be found in the LICENSE.txt file or at https://opensource.org/licenses/BSD-3-Clause */ #define BOOST_TEST_MODULE capi_functions #include <vector> #include <boost/test/unit_test.hpp> #include <capi/TuriCreate.h> #include <util/test_macros.hpp> #include "capi_utils.hpp" BOOST_AUTO_TEST_CASE(test_function_call) { tc_error* error = nullptr; CAPI_CHECK_ERROR(error); // Create raw inputs to the manhattan distance function. double arr_x[] = { 1.0, 2.0 }; double arr_y[] = { 5.0, 5.0 }; tc_flexible_type* ft_x = tc_ft_create_from_double_array(arr_x, 2, &error); CAPI_CHECK_ERROR(error); tc_flexible_type* ft_y = tc_ft_create_from_double_array(arr_y, 2, &error); CAPI_CHECK_ERROR(error); // Package the inputs into a tc_parameters. tc_parameters* arguments = tc_parameters_create_empty(&error); CAPI_CHECK_ERROR(error); tc_parameters_add_flexible_type(arguments, "x", ft_x, &error); CAPI_CHECK_ERROR(error); tc_parameters_add_flexible_type(arguments, "y", ft_y, &error); CAPI_CHECK_ERROR(error); // Invoke the function by name. tc_variant* result = tc_function_call("_distances.manhattan", arguments, &error); if(error == nullptr) { // The function isn't found -- it was part of the API that wasn't registered CAPI_CHECK_ERROR(error); TS_ASSERT(tc_variant_is_double(result)); // Verify the result. double double_result = tc_variant_double(result, &error); CAPI_CHECK_ERROR(error); TS_ASSERT(double_result == 7.0); // Cleanup. tc_release(result); } tc_release(arguments); tc_release(ft_x); tc_release(ft_y); } BOOST_AUTO_TEST_CASE(test_function_call_with_bad_name) { tc_error* error = nullptr; CAPI_CHECK_ERROR(error); tc_parameters* arguments = tc_parameters_create_empty(&error); CAPI_CHECK_ERROR(error); tc_variant* result = tc_function_call("b0gus 5unct10n nam3", arguments, &error); TS_ASSERT(error != nullptr); TS_ASSERT(result == nullptr); tc_release(error); tc_release(arguments); }
27.766234
86
0.734799
[ "vector" ]
4fc1743063b589b23cc7c194d7c3107334897de6
14,121
cpp
C++
src/renderer/renderer_volpt.cpp
Luvideria/lightmetrica-v3
3e83db59998e79648047bac29c37d8eb18d7600d
[ "MIT" ]
101
2019-05-31T21:27:58.000Z
2022-02-03T18:54:16.000Z
src/renderer/renderer_volpt.cpp
Luvideria/lightmetrica-v3
3e83db59998e79648047bac29c37d8eb18d7600d
[ "MIT" ]
11
2019-09-19T16:03:09.000Z
2020-12-05T18:37:54.000Z
src/renderer/renderer_volpt.cpp
Luvideria/lightmetrica-v3
3e83db59998e79648047bac29c37d8eb18d7600d
[ "MIT" ]
14
2019-06-05T03:06:09.000Z
2022-01-15T06:36:24.000Z
/* Lightmetrica - Copyright (c) 2019 Hisanari Otsu Distributed under MIT license. See LICENSE file for details. */ #include <pch.h> #include <lm/core.h> #include <lm/renderer.h> #include <lm/scene.h> #include <lm/film.h> #include <lm/scheduler.h> #include <lm/path.h> #include <lm/timer.h> #define VOLPT_IMAGE_SAMPLING 0 LM_NAMESPACE_BEGIN(LM_NAMESPACE) class Renderer_VolPT_Base : public Renderer { protected: Scene* scene_; Film* film_; int max_verts_; Float rr_prob_; std::optional<unsigned int> seed_; Component::Ptr<scheduler::Scheduler> sched_; public: LM_SERIALIZE_IMPL(ar) { ar(scene_, film_, max_verts_, rr_prob_, sched_); } virtual void foreach_underlying(const ComponentVisitor& visit) override { comp::visit(visit, scene_); comp::visit(visit, film_); comp::visit(visit, sched_); } public: virtual void construct(const Json& prop) override { scene_ = json::comp_ref<Scene>(prop, "scene"); film_ = json::comp_ref<Film>(prop, "output"); max_verts_ = json::value<int>(prop, "max_verts"); seed_ = json::value_or_none<unsigned int>(prop, "seed"); rr_prob_ = json::value<Float>(prop, "rr_prob", .2_f); const auto sched_name = json::value<std::string>(prop, "scheduler"); #if VOLPT_IMAGE_SAMPLING sched_ = comp::create<scheduler::Scheduler>( "scheduler::spi::" + sched_name, make_loc("scheduler"), prop); #else sched_ = comp::create<scheduler::Scheduler>( "scheduler::spp::" + sched_name, make_loc("scheduler"), prop); #endif } }; // ------------------------------------------------------------------------------------------------ class Renderer_VolPTNaive final : public Renderer_VolPT_Base { public: virtual Json render() const override { scene_->require_renderable(); film_->clear(); const auto size = film_->size(); timer::ScopedTimer st; const auto processed = sched_->run([&](long long pixel_index, long long sample_index, int threadid) { LM_KEEP_UNUSED(sample_index); // Per-thread random number generator thread_local Rng rng(seed_ ? *seed_ + threadid : math::rng_seed()); // ------------------------------------------------------------------------------------ // Sample window Vec4 window(0,0,1,1); #if VOLPT_IMAGE_SAMPLING LM_UNUSED(pixel_index); #else { const int x = int(pixel_index % size.w); const int y = int(pixel_index / size.w); const auto dx = 1_f / size.w; const auto dy = 1_f / size.h; window = { dx * x, dy * y, dx, dy }; } #endif // ------------------------------------------------------------------------------------ // Sample initial vertex const auto sE = path::sample_position(rng, scene_, TransDir::EL); const auto sE_comp = path::sample_component(rng, scene_, sE->sp, {}); auto sp = sE->sp; int comp = sE_comp.comp; auto throughput = sE->weight * sE_comp.weight; // ------------------------------------------------------------------------------------ // Perform random walk Vec3 wi{}; Vec2 raster_pos{}; for (int num_verts = 1; num_verts < max_verts_; num_verts++) { // Sample direction const auto s = [&]() -> std::optional<path::DirectionSample> { if (num_verts == 1) { const auto [x, y, w, h] = window.data.data; const auto ud = Vec2(x + w * rng.u(), y + h * rng.u()); return path::sample_direction({ ud, rng.next<Vec2>() }, scene_, sp, wi, comp, TransDir::EL); } else { return path::sample_direction(rng, scene_, sp, wi, comp, TransDir::EL); } }(); if (!s) { break; } // -------------------------------------------------------------------------------- // Compute and cache raster position if (num_verts == 1) { raster_pos = *path::raster_position(scene_, s->wo); } // -------------------------------------------------------------------------------- // Sample next scene interaction const auto sd = path::sample_distance(rng, scene_, sp, s->wo); if (!sd) { break; } // -------------------------------------------------------------------------------- // Update throughput throughput *= s->weight * sd->weight; // -------------------------------------------------------------------------------- // Accumulate contribution from emissive interaction if (scene_->is_light(sd->sp)) { const auto spL = sd->sp.as_type(SceneInteraction::LightEndpoint); const auto woL = -s->wo; const auto Le = path::eval_contrb_direction(scene_, spL, {}, woL, comp, TransDir::LE, true); const auto C = throughput * Le; film_->splat(raster_pos, C); } // -------------------------------------------------------------------------------- // Termination on a hit with environment if (sd->sp.geom.infinite) { break; } // Russian roulette if (num_verts > 5) { const auto q = glm::max(rr_prob_, 1_f - glm::compMax(throughput)); if (rng.u() < q) { break; } throughput /= 1_f - q; } // -------------------------------------------------------------------------------- // Sample component const auto s_comp = path::sample_component(rng, scene_, sd->sp, -s->wo); throughput *= s_comp.weight; // -------------------------------------------------------------------------------- // Update information wi = -s->wo; sp = sd->sp; comp = s_comp.comp; } }); // Rescale film #if VOLPT_IMAGE_SAMPLING film_->rescale(Float(size.w* size.h) / processed); #else film_->rescale(1_f / processed); #endif return { {"processed", processed}, {"elapsed", st.now()} }; } }; LM_COMP_REG_IMPL(Renderer_VolPTNaive, "renderer::volpt_naive"); // ------------------------------------------------------------------------------------------------ class Renderer_VolPT final : public Renderer_VolPT_Base { public: virtual Json render() const override { scene_->require_renderable(); film_->clear(); const auto size = film_->size(); timer::ScopedTimer st; const auto processed = sched_->run([&](long long pixel_index, long long sample_index, int threadid) { LM_KEEP_UNUSED(sample_index); // Per-thread random number generator thread_local Rng rng(seed_ ? *seed_ + threadid : math::rng_seed()); // ------------------------------------------------------------------------------------ // Sample window Vec4 window(0,0,1,1); #if VOLPT_IMAGE_SAMPLING LM_UNUSED(pixel_index); #else { const int x = int(pixel_index % size.w); const int y = int(pixel_index / size.w); const auto dx = 1_f / size.w; const auto dy = 1_f / size.h; window = { dx * x, dy * y, dx, dy }; } #endif // ------------------------------------------------------------------------------------ // Sample initial vertex const auto sE = path::sample_position(rng, scene_, TransDir::EL); const auto sE_comp = path::sample_component(rng, scene_, sE->sp, {}); auto sp = sE->sp; int comp = sE_comp.comp; auto throughput = sE->weight * sE_comp.weight; // ------------------------------------------------------------------------------------ // Perform random walk Vec3 wi{}; Vec2 raster_pos{}; for (int num_verts = 1; num_verts < max_verts_; num_verts++) { // Sample a NEE edge #if VOLPT_IMAGE_SAMPLING const auto samplable_by_nee = !path::is_specular_component(scene_, sp, comp); #else const auto samplable_by_nee = num_verts > 1 && !path::is_specular_component(scene_, sp, comp); #endif if (samplable_by_nee) [&] { // Sample a light const auto sL = path::sample_direct(rng, scene_, sp, TransDir::LE); if (!sL) { return; } // Recompute raster position for the primary edge Vec2 rp = raster_pos; if (num_verts == 1) { const auto rp_ = path::raster_position(scene_, -sL->wo); if (!rp_) { return; } rp = *rp_; } // Transmittance const auto Tr = path::eval_transmittance(rng, scene_, sp, sL->sp); if (math::is_zero(Tr)) { return; } // Evaluate BSDF const auto wo = -sL->wo; const auto fs = path::eval_contrb_direction(scene_, sp, wi, wo, comp, TransDir::EL, true); if (math::is_zero(fs)) { return; } // Evaluate and accumulate contribution const auto C = throughput * Tr * fs * sL->weight; film_->splat(rp, C); }(); // -------------------------------------------------------------------------------- // Sample direction const auto s = [&]() -> std::optional<path::DirectionSample> { if (num_verts == 1) { const auto [x, y, w, h] = window.data.data; const auto ud = Vec2(x + w * rng.u(), y + h * rng.u()); return path::sample_direction({ ud, rng.next<Vec2>() }, scene_, sp, wi, comp, TransDir::EL); } else { return path::sample_direction(rng, scene_, sp, wi, comp, TransDir::EL); } }(); if (!s) { break; } // -------------------------------------------------------------------------------- // Compute and cache raster position if (num_verts == 1) { raster_pos = *path::raster_position(scene_, s->wo); } // -------------------------------------------------------------------------------- // Sample next scene interaction const auto sd = path::sample_distance(rng, scene_, sp, s->wo); if (!sd) { break; } // -------------------------------------------------------------------------------- // Update throughput throughput *= s->weight * sd->weight; // -------------------------------------------------------------------------------- // Accumulate contribution from emissive interaction if (!samplable_by_nee && scene_->is_light(sd->sp)) { const auto spL = sd->sp.as_type(SceneInteraction::LightEndpoint); const auto woL = -s->wo; const auto Le = path::eval_contrb_direction(scene_, spL, {}, woL, comp, TransDir::LE, true); const auto C = throughput * Le; film_->splat(raster_pos, C); } // -------------------------------------------------------------------------------- // Termination on a hit with environment if (sd->sp.geom.infinite) { break; } // Russian roulette if (num_verts > 5) { const auto q = glm::max(rr_prob_, 1_f - glm::compMax(throughput)); if (rng.u() < q) { break; } throughput /= 1_f - q; } // -------------------------------------------------------------------------------- // Sample component const auto s_comp = path::sample_component(rng, scene_, sd->sp, -s->wo); throughput *= s_comp.weight; // -------------------------------------------------------------------------------- // Update information wi = -s->wo; sp = sd->sp; comp = s_comp.comp; } }); // Rescale film #if VOLPT_IMAGE_SAMPLING film_->rescale(Float(size.w* size.h) / processed); #else film_->rescale(1_f / processed); #endif return { {"processed", processed}, {"elapsed", st.now()} }; } }; LM_COMP_REG_IMPL(Renderer_VolPT, "renderer::volpt"); LM_NAMESPACE_END(LM_NAMESPACE)
37.857909
116
0.401884
[ "render" ]
4fc1ee9587f767674735e369521f01cf024f4347
6,306
hpp
C++
src/io/io.hpp
pepng-CU/pepng
6030798b6936a6f85655d5e5d1ca638be282de92
[ "MIT" ]
2
2021-04-28T20:51:25.000Z
2021-04-28T20:51:38.000Z
src/io/io.hpp
pepng-CU/pepng
6030798b6936a6f85655d5e5d1ca638be282de92
[ "MIT" ]
null
null
null
src/io/io.hpp
pepng-CU/pepng
6030798b6936a6f85655d5e5d1ca638be282de92
[ "MIT" ]
null
null
null
#pragma once #include <vector> #include <memory> #include <string> #include <GLFW/glfw3.h> #include <glm/glm.hpp> enum AxisType { FIRST, SECOND, THIRD, FORTH }; enum DeviceType { MOUSE, JOYSTICK, KEYBOARD, NONE }; class Device; class Input; /** * An abstract Device unit (Button, Axis, etc). */ class DeviceUnit : public std::enable_shared_from_this<DeviceUnit> { public: friend Device; friend Input; /** * Accessor for the device value. */ virtual float value(); protected: /** * The current device unit value. */ float _value; /** * The strength multiplier for the device. */ float _strength; /** * Parent device. */ std::shared_ptr<Device> _device; DeviceUnit(std::string name, float strength); private: /** * The label for device unit. */ std::string __name; }; /** * On/off device unit. */ class Button : public DeviceUnit, public std::enable_shared_from_this<Button> { public: friend Input; /** * Shared_ptr constructor for Button. */ static std::shared_ptr<Button> make_button(std::string name, int buttonId, float strength = 1); protected: Button(std::string name, int buttonId, float strength = 1); private: /** * The GLFW button value. */ int __button_id; /** * Instantiation of Buttons. */ static std::vector<std::shared_ptr<Button>> __buttons; /** * Keyboard button callback (which uses buttons vector). */ static void keyboardCallback(GLFWwindow* window, int key, int scancode, int action, int mods); /** * Mouse button callback (which uses buttons vector). */ static void mouseButtonCallback(GLFWwindow* window, int button, int action, int mods); }; /** * Float device unit. */ class Axis : public DeviceUnit, public std::enable_shared_from_this<Axis> { public: friend Input; static std::shared_ptr<Axis> make_axis(std::string name, AxisType axisType, float strength, bool needsReset); virtual float value() override; protected: Axis(std::string name, AxisType axisType, float strength, bool needsReset); private: /** * The GLFW axis type. */ AxisType __axis_type; /** * Method to reset value when reset. */ bool __needs_reset; /** * Instantiation of Axes. */ static std::vector<std::shared_ptr<Axis>> __axes; /** * The static XY position of the cursor. */ static glm::vec2 __cursor_position; /** * Scroll callback (uses axes). */ static void scrollCallback(GLFWwindow* window, double xoffset, double yoffset); /** * Cursor callback (uses cursorPosition). */ static void cursorPositionCallback(GLFWwindow* window, double xpos, double ypos); }; /** * Device for collection of Device unit. */ class Device : public std::enable_shared_from_this<Device> { public: friend Input; /** * Shared_ptr constructor of Device. */ static std::shared_ptr<Device> make_device(DeviceType deviceType); /** * Attaches a device unit to the device. */ std::shared_ptr<Device> attach_unit(std::shared_ptr<DeviceUnit> unit); /** * Get an Axis device unit value by name. */ float axis(std::string name); /** * Get a Button device unit value by name. */ bool button(std::string name); /** * Get a Button device unit value by name (reset to zero once called). */ bool button_down(std::string name); private: /** * The device type using the DeviceType enum. */ DeviceType __device_type; /** * The parent input device. */ std::shared_ptr<Input> __input; /** * List of attached device unit. */ std::vector<std::shared_ptr<DeviceUnit>> __units; Device(DeviceType deviceType); }; /** * Global input manager (which should be attached to window). */ class Input : public std::enable_shared_from_this<Input> { public: /** * Shared_ptr constructor for Input. */ static std::shared_ptr<Input> make_input(GLFWwindow* window); /** * Attaches a device to the input. */ std::shared_ptr<Input> attach_device(std::shared_ptr<Device> device); /** * Gets an Axis value from all attached devices by name. */ float axis(std::string name); /** * Gets a Button value from all attached devices by name. */ bool button(std::string name); /** * Get a Button device unit value by name (reset to zero once called). */ bool button_down(std::string name); /** * Gets the window that this input is attached to. */ GLFWwindow* window(); /** * Gets the current input manager. * * TODO: This currently assumes that there is only one window (which shouldn't really be an issue). */ static std::shared_ptr<Input> get(); private: /** * The window that this input manager is attached to. */ GLFWwindow* __window; /** * List of attached devices. */ std::vector<std::shared_ptr<Device>> __devices; /** * List of inputs. */ static std::vector<std::shared_ptr<Input>> __inputs; Input(GLFWwindow* window); }; namespace pepng { std::shared_ptr<Input> make_input(GLFWwindow* window); std::shared_ptr<Device> make_device(DeviceType deviceType); std::shared_ptr<Axis> make_axis(std::string name, AxisType axisType, float strength = 1, bool needsReset = false); std::shared_ptr<Button> make_button(std::string name, int buttonId, float strength = 1); }
25.530364
118
0.565969
[ "vector" ]
4fc4c215a9de0b1d2df83cc38e0199ce7854c7be
30,275
hpp
C++
libs/librtlnumber/src/include/internal_bits.hpp
Loksu/vtr-verilog-to-routing
96fbd309897a5743a3b37d07e896fc8e2ed3abe6
[ "MIT" ]
null
null
null
libs/librtlnumber/src/include/internal_bits.hpp
Loksu/vtr-verilog-to-routing
96fbd309897a5743a3b37d07e896fc8e2ed3abe6
[ "MIT" ]
null
null
null
libs/librtlnumber/src/include/internal_bits.hpp
Loksu/vtr-verilog-to-routing
96fbd309897a5743a3b37d07e896fc8e2ed3abe6
[ "MIT" ]
null
null
null
/* Authors: Aaron Graham (aaron.graham@unb.ca, aarongraham9@gmail.com), * Jean-Philippe Legault (jlegault@unb.ca, jeanphilippe.legault@gmail.com), * Alexandrea Demmings (alexandrea.demmings@unb.ca, lxdemmings@gmail.com) and * Dr. Kenneth B. Kent (ken@unb.ca) * for the Reconfigurable Computing Research Lab at the * Univerity of New Brunswick in Fredericton, New Brunswick, Canada */ #ifndef INTERNAL_BITS_HPP #define INTERNAL_BITS_HPP #include <cstdint> #include <string> #include <algorithm> #include <utility> #include <vector> #include <bitset> #include "rtl_utils.hpp" typedef uint16_t veri_internal_bits_t; // typedef VNumber<64> veri_64_t; // typedef VNumber<32> veri_32_t; template <typename T> uint8_t get_veri_integer_limit() { return (sizeof(T)*8); } #define _static_unused(x) namespace { constexpr auto _##x = x; } #define unroll_1d(lut) { lut[_0], lut[_1], lut[_x], lut[_z] } #define unroll_2d(lut) { unroll_1d(lut[_0]), unroll_1d(lut[_1]), unroll_1d(lut[_x]), unroll_1d(lut[_z]) } #define unroll_1d_invert(lut) { l_not[lut[_0]], l_not[lut[_1]], l_not[lut[_x]], l_not[lut[_z]] } #define unroll_2d_invert(lut) { unroll_1d_invert(lut[_0]), unroll_1d_invert(lut[_1]), unroll_1d_invert(lut[_x]), unroll_1d_invert(lut[_z]) } namespace BitSpace { typedef uint8_t bit_value_t; constexpr veri_internal_bits_t _All_0 = static_cast<veri_internal_bits_t>(0x0000000000000000UL); constexpr veri_internal_bits_t _All_1 = static_cast<veri_internal_bits_t>(0x5555555555555555UL); constexpr veri_internal_bits_t _All_x = static_cast<veri_internal_bits_t>(0xAAAAAAAAAAAAAAAAUL); constexpr veri_internal_bits_t _All_z = static_cast<veri_internal_bits_t>(0xFFFFFFFFFFFFFFFFUL); constexpr bit_value_t _0 = 0x0; constexpr bit_value_t _1 = 0x1; constexpr bit_value_t _x = 0x2; constexpr bit_value_t _z = 0x3; /*** * these are taken from the raw verilog truth tables so that the evaluation are correct. * only use this to evaluate any expression for the number_t binary digits. * reference: http://staff.ustc.edu.cn/~songch/download/IEEE.1364-2005.pdf * *******************************************************/ constexpr bit_value_t l_buf[4] = { /* 0 1 x z <- a*/ _0,_1,_x,_x }; _static_unused(l_buf) constexpr bit_value_t l_not[4] = { /* 0 1 x z <- a */ _1,_0,_x,_x }; _static_unused(l_not) constexpr bit_value_t is_unk[4] = { /* 0 1 x z <- a*/ _0,_0,_1,_1 }; _static_unused(is_unk) constexpr bit_value_t is_x_bit[4] = { /* 0 1 x z <- a*/ _0,_0,_1,_0 }; _static_unused(is_x_bit) constexpr bit_value_t is_z_bit[4] = { /* 0 1 x z <- a*/ _0,_0,_0,_1 }; _static_unused(is_z_bit) constexpr bit_value_t is_one_bit[4] = { /* 0 1 x z <- a*/ _0,_1,_0,_0 }; _static_unused(is_one_bit) constexpr bit_value_t is_zero_bit[4] = { /* 0 1 x z <- a*/ _1,_0,_0,_0 }; _static_unused(is_zero_bit) constexpr bit_value_t l_and[4][4] = { /* a / 0 1 x z <-b */ /* 0 */ {_0,_0,_0,_0}, /* 1 */ {_0,_1,_x,_x}, /* x */ {_0,_x,_x,_x}, /* z */ {_0,_x,_x,_x} }; _static_unused(l_and) constexpr bit_value_t l_nand[4][4] = unroll_2d_invert(l_and); _static_unused(l_nand) constexpr bit_value_t l_or[4][4] = { /* a / 0 1 x z <-b */ /* 0 */ {_0,_1,_x,_x}, /* 1 */ {_1,_1,_1,_1}, /* x */ {_x,_1,_x,_x}, /* z */ {_x,_1,_x,_x} }; _static_unused(l_or) constexpr bit_value_t l_nor[4][4] = unroll_2d_invert(l_or); _static_unused(l_nor) constexpr bit_value_t l_xor[4][4] = { /* a / 0 1 x z <-b */ /* 0 */ {_0,_1,_x,_x}, /* 1 */ {_1,_0,_x,_x}, /* x */ {_x,_x,_x,_x}, /* z */ {_x,_x,_x,_x} }; _static_unused(l_xor) constexpr bit_value_t l_xnor[4][4] = unroll_2d_invert(l_xor); _static_unused(l_xnor) /***************************************************** * Tran NO SUPPORT FOR THESE YET */ constexpr bit_value_t l_notif1[4][4] = { /* in / 0 1 x z <-control */ /* 0 */ {_z,_1,_x,_x}, /* 1 */ {_z,_0,_x,_x}, /* x */ {_z,_x,_x,_x}, /* z */ {_z,_x,_x,_x} }; _static_unused(l_notif1) constexpr bit_value_t l_notif0[4][4] = { /* in / 0 1 x z <-control */ /* 0 */ {_1,_z,_x,_x}, /* 1 */ {_0,_z,_x,_x}, /* x */ {_x,_z,_x,_x}, /* z */ {_x,_z,_x,_x} }; _static_unused(l_notif0) constexpr bit_value_t l_bufif1[4][4] = { /* in / 0 1 x z <-control */ /* 0 */ {_z,_0,_x,_x}, /* 1 */ {_z,_1,_x,_x}, /* x */ {_z,_x,_x,_x}, /* z */ {_z,_x,_x,_x} }; _static_unused(l_bufif1) constexpr bit_value_t l_bufif0[4][4] = { /* in / 0 1 x z <-control */ /* 0 */ {_0,_z,_x,_x}, /* 1 */ {_1,_z,_x,_x}, /* x */ {_x,_z,_x,_x}, /* z */ {_x,_z,_x,_x} }; _static_unused(l_bufif0) /* cmos gates */ constexpr bit_value_t l_rpmos[4][4] = { /* in / 0 1 x z <-control */ /* 0 */ {_0,_z,_x,_x}, /* 1 */ {_1,_z,_x,_x}, /* x */ {_x,_z,_x,_x}, /* z */ {_z,_z,_z,_z} }; _static_unused(l_rpmos) constexpr bit_value_t l_rnmos[4][4] = { /* in / 0 1 x z <-control */ /* 0 */ {_z,_0,_x,_x}, /* 1 */ {_z,_1,_x,_x}, /* x */ {_z,_x,_x,_x}, /* z */ {_z,_z,_z,_z} }; _static_unused(l_rnmos) constexpr bit_value_t l_nmos[4][4] = { /* in / 0 1 x z <-control */ /* 0 */ {_z,_0,_x,_x}, /* 1 */ {_z,_1,_x,_x}, /* x */ {_z,_x,_x,_x}, /* z */ {_z,_z,_z,_z} }; _static_unused(l_nmos) // see table 5-21 p:54 IEEE 1364-2005 constexpr bit_value_t l_ternary[4][4] = { /* in / 0 1 x z <-control */ /* 0 */ {_0,_x,_x,_x}, /* 1 */ {_x,_1,_x,_x}, /* x */ {_x,_x,_x,_x}, /* z */ {_x,_x,_x,_x} }; _static_unused(l_ternary) /***** * these extend the library and simplify the process */ /* helper */ constexpr bit_value_t l_unk[4][4] = { /* in / 0 1 x z <-control */ /* 0 */ {_x,_x,_x,_x}, /* 1 */ {_x,_x,_x,_x}, /* x */ {_x,_x,_x,_x}, /* z */ {_x,_x,_x,_x} }; _static_unused(l_unk) constexpr bit_value_t l_case_eq[4][4] = { /* a / 0 1 x z <-b */ /* 0 */ {_1,_0,_0,_0}, /* 1 */ {_0,_1,_0,_0}, /* x */ {_0,_0,_1,_0}, /* z */ {_0,_0,_0,_1} }; _static_unused(l_case_eq) constexpr bit_value_t l_lt[4][4] = { /* a / 0 1 x z <-b */ /* 0 */ {_0,_1,_x,_x}, /* 1 */ {_0,_0,_x,_x}, /* x */ {_x,_x,_x,_x}, /* z */ {_x,_x,_x,_x} }; _static_unused(l_lt) constexpr bit_value_t l_gt[4][4] = { /* a / 0 1 x z <-b */ /* 0 */ {_0,_0,_x,_x}, /* 1 */ {_1,_0,_x,_x}, /* x */ {_x,_x,_x,_x}, /* z */ {_x,_x,_x,_x} }; _static_unused(l_gt) constexpr bit_value_t l_eq[4][4] = unroll_2d(l_xnor); _static_unused(l_eq) constexpr bit_value_t l_sum[4][4][4] = { /* c_in */ /* 0 */ unroll_2d(l_xor), /* 1 */ unroll_2d(l_xnor), /* x */ unroll_2d(l_unk), /* z */ unroll_2d(l_unk) }; _static_unused(l_sum) constexpr bit_value_t l_carry[4][4][4] = { /* c_in */ /* 0 */ unroll_2d(l_and), /* 1 */ unroll_2d(l_or), /* x */ unroll_2d(l_ternary), /* z */ unroll_2d(l_ternary) }; _static_unused(l_carry) constexpr bit_value_t l_half_carry[4][4] = unroll_2d(l_carry[_0]); _static_unused(l_half_carry) constexpr bit_value_t l_half_sum[4][4] = unroll_2d(l_sum[_0]); _static_unused(l_half_sum) static char bit_to_c(bit_value_t bit) { switch(bit) { case _0: return '0'; case _1: return '1'; case _z: return 'z'; default: return 'x'; } } static bit_value_t c_to_bit(char c) { switch(tolower(c)) { case '0': return _0; case '1': return _1; case 'z': return _z; default: return _x; } } template<typename T> class BitFields { private : T bits = static_cast<T>(_All_x); template<typename Addr_t> size_t get_bit_location(Addr_t address) { size_t current_address = static_cast<size_t>(address); current_address %= this->size(); current_address <<= 1; return current_address; } public : BitFields(bit_value_t init_v) { this->bits = static_cast<T>( (_0 == init_v)? _All_0: (_1 == init_v)? _All_1: (_z == init_v)? _All_z: _All_x ); } template<typename Addr_t> bit_value_t get_bit(Addr_t address) { auto result = this->bits >> this->get_bit_location(address); result &= 0x3; return static_cast<bit_value_t>(result); } template<typename Addr_t> void set_bit(Addr_t address, bit_value_t value) { size_t real_address = this->get_bit_location(address); T set_value = static_cast<T>(value); set_value = static_cast<T>(set_value << real_address); T mask = static_cast<T>(0x3); mask = static_cast<T>(mask << real_address); mask = static_cast<T>(~(mask)); this->bits = static_cast<T>(this->bits & mask); this->bits = static_cast<T>(this->bits | set_value); } /** * get 16 real bit (8 verilog bits) as 8 bit (char) */ template<typename Addr_t> char get_as_char(Addr_t address) { size_t start = (8*(address)); size_t end = (8*(address+1))-1; char value = 0; for(size_t i = start; i <= end; i++) { value += (((this->get_bit(i))? 1: 0) << i); } return value; } static size_t size() { return (sizeof(T)<<2); // 8 bit in a byte, 2 bits for a verilog bits = 4 bits in a byte, << 2 = sizeof x 4 } }; // #define DEBUG_V_BITS /***** * we use large array since we process the bits in chunks */ class VerilogBits { private: std::vector<BitFields<veri_internal_bits_t>> bits; size_t bit_size = 0; size_t to_index(size_t address) { return ( address / BitFields<veri_internal_bits_t>::size() ); } size_t list_size() { return this->bits.size(); } public: VerilogBits() { this->bit_size = 0; this->bits = std::vector<BitSpace::BitFields<veri_internal_bits_t>>(); } VerilogBits(size_t data_size, bit_value_t value_in) { this->bit_size = data_size; this->bits = std::vector<BitSpace::BitFields<veri_internal_bits_t>>(); size_t bitfield_count = (this->bit_size / BitFields<veri_internal_bits_t>::size()) +1; for(size_t i=0; i<bitfield_count; i++) { this->bits.push_back(BitSpace::BitFields<veri_internal_bits_t>(value_in)); } } VerilogBits(VerilogBits *other) { this->bit_size = other->size(); this->bits = other->get_internal_bitvector(); } size_t size() { return this->bit_size; } std::vector<BitFields<veri_internal_bits_t>> get_internal_bitvector() { return this->bits; } BitFields<veri_internal_bits_t> *get_bitfield(size_t index) { #ifdef DEBUG_V_BITS if (index >= this->bits.size() ) { std::cerr << "Bit array indexing out of bounds " << index << " but size is " << this->bit_size << std::endl; std::abort(); } #endif return (&this->bits[index]); } bit_value_t get_bit(size_t address) { #ifdef DEBUG_V_BITS if (address >= this->bit_size ) { std::cerr << "Bit index array out of bounds " << address << " but size is " << this->bit_size << std::endl; std::abort(); } #endif return (this->get_bitfield(to_index(address))->get_bit(address)); } void set_bit(size_t address, bit_value_t value) { #ifdef DEBUG_V_BITS if (address >= this->bit_size ) { std::cerr << "Bit index array out of bounds " << address << " but size is " << this->bit_size << std::endl; std::abort(); } #endif (this->get_bitfield(to_index(address))->set_bit(address, value)); } std::string to_string(bool big_endian) { // make a big endian string std::string to_return = ""; for(size_t address=0x0; address < this->size(); address++) { char value = BitSpace::bit_to_c(this->get_bit(address)); if(big_endian) { to_return.push_back(value); } else { to_return.insert(0,1,value); } } return to_return; } std::string to_printable() { std::string to_return = ""; for(size_t i=0; i< this->size(); i += 8) { to_return.insert(0,1,this->get_bitfield(to_index(i))->get_as_char(i)); } return to_return; } bool has_unknowns() { for(size_t address=0x0; address < this->size(); address++) { if(is_unk[this->get_bit(address)]) return true; } return false; } bool is_only_z() { for(size_t address=0x0; address < this->size(); address++) { if(! is_z_bit[this->get_bit(address)]) return false; } return true; } bool is_only_x() { for(size_t address=0x0; address < this->size(); address++) { if(! is_x_bit[this->get_bit(address)]) return false; } return true; } bool is_true() { for(size_t address=0x0; address < this->size(); address++) { if(is_one_bit[this->get_bit(address)]) return true; } return false; } bool is_false() { for(size_t address=0x0; address < this->size(); address++) { if(! is_zero_bit[this->get_bit(address)]) return false; } return true; } /** * Unary Reduction operations * This is Msb to Lsb on purpose, as per specs */ VerilogBits bitwise_reduce(const bit_value_t lut[4][4]) { bit_value_t result = this->get_bit(this->size()-1); for(size_t i=this->size()-2; i < this->size(); i--) { result = lut[result][this->get_bit(i)]; } return VerilogBits(1, result); } VerilogBits invert() { VerilogBits other(this->bit_size, _0); for(size_t i=0; i<this->size(); i++) other.set_bit(i, BitSpace::l_not[this->get_bit(i)]); return other; } VerilogBits twos_complement() { BitSpace::bit_value_t previous_carry = BitSpace::_1; VerilogBits other(this->bit_size, _0); for(size_t i=0; i<this->size(); i++) { BitSpace::bit_value_t not_bit_i = BitSpace::l_not[this->get_bit(i)]; other.set_bit(i,BitSpace::l_half_sum[previous_carry][not_bit_i]); previous_carry = BitSpace::l_half_carry[previous_carry][not_bit_i]; } return other; } /** * size of zero compact to the least amount of bits */ VerilogBits resize(BitSpace::bit_value_t pad, size_t new_size) { /** * find the new size */ if(new_size == 0) { size_t last_bit_id = this->size() - 1; size_t next_bit_id = last_bit_id -1; while(next_bit_id < this->size()-1) { BitSpace::bit_value_t current = this->get_bit(last_bit_id); BitSpace::bit_value_t next = this->get_bit(next_bit_id); if(current == next && current == pad) { last_bit_id--; next_bit_id--; } else { break; /* it down. oh. oh! */ } } new_size = last_bit_id+1; } VerilogBits other(new_size, BitSpace::_0); size_t i = 0; while(i < this->size() && i < new_size) { other.set_bit(i, this->get_bit(i)); i++; } while(i < new_size) { other.set_bit(i, pad);/* <- ask Eve about it */ i++; } return other; } /** * replicates the bitset n times */ VerilogBits replicate(size_t n_times) { size_t old_size = this->size(); size_t new_size = old_size * n_times; VerilogBits other(new_size, BitSpace::_0); for(size_t i = 0; i < new_size; i += 1) { other.set_bit(i, this->get_bit( i%old_size )); } return other; } }; } //template<size_t bit_size> class VNumber { private: bool sign = false; bool defined_size = false; BitSpace::VerilogBits bitstring = BitSpace::VerilogBits(1, BitSpace::_x); VNumber(BitSpace::VerilogBits other_bitstring, bool other_defined_size, bool other_sign) { bitstring = BitSpace::VerilogBits(std::move(other_bitstring)); sign = other_sign; defined_size = other_defined_size; } VNumber insert(VNumber &other, size_t index_to_insert_at, size_t insertion_size) { assert_Werr(other.is_defined_size() && this->is_defined_size() ,"Size must be defined on both operand for insertion"); VNumber new_bitstring(this->size() + insertion_size, BitSpace::_0, this->is_signed() && other.is_signed(), true); size_t index = 0; for(size_t i=0; i < this->size() && i < index_to_insert_at; i += 1, index +=1) new_bitstring.set_bit_from_lsb(index, this->get_bit_from_lsb( i )); for(size_t i=0; i < insertion_size; i += 1, index +=1) new_bitstring.set_bit_from_lsb(index, other.get_bit_from_lsb( i )); for(size_t i=index_to_insert_at; i < this->size(); i += 1, index +=1) new_bitstring.set_bit_from_lsb(index, this->get_bit_from_lsb( i )); return new_bitstring; } public: VNumber() { this->sign = false; this->bitstring = BitSpace::VerilogBits(1, BitSpace::_x); this->defined_size = false; } VNumber(VNumber&&) = default; VNumber& operator=(VNumber&&) = default; VNumber& operator=(const VNumber& other) = default; VNumber(const VNumber& other) { this->sign = other.sign; this->bitstring = other.bitstring; this->defined_size = other.defined_size; } VNumber(VNumber other, size_t length) { this->sign = other.sign; this->bitstring = other.bitstring.resize(other.get_padding_bit(),length); // TODO this->defined_size = true?????; } VNumber(const std::string& verilog_string) { set_value(verilog_string); } VNumber(int64_t numeric_value) { set_value(numeric_value); } VNumber(size_t len, BitSpace::bit_value_t initial_bits, bool input_sign, bool this_defined_size) { this->bitstring = BitSpace::VerilogBits(len, initial_bits); this->sign = input_sign; this->defined_size = this_defined_size; } /*** * getters to 64 bit int */ int64_t get_value() { using integer_t = int64_t; size_t bit_size = 8*sizeof(integer_t); assert_Werr( (! this->bitstring.has_unknowns() ) , "Invalid Number contains dont care values. number: " + this->bitstring.to_string(false) ); size_t end = this->size(); if(end > bit_size) { printf(" === Warning: Returning a 64 bit integer from a larger bitstring (%zu). The bitstring will be truncated\n", bit_size); end = bit_size; } integer_t result = 0; BitSpace::bit_value_t pad = this->get_padding_bit(); // = this->is_negative(); for(size_t bit_index = 0; bit_index < end; bit_index++) { integer_t current_bit = static_cast<integer_t>(pad); if(bit_index < this->size()) current_bit = this->bitstring.get_bit(bit_index); result |= (current_bit << bit_index); } return result; } // convert lsb_msb bitstring to verilog std::string to_full_string() { std::string out = this->to_bit_string(); size_t len = this->bitstring.size(); return std::to_string(len) + ((this->is_signed())? "\'sb": "\'b") + out; } std::string to_bit_string() { std::string out = this->bitstring.to_string(false); return out; } std::string to_printable() { std::string out = this->bitstring.to_printable(); return out; } /*** * setters */ void set_value(const std::string& input) { if(!input.size()) { return; } std::string verilog_string(input); /** * set defaults */ size_t bitsize = 32; // 32 bit is the fall back this->defined_size = false; // the size is undefined unless otherwise specified size_t radix = 0; // the radix is unknown to start with this->sign = false; // we treat everything as unsigned unless specified // if this is a string if(verilog_string[0] == '\"') { assert_Werr(verilog_string.size() >= 2, "Malformed input String for VNumber, only open quote" + verilog_string); assert_Werr(verilog_string.back() == '\"', "Malformed input String for VNumber, expected closing quotes" + verilog_string); verilog_string.erase(0,1); verilog_string.pop_back(); size_t string_size = verilog_string.size(); if(string_size == 0) string_size = 1; bitsize = string_size * 8; this->defined_size = true; radix = 256; } else { size_t loc = verilog_string.find("\'"); if(loc == std::string::npos) { verilog_string.insert(0, "\'sd"); loc = 0; } if(loc != 0) { std::string bit_length_char = verilog_string.substr(0, loc); bitsize = strtoul(bit_length_char.c_str(), nullptr, 10); this->defined_size = true; } if(std::tolower(verilog_string[loc+1]) == 's') { this->sign = true; } char base = static_cast<char>(std::tolower(verilog_string[loc+1+sign])); switch(base) { case 'b': radix = 2; break; // binary case 'o': radix = 8; break; // octal case 'd': radix = 10; break; // decimal case 'h': radix = 16; break; // hexadecimal default: assert_Werr( false, "Invalid radix base for number: " + std::string(1,base) ); break; } //remove underscores verilog_string = verilog_string.substr(loc+2+sign); verilog_string.erase(std::remove(verilog_string.begin(), verilog_string.end(), '_'), verilog_string.end()); //little endian bitstring string } std::string temp_bitstring = string_of_radix_to_bitstring(verilog_string, radix); char pad = temp_bitstring[0]; if(!this->sign && pad == '1') { pad = '0'; } // convert the bits to the internal data struct (bit at index 0 in string is msb since string go from msb to lsb) BitSpace::VerilogBits new_bitstring(temp_bitstring.size(), BitSpace::_0); size_t counter = temp_bitstring.size()-1; for(char in: temp_bitstring) { new_bitstring.set_bit(counter--,BitSpace::c_to_bit(in)); } this->bitstring = new_bitstring.resize(BitSpace::c_to_bit(pad), bitsize); } void set_value(int64_t in) { this->set_value(std::to_string(in)); } size_t msb_index() { return this->bitstring.size()-1; } /**** * bit twiddling functions */ BitSpace::bit_value_t get_bit_from_msb(size_t index) { return this->bitstring.get_bit(msb_index()-index); } BitSpace::bit_value_t get_bit_from_lsb(size_t index) { if (index < this->size()) return this->bitstring.get_bit(index); else return this->get_padding_bit(); } void set_bit_from_msb(size_t index, BitSpace::bit_value_t val) { this->bitstring.set_bit(msb_index()-index, val); } void set_bit_from_lsb(size_t index, BitSpace::bit_value_t val) { this->bitstring.set_bit(index, val); } /*** * other */ size_t size() { return this->bitstring.size(); } BitSpace::bit_value_t get_padding_bit() { return this->is_negative()? BitSpace::_1:BitSpace::_0; } bool is_signed() const { return this->sign; } bool is_defined_size() { return this->defined_size; } bool is_negative() { return ( this->get_bit_from_msb(0) == BitSpace::_1 && this->sign ); } bool is_dont_care_string() { return this->bitstring.has_unknowns(); } bool is_z() { return this->bitstring.is_only_z(); } bool is_x() { return this->bitstring.is_only_x(); } bool is_true() { return this->bitstring.is_true(); } bool is_false() { return this->bitstring.is_false(); } VNumber twos_complement() { return VNumber(this->bitstring.twos_complement(),this->defined_size,this->sign); } VNumber to_signed() { return VNumber(this->bitstring,this->defined_size,true); } VNumber to_unsigned() { return VNumber(this->bitstring,this->defined_size,false); } VNumber invert() { return VNumber(this->bitstring.invert(),this->defined_size,this->sign); } VNumber bitwise_reduce(const BitSpace::bit_value_t lut[4][4]) { return VNumber(this->bitstring.bitwise_reduce(lut),this->defined_size,false); } /** * Binary Reduction operations */ VNumber bitwise(VNumber& b, const BitSpace::bit_value_t lut[4][4]) { size_t std_length = std::max(this->size(), b.size()); const BitSpace::bit_value_t pad_a = this->get_padding_bit(); const BitSpace::bit_value_t pad_b = b.get_padding_bit(); VNumber result(std_length, BitSpace::_x, false, this->is_defined_size() && b.is_defined_size() ); for(size_t i=0; i < result.size(); i++) { BitSpace::bit_value_t bit_a = pad_a; if(i < this->size()) bit_a = this->get_bit_from_lsb(i); BitSpace::bit_value_t bit_b = pad_b; if(i < b.size()) bit_b = b.get_bit_from_lsb(i); result.set_bit_from_lsb(i, lut[bit_a][bit_b]); } return result; } VNumber replicate(int64_t n_times_replicate) { assert_Werr(n_times_replicate > 0, "Cannot replicate bitstring less than 1 times"); size_t n_times_unsigned = static_cast<size_t>(n_times_replicate); return VNumber(this->bitstring.replicate(n_times_unsigned),true,this->sign); } VNumber insert_at_lsb(VNumber &other) { return this->insert(other, 0, other.size()); } VNumber insert_at_msb(VNumber &other) { return this->insert(other, this->size(), other.size()); } }; #endif
27.980591
140
0.507779
[ "vector" ]