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
22b8847d720beec7f1b98cac6fad07036c5dcb53
5,228
cpp
C++
arbitrator/test/test_beam_search_strategy.cpp
adamlm/carma-platform
f6d46274cf6b6e14eddf8715b1a5204050d4c0e2
[ "Apache-2.0", "CC-BY-4.0", "MIT" ]
112
2020-04-27T17:06:46.000Z
2022-03-31T15:27:14.000Z
arbitrator/test/test_beam_search_strategy.cpp
adamlm/carma-platform
f6d46274cf6b6e14eddf8715b1a5204050d4c0e2
[ "Apache-2.0", "CC-BY-4.0", "MIT" ]
982
2020-04-17T11:28:04.000Z
2022-03-31T21:12:19.000Z
arbitrator/test/test_beam_search_strategy.cpp
adamlm/carma-platform
f6d46274cf6b6e14eddf8715b1a5204050d4c0e2
[ "Apache-2.0", "CC-BY-4.0", "MIT" ]
57
2020-05-07T15:48:11.000Z
2022-03-09T23:31:45.000Z
/* * Copyright (C) 2019-2021 LEIDOS. * * 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 "test_utils.h" namespace arbitrator { TEST_F(BeamSearchStrategyTest, testEmptyList) { auto vec = bss.prioritize_plans(std::vector<std::pair<cav_msgs::ManeuverPlan, double>>()); ASSERT_EQ(0, vec.size()); ASSERT_TRUE(vec.empty()); } TEST_F(BeamSearchStrategyTest, testSort1) { auto vec = bss.prioritize_plans(std::vector< std::pair<cav_msgs::ManeuverPlan, double>>({ { cav_msgs::ManeuverPlan(), 10.0 }, { cav_msgs::ManeuverPlan(), 5.0 }, { cav_msgs::ManeuverPlan(), 0.0 }, })); ASSERT_EQ(3, vec.size()); ASSERT_NEAR(0.0, vec[0].second, 0.01); ASSERT_NEAR(5.0, vec[1].second, 0.01); ASSERT_NEAR(10.0, vec[2].second, 0.01); } TEST_F(BeamSearchStrategyTest, testSort2) { auto vec = bss.prioritize_plans(std::vector< std::pair<cav_msgs::ManeuverPlan, double>>({ { cav_msgs::ManeuverPlan(), 10.0 }, { cav_msgs::ManeuverPlan(), 0.0 }, { cav_msgs::ManeuverPlan(), 5.0 }, })); ASSERT_EQ(3, vec.size()); ASSERT_NEAR(0.0, vec[0].second, 0.01); ASSERT_NEAR(5.0, vec[1].second, 0.01); ASSERT_NEAR(10.0, vec[2].second, 0.01); } TEST_F(BeamSearchStrategyTest, testSort3) { auto vec = bss.prioritize_plans(std::vector< std::pair<cav_msgs::ManeuverPlan, double>>({ { cav_msgs::ManeuverPlan(), 0.0 }, { cav_msgs::ManeuverPlan(), 5.0 }, { cav_msgs::ManeuverPlan(), 10.0 }, })); ASSERT_EQ(3, vec.size()); ASSERT_NEAR(0.0, vec[0].second, 0.01); ASSERT_NEAR(5.0, vec[1].second, 0.01); ASSERT_NEAR(10.0, vec[2].second, 0.01); } TEST_F(BeamSearchStrategyTest, testSortAndPrune1) { auto vec = bss.prioritize_plans(std::vector< std::pair<cav_msgs::ManeuverPlan, double>>({ { cav_msgs::ManeuverPlan(), 10.0 }, { cav_msgs::ManeuverPlan(), 5.0 }, { cav_msgs::ManeuverPlan(), 3.0 }, { cav_msgs::ManeuverPlan(), 7.0 }, { cav_msgs::ManeuverPlan(), 6.0 }, { cav_msgs::ManeuverPlan(), 1.0 }, { cav_msgs::ManeuverPlan(), 9.0 }, { cav_msgs::ManeuverPlan(), 8.0 }, { cav_msgs::ManeuverPlan(), 2.0 }, { cav_msgs::ManeuverPlan(), 4.0 }, { cav_msgs::ManeuverPlan(), 0.0 }, })); ASSERT_EQ(3, vec.size()); ASSERT_NEAR(0.0, vec[0].second, 0.01); ASSERT_NEAR(1.0, vec[1].second, 0.01); ASSERT_NEAR(2.0, vec[2].second, 0.01); } TEST_F(BeamSearchStrategyTest, testSortAndPrune2) { auto vec = bss.prioritize_plans(std::vector< std::pair<cav_msgs::ManeuverPlan, double>>({ { cav_msgs::ManeuverPlan(), 10.0 }, { cav_msgs::ManeuverPlan(), 9.0 }, { cav_msgs::ManeuverPlan(), 8.0 }, { cav_msgs::ManeuverPlan(), 7.0 }, { cav_msgs::ManeuverPlan(), 6.0 }, { cav_msgs::ManeuverPlan(), 5.0 }, { cav_msgs::ManeuverPlan(), 4.0 }, { cav_msgs::ManeuverPlan(), 3.0 }, { cav_msgs::ManeuverPlan(), 2.0 }, { cav_msgs::ManeuverPlan(), 1.0 }, { cav_msgs::ManeuverPlan(), 0.0 }, })); ASSERT_EQ(3, vec.size()); ASSERT_NEAR(0.0, vec[0].second, 0.01); ASSERT_NEAR(1.0, vec[1].second, 0.01); ASSERT_NEAR(2.0, vec[2].second, 0.01); } TEST_F(BeamSearchStrategyTest, testSortAndPrune3) { auto vec = bss.prioritize_plans(std::vector< std::pair<cav_msgs::ManeuverPlan, double>>({ { cav_msgs::ManeuverPlan(), 0.0 }, { cav_msgs::ManeuverPlan(), 1.0 }, { cav_msgs::ManeuverPlan(), 2.0 }, { cav_msgs::ManeuverPlan(), 3.0 }, { cav_msgs::ManeuverPlan(), 4.0 }, { cav_msgs::ManeuverPlan(), 5.0 }, { cav_msgs::ManeuverPlan(), 6.0 }, { cav_msgs::ManeuverPlan(), 7.0 }, { cav_msgs::ManeuverPlan(), 8.0 }, { cav_msgs::ManeuverPlan(), 9.0 }, { cav_msgs::ManeuverPlan(), 10.0 }, })); ASSERT_EQ(3, vec.size()); ASSERT_NEAR(0.0, vec[0].second, 0.01); ASSERT_NEAR(1.0, vec[1].second, 0.01); ASSERT_NEAR(2.0, vec[2].second, 0.01); } }
35.564626
98
0.531561
[ "vector" ]
22bae5c9f25bca17bc8c73321f5341216db7b1f2
2,397
cpp
C++
36_find_four_sum.cpp
swapmali/Must-Do-Coding-Questions-For-Companies-GFG
b68340c150f572c0fad7311af87f79b684060fb9
[ "MIT" ]
1
2021-02-07T19:50:36.000Z
2021-02-07T19:50:36.000Z
36_find_four_sum.cpp
swapmali/Must-Do-Coding-Questions-For-Companies-GFG
b68340c150f572c0fad7311af87f79b684060fb9
[ "MIT" ]
null
null
null
36_find_four_sum.cpp
swapmali/Must-Do-Coding-Questions-For-Companies-GFG
b68340c150f572c0fad7311af87f79b684060fb9
[ "MIT" ]
1
2021-05-06T15:30:47.000Z
2021-05-06T15:30:47.000Z
// https://practice.geeksforgeeks.org/problems/maximum-sum-increasing-subsequence/0/ #include <iostream> #include <bits/stdc++.h> using namespace std; void print_vector(std::vector<int> v) { for (int i = 0; i < v.size(); ++i) { cout << v[i] << " "; } cout << endl; } int main() { #ifndef ONLINE_JUDGE freopen("input.txt", "r", stdin); freopen("output.txt", "w", stdout); #endif ios_base::sync_with_stdio(false); cin.tie(NULL); int t; cin >> t; while (t--) { long int n, s; cin >> n >> s; vector<int> v(n); for (long int i = 0; i < n; ++i) { cin >> v[i]; } sort(v.begin(), v.end()); std::vector<int> hash(v[v.size() - 1] + 1, 0); for (int i = 0; i < n; ++i) { hash[v[i]]++; } // cout << "hash: "; // print_vector(hash); /* std::vector<int> :: iterator ip; ip = unique(v.begin(), v.end()); v.resize(distance(v.begin(), ip));*/ // cout << "v: "; // print_vector(v); vector < vector<int> > ans; for (int i = 0; i < n; ++i) { for (int j = i + 1; j < n; ++j) { for (int k = j + 1; k < n; ++k) { int l = s - (v[i] + v[j] + v[k]); if (l >= v[k] && binary_search(v.begin(), v.end(), l)) { vector<int> a(4); a[0] = v[i]; a[1] = v[j]; a[2] = v[k]; a[3] = l; ans.push_back(a); } } } } int is_printed = 0, is_repeated = 0; for (int i = 0; i < ans.size(); ++i) { int is_repeated = 0; if (i) { int j = i - 1; while (j >= 0) { if (ans[i][0] == ans[j][0]) { if (ans[i][1] == ans[j][1] && ans[i][2] == ans[j][2] && ans[i][3] == ans[j][3]) { is_repeated = 1; //cout << "Repeated for : " << ans[i][0] << " " << ans[i][1] << " " << ans[i][2] << " " << ans[i][3] << " " << endl; break; } } else break; j--; } } if (!is_repeated) { std::vector<int> h(v[v.size() - 1] + 1, 0); for (int j = 0; j < 4; ++j) { h[ans[i][j]]++; } // cout << "h: "; // print_vector(h); int flg = 1; for (int j = 0; j < 4; ++j) { if (h[ans[i][j]] > hash[ans[i][j]]) { flg = 0; break; } } if (flg) { cout << ans[i][0] << " " << ans[i][1] << " " << ans[i][2] << " " << ans[i][3] << " $"; is_printed = 1; } } } if (!is_printed) cout << -1; cout << endl; } return 0; }
18.022556
123
0.420943
[ "vector" ]
22c00154676f1ab58afe66dd6f0d09f74ac128bf
32,988
cpp
C++
plugins/core/qCompass/src/ccTrace.cpp
ohanlonl/qCMAT
f6ca04fa7c171629f094ee886364c46ff8b27c0b
[ "BSD-Source-Code" ]
null
null
null
plugins/core/qCompass/src/ccTrace.cpp
ohanlonl/qCMAT
f6ca04fa7c171629f094ee886364c46ff8b27c0b
[ "BSD-Source-Code" ]
null
null
null
plugins/core/qCompass/src/ccTrace.cpp
ohanlonl/qCMAT
f6ca04fa7c171629f094ee886364c46ff8b27c0b
[ "BSD-Source-Code" ]
1
2019-02-03T12:19:42.000Z
2019-02-03T12:19:42.000Z
//########################################################################## //# # //# CLOUDCOMPARE PLUGIN: ccCompass # //# # //# This program is free software; you can redistribute it and/or modify # //# it under the terms of the GNU General Public License as published by # //# the Free Software Foundation; version 2 of the License. # //# # //# This program is distributed in the hope that it will be useful, # //# but WITHOUT ANY WARRANTY; without even the implied warranty of # //# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # //# GNU General Public License for more details. # //# # //# COPYRIGHT: Sam Thiele 2017 # //# # //########################################################################## #include "ccTrace.h" #include <queue> #include <bitset> ccTrace::ccTrace(ccPointCloud* associatedCloud) : ccPolyline(associatedCloud) { init(associatedCloud); } ccTrace::ccTrace(ccPolyline* obj) : ccPolyline(obj->getAssociatedCloud()) { ccPointCloud* cld = dynamic_cast<ccPointCloud*>(obj->getAssociatedCloud()); assert(cld != nullptr); //should never be null init(cld); //load waypoints from metadata if (obj->hasMetaData("waypoints")) { QString waypoints = obj->getMetaData("waypoints").toString(); for (QString str : waypoints.split(",")) { if (str != "") { int pID = str.toInt(); m_waypoints.push_back(pID); //add waypoint } } //store waypoints metadata QVariantMap* map = new QVariantMap(); map->insert("waypoints", waypoints); setMetaData(*map, true); } //load cost function from metadata if (obj->hasMetaData("cost_function")) { ccTrace::COST_MODE = obj->getMetaData("cost_function").toInt(); } setName(obj->getName()); //copy polyline into trace points std::deque<int> seg; for (unsigned i = 0; i < obj->size(); i++) { //copy into "trace" object int pId = obj->getPointGlobalIndex(i); //get global point ID seg.push_back(pId); //also copy into polyline object addPointIndex(pId); } m_trace.push_back(seg); //recalculate trace if polyline data somehow lost [redundancy thing..] if (obj->size() == 0) { m_trace.clear(); optimizePath(); //[slooooow...!] } computeBB(); //update bounding box (for picking) } void ccTrace::init(ccPointCloud* associatedCloud) { setAssociatedCloud(associatedCloud); //the ccPolyline c'tor should do this, but just to be sure... m_cloud = associatedCloud; //store pointer ourselves also m_search_r = calculateOptimumSearchRadius(); //estimate the search radius we want to use //store these info as object attributes updateMetadata(); } void ccTrace::updateMetadata() { QVariantMap* map = new QVariantMap(); map->insert("ccCompassType", "Trace"); map->insert("search_r", m_search_r); map->insert("cost_function", ccTrace::COST_MODE); setMetaData(*map, true); } int ccTrace::insertWaypoint(int pointId) { if (m_waypoints.size() >= 2) { //get location of point to add //const CCVector3* Q = m_cloud->getPoint(pointId); CCVector3 Q = *m_cloud->getPoint(pointId); CCVector3 start, end; //check if point is "inside" any segments for (int i = 1; i < m_waypoints.size(); i++) { //get start and end points m_cloud->getPoint(m_waypoints[i - 1], start); m_cloud->getPoint(m_waypoints[i], end); //are we are "inside" this segment if (inCircle(&start, &end, &Q)) { //insert waypoint m_waypoints.insert(m_waypoints.begin() + i, pointId); m_previous.push_back(i); return i; } } //check if the point is closer to the start than the end -> i.e. the point should be 'pre-pended' CCVector3 sp = Q - start; CCVector3 ep = Q - end; if (sp.norm2() < ep.norm2()) { m_waypoints.insert(m_waypoints.begin(), pointId); m_previous.push_back(0); return 0; } } //add point to end of the trace m_waypoints.push_back(pointId); int id = static_cast<int>(m_waypoints.size()) - 1; m_previous.push_back(id); //store for undo options return id; } //test if the query point is within a circle bound by segStart & segEnd bool ccTrace::inCircle(const CCVector3* segStart, const CCVector3* segEnd, const CCVector3* query) { //calculate vector Query->Start and Query->End CCVector3 QS(segStart->x - query->x, segStart->y - query->y, segStart->z - query->z); CCVector3 QE(segEnd->x - query->x, segEnd->y - query->y, segEnd->z - query->z); //is angle between these vectors obtuce (i.e. QS dot QE) < 0)? If so we are inside a circle between start&end, otherwise we are not QS.normalize();QE.normalize(); return QS.dot(QE) < 0; } bool ccTrace::optimizePath(int maxIterations) { bool success = true; if (m_waypoints.size() < 2) { m_trace.clear(); return false; //no segments... } #ifdef DEBUG_PATH int idx = m_cloud->getScalarFieldIndexByName("Search"); //look for scalar field to write search to if (idx == -1) //doesn't exist - create idx=m_cloud->addScalarField("Search"); m_cloud->setCurrentScalarField(idx); #endif //update stored cost function etc. updateMetadata(); //update internal vars m_maxIterations = maxIterations; //loop through segments and build/rebuild trace int start, end, tID; //declare vars for (unsigned i = 1; i < m_waypoints.size(); i++) { //calculate indices start = m_waypoints[i - 1]; //global point id for the start waypoint end = m_waypoints[i]; //global point id for the end waypoint tID = i - 1; //id of the trace segment id (in m_trace vector) //are we adding to the end of the trace? if (tID >= m_trace.size()) { std::deque<int> segment = optimizeSegment(start, end, m_search_r); //calculate segment m_trace.push_back(segment); //store segment success = success && !segment.empty(); //if the queue is empty, we failed } else //no... we're somewhere in the middle - update segment if necessary { if (!m_trace[tID].empty() && (m_trace[tID][0] == start) && (m_trace[tID][m_trace[tID].size() - 1] == end)) //valid trace and start/end match continue; //this trace has already been calculated - we can skip! :) else { //calculate segment std::deque<int> segment = optimizeSegment(start, end, m_search_r); //calculate segment success = success && !segment.empty(); //if the queue is empty, we failed //add trace if (m_trace[tID][m_trace[tID].size() - 1] == end) //end matches - we can replace the current trace & things should be sweet (all prior traces will have been updated already) m_trace[tID] = segment; //end is correct - overwrite this block, then hopefully we will match in the next one else //end doesn't match - we need to insert m_trace.insert(m_trace.begin()+tID, segment); } } } #ifdef DEBUG_PATH CCLib::ScalarField * f = m_cloud->getScalarField(idx); f->computeMinAndMax(); #endif //write control points to property (for reloading) QVariantMap* map = new QVariantMap(); QString waypoints = ""; for (unsigned i = 0; i < m_waypoints.size(); i++) { waypoints += QString::number(m_waypoints[i]) + ","; } map->insert("waypoints", waypoints); setMetaData(*map, true); //push points onto underlying polyline object (for picking & save/load) finalizePath(); return success; } void ccTrace::finalizePath() { //clear existing points in background "polyline" clear(); //push trace buffer to said polyline (for save/export etc.) for (std::deque<int> seg : m_trace) { for (int p : seg) { addPointIndex(p); } } //invalidate bb invalidateBoundingBox(); } void ccTrace::recalculatePath() { m_trace.clear(); optimizePath(); } int ccTrace::COST_MODE = ccTrace::MODE::DARK; //set default cost mode std::deque<int> ccTrace::optimizeSegment(int start, int end, int offset) { //check handle to point cloud if (!m_cloud) { return std::deque<int>(); //error -> no cloud } //retrieve and store start & end rgb if (m_cloud->hasColors()) { const ColorCompType* s = m_cloud->getPointColor(start); const ColorCompType* e = m_cloud->getPointColor(end); m_start_rgb[0] = s[0]; m_start_rgb[1] = s[1]; m_start_rgb[2] = s[2]; m_end_rgb[0] = e[0]; m_end_rgb[1] = e[1]; m_end_rgb[2] = e[2]; } else { //no colour... set to 0 just in case something tries to use these vars m_start_rgb[0] = 0; m_start_rgb[1] = 0; m_start_rgb[2] = 0; m_end_rgb[0] = 0; m_end_rgb[1] = 0; m_end_rgb[2] = 0; } //get location of target node - used to optimise algorithm to stop searching paths leading away from the target const CCVector3* end_v = m_cloud->getPoint(end); //code essentially taken from wikipedia page for Djikstra: https://en.wikipedia.org/wiki/Dijkstra%27s_algorithm std::vector<bool> visited; //an array of bits to check if node has been visited std::priority_queue<Node*,std::vector<Node*>,Compare> openQueue; //priority queue that stores nodes that haven't yet been explored/opened std::vector<Node*> nodes; //list of visited nodes. Used to cleanup memory after re-constructing shortest path. //set size of visited such that there is one bit per point in the cloud visited.resize(m_cloud->size(), false); //n.b. for 400 million points, this will still only be ~50Mb =) //declare variables used in the loop Node* current = nullptr; int current_idx = 0; int cost = 0; int smallest_cost = 999999; int iter_count = 0; float cur_d2, next_d2; //setup buffer for storing nodes int bufferSize = 500000; //500k node buffer (~1.5-2Mb). This should be enough for most small-medium size traces. More buffers will be created for bigger ones. Node* node_buffer = new Node[bufferSize]; nodes.push_back(node_buffer); //store buffer in nodes list (for cleanup) int nodeCount = 1; //start node will be added shortly //setup octree & values for nearest neighbour searches ccOctree::Shared oct = m_cloud->getOctree(); if (!oct) { oct = m_cloud->computeOctree(); //if the user clicked "no" when asked to compute the octree then tough.... } unsigned char level = oct->findBestLevelForAGivenNeighbourhoodSizeExtraction(m_search_r); //initialize start node on node_buffer and add to openQueue node_buffer[0].set(start, 0, nullptr); openQueue.push(&node_buffer[0]); //mark start node as visited visited[start] = true; while (openQueue.size() > 0) //while unvisited nodes exist { //check if we excede max iterations if (iter_count > m_maxIterations) { //cleanup buffers for (Node* n : nodes) { delete[] n; } //bail return std::deque<int>(); //bail } iter_count++; //get lowest cost node for expansion current = openQueue.top(); current_idx = current->index; //remove node from open set openQueue.pop(); //remove node from open set (queue) if (current_idx == end) //we've found it! { std::deque<int> path; path.push_back(end); //add end node //traverse backwards to reconstruct path while (current->index != start) { current = current->previous; path.push_front(current->index); } path.push_front(start); //cleanup node buffers for (Node* n : nodes) { delete[] n; } //return return path; } //calculate distance from current nodes parent to end -> avoid going backwards (in euclidean space) [essentially stops fracture turning > 90 degrees) const CCVector3* cur = m_cloud->getPoint(current_idx); cur_d2 = (cur->x - end_v->x)*(cur->x - end_v->x) + (cur->y - end_v->y)*(cur->y - end_v->y) + (cur->z - end_v->z)*(cur->z - end_v->z); //fill "neighbours" with nodes - essentially get results of a "sphere" search around active current point m_neighbours.clear(); oct->getPointsInSphericalNeighbourhood(*cur, PointCoordinateType(m_search_r), m_neighbours, level); //loop through neighbours for (size_t i = 0; i < m_neighbours.size(); i++) { m_p = m_neighbours[i]; if (visited[m_p.pointIndex]) //Has this node been visited before? If so then bail. continue; //calculate (squared) distance from this neighbour to the end next_d2 = (m_p.point->x - end_v->x)*(m_p.point->x - end_v->x) + (m_p.point->y - end_v->y)*(m_p.point->y - end_v->y) + (m_p.point->z - end_v->z)*(m_p.point->z - end_v->z); if (next_d2 >= cur_d2) //Bigger than the original distance? If so then bail. continue; //calculate cost to this neighbour cost = getSegmentCost(current_idx, m_p.pointIndex); #ifdef DEBUG_PATH m_cloud->setPointScalarValue(m_p.pointIndex, static_cast<ScalarType>(cost)); //STORE VISITED NODES (AND COST) FOR DEBUG VISUALISATIONS #endif //transform into cost from start node cost += current->total_cost; //check that the node buffer isn't full if (nodeCount == bufferSize) { //buffer is full - create a new one node_buffer = new Node[bufferSize]; nodes.push_back(node_buffer); nodeCount = 0; } //initialize node on node buffer node_buffer[nodeCount].set(m_p.pointIndex, cost, current); //push node to open set openQueue.push(&node_buffer[nodeCount]); //we now have one more node nodeCount++; //mark node as visited visited[m_p.pointIndex] = true; } } assert(false); return std::deque<int>(); //shouldn't come here? } int ccTrace::getSegmentCost(int p1, int p2) { int cost=1; //n.b. default value is 1 so that if no cost functions are used, the function doesn't crash (and returns the unweighted shortest path) if (m_cloud->hasColors()) //check cloud has colour data { if (COST_MODE & MODE::RGB) cost += getSegmentCostRGB(p1, p2); if (COST_MODE & MODE::DARK) cost += getSegmentCostDark(p1, p2); if (COST_MODE & MODE::LIGHT) cost += getSegmentCostLight(p1, p2); if (COST_MODE & MODE::GRADIENT) cost += getSegmentCostGrad(p1, p2, m_search_r); } if (m_cloud->hasDisplayedScalarField()) //check cloud has scalar field data { if (COST_MODE & MODE::SCALAR) cost += getSegmentCostScalar(p1, p2); if (COST_MODE & MODE::INV_SCALAR) cost += getSegmentCostScalarInv(p1, p2); } //these cost functions can be used regardless if (COST_MODE & MODE::CURVE) cost += getSegmentCostCurve(p1, p2); if (COST_MODE & MODE::DISTANCE) cost += getSegmentCostDist(p1, p2); return cost; } int ccTrace::getSegmentCostRGB(int p1, int p2) { //get colors const ColorCompType* p1_rgb = m_cloud->getPointColor(p1); const ColorCompType* p2_rgb = m_cloud->getPointColor(p2); //cost function: cost = |c1-c2| + 0.25 ( |c1-start| + |c1-end| + |c2-start| + |c2-end| ) //IDEA: can we somehow optimize all the square roots here (for speed)? return sqrt( //|c1-c2| (p1_rgb[0] - p2_rgb[0]) * (p1_rgb[0] - p2_rgb[0]) + (p1_rgb[1] - p2_rgb[1]) * (p1_rgb[1] - p2_rgb[1]) + (p1_rgb[2] - p2_rgb[2]) * (p1_rgb[2] - p2_rgb[2])) + 0.25 * ( //|c1-start| sqrt((p1_rgb[0] - m_start_rgb[0]) * (p1_rgb[0] - m_start_rgb[0]) + (p1_rgb[1] - m_start_rgb[1]) * (p1_rgb[1] - m_start_rgb[1]) + (p1_rgb[2] - m_start_rgb[2]) * (p1_rgb[2] - m_start_rgb[2])) + //|c1-end| sqrt((p1_rgb[0] - m_end_rgb[0]) * (p1_rgb[0] - m_end_rgb[0]) + (p1_rgb[1] - m_end_rgb[1]) * (p1_rgb[1] - m_end_rgb[1]) + (p1_rgb[2] - m_end_rgb[2]) * (p1_rgb[2] - m_end_rgb[2])) + //|c2-start| sqrt((p2_rgb[0] - m_start_rgb[0]) * (p2_rgb[0] - m_start_rgb[0]) + (p2_rgb[1] - m_start_rgb[1]) * (p2_rgb[1] - m_start_rgb[1]) + (p2_rgb[2] - m_start_rgb[2]) * (p2_rgb[2] - m_start_rgb[2])) + //|c2-end| sqrt((p2_rgb[0] - m_end_rgb[0]) * (p2_rgb[0] - m_end_rgb[0]) + (p2_rgb[1] - m_end_rgb[1]) * (p2_rgb[1] - m_end_rgb[1]) + (p2_rgb[2] - m_end_rgb[2]) * (p2_rgb[2] - m_end_rgb[2]))) / 3.5; //N.B. the divide by 3.5 scales this cost function to range between 0 & 255 } int ccTrace::getSegmentCostDark(int p1, int p2) { //return magnitude of the point p2 //const ColorCompType* p1_rgb = m_cloud->getPointColor(p1); const ColorCompType* p2_rgb = m_cloud->getPointColor(p2); //return "taxi-cab" length return (p2_rgb[0] + p2_rgb[1] + p2_rgb[2]); //note: this will naturally give a maximum of 765 (=255 + 255 + 255) } int ccTrace::getSegmentCostLight(int p1, int p2) { //return the opposite of getCostDark return 765 - getSegmentCostDark(p1, p2); } int ccTrace::getSegmentCostCurve(int p1, int p2) { int idx = m_cloud->getScalarFieldIndexByName("Curvature"); //look for pre-existing gradient SF if (isCurvaturePrecomputed()) //scalar field found - return from precomputed cost] { //activate SF m_cloud->setCurrentScalarField(idx); //return inverse of p2 value return m_cloud->getScalarField(idx)->getMax() - m_cloud->getPointScalarValue(p2); } else //scalar field not found - do slow calculation... { //put neighbourhood in a CCLib::Neighbourhood structure if (m_neighbours.size() > 4) //need at least 4 points to calculate curvature.... { m_neighbours.push_back(m_p); //add center point onto end of neighbourhood //compute curvature CCLib::DgmOctreeReferenceCloud nCloud(&m_neighbours, static_cast<unsigned>(m_neighbours.size())); CCLib::Neighbourhood Z(&nCloud); float c = Z.computeCurvature(0, CCLib::Neighbourhood::CC_CURVATURE_TYPE::MEAN_CURV); m_neighbours.erase(m_neighbours.end()-1); //remove center point from neighbourhood (so as not to screw up loops) //curvature tends to range between 0 (high cost) and 10 (low cost), though it can be greater than 10 in extreme cases //hence we need to map to domain 0 - 10 and then transform that to the (integer) domain 0 - 884 to meet the cost function spec if (c > 10) c = 10; //scale curvature to range 0, 765 c *= 76.5; //note that high curvature = low cost, hence subtract curvature from 765 return 765 - c; } return 765; //unknown curvature - this point is high cost. } } int ccTrace::getSegmentCostGrad(int p1, int p2, float search_r) { int idx = m_cloud->getScalarFieldIndexByName("Gradient"); //look for pre-existing gradient SF if (idx != -1) //found precomputed gradient { //activate SF m_cloud->setCurrentScalarField(idx); //return inverse of p2 value return m_cloud->getScalarField(idx)->getMax() - m_cloud->getPointScalarValue(p2); } else //not found... do expensive calculation { CCVector3 p = *m_cloud->getPoint(p2); const ColorCompType* p2_rgb = m_cloud->getPointColor(p2); int p_value = p2_rgb[0] + p2_rgb[1] + p2_rgb[2]; if (m_neighbours.size() > 2) //need at least 2 points to calculate gradient.... { //N.B. The following code is mostly stolen from the computeGradient function in CloudCompare CCVector3d sum(0, 0, 0); CCLib::DgmOctree::PointDescriptor n; for (int i = 0; i < m_neighbours.size(); i++) { n = m_neighbours[i]; //vector from p1 to m_p CCVector3 deltaPos = *n.point - p; double norm2 = deltaPos.norm2d(); //colour const ColorCompType* c = m_cloud->getPointColor(n.pointIndex); int c_value = c[0] + c[1] + c[2]; //calculate gradient weighted by distance to the point (i.e. divide by distance^2) if (norm2 > ZERO_TOLERANCE) { //color magnitude difference int deltaValue = p_value - c_value; //divide by norm^2 to get distance-weighted gradient deltaValue /= norm2; //we divide by 'norm' to get the normalized direction, and by 'norm' again to get the gradient (hence we use the squared norm) //sum stuff sum.x += deltaPos.x * deltaValue; //warning: here 'deltaValue'= deltaValue / squaredNorm(deltaPos) ;) sum.y += deltaPos.y * deltaValue; sum.z += deltaPos.z * deltaValue; } } float gradient = sum.norm() / m_neighbours.size(); //ensure gradient is lass than a case-specific maximum gradient (colour change from white to black across a distance or search_r, // giving a gradient of (255+255+255) / search_r) gradient = std::min(gradient, 765 / search_r); gradient *= search_r; //scale between 0 and 765 return 765 - gradient; //return inverse gradient (high gradient = low cost) } return 765; //no gradient = high cost } } int ccTrace::getSegmentCostDist(int p1, int p2) { return 255; } int ccTrace::getSegmentCostScalar(int p1, int p2) { //m_cloud->getCurrentDisplayedScalarFieldIndex(); ccScalarField* sf = static_cast<ccScalarField*>(m_cloud->getCurrentDisplayedScalarField()); return (sf->getValue(p2)-sf->getMin()) * (765 / (sf->getMax()-sf->getMin())); //return scalar field value mapped to range 0 - 765 } int ccTrace::getSegmentCostScalarInv(int p1, int p2) { ccScalarField* sf = static_cast<ccScalarField*>(m_cloud->getCurrentDisplayedScalarField()); return (sf->getMax() - sf->getValue(p2)) * (765 / (sf->getMax() - sf->getMin())); //return inverted scalar field value mapped to range 0 - 765 } //functions for calculating cost SFs void ccTrace::buildGradientCost(QWidget* parent) { //is there already a gradient SF? if (isGradientPrecomputed()) //already done :) return; //create new SF for greyscale int idx = m_cloud->addScalarField("Greyscale"); m_cloud->setCurrentScalarField(idx); //make colours greyscale and push to SF (otherwise copy active SF) for (unsigned i = 0; i < m_cloud->size(); i++) { m_cloud->setPointScalarValue(i, static_cast<ScalarType>(m_cloud->getPointColor(i)[0] + m_cloud->getPointColor(i)[1] + m_cloud->getPointColor(i)[2])); } //compute min/max m_cloud->getScalarField(idx)->computeMinAndMax(); //calculate new SF with gradient of the old one float roughnessKernelSize = m_search_r; m_cloud->setCurrentOutScalarField(idx); //set out gradient field - values are read from here for calc //make gradient sf int gIdx = m_cloud->addScalarField("Gradient"); m_cloud->setCurrentInScalarField(gIdx); //set in scalar field - gradient is written here //get/build octree ccProgressDialog* pDlg = new ccProgressDialog(true , parent); pDlg->show(); ccOctree::Shared octree = m_cloud->getOctree(); if (!octree) { octree = m_cloud->computeOctree(pDlg); } //calculate gradient int result = CCLib::ScalarFieldTools::computeScalarFieldGradient(m_cloud, m_search_r, //auto --> FIXME: should be properly set by the user! false, false, pDlg, octree.data()); pDlg->close(); delete pDlg; //calculate bounds m_cloud->getScalarField(gIdx)->computeMinAndMax(); //normalize and log-transform m_cloud->setCurrentScalarField(gIdx); float logMax = log(m_cloud->getScalarField(gIdx)->getMax() + 10); for (unsigned i = 0; i < m_cloud->size(); i++) { int nVal = 765 * log(m_cloud->getPointScalarValue(i) + 10) / logMax; if (nVal < 0) //this is caused by isolated points that were assigned "null" value gradients nVal = 1; //set to low gradient by default m_cloud->setPointScalarValue(i, nVal); } //recompute min-max... m_cloud->getScalarField(gIdx)->computeMinAndMax(); } void ccTrace::buildCurvatureCost(QWidget* parent) { if (isCurvaturePrecomputed()) //already done return; //create curvature SF //make gradient sf int idx = m_cloud->addScalarField("Curvature"); m_cloud->setCurrentInScalarField(idx); //set in scalar field - curvature is written here m_cloud->setCurrentScalarField(idx); //get/build octree ccProgressDialog* pDlg = new ccProgressDialog(true, parent); pDlg->show(); ccOctree::Shared octree = m_cloud->getOctree(); if (!octree) { octree = m_cloud->computeOctree(pDlg); } //calculate curvature int result = CCLib::GeometricalAnalysisTools::computeCurvature(m_cloud, CCLib::Neighbourhood::CC_CURVATURE_TYPE::MEAN_CURV, m_search_r, pDlg, octree.data()); pDlg->close(); delete pDlg; //calculate minmax m_cloud->getScalarField(idx)->computeMinAndMax(); //normalize and log-transform float logMax = log(m_cloud->getScalarField(idx)->getMax() + 10); for (unsigned i = 0; i < m_cloud->size(); i++) { int nVal = 765 * log(m_cloud->getPointScalarValue(i) + 10) / logMax; if (nVal < 0) //this is caused by isolated points that were assigned "null" value curvatures nVal = 1; //set to low gradient by default m_cloud->setPointScalarValue(i, nVal); } //recompute min-max... m_cloud->getScalarField(idx)->computeMinAndMax(); } bool ccTrace::isGradientPrecomputed() { int idx = m_cloud->getScalarFieldIndexByName("Gradient"); //look for pre-existing gradient SF return idx != -1; //was something found? } bool ccTrace::isCurvaturePrecomputed() { int idx = m_cloud->getScalarFieldIndexByName("Curvature"); //look for pre-existing gradient SF return idx != -1; //was something found? } ccFitPlane* ccTrace::fitPlane(int surface_effect_tolerance, float min_planarity) { //put all "trace" points into the cloud finalizePath(); if (size() < 3) return 0; //need three points to fit a plane //check we are not trying to fit a plane to a line CCLib::Neighbourhood Z(this); //calculate eigenvalues of neighbourhood CCLib::SquareMatrixd cov = Z.computeCovarianceMatrix(); CCLib::SquareMatrixd eigVectors; std::vector<double> eigValues; if (Jacobi<double>::ComputeEigenValuesAndVectors(cov, eigVectors, eigValues, true)) { //sort eigenvalues into decending order std::sort(eigValues.rbegin(), eigValues.rend()); float y = eigValues[1]; //middle eigen float z = eigValues[2]; //smallest eigen (parallel to plane normal) //calculate planarity (0 = line or random, 1 = plane) float planarity = 1.0f - z / y; if (planarity < min_planarity) { return nullptr; } } //fit plane double rms = 0.0; //output for rms ccFitPlane* p = ccFitPlane::Fit(this, &rms); if (!p) { return nullptr; //return null for invalid planes } p->updateAttributes(rms, m_search_r); //test for 'surface effect' if (m_cloud->hasNormals()) { //calculate average normal of points on trace CCVector3 n_avg; for (unsigned i = 0; i < size(); i++) { //get normal vector CCVector3 n = ccNormalVectors::GetNormal(m_cloud->getPointNormalIndex(this->getPointGlobalIndex(i))); n_avg += n; } n_avg *= (PC_ONE / size()); //turn sum into average //compare to plane normal CCVector3 n = p->getNormal(); if (acos(n_avg.dot(n)) < 0.01745329251*surface_effect_tolerance) //0.01745329251 converts deg to rad { //this is a false (surface) plane - reject return 0; //don't return plane } } //all is good! Return the plane :) return p; } void ccTrace::bakePathToScalarField() { //bake points int vertexCount = static_cast<int>(m_cloud->size()); for (const std::deque<int>& seg : m_trace) { for (int p : seg) { if (p >= 0 && p < vertexCount) { m_cloud->setPointScalarValue(static_cast<unsigned>(p), getUniqueID()); } } } } float ccTrace::calculateOptimumSearchRadius() { CCLib::DgmOctree::NeighboursSet neighbours; //setup octree & values for nearest neighbour searches ccOctree::Shared oct = m_cloud->getOctree(); if (!oct) { oct = m_cloud->computeOctree(); //if the user clicked "no" when asked to compute the octree then tough.... } //init vars needed for nearest neighbour search unsigned char level = oct->findBestLevelForAGivenPopulationPerCell(2); CCLib::ReferenceCloud* nCloud = new CCLib::ReferenceCloud(m_cloud); //pick 15 random points unsigned int npoints = m_cloud->size(); double dsum = 0; srand(npoints); //set seed as n for repeatability for (unsigned int i = 0; i < 30; i++) { //int rn = rand() * rand(); //need to make bigger than rand max... int r = (rand()*rand()) % npoints; //random(ish) number between 0 and n //find nearest neighbour for point nCloud->clear(false); double d = -1.0; oct->findPointNeighbourhood(m_cloud->getPoint(r), nCloud, 2, level, d); if (d != -1.0) //if a point was found { dsum += sqrt(d); } } //average nearest-neighbour distances double d = dsum / 30; //return a number slightly larger than the average distance return d * 1.5; } static QSharedPointer<ccSphere> c_unitPointMarker(0); void ccTrace::drawMeOnly(CC_DRAW_CONTEXT& context) { if (!MACRO_Foreground(context)) //2D foreground only return; //do nothing if (MACRO_Draw3D(context)) { if (m_waypoints.empty()) //no points -> bail! return; //get the set of OpenGL functions (version 2.1) QOpenGLFunctions_2_1 *glFunc = context.glFunctions<QOpenGLFunctions_2_1>(); if (glFunc == nullptr) { assert(false); return; } //check sphere exists if (!c_unitPointMarker) { c_unitPointMarker = QSharedPointer<ccSphere>(new ccSphere(1.0f, 0, "PointMarker", 6)); c_unitPointMarker->showColors(true); c_unitPointMarker->setVisible(true); c_unitPointMarker->setEnabled(true); c_unitPointMarker->showNormals(false); } glDrawParams glParams; getDrawingParameters(glParams); //not sure what this does, but it looks like fun CC_DRAW_CONTEXT markerContext = context; //build-up point maker own 'context' markerContext.display = 0; markerContext.drawingFlags &= (~CC_DRAW_ENTITY_NAMES); //we must remove the 'push name flag' so that the sphere doesn't push its own! //get camera info ccGLCameraParameters camera; glFunc->glGetIntegerv(GL_VIEWPORT, camera.viewport); glFunc->glGetDoublev(GL_PROJECTION_MATRIX, camera.projectionMat.data()); glFunc->glGetDoublev(GL_MODELVIEW_MATRIX, camera.modelViewMat.data()); const ccViewportParameters& viewportParams = context.display->getViewportParameters(); //push name for picking bool pushName = MACRO_DrawEntityNames(context); if (pushName) { glFunc->glPushName(getUniqueIDForDisplay()); //minimal display for picking mode! glParams.showNorms = false; glParams.showColors = false; } //set draw colour ccColor::Rgba color = getMeasurementColour(); c_unitPointMarker->setTempColor(color); //get point size for drawing float pSize; glFunc->glGetFloatv(GL_POINT_SIZE, &pSize); //draw key-points if (m_isActive) { for (size_t i = 0; i < m_waypoints.size(); i++) { glFunc->glMatrixMode(GL_MODELVIEW); glFunc->glPushMatrix(); const CCVector3* P = m_cloud->getPoint(m_waypoints[i]); ccGL::Translate(glFunc, P->x, P->y, P->z); float scale = context.labelMarkerSize * m_relMarkerScale * 0.3 * fmin(pSize,4); if (viewportParams.perspectiveView && viewportParams.zFar > 0) { //in perspective view, the actual scale depends on the distance to the camera! double d = (camera.modelViewMat * CCVector3d::fromArray(P->u)).norm(); double unitD = viewportParams.zFar / 2; //we consider that the 'standard' scale is at half the depth scale = static_cast<float>(scale * sqrt(d / unitD)); //sqrt = empirical (probably because the marker size is already partly compensated by ccGLWindow::computeActualPixelSize()) } glFunc->glScalef(scale, scale, scale); c_unitPointMarker->draw(markerContext); glFunc->glPopMatrix(); } } else //just draw lines { //draw lines for (const std::deque<int>& seg : m_trace) { if (m_width != 0) { glFunc->glPushAttrib(GL_LINE_BIT); glFunc->glLineWidth(static_cast<GLfloat>(m_width)); } glFunc->glBegin(GL_LINE_STRIP); glFunc->glColor3f(color.r, color.g, color.b); for (int p : seg) { ccGL::Vertex3v(glFunc, m_cloud->getPoint(p)->u); } glFunc->glEnd(); if (m_width != 0) { glFunc->glPopAttrib(); } } } //draw trace points if trace is active OR point size is large (otherwise line gets hidden) if (m_isActive || pSize > 8) { for (const std::deque<int>& seg : m_trace) { for (int p : seg) { glFunc->glMatrixMode(GL_MODELVIEW); glFunc->glPushMatrix(); const CCVector3* P = m_cloud->getPoint(p); ccGL::Translate(glFunc, P->x, P->y, P->z); float scale = context.labelMarkerSize * m_relMarkerScale * fmin(pSize, 4) * 0.2; if (viewportParams.perspectiveView && viewportParams.zFar > 0) { //in perspective view, the actual scale depends on the distance to the camera! const double* M = camera.modelViewMat.data(); double d = (camera.modelViewMat * CCVector3d::fromArray(P->u)).norm(); double unitD = viewportParams.zFar / 2; //we consider that the 'standard' scale is at half the depth scale = static_cast<float>(scale * sqrt(d / unitD)); //sqrt = empirical (probably because the marker size is already partly compensated by ccGLWindow::computeActualPixelSize()) } glFunc->glScalef(scale, scale, scale); c_unitPointMarker->draw(markerContext); glFunc->glPopMatrix(); } } } //finish picking name if (pushName) glFunc->glPopName(); } } bool ccTrace::isTrace(ccHObject* object) //return true if object is a valid trace [regardless of it's class type] { if (object->hasMetaData("ccCompassType")) { return object->getMetaData("ccCompassType").toString().contains("Trace"); } return false; }
31.688761
182
0.674488
[ "object", "vector", "transform" ]
22c0ec6949acfd0ef322f0198f123ecd93780882
2,448
cc
C++
linux/quick_usb_plugin.cc
ziakhan110/quick_usb
93a8505f278a351f36971b0ec248600a755aeaef
[ "BSD-3-Clause" ]
28
2021-02-17T04:11:10.000Z
2022-03-24T08:40:30.000Z
linux/quick_usb_plugin.cc
ziakhan110/quick_usb
93a8505f278a351f36971b0ec248600a755aeaef
[ "BSD-3-Clause" ]
34
2021-02-21T21:15:16.000Z
2022-03-24T11:23:22.000Z
linux/quick_usb_plugin.cc
ziakhan110/quick_usb
93a8505f278a351f36971b0ec248600a755aeaef
[ "BSD-3-Clause" ]
22
2021-04-07T06:22:37.000Z
2022-03-08T02:48:05.000Z
#include "include/quick_usb/quick_usb_plugin.h" #include <flutter_linux/flutter_linux.h> #include <gtk/gtk.h> #include <sys/utsname.h> #include <cstring> #define QUICK_USB_PLUGIN(obj) \ (G_TYPE_CHECK_INSTANCE_CAST((obj), quick_usb_plugin_get_type(), \ QuickUsbPlugin)) struct _QuickUsbPlugin { GObject parent_instance; }; G_DEFINE_TYPE(QuickUsbPlugin, quick_usb_plugin, g_object_get_type()) // Called when a method call is received from Flutter. static void quick_usb_plugin_handle_method_call( QuickUsbPlugin* self, FlMethodCall* method_call) { g_autoptr(FlMethodResponse) response = nullptr; const gchar* method = fl_method_call_get_name(method_call); if (strcmp(method, "getPlatformVersion") == 0) { struct utsname uname_data = {}; uname(&uname_data); g_autofree gchar *version = g_strdup_printf("Linux %s", uname_data.version); g_autoptr(FlValue) result = fl_value_new_string(version); response = FL_METHOD_RESPONSE(fl_method_success_response_new(result)); } else { response = FL_METHOD_RESPONSE(fl_method_not_implemented_response_new()); } fl_method_call_respond(method_call, response, nullptr); } static void quick_usb_plugin_dispose(GObject* object) { G_OBJECT_CLASS(quick_usb_plugin_parent_class)->dispose(object); } static void quick_usb_plugin_class_init(QuickUsbPluginClass* klass) { G_OBJECT_CLASS(klass)->dispose = quick_usb_plugin_dispose; } static void quick_usb_plugin_init(QuickUsbPlugin* self) {} static void method_call_cb(FlMethodChannel* channel, FlMethodCall* method_call, gpointer user_data) { QuickUsbPlugin* plugin = QUICK_USB_PLUGIN(user_data); quick_usb_plugin_handle_method_call(plugin, method_call); } void quick_usb_plugin_register_with_registrar(FlPluginRegistrar* registrar) { QuickUsbPlugin* plugin = QUICK_USB_PLUGIN( g_object_new(quick_usb_plugin_get_type(), nullptr)); g_autoptr(FlStandardMethodCodec) codec = fl_standard_method_codec_new(); g_autoptr(FlMethodChannel) channel = fl_method_channel_new(fl_plugin_registrar_get_messenger(registrar), "quick_usb", FL_METHOD_CODEC(codec)); fl_method_channel_set_method_call_handler(channel, method_call_cb, g_object_ref(plugin), g_object_unref); g_object_unref(plugin); }
34.478873
80
0.729984
[ "object" ]
42f09b1259a63629a2cae5bf9416027c06106090
1,187
cc
C++
vos/gui/sub/gui/file/ImageToReloadGlue.cc
NASA-AMMOS/VICAR
4504c1f558855d9c6eaef89f4460217aa4909f8e
[ "BSD-3-Clause" ]
16
2020-10-21T05:56:26.000Z
2022-03-31T10:02:01.000Z
vos/gui/sub/gui/file/ImageToReloadGlue.cc
NASA-AMMOS/VICAR
4504c1f558855d9c6eaef89f4460217aa4909f8e
[ "BSD-3-Clause" ]
null
null
null
vos/gui/sub/gui/file/ImageToReloadGlue.cc
NASA-AMMOS/VICAR
4504c1f558855d9c6eaef89f4460217aa4909f8e
[ "BSD-3-Clause" ]
2
2021-03-09T01:51:08.000Z
2021-03-23T00:23:24.000Z
//////////////////////////////////////////////////////////////////////// // ImageToReloadGlue: class that serves as a "glue" class between an // ImageData object and a ReloadFileCmd object. // // This class, though a UIComponent, creates no widget, and therefore // should never be managed. //////////////////////////////////////////////////////////////////////// #include "ImageToReloadGlue.h" #include "ImageData.h" #include "ReloadFileCmd.h" ImageToReloadGlue::ImageToReloadGlue (ImageData *model, Cmd *reloadFileCmd) : BasicImageView("glue", model) { _reloadFileCmd = reloadFileCmd; _model->attachView(this); } ImageToReloadGlue::~ImageToReloadGlue ( ) { // Detach itself from the model so that the are no more updates sent _model->detachView(this); } //////////////////////////////////////////////////////////////////////// // Whenever the image changes, reset the ReloadCmd interface. //////////////////////////////////////////////////////////////////////// void ImageToReloadGlue::update() { if(_model->isDataSourceOpened()) _reloadFileCmd->activate(); else _reloadFileCmd->deactivate(); } void ImageToReloadGlue::updatePart(int /* flags */) { }
31.236842
75
0.556024
[ "object", "model" ]
42f7d97c90aec7f01e698d6b9da09f0a51e34c20
2,660
cpp
C++
tests/regression_tests/dagmc/external/main.cpp
shimwell/openmc-1
edf913b80f5c80ee041bb0f950bf2239f0129df2
[ "MIT" ]
null
null
null
tests/regression_tests/dagmc/external/main.cpp
shimwell/openmc-1
edf913b80f5c80ee041bb0f950bf2239f0129df2
[ "MIT" ]
null
null
null
tests/regression_tests/dagmc/external/main.cpp
shimwell/openmc-1
edf913b80f5c80ee041bb0f950bf2239f0129df2
[ "MIT" ]
null
null
null
#include "openmc/capi.h" #include "openmc/cross_sections.h" #include "openmc/dagmc.h" #include "openmc/error.h" #include "openmc/geometry.h" #include "openmc/geometry_aux.h" #include "openmc/material.h" #include "openmc/nuclide.h" #include <iostream> int main(int argc, char* argv[]) { using namespace openmc; int openmc_err; // Initialise OpenMC openmc_err = openmc_init(argc, argv, nullptr); if (openmc_err == -1) { // This happens for the -h and -v flags return EXIT_SUCCESS; } else if (openmc_err) { fatal_error(openmc_err_msg); } // Create DAGMC ptr std::string filename = "dagmc.h5m"; std::shared_ptr<moab::DagMC> dag_ptr = std::make_shared<moab::DagMC>(); moab::ErrorCode rval = dag_ptr->load_file(filename.c_str()); if (rval != moab::MB_SUCCESS) { fatal_error("Failed to load file"); } // Initialize acceleration data structures rval = dag_ptr->init_OBBTree(); if (rval != moab::MB_SUCCESS) { fatal_error("Failed to initialise OBB tree"); } // Get rid of existing geometry std::unordered_map<std::string, int> nuclide_map_copy = openmc::data::nuclide_map; openmc::data::nuclides.clear(); openmc::data::nuclide_map = nuclide_map_copy; openmc::model::surfaces.clear(); openmc::model::surface_map.clear(); openmc::model::cells.clear(); openmc::model::cell_map.clear(); openmc::model::universes.clear(); openmc::model::universe_map.clear(); // Update materials (emulate an external program) for (auto& mat_ptr : openmc::model::materials) { mat_ptr->set_temperature(300); } // Create new DAGMC universe openmc::model::universes.push_back( std::make_unique<openmc::DAGUniverse>(dag_ptr)); model::universe_map[model::universes.back()->id_] = model::universes.size() - 1; // Add cells to universes openmc::populate_universes(); // Set root universe openmc::model::root_universe = openmc::find_root_universe(); openmc::check_dagmc_root_univ(); // Final geometry setup and assign temperatures openmc::finalize_geometry(); // Finalize cross sections having assigned temperatures openmc::finalize_cross_sections(); // Check that we correctly assigned cell temperatures with non-void fill for (auto& cell_ptr : openmc::model::cells) { if (cell_ptr->material_.front() != openmc::C_NONE && cell_ptr->temperature() != 300) { fatal_error("Failed to set cell temperature"); } } // Run OpenMC openmc_err = openmc_run(); if (openmc_err) fatal_error(openmc_err_msg); // Deallocate memory openmc_err = openmc_finalize(); if (openmc_err) fatal_error(openmc_err_msg); return EXIT_SUCCESS; }
28
74
0.697368
[ "geometry", "model" ]
42fd4a3d9c008e4aabc6058b1e9d19b9120068c1
975
cpp
C++
targets/TARGET_RDA/TARGET_UNO_91H/device/TOOLCHAIN_ARM_STD/sys.cpp
spiio/mbed-os
fde315a0ac8b87ba5986bc92b566980e6536cf37
[ "Apache-2.0" ]
8
2017-01-20T13:14:49.000Z
2020-10-22T01:12:40.000Z
targets/TARGET_RDA/TARGET_UNO_91H/device/TOOLCHAIN_ARM_STD/sys.cpp
engali94/mbed-os
d030c04a6039c832bfe1610efb8162e0807678d1
[ "Apache-2.0" ]
2
2018-07-11T13:42:22.000Z
2018-12-27T15:03:50.000Z
targets/TARGET_RDA/TARGET_UNO_91H/device/TOOLCHAIN_ARM_STD/sys.cpp
engali94/mbed-os
d030c04a6039c832bfe1610efb8162e0807678d1
[ "Apache-2.0" ]
5
2018-03-09T15:48:38.000Z
2020-10-22T01:12:44.000Z
/* mbed Microcontroller Library - stackheap * Copyright (C) 2009-2018 ARM Limited. All rights reserved. * * Setup a fixed single stack/heap memory model, * between the top of the RW/ZI region and the stackpointer */ #ifdef __cplusplus extern "C" { #endif #if defined(__ARMCC_VERSION) && (__ARMCC_VERSION >= 6010050) #include <arm_compat.h> #endif #include <rt_misc.h> #include <stdint.h> extern char Image$$ARM_LIB_HEAP$$ZI$$Base[]; extern char Image$$ARM_LIB_HEAP$$ZI$$Length[]; extern __value_in_regs struct __initial_stackheap _mbed_user_setup_stackheap(uint32_t R0, uint32_t R1, uint32_t R2, uint32_t R3) { uint32_t hp_base = (uint32_t)Image$$ARM_LIB_HEAP$$ZI$$Base; uint32_t hp_limit = (uint32_t)Image$$ARM_LIB_HEAP$$ZI$$Length + hp_base; struct __initial_stackheap r; hp_base = (hp_base + 7) & ~0x7; // ensure hp_base is 8-byte aligned r.heap_base = hp_base; r.heap_limit = hp_limit; return r; } #ifdef __cplusplus } #endif
26.351351
128
0.724103
[ "model" ]
42fdc26bf393a43aecc43e5beb5fedd96ca96900
1,352
cpp
C++
Engine/ResourceManagement/Manager/MeshManager.cpp
mariofv/LittleEngine
38ecfdf6041a24f304c679ee3b6b589ba2040e48
[ "MIT" ]
9
2020-04-05T07:44:38.000Z
2022-01-12T02:07:14.000Z
Engine/ResourceManagement/Manager/MeshManager.cpp
mariofv/LittleEngine
38ecfdf6041a24f304c679ee3b6b589ba2040e48
[ "MIT" ]
105
2020-03-13T19:12:23.000Z
2020-12-02T23:41:15.000Z
Engine/ResourceManagement/Manager/MeshManager.cpp
mariofv/LittleEngine
38ecfdf6041a24f304c679ee3b6b589ba2040e48
[ "MIT" ]
1
2021-04-24T16:11:49.000Z
2021-04-24T16:11:49.000Z
#include "MeshManager.h" #include "Helper/Timer.h" #include "Main/Application.h" #include "Module/ModuleFileSystem.h" #include "Module/ModuleResourceManager.h" #include "ResourceManagement/Metafile/Metafile.h" #include "ResourceManagement/Resources/Mesh.h" #include <Brofiler/Brofiler.h> #include <vector> Timer MeshManager::timer = Timer(); std::shared_ptr<Mesh> MeshManager::Load(uint32_t uuid, const FileData& resource_data, bool async) { BROFILER_CATEGORY("Load Mesh Manager", Profiler::Color::PaleGoldenRod); timer.Start(); char * data = (char*)resource_data.buffer; char* cursor = data; uint32_t ranges[2]; //Get ranges size_t bytes = sizeof(ranges); // First store ranges memcpy(ranges, cursor, bytes); std::vector<uint32_t> indices; std::vector<Mesh::Vertex> vertices; indices.resize(ranges[0]); cursor += bytes; // Get indices bytes = sizeof(uint32_t) * ranges[0]; memcpy(&indices.front(), cursor, bytes); vertices.resize(ranges[1]); cursor += bytes; // Get vertices bytes = sizeof(Mesh::Vertex) * ranges[1]; memcpy(&vertices.front(), cursor, bytes); std::shared_ptr<Mesh> new_mesh = std::make_shared<Mesh>(uuid, std::move(vertices), std::move(indices), async); float time = timer.Stop(); App->resources->time_loading_meshes += time; APP_LOG_INFO("MESH DATA WAS LOADED IN: %.3f", time); return new_mesh; }
26.509804
111
0.725592
[ "mesh", "vector" ]
6e09ece812682d4d2aac8f2d6258291f8b551f9d
3,687
cpp
C++
samples/snippets/cpp/VS_Snippets_Remoting/HttpBinding_HttpBinding/CPP/httpbinding_ctor.cpp
BaruaSourav/docs
c288ed777de6b091f5e074d3488f7934683f3eb5
[ "CC-BY-4.0", "MIT" ]
3,294
2016-10-30T05:27:20.000Z
2022-03-31T15:59:30.000Z
samples/snippets/cpp/VS_Snippets_Remoting/HttpBinding_HttpBinding/CPP/httpbinding_ctor.cpp
BaruaSourav/docs
c288ed777de6b091f5e074d3488f7934683f3eb5
[ "CC-BY-4.0", "MIT" ]
16,739
2016-10-28T19:41:29.000Z
2022-03-31T22:38:48.000Z
samples/snippets/cpp/VS_Snippets_Remoting/HttpBinding_HttpBinding/CPP/httpbinding_ctor.cpp
BaruaSourav/docs
c288ed777de6b091f5e074d3488f7934683f3eb5
[ "CC-BY-4.0", "MIT" ]
6,701
2016-10-29T20:56:11.000Z
2022-03-31T12:32:26.000Z
// System.Web.Services.Description.HttpBinding.HttpBinding() // System.Web.Services.Description.HttpBinding.Namespace // System.Web.Services.Description.HttpAddressBinding.HttpAddressBinding() /* The following program demonstrates the constructor, field 'Namespace' of class 'HttpBinding' and constructor of class 'HttpAddressBinding'. This program writes all 'HttpPost' binding related information to the input wsdl file and genrates an output file which is later on compiled using wsdl tool. */ #using <System.Xml.dll> #using <System.Web.Services.dll> #using <System.dll> using namespace System; using namespace System::Web::Services::Description; using namespace System::Collections; using namespace System::Xml; int main() { ServiceDescription^ myDescription = ServiceDescription::Read( "HttpBinding_ctor_Input_CPP.wsdl" ); // <Snippet1> // <Snippet2> // Create 'Binding' object. Binding^ myBinding = gcnew Binding; myBinding->Name = "MyHttpBindingServiceHttpPost"; XmlQualifiedName^ qualifiedName = gcnew XmlQualifiedName( "s0:MyHttpBindingServiceHttpPost" ); myBinding->Type = qualifiedName; // Create 'HttpBinding' object. HttpBinding^ myHttpBinding = gcnew HttpBinding; myHttpBinding->Verb = "POST"; Console::WriteLine( "HttpBinding Namespace : {0}", HttpBinding::Namespace ); // </Snippet2> // Add 'HttpBinding' to 'Binding'. myBinding->Extensions->Add( myHttpBinding ); // </Snippet1> // Create 'OperationBinding' object. OperationBinding^ myOperationBinding = gcnew OperationBinding; myOperationBinding->Name = "AddNumbers"; HttpOperationBinding^ myOperation = gcnew HttpOperationBinding; myOperation->Location = "/AddNumbers"; // Add 'HttpOperationBinding' to 'OperationBinding'. myOperationBinding->Extensions->Add( myOperation ); // Create 'InputBinding' object. InputBinding^ myInput = gcnew InputBinding; MimeContentBinding^ postMimeContentbinding = gcnew MimeContentBinding; postMimeContentbinding->Type = "application/x-www-form-urlencoded"; myInput->Extensions->Add( postMimeContentbinding ); // Add 'InputBinding' to 'OperationBinding'. myOperationBinding->Input = myInput; // Create 'OutputBinding' object. OutputBinding^ myOutput = gcnew OutputBinding; MimeXmlBinding^ postMimeXmlbinding = gcnew MimeXmlBinding; postMimeXmlbinding->Part = "Body"; myOutput->Extensions->Add( postMimeXmlbinding ); // Add 'OutPutBinding' to 'OperationBinding'. myOperationBinding->Output = myOutput; // Add 'OperationBinding' to 'Binding'. myBinding->Operations->Add( myOperationBinding ); // Add 'Binding' to 'BindingCollection' of 'ServiceDescription'. myDescription->Bindings->Add( myBinding ); // <Snippet3> // Create a 'Port' object. Port^ postPort = gcnew Port; postPort->Name = "MyHttpBindingServiceHttpPost"; postPort->Binding = gcnew XmlQualifiedName( "s0:MyHttpBindingServiceHttpPost" ); // Create 'HttpAddressBinding' object. HttpAddressBinding^ postAddressBinding = gcnew HttpAddressBinding; postAddressBinding->Location = "http://localhost/HttpBinding_ctor/HttpBinding_ctor_Service.cs.asmx"; // Add 'HttpAddressBinding' to 'Port'. postPort->Extensions->Add( postAddressBinding ); // </Snippet3> // Add 'Port' to 'PortCollection' of 'ServiceDescription'. myDescription->Services[ 0 ]->Ports->Add( postPort ); // Write 'ServiceDescription' as a WSDL file. myDescription->Write( "HttpBinding_ctor_Output_CPP.wsdl" ); Console::WriteLine( "WSDL file with name 'HttpBinding_ctor_Output_CPP.wsdl' file created Successfully" ); }
39.223404
239
0.73393
[ "object" ]
6e0ce9b5b3715da901f3cb55211d755aa92d18fc
4,728
cpp
C++
third_party/librealsense/examples/cpp-headless.cpp
BeibeiShu/hand_tracking
3ac817dbed558a56fb3088cd384376aeea45cfb7
[ "Apache-2.0" ]
207
2017-08-02T02:13:00.000Z
2022-02-22T09:18:10.000Z
disposing/librealsense/examples/cpp-headless.cpp
i-am-neet/wrs2020
3b388eac6832f2559c59fa0c1f7732589c5eff0c
[ "MIT" ]
14
2017-08-07T22:31:13.000Z
2021-07-09T10:29:36.000Z
disposing/librealsense/examples/cpp-headless.cpp
i-am-neet/wrs2020
3b388eac6832f2559c59fa0c1f7732589c5eff0c
[ "MIT" ]
82
2017-08-02T01:23:13.000Z
2022-02-10T02:45:51.000Z
// License: Apache 2.0. See LICENSE file in root directory. // Copyright(c) 2015 Intel Corporation. All Rights Reserved. /////////////////// // cpp-headless // /////////////////// // This sample captures 30 frames and writes the last frame to disk. // It can be useful for debugging an embedded system with no display. #include <librealsense/rs.hpp> #include <cstdio> #include <stdint.h> #include <vector> #include <map> #include <limits> #include <iostream> #define STB_IMAGE_WRITE_IMPLEMENTATION #include "third_party/stb_image_write.h" void normalize_depth_to_rgb(uint8_t rgb_image[], const uint16_t depth_image[], int width, int height) { for (int i = 0; i < width * height; ++i) { if (auto d = depth_image[i]) { uint8_t v = d * 255 / std::numeric_limits<uint16_t>::max(); rgb_image[i*3 + 0] = 255 - v; rgb_image[i*3 + 1] = 255 - v; rgb_image[i*3 + 2] = 255 - v; } else { rgb_image[i*3 + 0] = 0; rgb_image[i*3 + 1] = 0; rgb_image[i*3 + 2] = 0; } } } std::map<rs::stream,int> components_map = { { rs::stream::depth, 3 }, // RGB { rs::stream::color, 3 }, { rs::stream::infrared , 1 }, // Monochromatic { rs::stream::infrared2, 1 }, { rs::stream::fisheye, 1 } }; struct stream_record { stream_record(void): frame_data(nullptr) {}; stream_record(rs::stream value): stream(value), frame_data(nullptr) {}; ~stream_record() { frame_data = nullptr;} rs::stream stream; rs::intrinsics intrinsics; unsigned char * frame_data; }; int main() try { rs::log_to_console(rs::log_severity::warn); //rs::log_to_file(rs::log_severity::debug, "librealsense.log"); rs::context ctx; printf("There are %d connected RealSense devices.\n", ctx.get_device_count()); if(ctx.get_device_count() == 0) return EXIT_FAILURE; rs::device * dev = ctx.get_device(0); printf("\nUsing device 0, an %s\n", dev->get_name()); printf(" Serial number: %s\n", dev->get_serial()); printf(" Firmware version: %s\n", dev->get_firmware_version()); std::vector<stream_record> supported_streams; for (int i=(int)rs::capabilities::depth; i <=(int)rs::capabilities::fish_eye; i++) if (dev->supports((rs::capabilities)i)) supported_streams.push_back(stream_record((rs::stream)i)); for (auto & stream_record : supported_streams) dev->enable_stream(stream_record.stream, rs::preset::best_quality); /* activate video streaming */ dev->start(); /* retrieve actual frame size for each enabled stream*/ for (auto & stream_record : supported_streams) stream_record.intrinsics = dev->get_stream_intrinsics(stream_record.stream); /* Capture 30 frames to give autoexposure, etc. a chance to settle */ for (int i = 0; i < 30; ++i) dev->wait_for_frames(); /* Retrieve data from all the enabled streams */ for (auto & stream_record : supported_streams) stream_record.frame_data = const_cast<uint8_t *>((const uint8_t*)dev->get_frame_data(stream_record.stream)); /* Transform Depth range map into color map */ stream_record depth = supported_streams[(int)rs::stream::depth]; std::vector<uint8_t> coloredDepth(depth.intrinsics.width * depth.intrinsics.height * components_map[depth.stream]); /* Encode depth data into color image */ normalize_depth_to_rgb(coloredDepth.data(), (const uint16_t *)depth.frame_data, depth.intrinsics.width, depth.intrinsics.height); /* Update captured data */ supported_streams[(int)rs::stream::depth].frame_data = coloredDepth.data(); /* Store captured frames into current directory */ for (auto & captured : supported_streams) { std::stringstream ss; ss << "cpp-headless-output-" << captured.stream << ".png"; std::cout << "Writing " << ss.str().data() << ", " << captured.intrinsics.width << " x " << captured.intrinsics.height << " pixels" << std::endl; stbi_write_png(ss.str().data(), captured.intrinsics.width,captured.intrinsics.height, components_map[captured.stream], captured.frame_data, captured.intrinsics.width * components_map[captured.stream] ); } printf("wrote frames to current working directory.\n"); return EXIT_SUCCESS; } catch(const rs::error & e) { std::cerr << "RealSense error calling " << e.get_failed_function() << "(" << e.get_failed_args() << "):\n " << e.what() << std::endl; return EXIT_FAILURE; } catch(const std::exception & e) { std::cerr << e.what() << std::endl; return EXIT_FAILURE; }
34.26087
155
0.630076
[ "vector", "transform" ]
6e10df1bc45bd15d77075a9b26968eb326fd0ddf
3,036
cpp
C++
src/slg/textures/texturedefs.cpp
julescmay/LuxCore
3a6233f37afaf064300f52854715c0ab9ca2103e
[ "Apache-2.0" ]
826
2017-12-12T15:38:16.000Z
2022-03-28T07:12:40.000Z
src/slg/textures/texturedefs.cpp
julescmay/LuxCore
3a6233f37afaf064300f52854715c0ab9ca2103e
[ "Apache-2.0" ]
531
2017-12-03T17:21:06.000Z
2022-03-20T19:22:11.000Z
src/slg/textures/texturedefs.cpp
julescmay/LuxCore
3a6233f37afaf064300f52854715c0ab9ca2103e
[ "Apache-2.0" ]
133
2017-12-13T18:46:10.000Z
2022-03-27T16:21:00.000Z
/*************************************************************************** * Copyright 1998-2020 by authors (see AUTHORS.txt) * * * * This file is part of LuxCoreRender. * * * * 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 <boost/foreach.hpp> #include "slg/textures/texturedefs.h" using namespace std; using namespace luxrays; using namespace slg; //------------------------------------------------------------------------------ // TextureDefinitions //------------------------------------------------------------------------------ void TextureDefinitions::DefineTexture(Texture *newTex) { const Texture *oldTex = static_cast<const Texture *>(texs.DefineObj(newTex)); if (oldTex) { // Update all references BOOST_FOREACH(NamedObject *tex, texs.GetObjs()) static_cast<Texture *>(tex)->UpdateTextureReferences(oldTex, newTex); // Delete the old texture definition delete oldTex; } } void TextureDefinitions::GetTextureSortedNames(vector<std::string> &names) const { boost::unordered_set<string> doneNames; for (u_int i = 0; i < GetSize(); ++i) { const Texture *tex = GetTexture(i); GetTextureSortedNamesImpl(tex, names, doneNames); } } void TextureDefinitions::GetTextureSortedNamesImpl(const Texture *tex, vector<std::string> &names, boost::unordered_set<string> &doneNames) const { // Check it has not been already added const string &texName = tex->GetName(); if (doneNames.count(texName) != 0) return; // Get the list of reference textures by this one boost::unordered_set<const Texture *> referencedTexs; tex->AddReferencedTextures(referencedTexs); // Add all referenced texture names for (auto refTex : referencedTexs) { // AddReferencedTextures() adds also itself to the list of referenced textures if (refTex != tex) GetTextureSortedNamesImpl(refTex, names, doneNames); } // I can now add the name of this texture name names.push_back(texName); doneNames.insert(texName); }
39.947368
82
0.542161
[ "vector" ]
6e1412b4cbe6d60b73390e8f8f3f986548086b3e
2,163
cpp
C++
src/tablebuttons/tablebuttongroup.cpp
mugiseyebrows/mugi-grep
9cb924e5cbfe7a085741b579d9cbd0de45d8decc
[ "MIT" ]
5
2019-02-15T17:53:32.000Z
2022-03-26T06:44:23.000Z
src/tablebuttons/tablebuttongroup.cpp
mugiseyebrows/mugi-grep
9cb924e5cbfe7a085741b579d9cbd0de45d8decc
[ "MIT" ]
16
2018-12-18T09:13:57.000Z
2021-06-13T16:45:06.000Z
src/tablebuttons/tablebuttongroup.cpp
mugiseyebrows/mugi-grep
9cb924e5cbfe7a085741b579d9cbd0de45d8decc
[ "MIT" ]
1
2022-03-26T06:44:32.000Z
2022-03-26T06:44:32.000Z
#include "tablebuttongroup.h" namespace { QList<TableButtonImpl*> filterOrientation(const QList<TableButtonImpl*>& buttons, Qt::Orientation orientation) { QList<TableButtonImpl*> res; foreach(TableButtonImpl* button, buttons) { if (button->orientation() == orientation) { res.append(button); } } return res; } int minLeft(const QList<TableButtonImpl*>& buttons) { std::vector<int> lefts; std::transform(buttons.begin(),buttons.end(),std::back_inserter(lefts), [](TableButtonImpl* button){return button->left();}); return *std::min_element(lefts.begin(),lefts.end()); } int maxRight(const QList<TableButtonImpl*>& buttons) { std::vector<int> rights; std::transform(buttons.begin(),buttons.end(),std::back_inserter(rights), [](TableButtonImpl* button){return button->right();}); return *std::max_element(rights.begin(),rights.end()); } int maxBottom(const QList<TableButtonImpl*>& buttons) { std::vector<int> bottoms; std::transform(buttons.begin(),buttons.end(),std::back_inserter(bottoms), [](TableButtonImpl* button){return button->bottom();}); return *std::max_element(bottoms.begin(),bottoms.end()); } int minTop(const QList<TableButtonImpl*>& buttons) { std::vector<int> tops; std::transform(buttons.begin(),buttons.end(),std::back_inserter(tops), [](TableButtonImpl* button){return button->top();}); return *std::min_element(tops.begin(),tops.end()); } } TableButtonGroup::TableButtonGroup(const QList<TableButtonImpl *> &buttons, Qt::Orientation orientation) { QList<TableButtonImpl *> filtered = filterOrientation(buttons, orientation); append(filtered); } int TableButtonGroup::left() const { return minLeft(*this); } int TableButtonGroup::right() const { return maxRight(*this); } int TableButtonGroup::width() const { return right() - left(); } int TableButtonGroup::height() const { return bottom() - top(); } int TableButtonGroup::top() const { return minTop(*this); } int TableButtonGroup::bottom() const { return maxBottom(*this); }
27.379747
112
0.667591
[ "vector", "transform" ]
6e1bb78d6a906728accef47e0247b90a330eb631
2,374
cpp
C++
applications/physbam/physbam-lib/Public_Library/PhysBAM_Rendering/PhysBAM_OpenGL/OpenGL/OPENGL_UNIFORM_SLICE.cpp
schinmayee/nimbus
170cd15e24a7a88243a6ea80aabadc0fc0e6e177
[ "BSD-3-Clause" ]
20
2017-07-03T19:09:09.000Z
2021-09-10T02:53:56.000Z
applications/physbam/physbam-lib/Public_Library/PhysBAM_Rendering/PhysBAM_OpenGL/OpenGL/OPENGL_UNIFORM_SLICE.cpp
schinmayee/nimbus
170cd15e24a7a88243a6ea80aabadc0fc0e6e177
[ "BSD-3-Clause" ]
null
null
null
applications/physbam/physbam-lib/Public_Library/PhysBAM_Rendering/PhysBAM_OpenGL/OpenGL/OPENGL_UNIFORM_SLICE.cpp
schinmayee/nimbus
170cd15e24a7a88243a6ea80aabadc0fc0e6e177
[ "BSD-3-Clause" ]
9
2017-09-17T02:05:06.000Z
2020-01-31T00:12:01.000Z
//##################################################################### // Copyright 2004, Eran Guendelman. // This file is part of PhysBAM whose distribution is governed by the license contained in the accompanying file PHYSBAM_COPYRIGHT.txt. //##################################################################### // Class OPENGL_UNIFORM_SLICE //##################################################################### #include <PhysBAM_Rendering/PhysBAM_OpenGL/OpenGL/OPENGL_UNIFORM_SLICE.h> #include <PhysBAM_Rendering/PhysBAM_OpenGL/OpenGL/OPENGL_WORLD.h> using namespace PhysBAM; //##################################################################### // Function Print_Slice_Info //##################################################################### void OPENGL_UNIFORM_SLICE:: Print_Slice_Info(std::ostream& output_stream) { const char* axis_name[]={"","x","y","z"}; if(mode==CELL_SLICE){output_stream<<"Slice: cell="<<index<<", "<<axis_name[axis]<<"="<<grid.Center(index,index,index)[axis]<<std::endl;} else if(mode==NODE_SLICE){output_stream<<"Slice: node="<<index<<", "<<axis_name[axis]<<"="<<grid.Node(index,index,index)[axis]<<std::endl;} } //##################################################################### // Function Update_Clip_Planes //##################################################################### void OPENGL_UNIFORM_SLICE:: Update_Clip_Planes() { if (mode==NO_SLICE) { if (clip_plane_id1!=0) world.Remove_Clipping_Plane(clip_plane_id1); if (clip_plane_id2!=0) world.Remove_Clipping_Plane(clip_plane_id2); clip_plane_id1=clip_plane_id2=0; } else { float pos=(mode==NODE_SLICE)?grid.Node(index,index,index)[axis]:grid.Center(index,index,index)[axis]; PLANE<float> plane1(VECTOR<float,3>(0,0,0),VECTOR<float,3>(0,0,0)),plane2(VECTOR<float,3>(0,0,0),VECTOR<float,3>(0,0,0)); plane1.normal[axis]=1;plane1.x1[axis]=pos-grid.dX[axis]/1.9f; plane2.normal[axis]=-1;plane2.x1[axis]=pos+grid.dX[axis]/1.9f; if (clip_plane_id1==0) clip_plane_id1=world.Add_Clipping_Plane(plane1); else world.Set_Clipping_Plane(clip_plane_id1,plane1); if (clip_plane_id2==0) clip_plane_id2=world.Add_Clipping_Plane(plane2); else world.Set_Clipping_Plane(clip_plane_id2,plane2); } } //#####################################################################
55.209302
143
0.545072
[ "vector" ]
6e1e0cd6c7f1c8d6e400294f89e29830831b14d9
1,075
cpp
C++
test/_5GS/ie/Maximum_data_rate_per_UE_for_user_plane.cpp
OPENAIRINTERFACE/oai-libnascodec-cpp
c87005933fa6d748909f7fd8f1e0b1412abd0458
[ "Apache-2.0" ]
3
2019-12-06T14:17:41.000Z
2020-09-30T17:26:17.000Z
test/_5GS/ie/Maximum_data_rate_per_UE_for_user_plane.cpp
OPENAIRINTERFACE/oai-libnascodec-cpp
c87005933fa6d748909f7fd8f1e0b1412abd0458
[ "Apache-2.0" ]
null
null
null
test/_5GS/ie/Maximum_data_rate_per_UE_for_user_plane.cpp
OPENAIRINTERFACE/oai-libnascodec-cpp
c87005933fa6d748909f7fd8f1e0b1412abd0458
[ "Apache-2.0" ]
4
2019-12-06T14:22:37.000Z
2021-03-20T01:44:55.000Z
#include <_5GS/ie/Maximum_data_rate_per_UE_for_user_plane.h> using namespace _5GS::IE; #include <test_template.h> int main() { code_V<Maximum_data_rate_per_UE_for_user_plane, Maximum_data_rate_per_UE_for_user_plane::Value>( Maximum_data_rate_per_UE_for_user_plane::Value::_64_kbps, std::vector<uint8_t>({0x00}) ); code_V<Maximum_data_rate_per_UE_for_user_plane, Maximum_data_rate_per_UE_for_user_plane::Value>( Maximum_data_rate_per_UE_for_user_plane::Value::Full_data_rate, std::vector<uint8_t>({0xff}) ); decode_V<Maximum_data_rate_per_UE_for_user_plane, Maximum_data_rate_per_UE_for_user_plane::Value>( std::vector<uint8_t>({255}), Maximum_data_rate_per_UE_for_user_plane::Value::Full_data_rate ); // The receiving entity shall treat a spare value as "64 kbps". decode_V<Maximum_data_rate_per_UE_for_user_plane, Maximum_data_rate_per_UE_for_user_plane::Value>( std::vector<uint8_t>({200}), Maximum_data_rate_per_UE_for_user_plane::Value::_64_kbps ); return 0; }
34.677419
102
0.756279
[ "vector" ]
6e1fb9943c5fd9c2342a03123f2998742b6e1b3d
9,951
cpp
C++
src/qt/src/3rdparty/webkit/Source/WebCore/svg/SVGAnimateTransformElement.cpp
ant0ine/phantomjs
8114d44a28134b765ab26b7e13ce31594fa81253
[ "BSD-3-Clause" ]
46
2015-01-08T14:32:34.000Z
2022-02-05T16:48:26.000Z
src/qt/src/3rdparty/webkit/Source/WebCore/svg/SVGAnimateTransformElement.cpp
ant0ine/phantomjs
8114d44a28134b765ab26b7e13ce31594fa81253
[ "BSD-3-Clause" ]
7
2015-01-20T14:28:12.000Z
2017-01-18T17:21:44.000Z
src/qt/src/3rdparty/webkit/Source/WebCore/svg/SVGAnimateTransformElement.cpp
ant0ine/phantomjs
8114d44a28134b765ab26b7e13ce31594fa81253
[ "BSD-3-Clause" ]
14
2015-10-27T06:17:48.000Z
2020-03-03T06:15:50.000Z
/* * Copyright (C) 2004, 2005 Nikolas Zimmermann <zimmermann@kde.org> * Copyright (C) 2004, 2005, 2006, 2007 Rob Buis <buis@kde.org> * Copyright (C) 2007 Eric Seidel <eric@webkit.org> * Copyright (C) 2008 Apple Inc. All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 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 * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public License * along with this library; see the file COPYING.LIB. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. */ #include "config.h" #if ENABLE(SVG) && ENABLE(SVG_ANIMATION) #include "SVGAnimateTransformElement.h" #include "AffineTransform.h" #include "Attribute.h" #include "RenderObject.h" #include "RenderSVGResource.h" #include "SVGAngle.h" #include "SVGElementInstance.h" #include "SVGGradientElement.h" #include "SVGNames.h" #include "SVGParserUtilities.h" #include "SVGSVGElement.h" #include "SVGStyledTransformableElement.h" #include "SVGTextElement.h" #include "SVGTransform.h" #include "SVGTransformList.h" #include "SVGUseElement.h" #include <math.h> #include <wtf/MathExtras.h> using namespace std; namespace WebCore { inline SVGAnimateTransformElement::SVGAnimateTransformElement(const QualifiedName& tagName, Document* document) : SVGAnimationElement(tagName, document) , m_type(SVGTransform::SVG_TRANSFORM_UNKNOWN) , m_baseIndexInTransformList(0) { } PassRefPtr<SVGAnimateTransformElement> SVGAnimateTransformElement::create(const QualifiedName& tagName, Document* document) { return adoptRef(new SVGAnimateTransformElement(tagName, document)); } bool SVGAnimateTransformElement::hasValidAttributeType() const { SVGElement* targetElement = this->targetElement(); if (!targetElement) return false; return determineAnimatedAttributeType(targetElement) == AnimatedTransformList; } AnimatedAttributeType SVGAnimateTransformElement::determineAnimatedAttributeType(SVGElement* targetElement) const { ASSERT(targetElement); // Just transform lists can be animated with <animateTransform> // http://www.w3.org/TR/SVG/animate.html#AnimationAttributesAndProperties if (targetElement->animatedPropertyTypeForAttribute(attributeName()) != AnimatedTransformList) return AnimatedUnknown; return AnimatedTransformList; } void SVGAnimateTransformElement::parseMappedAttribute(Attribute* attr) { if (attr->name() == SVGNames::typeAttr) { if (attr->value() == "translate") m_type = SVGTransform::SVG_TRANSFORM_TRANSLATE; else if (attr->value() == "scale") m_type = SVGTransform::SVG_TRANSFORM_SCALE; else if (attr->value() == "rotate") m_type = SVGTransform::SVG_TRANSFORM_ROTATE; else if (attr->value() == "skewX") m_type = SVGTransform::SVG_TRANSFORM_SKEWX; else if (attr->value() == "skewY") m_type = SVGTransform::SVG_TRANSFORM_SKEWY; } else SVGAnimationElement::parseMappedAttribute(attr); } static SVGTransformList* transformListFor(SVGElement* element) { ASSERT(element); if (element->isStyledTransformable()) return &static_cast<SVGStyledTransformableElement*>(element)->transform(); if (element->hasTagName(SVGNames::textTag)) return &static_cast<SVGTextElement*>(element)->transform(); if (element->hasTagName(SVGNames::linearGradientTag) || element->hasTagName(SVGNames::radialGradientTag)) return &static_cast<SVGGradientElement*>(element)->gradientTransform(); // FIXME: Handle patternTransform, which is obviously missing! return 0; } void SVGAnimateTransformElement::resetToBaseValue(const String& baseValue) { SVGElement* targetElement = this->targetElement(); if (!targetElement || determineAnimatedAttributeType(targetElement) == AnimatedUnknown) return; if (targetElement->hasTagName(SVGNames::linearGradientTag) || targetElement->hasTagName(SVGNames::radialGradientTag)) { targetElement->setAttribute(SVGNames::gradientTransformAttr, baseValue.isEmpty() ? "matrix(1 0 0 1 0 0)" : baseValue); return; } if (baseValue.isEmpty()) { if (SVGTransformList* list = transformListFor(targetElement)) list->clear(); } else targetElement->setAttribute(SVGNames::transformAttr, baseValue); } void SVGAnimateTransformElement::calculateAnimatedValue(float percentage, unsigned repeat, SVGSMILElement*) { SVGElement* targetElement = this->targetElement(); if (!targetElement || determineAnimatedAttributeType(targetElement) == AnimatedUnknown) return; SVGTransformList* transformList = transformListFor(targetElement); ASSERT(transformList); if (!isAdditive()) transformList->clear(); if (isAccumulated() && repeat) { SVGTransform accumulatedTransform = SVGTransformDistance(m_fromTransform, m_toTransform).scaledDistance(repeat).addToSVGTransform(SVGTransform()); transformList->append(accumulatedTransform); } SVGTransform transform = SVGTransformDistance(m_fromTransform, m_toTransform).scaledDistance(percentage).addToSVGTransform(m_fromTransform); transformList->append(transform); } bool SVGAnimateTransformElement::calculateFromAndToValues(const String& fromString, const String& toString) { m_fromTransform = parseTransformValue(fromString); if (!m_fromTransform.isValid()) return false; m_toTransform = parseTransformValue(toString); return m_toTransform.isValid(); } bool SVGAnimateTransformElement::calculateFromAndByValues(const String& fromString, const String& byString) { m_fromTransform = parseTransformValue(fromString); if (!m_fromTransform.isValid()) return false; m_toTransform = SVGTransformDistance::addSVGTransforms(m_fromTransform, parseTransformValue(byString)); return m_toTransform.isValid(); } SVGTransform SVGAnimateTransformElement::parseTransformValue(const String& value) const { if (value.isEmpty()) return SVGTransform(m_type); SVGTransform result; // FIXME: This is pretty dumb but parseTransformValue() wants those parenthesis. String parseString("(" + value + ")"); const UChar* ptr = parseString.characters(); SVGTransformable::parseTransformValue(m_type, ptr, ptr + parseString.length(), result); // ignoring return value return result; } void SVGAnimateTransformElement::applyResultsToTarget() { SVGElement* targetElement = this->targetElement(); if (!targetElement || determineAnimatedAttributeType(targetElement) == AnimatedUnknown) return; // We accumulate to the target element transform list so there is not much to do here. if (RenderObject* renderer = targetElement->renderer()) { renderer->setNeedsTransformUpdate(); RenderSVGResource::markForLayoutAndParentResourceInvalidation(renderer); } // ...except in case where we have additional instances in <use> trees. SVGTransformList* transformList = transformListFor(targetElement); if (!transformList) return; const HashSet<SVGElementInstance*>& instances = targetElement->instancesForElement(); const HashSet<SVGElementInstance*>::const_iterator end = instances.end(); for (HashSet<SVGElementInstance*>::const_iterator it = instances.begin(); it != end; ++it) { SVGElement* shadowTreeElement = (*it)->shadowTreeElement(); ASSERT(shadowTreeElement); if (shadowTreeElement->isStyledTransformable()) static_cast<SVGStyledTransformableElement*>(shadowTreeElement)->setTransformBaseValue(*transformList); else if (shadowTreeElement->hasTagName(SVGNames::textTag)) static_cast<SVGTextElement*>(shadowTreeElement)->setTransformBaseValue(*transformList); else if (shadowTreeElement->hasTagName(SVGNames::linearGradientTag) || shadowTreeElement->hasTagName(SVGNames::radialGradientTag)) static_cast<SVGGradientElement*>(shadowTreeElement)->setGradientTransformBaseValue(*transformList); // FIXME: Handle patternTransform, obviously missing! if (RenderObject* renderer = shadowTreeElement->renderer()) { renderer->setNeedsTransformUpdate(); RenderSVGResource::markForLayoutAndParentResourceInvalidation(renderer); } } } float SVGAnimateTransformElement::calculateDistance(const String& fromString, const String& toString) { // FIXME: This is not correct in all cases. The spec demands that each component (translate x and y for example) // is paced separately. To implement this we need to treat each component as individual animation everywhere. SVGTransform from = parseTransformValue(fromString); if (!from.isValid()) return -1; SVGTransform to = parseTransformValue(toString); if (!to.isValid() || from.type() != to.type()) return -1; if (to.type() == SVGTransform::SVG_TRANSFORM_TRANSLATE) { FloatSize diff = to.translate() - from.translate(); return sqrtf(diff.width() * diff.width() + diff.height() * diff.height()); } if (to.type() == SVGTransform::SVG_TRANSFORM_ROTATE) return fabsf(to.angle() - from.angle()); if (to.type() == SVGTransform::SVG_TRANSFORM_SCALE) { FloatSize diff = to.scale() - from.scale(); return sqrtf(diff.width() * diff.width() + diff.height() * diff.height()); } return -1; } } #endif // ENABLE(SVG)
41.290456
154
0.727766
[ "transform" ]
6e2c6da909bf24bbd3dbe503e01c8bd78dfca3c9
1,202
cpp
C++
MathNumberTheory/Eratosthenes_segment.cpp
landcelita/algorithm
544736df6b3cbe20ec58d44d81fe9372b8acd93e
[ "CC0-1.0" ]
197
2018-08-19T06:49:14.000Z
2022-03-26T04:11:48.000Z
MathNumberTheory/Eratosthenes_segment.cpp
landcelita/algorithm
544736df6b3cbe20ec58d44d81fe9372b8acd93e
[ "CC0-1.0" ]
null
null
null
MathNumberTheory/Eratosthenes_segment.cpp
landcelita/algorithm
544736df6b3cbe20ec58d44d81fe9372b8acd93e
[ "CC0-1.0" ]
15
2018-09-14T09:15:12.000Z
2021-11-16T12:43:43.000Z
// // エラトステネスの区間篩 // // cf. // 高校数学の美しい物語: エラトスネテスの篩 // https://mathtrain.jp/eratosthenes // // verified // AOJ 2858 Prime-Factor Prime // http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=2858 // #include <bits/stdc++.h> using namespace std; const int MAX = 110000; long long solve(long long L, long long R) { vector<bool> is_prime(MAX, true); is_prime[0] = is_prime[1] = false; vector<vector<long long>> prime_factors(R-L+1); for (long long p = 2; p * p <= R; ++p) { if (!is_prime[p]) continue; for (long long v = p*2; v < MAX; v += p) { is_prime[v] = false; } for (long long v = (L+p-1)/p*p; v <= R; v += p) { prime_factors[v-L].push_back(p); } } long long res = 0; for (long long v = L; v <= R; ++v) { long long prime_num = 0; long long v2 = v; const auto& ps = prime_factors[v2-L]; for (auto p : ps) { while (v2 % p == 0) v2 /= p, ++prime_num; } if (v2 > 1) ++prime_num; if (is_prime[prime_num]) ++res; } return res; } int main() { long long L, R; cin >> L >> R; cout << solve(L, R) << endl; }
24.04
68
0.514143
[ "vector" ]
6e30b0698494ded5f50ab064459ae34f3f05a5db
5,973
cpp
C++
filters.cpp
waps12b/Implementation-of-fast-median-filter
ad832154a1b88c72588a6937a4a8317b303bc859
[ "MIT" ]
1
2018-07-20T21:04:18.000Z
2018-07-20T21:04:18.000Z
filters.cpp
waps12b/Implementation-of-fast-median-filter
ad832154a1b88c72588a6937a4a8317b303bc859
[ "MIT" ]
null
null
null
filters.cpp
waps12b/Implementation-of-fast-median-filter
ad832154a1b88c72588a6937a4a8317b303bc859
[ "MIT" ]
1
2019-11-16T13:37:13.000Z
2019-11-16T13:37:13.000Z
#include "filters.h" #include<memory.h> #include <algorithm> #include<vector> using namespace std; void Image::addGaussianNoise() { int dc = (rand() % 7) - 3; int i = rand() % height; int j = rand() % width; int org = bitmap[i][j]; bitmap[i][j] = min(255,max(0, org + dc)); } void Image::addSaltAndPepperNoise() { int i = rand() % height; int j = rand() % width; bitmap[i][j] = (rand() % 2) * 255; } Image BruteForceFilter::process(Image m) { Image X(m.height - mKernelRadius * 2, m.width - 2 * mKernelRadius); vector<int> window((mKernelRadius*2 + 1)*(mKernelRadius*2+1)); for (int ci = mKernelRadius; ci + mKernelRadius < m.height; ci++) { for (int cj = mKernelRadius; cj + mKernelRadius < m.width; cj++) { int y = ci - mKernelRadius; int x = cj - mKernelRadius; int cnt = 0; for (int i = ci - mKernelRadius; i <= ci + mKernelRadius; i++) { for (int j = cj - mKernelRadius; j <= cj + mKernelRadius; j++) { window[cnt++] = m.bitmap[i][j]; } } sort(window.begin(), window.end()); X.bitmap[y][x] = window[mKernelRadius]; } } return X; } Image BruteForceOptimizedFilter::process(Image m) { Image X(m.height - mKernelRadius * 2,m.width - 2 * mKernelRadius); int cnt[256]; int cntSub[16]; memset(cnt, 0, sizeof(cnt)); memset(cntSub, 0, sizeof(cntSub)); for (int ci = mKernelRadius; ci + mKernelRadius < m.height; ci++) { for (int cj = mKernelRadius; cj + mKernelRadius < m.width; cj++) { int y = ci - mKernelRadius; int x = cj - mKernelRadius; for (int i = ci - mKernelRadius; i <= ci + mKernelRadius; i++) { for (int j = cj - mKernelRadius; j <= cj + mKernelRadius; j++) { cnt[m.bitmap[i][j]]++; cntSub[m.bitmap[i][j] / 16]++; } } int noc = 0; for (int color = 0; color < 256; color++) { if (noc + cntSub[color / 16] <= mKernelRadius) { noc += cntSub[color / 16]; continue; } noc += cnt[color]; if (noc > mKernelRadius) { X.bitmap[y][x] = color; break; } } } } return X; } Image HuangsFilter::process(Image m) { Image X(m.height - mKernelRadius * 2, m.width - 2 * mKernelRadius); for (int ci = mKernelRadius; ci + mKernelRadius < m.height; ci++) { int cnt[256]; int cntSub[16]; memset(cnt, 0, sizeof(cnt)); memset(cntSub, 0, sizeof(cntSub)); for (int j = 0; j < m.width; j++) { for (int i = ci - mKernelRadius; i <= ci + mKernelRadius; i++) { byte colorToAdd = m.bitmap[i][j]; cnt[colorToAdd] ++; cntSub[colorToAdd/16]++; if (j - (mKernelRadius * 2 + 1) >= 0) { byte colorToRemove = m.bitmap[i][j - (mKernelRadius*2+1)]; cnt[colorToRemove] --; cntSub[colorToAdd / 16] --; } } int y = ci - mKernelRadius; int x = j - mKernelRadius*2; if (x < 0 || y < 0) continue; int noc = 0; for (int color = 0; color < 256; color++) { if (noc + cntSub[color / 16] <= mKernelRadius) { noc += cntSub[color / 16]; continue; } noc += cnt[color]; if (noc > mKernelRadius) { X.bitmap[y][x] = color; break; } } } } return X; } Image ProposedFilter::process(Image m) { Image X(m.height - mKernelRadius * 2, m.width - 2 * mKernelRadius); vector<vector<int> > h(m.width, vector<int>(256, 0)); for (int i = 0; i < m.height; i++) { int cnt[256]; int cntSub[16]; memset(cnt, 0, sizeof(cnt)); memset(cntSub, 0, sizeof(cntSub)); for (int j = 0; j < m.width; j++) { byte colorToAdd = m.bitmap[i][j]; h[j][colorToAdd]++; int ri = i - (mKernelRadius * 2 + 1); if (ri >= 0) { byte colortoRemove = m.bitmap[i][j]; h[j][colortoRemove]--; } for (int color = 0; color < 256; color++) { cnt[color] += h[j][color]; cntSub[color / 16] += h[j][color]; } int rj = j - (mKernelRadius * 2 + 1); if (rj >= 0) { for (int color = 0; color < 256;color++) { cnt[color] -= h[rj][color]; cntSub[color / 16] -= h[rj][color]; } } int y = i - mKernelRadius*2; int x = j - mKernelRadius*2; if (y < 0 || x < 0) continue; int noc = 0; for (int color = 0; color < 256; color++) { if (noc + cntSub[color / 16] <= mKernelRadius) { noc += cntSub[color / 16]; continue; } noc += cnt[color]; if (noc > mKernelRadius) { X.bitmap[y][x] = color; break; } } } } return X; } Image ProposedOptimizedV1Filter::process(Image m) { Image X(m.height - mKernelRadius * 2, m.width - 2 * mKernelRadius); vector<vector<int> > h(m.width, vector<int>(256, 0)); vector<vector<int> > hSub(m.width, vector<int>(16, 0)); for (int i = 0; i < m.height; i++) { int cnt[256]; int cntSub[16]; memset(cnt, 0, sizeof(cnt)); memset(cntSub, 0, sizeof(cntSub)); for (int j = 0; j < m.width; j++) { byte colorToAdd = m.bitmap[i][j]; h[j][colorToAdd]++; hSub[j][colorToAdd / 16]++; int ri = i - (mKernelRadius * 2 + 1); if (ri >= 0) { byte colortoRemove = m.bitmap[i][j]; h[j][colortoRemove]--; hSub[j][colortoRemove / 16]--; } int noc = 0; int med = -1; int rj = j - (mKernelRadius * 2 + 1); int y = i - mKernelRadius * 2; int x = j - mKernelRadius * 2; for (int csub = 0; csub < 16; csub++) { int cl = csub * 16; int cr = cl + 15; if (hSub[j][csub] > 0) { for (int color = cl; color <= cr; color++) { cnt[color] += h[j][color]; cntSub[color / 16] += h[j][color]; } } if (rj >= 0 && hSub[rj][csub]>0) { for (int color = cl; color <= cr; color++) { cnt[color] -= h[rj][color]; cntSub[color / 16] -= h[rj][color]; } } if (y < 0 || x < 0) continue; if (med == -1 && noc + cntSub[csub] <= mKernelRadius) { noc += cntSub[csub]; continue; } else { for (int color = cl; color <= cr; color++) { noc += cnt[color]; if (noc > mKernelRadius) { med = color; break; } } } } if (y < 0 || x < 0) continue; X.bitmap[y][x] = med; } } return X; }
25.202532
68
0.546459
[ "vector" ]
6e3fa8c4aef74a0bdd10875f615aa604809343e4
95,101
cpp
C++
plugin/hdCycles/renderParam.cpp
bareya/hdcycles
9ac7be3f53a0a180b4c05460b0ff039e6dc1fb92
[ "Apache-2.0", "BSD-3-Clause" ]
null
null
null
plugin/hdCycles/renderParam.cpp
bareya/hdcycles
9ac7be3f53a0a180b4c05460b0ff039e6dc1fb92
[ "Apache-2.0", "BSD-3-Clause" ]
null
null
null
plugin/hdCycles/renderParam.cpp
bareya/hdcycles
9ac7be3f53a0a180b4c05460b0ff039e6dc1fb92
[ "Apache-2.0", "BSD-3-Clause" ]
null
null
null
// Copyright 2020 Tangent Animation // // 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, // including without limitation, as related to merchantability and fitness // for a particular purpose. // // In no event shall any copyright holder be liable for any damages of any kind // arising from the use of this software, whether in contract, tort or otherwise. // See the License for the specific language governing permissions and // limitations under the License. #include "renderParam.h" #include "config.h" #include "renderBuffer.h" #include "renderDelegate.h" #include "utils.h" #include <algorithm> #include <memory> #include <unordered_set> #include <device/device.h> #include <render/background.h> #include <render/buffers.h> #include <render/camera.h> #include <render/curves.h> #include <render/hair.h> #include <render/integrator.h> #include <render/light.h> #include <render/mesh.h> #include <render/nodes.h> #include <render/object.h> #include <render/pointcloud.h> #include <render/scene.h> #include <render/session.h> #include <render/stats.h> #include <util/util_murmurhash.h> #include <util/util_task.h> #include <tbb/parallel_for.h> #ifdef WITH_CYCLES_LOGGING # include <util/util_logging.h> #endif #include <pxr/usd/usdRender/tokens.h> #include <usdCycles/tokens.h> PXR_NAMESPACE_OPEN_SCOPE namespace { struct HdCyclesAov { std::string name; ccl::PassType type; TfToken token; HdFormat format; bool filter; }; std::array<HdCyclesAov, 27> DefaultAovs = { { { "Combined", ccl::PASS_COMBINED, HdAovTokens->color, HdFormatFloat32Vec4, true }, { "Depth", ccl::PASS_DEPTH, HdAovTokens->depth, HdFormatFloat32, false }, { "Normal", ccl::PASS_NORMAL, HdAovTokens->normal, HdFormatFloat32Vec3, true }, { "IndexOB", ccl::PASS_OBJECT_ID, HdAovTokens->primId, HdFormatFloat32, false }, { "IndexMA", ccl::PASS_MATERIAL_ID, HdCyclesAovTokens->IndexMA, HdFormatFloat32, false }, { "Mist", ccl::PASS_MIST, HdCyclesAovTokens->Mist, HdFormatFloat32, true }, { "Emission", ccl::PASS_EMISSION, HdCyclesAovTokens->Emit, HdFormatFloat32Vec3, true }, { "Shadow", ccl::PASS_SHADOW, HdCyclesAovTokens->Shadow, HdFormatFloat32Vec3, true }, { "AO", ccl::PASS_AO, HdCyclesAovTokens->AO, HdFormatFloat32Vec3, true }, { "UV", ccl::PASS_UV, HdCyclesAovTokens->UV, HdFormatFloat32Vec3, true }, { "Vector", ccl::PASS_MOTION, HdCyclesAovTokens->Vector, HdFormatFloat32Vec4, true }, { "DiffDir", ccl::PASS_DIFFUSE_DIRECT, HdCyclesAovTokens->DiffDir, HdFormatFloat32Vec3, true }, { "DiffInd", ccl::PASS_DIFFUSE_INDIRECT, HdCyclesAovTokens->DiffInd, HdFormatFloat32Vec3, true }, { "DiffCol", ccl::PASS_DIFFUSE_COLOR, HdCyclesAovTokens->DiffCol, HdFormatFloat32Vec3, true }, { "GlossDir", ccl::PASS_GLOSSY_DIRECT, HdCyclesAovTokens->GlossDir, HdFormatFloat32Vec3, true }, { "GlossInd", ccl::PASS_GLOSSY_INDIRECT, HdCyclesAovTokens->GlossInd, HdFormatFloat32Vec3, true }, { "GlossCol", ccl::PASS_GLOSSY_COLOR, HdCyclesAovTokens->GlossCol, HdFormatFloat32Vec3, true }, { "TransDir", ccl::PASS_TRANSMISSION_DIRECT, HdCyclesAovTokens->TransDir, HdFormatFloat32Vec3, true }, { "TransInd", ccl::PASS_TRANSMISSION_INDIRECT, HdCyclesAovTokens->TransInd, HdFormatFloat32Vec3, true }, { "TransCol", ccl::PASS_TRANSMISSION_COLOR, HdCyclesAovTokens->TransCol, HdFormatFloat32Vec3, true }, { "VolumeDir", ccl::PASS_VOLUME_DIRECT, HdCyclesAovTokens->VolumeDir, HdFormatFloat32Vec3, true }, { "VolumeInd", ccl::PASS_VOLUME_INDIRECT, HdCyclesAovTokens->VolumeInd, HdFormatFloat32Vec3, true }, { "RenderTime", ccl::PASS_RENDER_TIME, HdCyclesAovTokens->RenderTime, HdFormatFloat32, false }, { "SampleCount", ccl::PASS_SAMPLE_COUNT, HdCyclesAovTokens->SampleCount, HdFormatFloat32, false }, { "P", ccl::PASS_AOV_COLOR, HdCyclesAovTokens->P, HdFormatFloat32Vec3, false }, { "Pref", ccl::PASS_AOV_COLOR, HdCyclesAovTokens->Pref, HdFormatFloat32Vec3, false }, { "Ngn", ccl::PASS_AOV_COLOR, HdCyclesAovTokens->Ngn, HdFormatFloat32Vec3, false }, } }; std::array<HdCyclesAov, 3> CustomAovs = { { { "AOVC", ccl::PASS_AOV_COLOR, HdCyclesAovTokens->AOVC, HdFormatFloat32Vec3, true }, { "AOVV", ccl::PASS_AOV_VALUE, HdCyclesAovTokens->AOVV, HdFormatFloat32, true }, { "LightGroup", ccl::PASS_LIGHTGROUP, HdCyclesAovTokens->LightGroup, HdFormatFloat32Vec3, true }, } }; std::array<HdCyclesAov, 3> CryptomatteAovs = { { { "CryptoObject", ccl::PASS_CRYPTOMATTE, HdCyclesAovTokens->CryptoObject, HdFormatFloat32Vec4, true }, { "CryptoMaterial", ccl::PASS_CRYPTOMATTE, HdCyclesAovTokens->CryptoMaterial, HdFormatFloat32Vec4, true }, { "CryptoAsset", ccl::PASS_CRYPTOMATTE, HdCyclesAovTokens->CryptoAsset, HdFormatFloat32Vec4, true }, } }; std::array<HdCyclesAov, 2> DenoiseAovs = { { { "DenoiseNormal", ccl::PASS_NONE, HdCyclesAovTokens->DenoiseNormal, HdFormatFloat32Vec3, true }, { "DenoiseAlbedo", ccl::PASS_NONE, HdCyclesAovTokens->DenoiseAlbedo, HdFormatFloat32Vec3, true }, } }; // Workaround for Houdini's default color buffer naming convention (not using HdAovTokens->color) const TfToken defaultHoudiniColor = TfToken("C.*"); TfToken GetSourceName(const HdRenderPassAovBinding& aov) { const auto& it = aov.aovSettings.find(UsdRenderTokens->sourceName); if (it != aov.aovSettings.end()) { if (it->second.IsHolding<std::string>()) { TfToken token = TfToken(it->second.UncheckedGet<std::string>()); if (token == defaultHoudiniColor) { return HdAovTokens->color; } else if (token == HdAovTokens->cameraDepth) { // To be backwards-compatible with older scenes return HdAovTokens->depth; } else { return token; } } } // If a source name is not present, we attempt to use the name of the // AOV for the same purpose. This picks up the default aovs in // usdview and the Houdini Render Outputs pane return aov.aovName; } bool GetCyclesAov(const HdRenderPassAovBinding& aov, HdCyclesAov& cyclesAov) { TfToken sourceName = GetSourceName(aov); for (HdCyclesAov& _cyclesAov : DefaultAovs) { if (sourceName == _cyclesAov.token) { cyclesAov = _cyclesAov; return true; } } for (HdCyclesAov& _cyclesAov : CustomAovs) { if (sourceName == _cyclesAov.token) { cyclesAov = _cyclesAov; return true; } } for (HdCyclesAov& _cyclesAov : CryptomatteAovs) { if (sourceName == _cyclesAov.token) { cyclesAov = _cyclesAov; return true; } } for (HdCyclesAov& _cyclesAov : DenoiseAovs) { if (sourceName == _cyclesAov.token) { cyclesAov = _cyclesAov; return true; } } return false; } int GetDenoisePass(const TfToken token) { if (token == HdCyclesAovTokens->DenoiseNormal) { return ccl::DENOISING_PASS_PREFILTERED_NORMAL; } else if (token == HdCyclesAovTokens->DenoiseAlbedo) { return ccl::DENOISING_PASS_PREFILTERED_ALBEDO; } else { return -1; } } void GetAovFlags(const HdCyclesAov& cyclesAov, bool& custom, bool& denoise) { custom = false; denoise = false; if ((cyclesAov.token == HdCyclesAovTokens->CryptoObject) || (cyclesAov.token == HdCyclesAovTokens->CryptoMaterial) || (cyclesAov.token == HdCyclesAovTokens->CryptoAsset) || (cyclesAov.token == HdCyclesAovTokens->AOVC) || (cyclesAov.token == HdCyclesAovTokens->AOVV) || (cyclesAov.token == HdCyclesAovTokens->LightGroup)) { custom = true; } else if ((cyclesAov.token == HdCyclesAovTokens->DenoiseNormal) || (cyclesAov.token == HdCyclesAovTokens->DenoiseAlbedo)) { denoise = true; } } } // namespace HdCyclesRenderParam::HdCyclesRenderParam() : m_renderPercent(0) , m_renderProgress(0.0f) , m_useTiledRendering(false) , m_objectsUpdated(false) , m_geometryUpdated(false) , m_lightsUpdated(false) , m_shadersUpdated(false) , m_shouldUpdate(false) , m_numDomeLights(0) , m_useSquareSamples(false) , m_cyclesSession(nullptr) , m_cyclesScene(nullptr) { _InitializeDefaults(); } void HdCyclesRenderParam::_InitializeDefaults() { // These aren't directly cycles settings, but inform the creation and behaviour // of a render. These should be will need to be set by schema too... static const HdCyclesConfig& config = HdCyclesConfig::GetInstance(); m_deviceName = config.device_name.value; m_useSquareSamples = config.use_square_samples.value; m_useTiledRendering = config.use_tiled_rendering; m_dataWindowNDC = GfVec4f(0.f, 0.f, 1.f, 1.f); m_resolutionAuthored = false; m_upAxis = UpAxis::Z; if (config.up_axis == "Z") { m_upAxis = UpAxis::Z; } else if (config.up_axis == "Y") { m_upAxis = UpAxis::Y; } #ifdef WITH_CYCLES_LOGGING if (config.cycles_enable_logging) { ccl::util_logging_start(); ccl::util_logging_verbosity_set(config.cycles_logging_severity); } #endif } float HdCyclesRenderParam::GetProgress() { return m_renderProgress; } bool HdCyclesRenderParam::IsConverged() { return GetProgress() >= 1.0f; } void HdCyclesRenderParam::_SessionUpdateCallback() { // - Get Session progress integer amount m_renderProgress = m_cyclesSession->progress.get_progress(); int newPercent = static_cast<int>(floor(m_renderProgress * 100.0f)); if (newPercent != m_renderPercent) { m_renderPercent = newPercent; if (HdCyclesConfig::GetInstance().enable_progress) { std::cout << "Progress: " << m_renderPercent << "%" << std::endl << std::flush; } } // - Get Render time m_cyclesSession->progress.get_time(m_totalTime, m_renderTime); // - Handle Session status logging if (HdCyclesConfig::GetInstance().enable_logging) { std::string status, substatus; m_cyclesSession->progress.get_status(status, substatus); if (substatus != "") status += ": " + substatus; std::cout << "cycles: " << m_renderProgress << " : " << status << '\n'; } } /* This paradigm does cause unecessary loops through settingsMap for each feature. This should be addressed in the future. For the moment, the flexibility of setting order of operations is more important. */ bool HdCyclesRenderParam::Initialize(HdRenderSettingsMap const& settingsMap) { // -- Delegate _UpdateDelegateFromConfig(true); _UpdateDelegateFromRenderSettings(settingsMap); _UpdateDelegateFromConfig(); // -- Session _UpdateSessionFromConfig(true); _UpdateSessionFromRenderSettings(settingsMap); _UpdateSessionFromConfig(); // Setting up number of threads, this is useful for applications(husk) that control task arena m_sessionParams.threads = tbb::this_task_arena::max_concurrency(); if (!_CreateSession()) { std::cout << "COULD NOT CREATE CYCLES SESSION\n"; // Couldn't create session, big issue return false; } // -- Scene _UpdateSceneFromConfig(true); _UpdateSceneFromRenderSettings(settingsMap); _UpdateSceneFromConfig(); if (!_CreateScene()) { std::cout << "COULD NOT CREATE CYCLES SCENE\n"; // Couldn't create scene, big issue return false; } // -- Film _UpdateFilmFromConfig(true); _UpdateFilmFromRenderSettings(settingsMap); _UpdateFilmFromConfig(); // -- Integrator _UpdateIntegratorFromConfig(true); _UpdateIntegratorFromRenderSettings(settingsMap); _UpdateIntegratorFromConfig(); // -- Background _UpdateBackgroundFromConfig(true); _UpdateBackgroundFromRenderSettings(settingsMap); _UpdateBackgroundFromConfig(); _HandlePasses(); return true; } // -- HdCycles Misc Delegate Settings void HdCyclesRenderParam::_UpdateDelegateFromConfig(bool a_forceInit) { static const HdCyclesConfig& config = HdCyclesConfig::GetInstance(); (void)config; } void HdCyclesRenderParam::_UpdateDelegateFromRenderSettings(HdRenderSettingsMap const& settingsMap) { for (auto& entry : settingsMap) { TfToken key = entry.first; VtValue value = entry.second; _HandleDelegateRenderSetting(key, value); } } bool HdCyclesRenderParam::_HandleDelegateRenderSetting(const TfToken& key, const VtValue& value) { bool delegate_updated = false; if (key == usdCyclesTokens->cyclesUse_square_samples) { m_useSquareSamples = _HdCyclesGetVtValue<bool>(value, m_useSquareSamples, &delegate_updated); } if (delegate_updated) { // Although this is called, it does not correctly reset session in IPR //Interrupt(); return true; } return false; } // -- Session void HdCyclesRenderParam::_UpdateSessionFromConfig(bool a_forceInit) { static const HdCyclesConfig& config = HdCyclesConfig::GetInstance(); ccl::SessionParams* sessionParams = &m_sessionParams; if (m_cyclesSession) sessionParams = &m_cyclesSession->params; config.enable_experimental.eval(sessionParams->experimental, a_forceInit); config.display_buffer_linear.eval(sessionParams->display_buffer_linear, a_forceInit); sessionParams->shadingsystem = ccl::SHADINGSYSTEM_SVM; if (config.shading_system.value == "OSL" || config.shading_system.value == "SHADINGSYSTEM_OSL") sessionParams->shadingsystem = ccl::SHADINGSYSTEM_OSL; sessionParams->background = false; config.start_resolution.eval(sessionParams->start_resolution, a_forceInit); sessionParams->progressive = true; sessionParams->progressive_refine = false; sessionParams->progressive_update_timeout = 0.1; config.pixel_size.eval(sessionParams->pixel_size, a_forceInit); config.tile_size_x.eval(sessionParams->tile_size.x, a_forceInit); config.tile_size_y.eval(sessionParams->tile_size.y, a_forceInit); // Tiled rendering requires some settings to be forced on... // This requires some more thought and testing in regards // to the usdCycles schema... if (m_useTiledRendering) { sessionParams->background = true; sessionParams->start_resolution = INT_MAX; sessionParams->progressive = false; sessionParams->progressive_refine = false; } config.max_samples.eval(sessionParams->samples, a_forceInit); } void HdCyclesRenderParam::_UpdateSessionFromRenderSettings(HdRenderSettingsMap const& settingsMap) { for (auto& entry : settingsMap) { TfToken key = entry.first; VtValue value = entry.second; _HandleSessionRenderSetting(key, value); } } bool HdCyclesRenderParam::_HandleSessionRenderSetting(const TfToken& key, const VtValue& value) { ccl::SessionParams* sessionParams = &m_sessionParams; if (m_cyclesSession) sessionParams = &m_cyclesSession->params; bool session_updated = false; bool samples_updated = false; // This is now handled by HdCycles depending on tiled or not tiled rendering... /*if (key == usdCyclesTokens->cyclesBackground) { sessionParams->background = _HdCyclesGetVtValue<bool>(value, sessionParams->background, &session_updated); }*/ if (key == usdCyclesTokens->cyclesProgressive_refine) { sessionParams->progressive_refine = _HdCyclesGetVtValue<bool>(value, sessionParams->progressive_refine, &session_updated); } if (key == usdCyclesTokens->cyclesProgressive) { sessionParams->progressive = _HdCyclesGetVtValue<bool>(value, sessionParams->progressive, &session_updated); } if (key == usdCyclesTokens->cyclesProgressive_update_timeout) { sessionParams->progressive_update_timeout = static_cast<double>( _HdCyclesGetVtValue<float>(value, static_cast<float>(sessionParams->progressive_update_timeout), &session_updated)); } if (key == usdCyclesTokens->cyclesExperimental) { sessionParams->experimental = _HdCyclesGetVtValue<bool>(value, sessionParams->experimental, &session_updated); } if (key == usdCyclesTokens->cyclesSamples) { // If branched-path mode is set, make sure to set samples to use the // aa_samples instead from the integrator. int samples = sessionParams->samples; int aa_samples = 0; ccl::Integrator::Method method = ccl::Integrator::PATH; if (m_cyclesScene) { method = m_cyclesScene->integrator->method; aa_samples = m_cyclesScene->integrator->aa_samples; // Don't apply aa_samples if it is 0 if (aa_samples && method == ccl::Integrator::BRANCHED_PATH) { samples = aa_samples; } } sessionParams->samples = _HdCyclesGetVtValue<int>(value, samples, &samples_updated); if (samples_updated) { session_updated = true; if (m_cyclesScene && aa_samples && method == ccl::Integrator::BRANCHED_PATH) { sessionParams->samples = aa_samples; } } } // Tiles if (key == usdCyclesTokens->cyclesTile_size) { if (value.IsHolding<GfVec2i>()) { sessionParams->tile_size = vec2i_to_int2( _HdCyclesGetVtValue<GfVec2i>(value, int2_to_vec2i(sessionParams->tile_size), &session_updated)); } else if (value.IsHolding<GfVec2f>()) { // Adding this check for safety since the original implementation was using GfVec2i which // might have been valid at some point but does not match the current schema. sessionParams->tile_size = vec2f_to_int2( _HdCyclesGetVtValue<GfVec2f>(value, int2_to_vec2f(sessionParams->tile_size), &session_updated)); TF_WARN( "Tile size was specified as float, but the schema uses int. The value will be converted but you should update the schema version."); } else { TF_WARN("Tile size has unsupported type %s, expected GfVec2f", value.GetTypeName().c_str()); } } TfToken tileOrder; if (key == usdCyclesTokens->cyclesTile_order) { tileOrder = _HdCyclesGetVtValue<TfToken>(value, tileOrder, &session_updated); if (tileOrder == usdCyclesTokens->hilbert_spiral) { sessionParams->tile_order = ccl::TILE_HILBERT_SPIRAL; } else if (tileOrder == usdCyclesTokens->center) { sessionParams->tile_order = ccl::TILE_CENTER; } else if (tileOrder == usdCyclesTokens->right_to_left) { sessionParams->tile_order = ccl::TILE_RIGHT_TO_LEFT; } else if (tileOrder == usdCyclesTokens->left_to_right) { sessionParams->tile_order = ccl::TILE_LEFT_TO_RIGHT; } else if (tileOrder == usdCyclesTokens->top_to_bottom) { sessionParams->tile_order = ccl::TILE_TOP_TO_BOTTOM; } else if (tileOrder == usdCyclesTokens->bottom_to_top) { sessionParams->tile_order = ccl::TILE_BOTTOM_TO_TOP; } } if (key == usdCyclesTokens->cyclesStart_resolution) { sessionParams->start_resolution = _HdCyclesGetVtValue<int>(value, sessionParams->start_resolution, &session_updated); } if (key == usdCyclesTokens->cyclesPixel_size) { sessionParams->pixel_size = _HdCyclesGetVtValue<int>(value, sessionParams->pixel_size, &session_updated); } if (key == usdCyclesTokens->cyclesAdaptive_sampling) { sessionParams->adaptive_sampling = _HdCyclesGetVtValue<bool>(value, sessionParams->adaptive_sampling, &session_updated); if (sessionParams->adaptive_sampling) { /* Integrator settings are applied after the scene is created */ if (m_cyclesScene) { m_cyclesScene->integrator->sampling_pattern = ccl::SAMPLING_PATTERN_PMJ; m_cyclesScene->integrator->tag_update(m_cyclesScene); session_updated = true; } } } if (key == usdCyclesTokens->cyclesUse_profiling) { sessionParams->use_profiling = _HdCyclesGetVtValue<bool>(value, sessionParams->use_profiling, &session_updated); } if (key == usdCyclesTokens->cyclesDisplay_buffer_linear) { sessionParams->display_buffer_linear = _HdCyclesGetVtValue<bool>(value, sessionParams->display_buffer_linear, &session_updated); } TfToken shadingSystem; if (key == usdCyclesTokens->cyclesShading_system) { shadingSystem = _HdCyclesGetVtValue<TfToken>(value, shadingSystem, &session_updated); if (shadingSystem == usdCyclesTokens->osl) { sessionParams->shadingsystem = ccl::SHADINGSYSTEM_OSL; } else { sessionParams->shadingsystem = ccl::SHADINGSYSTEM_SVM; } } if (key == usdCyclesTokens->cyclesUse_profiling) { sessionParams->use_profiling = _HdCyclesGetVtValue<bool>(value, sessionParams->use_profiling, &session_updated); } // Denoising bool denoising_updated = false; bool denoising_start_sample_updated = false; ccl::DenoiseParams denoisingParams = sessionParams->denoising; if (key == usdCyclesTokens->cyclesDenoiseUse) { denoisingParams.use = _HdCyclesGetVtValue<bool>(value, denoisingParams.use, &denoising_updated); } if (key == usdCyclesTokens->cyclesDenoiseStore_passes) { denoisingParams.store_passes = _HdCyclesGetVtValue<bool>(value, denoisingParams.store_passes, &denoising_updated); } if (key == usdCyclesTokens->cyclesDenoiseStart_sample) { sessionParams->denoising_start_sample = _HdCyclesGetVtValue<int>(value, sessionParams->denoising_start_sample, &denoising_start_sample_updated); } if (key == usdCyclesTokens->cyclesDenoiseType) { TfToken type = usdCyclesTokens->none; type = _HdCyclesGetVtValue<TfToken>(value, type, &denoising_updated); if (type == usdCyclesTokens->none) { denoisingParams.type = ccl::DENOISER_NONE; } else if (type == usdCyclesTokens->openimagedenoise) { denoisingParams.type = ccl::DENOISER_OPENIMAGEDENOISE; } else if (type == usdCyclesTokens->optix) { denoisingParams.type = ccl::DENOISER_OPTIX; } else { denoisingParams.type = ccl::DENOISER_NONE; } } if (key == usdCyclesTokens->cyclesDenoiseInput_passes) { TfToken inputPasses = usdCyclesTokens->rgb_albedo_normal; inputPasses = _HdCyclesGetVtValue<TfToken>(value, inputPasses, &denoising_updated); if (inputPasses == usdCyclesTokens->rgb) { denoisingParams.input_passes = ccl::DENOISER_INPUT_RGB; } else if (inputPasses == usdCyclesTokens->rgb_albedo) { denoisingParams.input_passes = ccl::DENOISER_INPUT_RGB_ALBEDO; } else if (inputPasses == usdCyclesTokens->rgb_albedo_normal) { denoisingParams.input_passes = ccl::DENOISER_INPUT_RGB_ALBEDO_NORMAL; } } if (denoising_updated || denoising_start_sample_updated) { if (m_cyclesSession) { m_cyclesSession->set_denoising(denoisingParams); if (denoising_start_sample_updated) { m_cyclesSession->set_denoising_start_sample(sessionParams->denoising_start_sample); } } else { sessionParams->denoising = denoisingParams; } session_updated = true; } // Final if (session_updated) { // Although this is called, it does not correctly reset session in IPR //Interrupt(); return true; } return false; } // -- Scene void HdCyclesRenderParam::_UpdateSceneFromConfig(bool a_forceInit) { static const HdCyclesConfig& config = HdCyclesConfig::GetInstance(); ccl::SceneParams* sceneParams = &m_sceneParams; if (m_cyclesScene) sceneParams = &m_cyclesScene->params; ccl::SessionParams* sessionParams = &m_sessionParams; if (m_cyclesSession) sessionParams = &m_cyclesSession->params; // -- Scene init sceneParams->shadingsystem = sessionParams->shadingsystem; sceneParams->bvh_type = ccl::SceneParams::BVH_DYNAMIC; if (config.bvh_type.value == "STATIC") sceneParams->bvh_type = ccl::SceneParams::BVH_STATIC; sceneParams->bvh_layout = ccl::BVH_LAYOUT_EMBREE; sceneParams->persistent_data = false; config.curve_subdivisions.eval(sceneParams->hair_subdivisions, a_forceInit); // Texture sceneParams->texture.use_cache = config.texture_use_cache.value; sceneParams->texture.cache_size = config.texture_cache_size.value; sceneParams->texture.tile_size = config.texture_tile_size.value; sceneParams->texture.diffuse_blur = config.texture_diffuse_blur.value; sceneParams->texture.glossy_blur = config.texture_glossy_blur.value; sceneParams->texture.auto_convert = config.texture_auto_convert.value; sceneParams->texture.accept_unmipped = config.texture_accept_unmipped.value; sceneParams->texture.accept_untiled = config.texture_accept_untiled.value; sceneParams->texture.auto_tile = config.texture_auto_tile.value; sceneParams->texture.auto_mip = config.texture_auto_mip.value; sceneParams->texture.use_custom_cache_path = config.texture_use_custom_path.value; sceneParams->texture.custom_cache_path = config.texture_custom_path.value; sceneParams->texture_limit = config.texture_max_size.value; } void HdCyclesRenderParam::_UpdateSceneFromRenderSettings(HdRenderSettingsMap const& settingsMap) { for (auto& entry : settingsMap) { TfToken key = entry.first; VtValue value = entry.second; _HandleSceneRenderSetting(key, value); } } bool HdCyclesRenderParam::_HandleSceneRenderSetting(const TfToken& key, const VtValue& value) { // -- Scene ccl::SceneParams* sceneParams = &m_sceneParams; if (m_cyclesScene) sceneParams = &m_cyclesScene->params; bool scene_updated = false; bool texture_updated = false; if (key == usdCyclesTokens->cyclesShading_system) { TfToken shading_system = _HdCyclesGetVtValue<TfToken>(value, usdCyclesTokens->svm, &scene_updated); if (shading_system == usdCyclesTokens->svm) { sceneParams->shadingsystem = ccl::SHADINGSYSTEM_SVM; } else if (shading_system == usdCyclesTokens->osl) { sceneParams->shadingsystem = ccl::SHADINGSYSTEM_OSL; } } if (key == usdCyclesTokens->cyclesBvh_type) { TfToken bvh_type = _HdCyclesGetVtValue<TfToken>(value, usdCyclesTokens->bvh_dynamic, &scene_updated); if (bvh_type == usdCyclesTokens->bvh_dynamic) { sceneParams->bvh_type = ccl::SceneParams::BVH_DYNAMIC; } else if (bvh_type == usdCyclesTokens->bvh_static) { sceneParams->bvh_type = ccl::SceneParams::BVH_STATIC; } } if (key == usdCyclesTokens->cyclesCurve_subdivisions) { sceneParams->hair_subdivisions = _HdCyclesGetVtValue<int>(value, sceneParams->hair_subdivisions, &scene_updated); } // TODO: Unsure how we will handle this if the camera hasn't been created yet/at all... /*if (key == usdCyclesTokens->cyclesDicing_camera) { scene->dicing_camera = _HdCyclesGetVtValue<std::string>(value, scene->dicing_camera, &scene_updated); }*/ if (key == usdCyclesTokens->cyclesUse_bvh_spatial_split) { sceneParams->use_bvh_spatial_split = _HdCyclesGetVtValue<bool>(value, sceneParams->use_bvh_spatial_split, &scene_updated); } if (key == usdCyclesTokens->cyclesUse_bvh_unaligned_nodes) { sceneParams->use_bvh_unaligned_nodes = _HdCyclesGetVtValue<bool>(value, sceneParams->use_bvh_unaligned_nodes, &scene_updated); } if (key == usdCyclesTokens->cyclesNum_bvh_time_steps) { sceneParams->num_bvh_time_steps = _HdCyclesGetVtValue<int>(value, sceneParams->num_bvh_time_steps, &scene_updated); } if (key == usdCyclesTokens->cyclesTexture_use_cache) { sceneParams->texture.use_cache = _HdCyclesGetVtValue<bool>(value, sceneParams->texture.use_cache, &texture_updated); } if (key == usdCyclesTokens->cyclesTexture_cache_size) { sceneParams->texture.cache_size = _HdCyclesGetVtValue<int>(value, sceneParams->texture.cache_size, &texture_updated); } if (key == usdCyclesTokens->cyclesTexture_tile_size) { sceneParams->texture.tile_size = _HdCyclesGetVtValue<int>(value, sceneParams->texture.tile_size, &texture_updated); } if (key == usdCyclesTokens->cyclesTexture_diffuse_blur) { sceneParams->texture.diffuse_blur = _HdCyclesGetVtValue<float>(value, sceneParams->texture.diffuse_blur, &texture_updated); } if (key == usdCyclesTokens->cyclesTexture_glossy_blur) { sceneParams->texture.glossy_blur = _HdCyclesGetVtValue<float>(value, sceneParams->texture.glossy_blur, &texture_updated); } if (key == usdCyclesTokens->cyclesTexture_auto_convert) { sceneParams->texture.auto_convert = _HdCyclesGetVtValue<bool>(value, sceneParams->texture.auto_convert, &texture_updated); } if (key == usdCyclesTokens->cyclesTexture_accept_unmipped) { sceneParams->texture.accept_unmipped = _HdCyclesGetVtValue<bool>(value, sceneParams->texture.accept_unmipped, &texture_updated); } if (key == usdCyclesTokens->cyclesTexture_accept_untiled) { sceneParams->texture.accept_untiled = _HdCyclesGetVtValue<bool>(value, sceneParams->texture.accept_untiled, &texture_updated); } if (key == usdCyclesTokens->cyclesTexture_auto_tile) { sceneParams->texture.auto_tile = _HdCyclesGetVtValue<bool>(value, sceneParams->texture.auto_tile, &texture_updated); } if (key == usdCyclesTokens->cyclesTexture_auto_mip) { sceneParams->texture.auto_mip = _HdCyclesGetVtValue<bool>(value, sceneParams->texture.auto_mip, &texture_updated); } if (key == usdCyclesTokens->cyclesTexture_use_custom_path) { sceneParams->texture.use_custom_cache_path = _HdCyclesGetVtValue<bool>(value, sceneParams->texture.use_custom_cache_path, &texture_updated); } if (key == usdCyclesTokens->cyclesTexture_max_size) { sceneParams->texture_limit = _HdCyclesGetVtValue<int>(value, sceneParams->texture_limit, &texture_updated); } if (scene_updated || texture_updated) { // Although this is called, it does not correctly reset session in IPR if (m_cyclesSession && m_cyclesScene) { Interrupt(true); if (texture_updated) { m_cyclesScene->image_manager->need_update = true; m_cyclesScene->shader_manager->need_update = true; } } return true; } return false; } // -- Config void HdCyclesRenderParam::_UpdateIntegratorFromConfig(bool a_forceInit) { if (!m_cyclesScene) return; static const HdCyclesConfig& config = HdCyclesConfig::GetInstance(); ccl::Integrator* integrator = m_cyclesScene->integrator; if (a_forceInit) { if (config.integrator_method.value == "PATH") { integrator->method = ccl::Integrator::PATH; } else { integrator->method = ccl::Integrator::BRANCHED_PATH; } } // Samples if (config.diffuse_samples.eval(integrator->diffuse_samples, a_forceInit) && m_useSquareSamples) { integrator->diffuse_samples = integrator->diffuse_samples * integrator->diffuse_samples; } if (config.glossy_samples.eval(integrator->glossy_samples, a_forceInit) && m_useSquareSamples) { integrator->glossy_samples = integrator->glossy_samples * integrator->glossy_samples; } if (config.transmission_samples.eval(integrator->transmission_samples, a_forceInit) && m_useSquareSamples) { integrator->transmission_samples = integrator->transmission_samples * integrator->transmission_samples; } if (config.ao_samples.eval(integrator->ao_samples, a_forceInit) && m_useSquareSamples) { integrator->ao_samples = integrator->ao_samples * integrator->ao_samples; } if (config.mesh_light_samples.eval(integrator->mesh_light_samples, a_forceInit) && m_useSquareSamples) { integrator->mesh_light_samples = integrator->mesh_light_samples * integrator->mesh_light_samples; } if (config.subsurface_samples.eval(integrator->subsurface_samples, a_forceInit) && m_useSquareSamples) { integrator->subsurface_samples = integrator->subsurface_samples * integrator->subsurface_samples; } if (config.volume_samples.eval(integrator->volume_samples, a_forceInit) && m_useSquareSamples) { integrator->volume_samples = integrator->volume_samples * integrator->volume_samples; } /*if (config.adaptive_min_samples.eval(integrator->adaptive_min_samples) && m_useSquareSamples) { integrator->adaptive_min_samples = std::min(integrator->adaptive_min_samples * integrator->adaptive_min_samples, INT_MAX); }*/ integrator->motion_blur = config.motion_blur.value; integrator->tag_update(m_cyclesScene); } void HdCyclesRenderParam::_UpdateIntegratorFromRenderSettings(HdRenderSettingsMap const& settingsMap) { for (auto& entry : settingsMap) { TfToken key = entry.first; VtValue value = entry.second; _HandleIntegratorRenderSetting(key, value); } } bool HdCyclesRenderParam::_HandleIntegratorRenderSetting(const TfToken& key, const VtValue& value) { // -- Integrator Settings ccl::Integrator* integrator = m_cyclesScene->integrator; bool integrator_updated = false; bool method_updated = false; if (key == usdCyclesTokens->cyclesIntegratorSeed) { integrator->seed = _HdCyclesGetVtValue<int>(value, integrator->seed, &integrator_updated); } if (key == usdCyclesTokens->cyclesIntegratorMin_bounce) { integrator->min_bounce = _HdCyclesGetVtValue<int>(value, integrator->min_bounce, &integrator_updated); } if (key == usdCyclesTokens->cyclesIntegratorMax_bounce) { integrator->max_bounce = _HdCyclesGetVtValue<int>(value, integrator->max_bounce, &integrator_updated); } if (key == usdCyclesTokens->cyclesIntegratorMethod) { TfToken integratorMethod = _HdCyclesGetVtValue<TfToken>(value, usdCyclesTokens->path, &method_updated); if (integratorMethod == usdCyclesTokens->path) { integrator->method = ccl::Integrator::PATH; } else { integrator->method = ccl::Integrator::BRANCHED_PATH; } if (method_updated) { integrator_updated = true; if (integrator->aa_samples && integrator->method == ccl::Integrator::BRANCHED_PATH) { m_cyclesSession->params.samples = integrator->aa_samples; } } } if (key == usdCyclesTokens->cyclesIntegratorSampling_method) { TfToken defaultPattern = usdCyclesTokens->sobol; if (integrator->sampling_pattern == ccl::SAMPLING_PATTERN_CMJ) { defaultPattern = usdCyclesTokens->cmj; } else if (integrator->sampling_pattern == ccl::SAMPLING_PATTERN_PMJ) { defaultPattern = usdCyclesTokens->pmj; } TfToken samplingMethod = _HdCyclesGetVtValue<TfToken>(value, defaultPattern, &integrator_updated); if (samplingMethod == usdCyclesTokens->sobol) { integrator->sampling_pattern = ccl::SAMPLING_PATTERN_SOBOL; } else if (samplingMethod == usdCyclesTokens->cmj) { integrator->sampling_pattern = ccl::SAMPLING_PATTERN_CMJ; } else { integrator->sampling_pattern = ccl::SAMPLING_PATTERN_PMJ; } // Adaptive sampling must use PMJ if (m_cyclesSession->params.adaptive_sampling && integrator->sampling_pattern != ccl::SAMPLING_PATTERN_PMJ) { integrator_updated = true; integrator->sampling_pattern = ccl::SAMPLING_PATTERN_PMJ; } } if (key == usdCyclesTokens->cyclesIntegratorMax_diffuse_bounce) { integrator->max_diffuse_bounce = _HdCyclesGetVtValue<int>(value, integrator->max_diffuse_bounce, &integrator_updated); } if (key == usdCyclesTokens->cyclesIntegratorMax_glossy_bounce) { integrator->max_glossy_bounce = _HdCyclesGetVtValue<int>(value, integrator->max_glossy_bounce, &integrator_updated); } if (key == usdCyclesTokens->cyclesIntegratorMax_transmission_bounce) { integrator->max_transmission_bounce = _HdCyclesGetVtValue<int>(value, integrator->max_transmission_bounce, &integrator_updated); } if (key == usdCyclesTokens->cyclesIntegratorMax_volume_bounce) { integrator->max_volume_bounce = _HdCyclesGetVtValue<int>(value, integrator->max_volume_bounce, &integrator_updated); } if (key == usdCyclesTokens->cyclesIntegratorTransparent_min_bounce) { integrator->transparent_min_bounce = _HdCyclesGetVtValue<int>(value, integrator->transparent_min_bounce, &integrator_updated); } if (key == usdCyclesTokens->cyclesIntegratorTransparent_max_bounce) { integrator->transparent_max_bounce = _HdCyclesGetVtValue<int>(value, integrator->transparent_max_bounce, &integrator_updated); } if (key == usdCyclesTokens->cyclesIntegratorAo_bounces) { integrator->ao_bounces = _HdCyclesGetVtValue<int>(value, integrator->ao_bounces, &integrator_updated); } if (key == usdCyclesTokens->cyclesIntegratorVolume_max_steps) { integrator->volume_max_steps = _HdCyclesGetVtValue<int>(value, integrator->volume_max_steps, &integrator_updated); } if (key == usdCyclesTokens->cyclesIntegratorVolume_step_size) { integrator->volume_step_rate = _HdCyclesGetVtValue<float>(value, integrator->volume_step_rate, &integrator_updated); } if (key == usdCyclesTokens->cyclesIntegratorAdaptive_threshold) { integrator->adaptive_threshold = _HdCyclesGetVtValue<float>(value, integrator->adaptive_threshold, &integrator_updated); } // Samples if (key == usdCyclesTokens->cyclesIntegratorAa_samples) { bool sample_updated = false; integrator->aa_samples = _HdCyclesGetVtValue<int>(value, integrator->aa_samples, &sample_updated); if (sample_updated) { if (m_useSquareSamples) { integrator->aa_samples = integrator->aa_samples * integrator->aa_samples; } if (integrator->aa_samples && integrator->method == ccl::Integrator::BRANCHED_PATH) { m_cyclesSession->params.samples = integrator->aa_samples; } integrator_updated = true; } } if (key == usdCyclesTokens->cyclesIntegratorAdaptive_min_samples) { bool sample_updated = false; integrator->adaptive_min_samples = _HdCyclesGetVtValue<int>(value, integrator->adaptive_min_samples, &sample_updated); if (sample_updated) { if (m_useSquareSamples) { integrator->adaptive_min_samples = std::min(integrator->adaptive_min_samples * integrator->adaptive_min_samples, INT_MAX); } integrator_updated = true; } } if (key == usdCyclesTokens->cyclesIntegratorDiffuse_samples) { bool sample_updated = false; integrator->diffuse_samples = _HdCyclesGetVtValue<int>(value, integrator->diffuse_samples, &sample_updated); if (sample_updated) { if (m_useSquareSamples) { integrator->diffuse_samples = integrator->diffuse_samples * integrator->diffuse_samples; } integrator_updated = true; } } if (key == usdCyclesTokens->cyclesIntegratorGlossy_samples) { bool sample_updated = false; integrator->glossy_samples = _HdCyclesGetVtValue<int>(value, integrator->glossy_samples, &sample_updated); if (sample_updated) { if (m_useSquareSamples) { integrator->glossy_samples = integrator->glossy_samples * integrator->glossy_samples; } integrator_updated = true; } } if (key == usdCyclesTokens->cyclesIntegratorTransmission_samples) { bool sample_updated = false; integrator->transmission_samples = _HdCyclesGetVtValue<int>(value, integrator->transmission_samples, &sample_updated); if (sample_updated) { if (m_useSquareSamples) { integrator->transmission_samples = integrator->transmission_samples * integrator->transmission_samples; } integrator_updated = true; } } if (key == usdCyclesTokens->cyclesIntegratorAo_samples) { bool sample_updated = false; integrator->ao_samples = _HdCyclesGetVtValue<int>(value, integrator->ao_samples, &sample_updated); if (sample_updated) { if (m_useSquareSamples) { integrator->ao_samples = integrator->ao_samples * integrator->ao_samples; } integrator_updated = true; } } if (key == usdCyclesTokens->cyclesIntegratorMesh_light_samples) { bool sample_updated = false; integrator->mesh_light_samples = _HdCyclesGetVtValue<int>(value, integrator->mesh_light_samples, &sample_updated); if (sample_updated) { if (m_useSquareSamples) { integrator->mesh_light_samples = integrator->mesh_light_samples * integrator->mesh_light_samples; } integrator_updated = true; } } if (key == usdCyclesTokens->cyclesIntegratorSubsurface_samples) { bool sample_updated = false; integrator->subsurface_samples = _HdCyclesGetVtValue<int>(value, integrator->subsurface_samples, &sample_updated); if (sample_updated) { if (m_useSquareSamples) { integrator->subsurface_samples = integrator->subsurface_samples * integrator->subsurface_samples; } integrator_updated = true; } } if (key == usdCyclesTokens->cyclesIntegratorVolume_samples) { bool sample_updated = false; integrator->volume_samples = _HdCyclesGetVtValue<int>(value, integrator->volume_samples, &sample_updated); if (sample_updated) { if (m_useSquareSamples) { integrator->volume_samples = integrator->volume_samples * integrator->volume_samples; } integrator_updated = true; } } if (key == usdCyclesTokens->cyclesIntegratorStart_sample) { integrator->start_sample = _HdCyclesGetVtValue<int>(value, integrator->start_sample, &integrator_updated); } // Caustics if (key == usdCyclesTokens->cyclesIntegratorCaustics_reflective) { integrator->caustics_reflective = _HdCyclesGetVtValue<bool>(value, integrator->caustics_reflective, &integrator_updated); } if (key == usdCyclesTokens->cyclesIntegratorCaustics_refractive) { integrator->caustics_refractive = _HdCyclesGetVtValue<bool>(value, integrator->caustics_refractive, &integrator_updated); } // Filter if (key == usdCyclesTokens->cyclesIntegratorFilter_glossy) { integrator->filter_glossy = _HdCyclesGetVtValue<float>(value, integrator->filter_glossy, &integrator_updated); } if (key == usdCyclesTokens->cyclesIntegratorSample_clamp_direct) { integrator->sample_clamp_direct = _HdCyclesGetVtValue<float>(value, integrator->sample_clamp_direct, &integrator_updated); } if (key == usdCyclesTokens->cyclesIntegratorSample_clamp_indirect) { integrator->sample_clamp_indirect = _HdCyclesGetVtValue<float>(value, integrator->sample_clamp_indirect, &integrator_updated); } if (key == usdCyclesTokens->cyclesIntegratorMotion_blur) { integrator->motion_blur = _HdCyclesGetVtValue<bool>(value, integrator->motion_blur, &integrator_updated); } if (key == usdCyclesTokens->cyclesIntegratorSample_all_lights_direct) { integrator->sample_all_lights_direct = _HdCyclesGetVtValue<bool>(value, integrator->sample_all_lights_direct, &integrator_updated); } if (key == usdCyclesTokens->cyclesIntegratorSample_all_lights_indirect) { integrator->sample_all_lights_indirect = _HdCyclesGetVtValue<bool>(value, integrator->sample_all_lights_indirect, &integrator_updated); } if (key == usdCyclesTokens->cyclesIntegratorLight_sampling_threshold) { integrator->light_sampling_threshold = _HdCyclesGetVtValue<float>(value, integrator->light_sampling_threshold, &integrator_updated); } if (integrator_updated) { integrator->tag_update(m_cyclesScene); if (method_updated) { DirectReset(); } return true; } return false; } // -- Film void HdCyclesRenderParam::_UpdateFilmFromConfig(bool a_forceInit) { if (!m_cyclesScene) return; static const HdCyclesConfig& config = HdCyclesConfig::GetInstance(); ccl::Film* film = m_cyclesScene->film; config.exposure.eval(film->exposure, a_forceInit); film->tag_update(m_cyclesScene); } void HdCyclesRenderParam::_UpdateFilmFromRenderSettings(HdRenderSettingsMap const& settingsMap) { for (auto& entry : settingsMap) { TfToken key = entry.first; VtValue value = entry.second; _HandleFilmRenderSetting(key, value); } } bool HdCyclesRenderParam::_HandleFilmRenderSetting(const TfToken& key, const VtValue& value) { // -- Film Settings ccl::Film* film = m_cyclesScene->film; bool film_updated = false; bool doResetBuffers = false; if (key == usdCyclesTokens->cyclesFilmExposure) { film->exposure = _HdCyclesGetVtValue<float>(value, film->exposure, &film_updated, false); } if (key == usdCyclesTokens->cyclesFilmPass_alpha_threshold) { film->pass_alpha_threshold = _HdCyclesGetVtValue<float>(value, film->pass_alpha_threshold, &film_updated, false); } // https://www.sidefx.com/docs/hdk/_h_d_k__u_s_d_hydra.html if (key == UsdRenderTokens->resolution) { GfVec2i resolutionDefault = m_resolutionImage; if (value.IsHolding<GfVec2i>()) { m_resolutionImage = _HdCyclesGetVtValue<GfVec2i>(value, resolutionDefault, &film_updated, false); m_resolutionAuthored = true; doResetBuffers = true; } else { TF_WARN("Unexpected type for resolution %s", value.GetTypeName().c_str()); } } if (key == UsdRenderTokens->dataWindowNDC) { GfVec4f dataWindowNDCDefault = { 0.f, 0.f, 1.f, 1.f }; if (value.IsHolding<GfVec4f>()) { m_dataWindowNDC = _HdCyclesGetVtValue<GfVec4f>(value, dataWindowNDCDefault, &film_updated, false); // Rect has to be valid, otherwise reset to default if (m_dataWindowNDC[0] > m_dataWindowNDC[2] || m_dataWindowNDC[1] > m_dataWindowNDC[3]) { TF_WARN("Invalid dataWindowNDC rectangle %f %f %f %f", m_dataWindowNDC[0], m_dataWindowNDC[1], m_dataWindowNDC[2], m_dataWindowNDC[3]); m_dataWindowNDC = dataWindowNDCDefault; } doResetBuffers = true; } else { TF_WARN("Unexpected type for ndcDataWindow %s", value.GetTypeName().c_str()); } } // Filter if (key == usdCyclesTokens->cyclesFilmFilter_type) { TfToken filter = _HdCyclesGetVtValue<TfToken>(value, usdCyclesTokens->box, &film_updated); if (filter == usdCyclesTokens->box) { film->filter_type = ccl::FilterType::FILTER_BOX; } else if (filter == usdCyclesTokens->gaussian) { film->filter_type = ccl::FilterType::FILTER_GAUSSIAN; } else { film->filter_type = ccl::FilterType::FILTER_BLACKMAN_HARRIS; } } if (key == usdCyclesTokens->cyclesFilmFilter_width) { film->filter_width = _HdCyclesGetVtValue<float>(value, film->filter_width, &film_updated, false); } // Mist if (key == usdCyclesTokens->cyclesFilmMist_start) { film->mist_start = _HdCyclesGetVtValue<float>(value, film->mist_start, &film_updated, false); } if (key == usdCyclesTokens->cyclesFilmMist_depth) { film->mist_depth = _HdCyclesGetVtValue<float>(value, film->mist_depth, &film_updated, false); } if (key == usdCyclesTokens->cyclesFilmMist_falloff) { film->mist_falloff = _HdCyclesGetVtValue<float>(value, film->mist_falloff, &film_updated, false); } // Light if (key == usdCyclesTokens->cyclesFilmUse_light_visibility) { film->use_light_visibility = _HdCyclesGetVtValue<bool>(value, film->use_light_visibility, &film_updated, false); } if (key == usdCyclesTokens->cyclesFilmCryptomatte_depth) { auto cryptomatte_depth = _HdCyclesGetVtValue<int>(value, 4, &film_updated, false); film->cryptomatte_depth = static_cast<int>( ccl::divide_up(static_cast<size_t>(ccl::min(16, cryptomatte_depth)), 2)); } if (film_updated) { film->tag_update(m_cyclesScene); // todo: Should this live in another location? if (doResetBuffers) { film->tag_passes_update(m_cyclesScene, m_bufferParams.passes); SetViewport(m_resolutionDisplay[0], m_resolutionDisplay[1]); for (HdRenderPassAovBinding& aov : m_aovs) { if (aov.renderBuffer) { dynamic_cast<HdCyclesRenderBuffer*>(aov.renderBuffer)->Clear(); } } } return true; } return false; } void HdCyclesRenderParam::_UpdateBackgroundFromConfig(bool a_forceInit) { if (!m_cyclesScene) return; static const HdCyclesConfig& config = HdCyclesConfig::GetInstance(); ccl::Background* background = m_cyclesScene->background; if (config.enable_transparent_background.value) background->transparent = true; background->tag_update(m_cyclesScene); } void HdCyclesRenderParam::_UpdateBackgroundFromRenderSettings(HdRenderSettingsMap const& settingsMap) { for (auto& entry : settingsMap) { TfToken key = entry.first; VtValue value = entry.second; _HandleBackgroundRenderSetting(key, value); } } bool HdCyclesRenderParam::_HandleBackgroundRenderSetting(const TfToken& key, const VtValue& value) { // -- Background Settings ccl::Background* background = m_cyclesScene->background; bool background_updated = false; if (key == usdCyclesTokens->cyclesBackgroundAo_factor) { background->ao_factor = _HdCyclesGetVtValue<float>(value, background->ao_factor, &background_updated); } if (key == usdCyclesTokens->cyclesBackgroundAo_distance) { background->ao_distance = _HdCyclesGetVtValue<float>(value, background->ao_distance, &background_updated); } if (key == usdCyclesTokens->cyclesBackgroundUse_shader) { background->use_shader = _HdCyclesGetVtValue<bool>(value, background->use_shader, &background_updated); } if (key == usdCyclesTokens->cyclesBackgroundUse_ao) { background->use_ao = _HdCyclesGetVtValue<bool>(value, background->use_ao, &background_updated); } // Visibility bool visCamera, visDiffuse, visGlossy, visTransmission, visScatter; visCamera = visDiffuse = visGlossy = visTransmission = visScatter = true; unsigned int visFlags = 0; if (key == usdCyclesTokens->cyclesBackgroundVisibilityCamera) { visCamera = _HdCyclesGetVtValue<bool>(value, visCamera, &background_updated); } if (key == usdCyclesTokens->cyclesBackgroundVisibilityDiffuse) { visDiffuse = _HdCyclesGetVtValue<bool>(value, visDiffuse, &background_updated); } if (key == usdCyclesTokens->cyclesBackgroundVisibilityGlossy) { visGlossy = _HdCyclesGetVtValue<bool>(value, visGlossy, &background_updated); } if (key == usdCyclesTokens->cyclesBackgroundVisibilityTransmission) { visTransmission = _HdCyclesGetVtValue<bool>(value, visTransmission, &background_updated); } if (key == usdCyclesTokens->cyclesBackgroundVisibilityScatter) { visScatter = _HdCyclesGetVtValue<bool>(value, visScatter, &background_updated); } visFlags |= visCamera ? ccl::PATH_RAY_CAMERA : 0; visFlags |= visDiffuse ? ccl::PATH_RAY_DIFFUSE : 0; visFlags |= visGlossy ? ccl::PATH_RAY_GLOSSY : 0; visFlags |= visTransmission ? ccl::PATH_RAY_TRANSMIT : 0; visFlags |= visScatter ? ccl::PATH_RAY_VOLUME_SCATTER : 0; background->visibility = visFlags; // Glass if (key == usdCyclesTokens->cyclesBackgroundTransparent) { background->transparent = _HdCyclesGetVtValue<bool>(value, background->transparent, &background_updated); } if (key == usdCyclesTokens->cyclesBackgroundTransparent_glass) { background->transparent_glass = _HdCyclesGetVtValue<bool>(value, background->transparent_glass, &background_updated); } if (key == usdCyclesTokens->cyclesBackgroundTransparent_roughness_threshold) { background->transparent_roughness_threshold = _HdCyclesGetVtValue<float>(value, background->transparent_roughness_threshold, &background_updated); } // Volume if (key == usdCyclesTokens->cyclesBackgroundVolume_step_size) { background->volume_step_size = _HdCyclesGetVtValue<float>(value, background->volume_step_size, &background_updated); } if (background_updated) { background->tag_update(m_cyclesScene); return true; } return false; } void HdCyclesRenderParam::_HandlePasses() { // TODO: These might need to live elsewhere when we fully implement aovs/passes m_bufferParams.passes.clear(); ccl::Pass::add(ccl::PASS_COMBINED, m_bufferParams.passes, "Combined"); m_cyclesScene->film->tag_passes_update(m_cyclesScene, m_bufferParams.passes); } bool HdCyclesRenderParam::SetRenderSetting(const TfToken& key, const VtValue& value) { // This has some inherent performance overheads (runs multiple times, unecessary) // however for now, this works the most clearly due to Cycles restrictions _HandleSessionRenderSetting(key, value); _HandleSceneRenderSetting(key, value); _HandleIntegratorRenderSetting(key, value); _HandleFilmRenderSetting(key, value); _HandleBackgroundRenderSetting(key, value); return false; } bool HdCyclesRenderParam::_CreateSession() { bool foundDevice = SetDeviceType(m_deviceName, m_sessionParams); if (!foundDevice) return false; m_cyclesSession = new ccl::Session(m_sessionParams); m_cyclesSession->display_copy_cb = [this](int samples) { const int width = m_cyclesSession->tile_manager.state.buffer.width; const int height = m_cyclesSession->tile_manager.state.buffer.height; tbb::parallel_for(tbb::blocked_range<size_t>(0, m_aovs.size(), 1), [this, width, height, samples](const tbb::blocked_range<size_t>& r) { for (size_t i = r.begin(); i < r.end(); ++i) { BlitFromCyclesPass(m_aovs[i], width, height, samples); } }); }; m_cyclesSession->write_render_tile_cb = std::bind(&HdCyclesRenderParam::_WriteRenderTile, this, ccl::_1); m_cyclesSession->update_render_tile_cb = std::bind(&HdCyclesRenderParam::_UpdateRenderTile, this, ccl::_1, ccl::_2); m_cyclesSession->progress.set_update_callback(std::bind(&HdCyclesRenderParam::_SessionUpdateCallback, this)); return true; } void HdCyclesRenderParam::_WriteRenderTile(ccl::RenderTile& rtile) { // No session, exit out if (!m_cyclesSession) return; if (!m_useTiledRendering) return; const int w = rtile.w; const int h = rtile.h; ccl::RenderBuffers* buffers = rtile.buffers; // copy data from device if (!buffers->copy_from_device()) return; // Adjust absolute sample number to the range. int sample = rtile.sample; const int range_start_sample = m_cyclesSession->tile_manager.range_start_sample; if (range_start_sample != -1) { sample -= range_start_sample; } const float exposure = m_cyclesScene->film->exposure; if (!m_aovs.empty()) { // Blit from the framebuffer to currently selected aovs... for (auto& aov : m_aovs) { if (!TF_VERIFY(aov.renderBuffer != nullptr)) { continue; } auto* rb = static_cast<HdCyclesRenderBuffer*>(aov.renderBuffer); if (rb == nullptr) { continue; } if (rb->GetFormat() == HdFormatInvalid) { continue; } HdCyclesAov cyclesAov; if (!GetCyclesAov(aov, cyclesAov)) { continue; } // We don't want a mismatch of formats if (rb->GetFormat() != cyclesAov.format) { continue; } bool custom, denoise; GetAovFlags(cyclesAov, custom, denoise); // Pixels we will use to get from cycles. size_t numComponents = HdGetComponentCount(cyclesAov.format); ccl::vector<float> tileData(w * h * numComponents); rb->SetConverged(IsConverged()); bool read = false; if (!custom && !denoise) { read = buffers->get_pass_rect(cyclesAov.name.c_str(), exposure, sample, static_cast<int>(numComponents), &tileData[0]); } else if (denoise) { read = buffers->get_denoising_pass_rect(GetDenoisePass(cyclesAov.token), exposure, sample, static_cast<int>(numComponents), &tileData[0]); } else if (custom) { read = buffers->get_pass_rect(aov.aovName.GetText(), exposure, sample, static_cast<int>(numComponents), &tileData[0]); } if (!read) { memset(&tileData[0], 0, tileData.size() * sizeof(float)); } // Translate source subrect to the origin const unsigned int x_src = rtile.x - m_cyclesSession->tile_manager.params.full_x; const unsigned int y_src = rtile.y - m_cyclesSession->tile_manager.params.full_y; // Passing the dimension as float to not lose the decimal points in the conversion to int // We need to do this only for tiles becase we are scaling the source rect to calculate // the region to write to in the destination rect const float width_data_src = m_bufferParams.width; const float height_data_src = m_bufferParams.height; rb->BlitTile(cyclesAov.format, x_src, y_src, rtile.w, rtile.h, width_data_src, height_data_src, 0, rtile.w, reinterpret_cast<uint8_t*>(tileData.data())); } } } void HdCyclesRenderParam::_UpdateRenderTile(ccl::RenderTile& rtile, bool highlight) { if (m_cyclesSession->params.progressive_refine) _WriteRenderTile(rtile); } bool HdCyclesRenderParam::_CreateScene() { static const HdCyclesConfig& config = HdCyclesConfig::GetInstance(); m_cyclesScene = new ccl::Scene(m_sceneParams, m_cyclesSession->device); m_resolutionImage = GfVec2i(0, 0); m_resolutionDisplay = GfVec2i(config.render_width.value, config.render_height.value); m_cyclesScene->camera->width = m_resolutionDisplay[0]; m_cyclesScene->camera->height = m_resolutionDisplay[1]; m_cyclesScene->camera->compute_auto_viewplane(); m_cyclesSession->scene = m_cyclesScene; m_bufferParams.width = m_resolutionDisplay[0]; m_bufferParams.height = m_resolutionDisplay[1]; m_bufferParams.full_width = m_resolutionDisplay[0]; m_bufferParams.full_height = m_resolutionDisplay[1]; default_attrib_display_color_surface = HdCyclesCreateAttribColorSurface(); default_attrib_display_color_surface->tag_update(m_cyclesScene); m_cyclesScene->shaders.push_back(default_attrib_display_color_surface); default_object_display_color_surface = HdCyclesCreateObjectColorSurface(); default_object_display_color_surface->tag_update(m_cyclesScene); m_cyclesScene->shaders.push_back(default_object_display_color_surface); default_vcol_display_color_surface = HdCyclesCreateDefaultShader(); default_vcol_display_color_surface->tag_update(m_cyclesScene); m_cyclesScene->shaders.push_back(default_vcol_display_color_surface); SetBackgroundShader(nullptr); m_cyclesSession->reset(m_bufferParams, m_sessionParams.samples); return true; } void HdCyclesRenderParam::StartRender() { _CyclesStart(); } void HdCyclesRenderParam::StopRender() { _CyclesExit(); } // Deprecate? This isnt used... Also doesnt work void HdCyclesRenderParam::RestartRender() { StopRender(); Initialize({}); StartRender(); } void HdCyclesRenderParam::PauseRender() { if (m_cyclesSession) m_cyclesSession->set_pause(true); } void HdCyclesRenderParam::ResumeRender() { if (m_cyclesSession) m_cyclesSession->set_pause(false); } void HdCyclesRenderParam::Interrupt(bool a_forceUpdate) { m_shouldUpdate = true; PauseRender(); } void HdCyclesRenderParam::CommitResources() { ccl::thread_scoped_lock lock { m_cyclesScene->mutex }; if (m_shouldUpdate) { if (m_cyclesScene->lights.size() > 0) { if (m_numDomeLights <= 0) SetBackgroundShader(nullptr, false); } else { SetBackgroundShader(nullptr, true); } CyclesReset(false); m_shouldUpdate = false; ResumeRender(); } } void HdCyclesRenderParam::SetBackgroundShader(ccl::Shader* a_shader, bool a_emissive) { if (a_shader) m_cyclesScene->default_background = a_shader; else { // TODO: These aren't properly destroyed from memory // Create empty background shader m_cyclesScene->default_background = new ccl::Shader(); m_cyclesScene->default_background->name = "default_background"; m_cyclesScene->default_background->graph = new ccl::ShaderGraph(); if (a_emissive) { ccl::BackgroundNode* bgNode = new ccl::BackgroundNode(); bgNode->color = ccl::make_float3(0.6f, 0.6f, 0.6f); m_cyclesScene->default_background->graph->add(bgNode); ccl::ShaderNode* out = m_cyclesScene->default_background->graph->output(); m_cyclesScene->default_background->graph->connect(bgNode->output("Background"), out->input("Surface")); } m_cyclesScene->default_background->tag_update(m_cyclesScene); m_cyclesScene->shaders.push_back(m_cyclesScene->default_background); } m_cyclesScene->background->tag_update(m_cyclesScene); } /* ======= Cycles Settings ======= */ // -- Cycles render device bool HdCyclesRenderParam::SetDeviceType(ccl::DeviceType a_deviceType, ccl::SessionParams& params) { if (a_deviceType == ccl::DeviceType::DEVICE_NONE) { TF_WARN("Attempted to set device of type DEVICE_NONE."); return false; } m_deviceType = a_deviceType; m_deviceName = ccl::Device::string_from_type(a_deviceType); return _SetDevice(m_deviceType, params); } bool HdCyclesRenderParam::SetDeviceType(const std::string& a_deviceType, ccl::SessionParams& params) { return SetDeviceType(ccl::Device::type_from_string(a_deviceType.c_str()), params); } bool HdCyclesRenderParam::SetDeviceType(const std::string& a_deviceType) { ccl::SessionParams* params = &m_sessionParams; if (m_cyclesSession) params = &m_cyclesSession->params; return SetDeviceType(a_deviceType, *params); } bool HdCyclesRenderParam::_SetDevice(const ccl::DeviceType& a_deviceType, ccl::SessionParams& params) { std::vector<ccl::DeviceInfo> devices = ccl::Device::available_devices( static_cast<ccl::DeviceTypeMask>(1 << a_deviceType)); bool device_available = false; if (!devices.empty()) { params.device = devices.front(); device_available = true; } if (params.device.type == ccl::DEVICE_NONE || !device_available) { TF_RUNTIME_ERROR("No device available exiting."); } return device_available; } /* ====== HdCycles Settings ====== */ /* ====== Cycles Lifecycle ====== */ void HdCyclesRenderParam::_CyclesStart() { m_cyclesSession->start(); } void HdCyclesRenderParam::_CyclesExit() { m_cyclesSession->set_pause(true); ccl::thread_scoped_lock lock { m_cyclesScene->mutex }; m_cyclesScene->shaders.clear(); m_cyclesScene->geometry.clear(); m_cyclesScene->objects.clear(); m_cyclesScene->lights.clear(); m_cyclesScene->particle_systems.clear(); if (m_cyclesSession) { delete m_cyclesSession; m_cyclesSession = nullptr; } } // TODO: Refactor these two resets void HdCyclesRenderParam::CyclesReset(bool a_forceUpdate) { m_cyclesSession->progress.reset(); if (m_geometryUpdated || m_shadersUpdated) { m_cyclesScene->geometry_manager->tag_update(m_cyclesScene); m_geometryUpdated = false; } if (m_objectsUpdated || m_shadersUpdated) { m_cyclesScene->object_manager->tag_update(m_cyclesScene); if (m_shadersUpdated) { m_cyclesScene->background->tag_update(m_cyclesScene); } m_objectsUpdated = false; m_shadersUpdated = false; } if (m_lightsUpdated) { m_cyclesScene->light_manager->tag_update(m_cyclesScene); m_lightsUpdated = false; } if (a_forceUpdate) { m_cyclesScene->integrator->tag_update(m_cyclesScene); m_cyclesScene->background->tag_update(m_cyclesScene); m_cyclesScene->film->tag_update(m_cyclesScene); } m_cyclesSession->reset(m_bufferParams, m_cyclesSession->params.samples); } void HdCyclesRenderParam::SetViewport(int w, int h) { m_resolutionDisplay = GfVec2i(w, h); // If no image resolution was specified, we use the display's if (!m_resolutionAuthored) { m_resolutionImage = m_resolutionDisplay; } // Since the sensor is scaled uniformly, we also scale all the corners // of the image rect by the maximum amount of overscan // But only allocate and render a subrect const float overscan = MaxOverscan(); // Full rect m_bufferParams.full_width = (1.f + overscan * 2.f) * m_resolutionImage[0]; m_bufferParams.full_height = (1.f + overscan * 2.f) * m_resolutionImage[1]; // Translate to the origin of the full rect m_bufferParams.full_x = (m_dataWindowNDC[0] - (-overscan)) * m_resolutionImage[0]; m_bufferParams.full_y = (m_dataWindowNDC[1] - (-overscan)) * m_resolutionImage[1]; m_bufferParams.width = (m_dataWindowNDC[2] - m_dataWindowNDC[0]) * m_resolutionImage[0]; m_bufferParams.height = (m_dataWindowNDC[3] - m_dataWindowNDC[1]) * m_resolutionImage[1]; m_cyclesScene->camera->width = m_bufferParams.full_width; m_cyclesScene->camera->height = m_bufferParams.full_height; m_cyclesScene->camera->overscan = overscan; m_bufferParams.width = ::std::max(m_bufferParams.width, 1); m_bufferParams.height = ::std::max(m_bufferParams.height, 1); m_cyclesScene->camera->compute_auto_viewplane(); m_cyclesScene->camera->need_update = true; m_cyclesScene->camera->need_device_update = true; m_aovBindingsNeedValidation = true; DirectReset(); } void HdCyclesRenderParam::DirectReset() { m_cyclesSession->reset(m_bufferParams, m_cyclesSession->params.samples); } void HdCyclesRenderParam::UpdateShadersTag(ccl::vector<ccl::Shader*>& shaders) { for (auto& shader : shaders) { shader->tag_update(m_cyclesScene); } } void HdCyclesRenderParam::AddShader(ccl::Shader* shader) { if (!m_cyclesScene) { TF_WARN("Couldn't add geometry to scene. Scene is null."); return; } m_shadersUpdated = true; m_cyclesScene->shaders.push_back(shader); } void HdCyclesRenderParam::AddLight(ccl::Light* light) { if (!m_cyclesScene) { TF_WARN("Couldn't add light to scene. Scene is null."); return; } m_lightsUpdated = true; m_cyclesScene->lights.push_back(light); if (light->type == ccl::LIGHT_BACKGROUND) { m_numDomeLights += 1; } } void HdCyclesRenderParam::AddObject(ccl::Object* object) { if (!m_cyclesScene) { TF_WARN("Couldn't add object to scene. Scene is null."); return; } m_objectsUpdated = true; m_cyclesScene->objects.push_back(object); Interrupt(); } void HdCyclesRenderParam::AddObjectArray(std::vector<ccl::Object>& objects) { if (!m_cyclesScene) { TF_WARN("Couldn't add object to scene. Scene is null."); return; } const size_t numObjects = objects.size(); const size_t startIndex = m_cyclesScene->objects.size(); m_cyclesScene->objects.resize(startIndex + numObjects); for (size_t i = 0; i < numObjects; i++) { m_cyclesScene->objects[startIndex + i] = &objects[i]; } m_objectsUpdated = true; Interrupt(); } void HdCyclesRenderParam::RemoveObjectArray(const std::vector<ccl::Object>& objects) { if (!m_cyclesScene) { TF_WARN("Couldn't add object to scene. Scene is null."); return; } size_t numObjectsToRemove = objects.size(); const size_t numSceneObjects = m_cyclesScene->objects.size(); // Find the first object for (size_t i = 0; i < numSceneObjects; i++) { if (m_cyclesScene->objects[i] == &objects[0]) { m_cyclesScene->objects.erase(m_cyclesScene->objects.begin() + i, m_cyclesScene->objects.begin() + i + numObjectsToRemove); break; } } m_objectsUpdated = true; Interrupt(); } void HdCyclesRenderParam::AddGeometry(ccl::Geometry* geometry) { if (!m_cyclesScene) { TF_WARN("Couldn't add geometry to scene. Scene is null."); return; } m_geometryUpdated = true; m_cyclesScene->geometry.push_back(geometry); Interrupt(); } void HdCyclesRenderParam::RemoveShader(ccl::Shader* shader) { for (auto it = m_cyclesScene->shaders.begin(); it != m_cyclesScene->shaders.end();) { if (shader == *it) { it = m_cyclesScene->shaders.erase(it); m_shadersUpdated = true; break; } else { ++it; } } if (m_shadersUpdated) Interrupt(); } void HdCyclesRenderParam::RemoveLight(ccl::Light* light) { for (auto it = m_cyclesScene->lights.begin(); it != m_cyclesScene->lights.end();) { if (light == *it) { it = m_cyclesScene->lights.erase(it); // TODO: This doesnt respect multiple dome lights if (light->type == ccl::LIGHT_BACKGROUND) { m_numDomeLights = std::max(0, m_numDomeLights - 1); } m_lightsUpdated = true; break; } else { ++it; } } if (m_lightsUpdated) Interrupt(); } void HdCyclesRenderParam::RemoveObject(ccl::Object* object) { for (auto it = m_cyclesScene->objects.begin(); it != m_cyclesScene->objects.end();) { if (object == *it) { it = m_cyclesScene->objects.erase(it); m_objectsUpdated = true; break; } else { ++it; } } if (m_objectsUpdated) Interrupt(); } void HdCyclesRenderParam::RemoveGeometry(ccl::Geometry* geometry) { for (auto it = m_cyclesScene->geometry.begin(); it != m_cyclesScene->geometry.end();) { if (geometry == *it) { it = m_cyclesScene->geometry.erase(it); m_geometryUpdated = true; break; } else { ++it; } } if (m_geometryUpdated) Interrupt(); } void HdCyclesRenderParam::AddShaderSafe(ccl::Shader* shader) { ccl::thread_scoped_lock lock { m_cyclesScene->mutex }; AddShader(shader); } void HdCyclesRenderParam::AddLightSafe(ccl::Light* light) { ccl::thread_scoped_lock lock { m_cyclesScene->mutex }; AddLight(light); } void HdCyclesRenderParam::AddObjectSafe(ccl::Object* object) { ccl::thread_scoped_lock lock { m_cyclesScene->mutex }; AddObject(object); } void HdCyclesRenderParam::AddGeometrySafe(ccl::Geometry* geometry) { ccl::thread_scoped_lock lock { m_cyclesScene->mutex }; AddGeometry(geometry); } void HdCyclesRenderParam::RemoveShaderSafe(ccl::Shader* shader) { ccl::thread_scoped_lock lock { m_cyclesScene->mutex }; RemoveShader(shader); } void HdCyclesRenderParam::RemoveLightSafe(ccl::Light* light) { ccl::thread_scoped_lock lock { m_cyclesScene->mutex }; RemoveLight(light); } void HdCyclesRenderParam::RemoveObjectSafe(ccl::Object* object) { ccl::thread_scoped_lock lock { m_cyclesScene->mutex }; RemoveObject(object); } void HdCyclesRenderParam::RemoveGeometrySafe(ccl::Geometry* geometry) { ccl::thread_scoped_lock lock { m_cyclesScene->mutex }; RemoveGeometry(geometry); } VtDictionary HdCyclesRenderParam::GetRenderStats() const { // Currently, collect_statistics errors seemingly during render, // we probably need to only access these when the render is complete // however this codeflow is currently undefined... //ccl::RenderStats stats; //m_cyclesSession->collect_statistics(&stats); VtDictionary result = { { "hdcycles:version", VtValue(HD_CYCLES_VERSION) }, // - Cycles specific // These error out currently, kept for future reference /*{ "hdcycles:geometry:total_memory", VtValue(ccl::string_human_readable_size(stats.mesh.geometry.total_size) .c_str()) },*/ /*{ "hdcycles:textures:total_memory", VtValue( ccl::string_human_readable_size(stats.image.textures.total_size) .c_str()) },*/ { "hdcycles:scene:num_objects", VtValue(m_cyclesScene->objects.size()) }, { "hdcycles:scene:num_shaders", VtValue(m_cyclesScene->shaders.size()) }, // - Solaris, husk specific // Currently these don't update properly. It is unclear if we need to tag renderstats as // dynamic. Maybe our VtValues need to live longer? { "rendererName", VtValue("Cycles") }, { "rendererVersion", VtValue(HD_CYCLES_VERSION) }, { "percentDone", VtValue(m_renderPercent) }, { "fractionDone", VtValue(m_renderProgress) }, { "lightCounts", VtValue(m_cyclesScene->lights.size()) }, { "totalClockTime", VtValue(m_totalTime) }, { "cameraRays", VtValue(0) }, { "numCompletedSamples", VtValue(0) } }; // We need to store the cryptomatte metadata here, based on if there's any Cryptomatte AOVs bool cryptoAsset = false; bool cryptoObject = false; bool cryptoMaterial = false; std::string cryptoAssetName; std::string cryptoObjectName; std::string cryptoMaterialName; for (const HdRenderPassAovBinding& aov : m_aovs) { TfToken sourceName = GetSourceName(aov); if (!cryptoAsset && sourceName == HdCyclesAovTokens->CryptoAsset) { cryptoAssetName = aov.aovName.GetText(); if (cryptoAssetName.length() > 2) { cryptoAsset = true; cryptoAssetName.erase(cryptoAssetName.end() - 2, cryptoAssetName.end()); } continue; } if (!cryptoObject && sourceName == HdCyclesAovTokens->CryptoObject) { cryptoObjectName = aov.aovName.GetText(); if (cryptoObjectName.length() > 2) { cryptoObject = true; cryptoObjectName.erase(cryptoObjectName.end() - 2, cryptoObjectName.end()); } continue; } if (!cryptoMaterial && sourceName == HdCyclesAovTokens->CryptoMaterial) { cryptoMaterialName = aov.aovName.GetText(); if (cryptoMaterialName.length() > 2) { cryptoMaterial = true; cryptoMaterialName.erase(cryptoMaterialName.end() - 2, cryptoMaterialName.end()); } continue; } } if (cryptoAsset) { auto cryptoNameLength = static_cast<int>(cryptoAssetName.length()); std::string identifier = ccl::string_printf("%08x", ccl::util_murmur_hash3(cryptoAssetName.c_str(), cryptoNameLength, 0)); std::string prefix = "cryptomatte/" + identifier.substr(0, 7) + "/"; result[prefix + "name"] = VtValue(cryptoAssetName); result[prefix + "hash"] = VtValue("MurmurHash3_32"); result[prefix + "conversion"] = VtValue("uint32_to_float32"); result[prefix + "manifest"] = VtValue(m_cyclesScene->object_manager->get_cryptomatte_assets(m_cyclesScene)); } if (cryptoObject) { auto cryptoNameLength = static_cast<int>(cryptoObjectName.length()); std::string identifier = ccl::string_printf("%08x", ccl::util_murmur_hash3(cryptoObjectName.c_str(), cryptoNameLength, 0)); std::string prefix = "cryptomatte/" + identifier.substr(0, 7) + "/"; result[prefix + "name"] = VtValue(cryptoObjectName); result[prefix + "hash"] = VtValue("MurmurHash3_32"); result[prefix + "conversion"] = VtValue("uint32_to_float32"); result[prefix + "manifest"] = VtValue(m_cyclesScene->object_manager->get_cryptomatte_objects(m_cyclesScene)); } if (cryptoMaterial) { auto cryptoNameLength = static_cast<int>(cryptoMaterialName.length()); std::string identifier = ccl::string_printf("%08x", ccl::util_murmur_hash3(cryptoMaterialName.c_str(), cryptoNameLength, 0)); std::string prefix = "cryptomatte/" + identifier.substr(0, 7) + "/"; result[prefix + "name"] = VtValue(cryptoMaterialName); result[prefix + "hash"] = VtValue("MurmurHash3_32"); result[prefix + "conversion"] = VtValue("uint32_to_float32"); result[prefix + "manifest"] = VtValue(m_cyclesScene->shader_manager->get_cryptomatte_materials(m_cyclesScene)); } return result; } void HdCyclesRenderParam::SetAovBindings(HdRenderPassAovBindingVector const& a_aovs) { // Synchronizes with the render buffers reset and blitting (display) // Also mirror the locks used when in the display_copy_cb callback ccl::thread_scoped_lock display_lock = m_cyclesSession->acquire_display_lock(); ccl::thread_scoped_lock buffers_lock = m_cyclesSession->acquire_buffers_lock(); // This is necessary as the scene film is edited ccl::thread_scoped_lock scene_lock { m_cyclesScene->mutex }; m_aovs = a_aovs; m_bufferParams.passes.clear(); bool has_combined = false; bool has_sample_count = false; ccl::Film* film = m_cyclesScene->film; ccl::CryptomatteType cryptomatte_passes = ccl::CRYPT_NONE; if (film->cryptomatte_passes & ccl::CRYPT_ACCURATE) { cryptomatte_passes = static_cast<ccl::CryptomatteType>(cryptomatte_passes | ccl::CRYPT_ACCURATE); } film->cryptomatte_passes = cryptomatte_passes; int cryptoObject = 0; int cryptoMaterial = 0; int cryptoAsset = 0; std::string cryptoObjectName; std::string cryptoMaterialName; std::string cryptoAssetName; film->denoising_flags = 0; film->denoising_data_pass = false; film->denoising_clean_pass = false; bool denoiseNormal = false; bool denoiseAlbedo = false; for (const HdRenderPassAovBinding& aov : m_aovs) { TfToken sourceName = GetSourceName(aov); for (HdCyclesAov& cyclesAov : DefaultAovs) { if (sourceName == cyclesAov.token) { if (cyclesAov.type == ccl::PASS_COMBINED) { has_combined = true; } else if (cyclesAov.type == ccl::PASS_SAMPLE_COUNT) { has_sample_count = true; } ccl::Pass::add(cyclesAov.type, m_bufferParams.passes, cyclesAov.name.c_str(), cyclesAov.filter); continue; } } for (HdCyclesAov& cyclesAov : CustomAovs) { if (sourceName == cyclesAov.token) { ccl::Pass::add(cyclesAov.type, m_bufferParams.passes, aov.aovName.GetText(), cyclesAov.filter); continue; } } for (HdCyclesAov& cyclesAov : CryptomatteAovs) { if (sourceName == cyclesAov.token) { if (cyclesAov.token == HdCyclesAovTokens->CryptoObject) { if (cryptoObject == 0) { cryptoObjectName = aov.aovName.GetText(); } cryptoObject += 1; continue; } if (cyclesAov.token == HdCyclesAovTokens->CryptoMaterial) { if (cryptoMaterial == 0) { cryptoMaterialName = aov.aovName.GetText(); } cryptoMaterial += 1; continue; } if (cyclesAov.token == HdCyclesAovTokens->CryptoAsset) { if (cryptoAsset == 0) { cryptoAssetName = aov.aovName.GetText(); } cryptoAsset += 1; continue; } } } for (HdCyclesAov& cyclesAov : DenoiseAovs) { if (sourceName == cyclesAov.token) { if (cyclesAov.token == HdCyclesAovTokens->DenoiseNormal) { denoiseNormal = true; continue; } if (cyclesAov.token == HdCyclesAovTokens->DenoiseAlbedo) { denoiseAlbedo = true; } } } } if (!denoiseNormal && !denoiseAlbedo) { m_cyclesSession->params.denoising.store_passes = false; } film->denoising_data_pass = m_cyclesSession->params.denoising.use || m_cyclesSession->params.denoising.store_passes; film->denoising_flags = ccl::DENOISING_PASS_PREFILTERED_COLOR | ccl::DENOISING_PASS_PREFILTERED_NORMAL | ccl::DENOISING_PASS_PREFILTERED_ALBEDO; film->denoising_clean_pass = (film->denoising_flags & ccl::DENOISING_CLEAN_ALL_PASSES); film->denoising_prefiltered_pass = m_cyclesSession->params.denoising.store_passes && m_cyclesSession->params.denoising.type == ccl::DENOISER_NLM; m_bufferParams.denoising_data_pass = film->denoising_data_pass; m_bufferParams.denoising_clean_pass = film->denoising_clean_pass; m_bufferParams.denoising_prefiltered_pass = film->denoising_prefiltered_pass; // Check for issues if (cryptoObject != film->cryptomatte_depth) { TF_WARN("Cryptomatte Object AOV/depth mismatch"); cryptoObject = 0; } if (cryptoMaterial != film->cryptomatte_depth) { TF_WARN("Cryptomatte Material AOV/depth mismatch"); cryptoMaterial = 0; } if (cryptoAsset != film->cryptomatte_depth) { TF_WARN("Cryptomatte Asset AOV/depth mismatch"); cryptoAsset = 0; } if (cryptoObjectName.length() < 3) { TF_WARN("Cryptomatte Object has an invalid layer name"); cryptoObject = 0; } else { cryptoObjectName.erase(cryptoObjectName.end() - 2, cryptoObjectName.end()); } if (cryptoMaterialName.length() < 3) { TF_WARN("Cryptomatte Material has an invalid layer name"); cryptoMaterial = 0; } else { cryptoMaterialName.erase(cryptoMaterialName.end() - 2, cryptoMaterialName.end()); } if (cryptoAssetName.length() < 3) { TF_WARN("Cryptomatte Asset has an invalid layer name"); cryptoAsset = 0; } else { cryptoAssetName.erase(cryptoAssetName.end() - 2, cryptoAssetName.end()); } // Ordering matters if (cryptoObject) { film->cryptomatte_passes = static_cast<ccl::CryptomatteType>(film->cryptomatte_passes | ccl::CRYPT_OBJECT); for (int i = 0; i < cryptoObject; ++i) { ccl::Pass::add(ccl::PASS_CRYPTOMATTE, m_bufferParams.passes, ccl::string_printf("%s%02i", cryptoObjectName.c_str(), i).c_str()); } } if (cryptoMaterial) { film->cryptomatte_passes = static_cast<ccl::CryptomatteType>(film->cryptomatte_passes | ccl::CRYPT_MATERIAL); for (int i = 0; i < cryptoMaterial; ++i) { ccl::Pass::add(ccl::PASS_CRYPTOMATTE, m_bufferParams.passes, ccl::string_printf("%s%02i", cryptoMaterialName.c_str(), i).c_str()); } } if (cryptoAsset) { film->cryptomatte_passes = static_cast<ccl::CryptomatteType>(film->cryptomatte_passes | ccl::CRYPT_ASSET); for (int i = 0; i < cryptoAsset; ++i) { ccl::Pass::add(ccl::PASS_CRYPTOMATTE, m_bufferParams.passes, ccl::string_printf("%s%02i", cryptoAssetName.c_str(), i).c_str()); } } /* Reading the latest version of the settings. In viewport mode the session * has already been started typically. */ const bool use_adaptive_sampling = m_cyclesSession ? m_cyclesSession->params.adaptive_sampling : m_sessionParams.adaptive_sampling; if (use_adaptive_sampling) { ccl::Pass::add(ccl::PASS_ADAPTIVE_AUX_BUFFER, m_bufferParams.passes); if (!has_sample_count) { ccl::Pass::add(ccl::PASS_SAMPLE_COUNT, m_bufferParams.passes); } } if (!has_combined) { ccl::Pass::add(DefaultAovs[0].type, m_bufferParams.passes, DefaultAovs[0].name.c_str(), DefaultAovs[0].filter); } film->display_pass = m_bufferParams.passes[0].type; film->tag_passes_update(m_cyclesScene, m_bufferParams.passes); film->tag_update(m_cyclesScene); } // We need to remove the aov binding because the renderbuffer can be // deallocated before new aov bindings are set in the renderpass. // // clang-format off void HdCyclesRenderParam::RemoveAovBinding(HdRenderBuffer* rb) { if (!rb) { return; } // Aovs access is synchronized with the Cycles display lock ccl::thread_scoped_lock display_lock = m_cyclesSession->acquire_display_lock(); ccl::thread_scoped_lock buffers_lock = m_cyclesSession->acquire_buffers_lock(); m_aovs.erase(std::remove_if(m_aovs.begin(), m_aovs.end(), [rb](HdRenderPassAovBinding& aov) { return aov.renderBuffer == rb; }), m_aovs.end()); } // clang-format on void HdCyclesRenderParam::BlitFromCyclesPass(const HdRenderPassAovBinding& aov, int w, int h, int samples) { if (samples < 0) { return; } HdCyclesAov cyclesAov; if (!GetCyclesAov(aov, cyclesAov)) { return; } // The RenderParam logic should guarantee that aov bindings always point to valid renderbuffer auto* rb = static_cast<HdCyclesRenderBuffer*>(aov.renderBuffer); if (!rb) { return; } if (rb->GetFormat() == HdFormatInvalid) { return; } // No point in blitting since the session will be reset const unsigned int dstWidth = rb->GetWidth(); const unsigned int dstHeight = rb->GetHeight(); if (m_resolutionDisplay[0] != dstWidth || m_resolutionDisplay[1] != dstHeight) { return; } // This acquires the whole object, not just the pixel buffer // It needs to wrap any getters void* data = rb->Map(); if (data) { const int n_comps_cycles = static_cast<int>(HdGetComponentCount(cyclesAov.format)); const int n_comps_hd = static_cast<int>(HdGetComponentCount(rb->GetFormat())); if (n_comps_cycles <= n_comps_hd) { ccl::RenderBuffers::ComponentType pixels_type = ccl::RenderBuffers::ComponentType::None; switch (rb->GetFormat()) { case HdFormatFloat16: pixels_type = ccl::RenderBuffers::ComponentType::Float16; break; case HdFormatFloat16Vec3: pixels_type = ccl::RenderBuffers::ComponentType::Float16x3; break; case HdFormatFloat16Vec4: pixels_type = ccl::RenderBuffers::ComponentType::Float16x4; break; case HdFormatFloat32: pixels_type = ccl::RenderBuffers::ComponentType::Float32; break; case HdFormatFloat32Vec3: pixels_type = ccl::RenderBuffers::ComponentType::Float32x3; break; case HdFormatFloat32Vec4: pixels_type = ccl::RenderBuffers::ComponentType::Float32x4; break; case HdFormatInt32: pixels_type = ccl::RenderBuffers::ComponentType::Int32; break; default: assert(false); break; } // todo: Is there a utility to convert HdFormat to string? if (pixels_type == ccl::RenderBuffers::ComponentType::None) { TF_WARN("Unsupported component type %d for aov %s ", static_cast<int>(rb->GetFormat()), aov.aovName.GetText()); rb->Unmap(); return; } bool custom, denoise; GetAovFlags(cyclesAov, custom, denoise); const int stride = static_cast<int>(HdDataSizeOfFormat(rb->GetFormat())); const float exposure = m_cyclesScene->film->exposure; auto buffers = m_cyclesSession->buffers; if (!custom && !denoise) { buffers->get_pass_rect_as(cyclesAov.name.c_str(), exposure, samples + 1, n_comps_cycles, static_cast<uint8_t*>(data), pixels_type, w, h, dstWidth, dstHeight, stride); } else if (custom) { buffers->get_pass_rect_as(aov.aovName.GetText(), exposure, samples + 1, n_comps_cycles, static_cast<uint8_t*>(data), pixels_type, w, h, dstWidth, dstHeight, stride); } if (cyclesAov.type == ccl::PASS_OBJECT_ID) { if (n_comps_hd == 1 && rb->GetFormat() == HdFormatInt32) { /* We bump the PrimId() before sending it to hydra, decrementing it here */ int32_t* pixels = static_cast<int32_t*>(data); for (size_t i = 0; i < rb->GetWidth() * rb->GetHeight(); ++i) { pixels[i] -= 1; } } else { TF_WARN("Object ID pass %s has unrecognized type", aov.aovName.GetText()); } } } else { TF_WARN("Don't know how to narrow aov %s from %d components (cycles) to %d components (HdRenderBuffer)", aov.aovName.GetText(), n_comps_cycles, n_comps_hd); } rb->Unmap(); } else { TF_WARN("Failed to map renderbuffer %s for writing on Cycles display callback", aov.aovName.GetText()); } } float HdCyclesRenderParam::MaxOverscan() const { float overscan = ::std::max(-m_dataWindowNDC[0], 0.f); overscan = ::std::max(overscan, ::std::max(-m_dataWindowNDC[1], 0.f)); overscan = ::std::max(overscan, ::std::max(m_dataWindowNDC[2] - 1, 0.f)); overscan = ::std::max(overscan, ::std::max(m_dataWindowNDC[3] - 1, 0.f)); return overscan; } PXR_NAMESPACE_CLOSE_SCOPE
36.661912
148
0.647038
[ "mesh", "geometry", "render", "object", "vector" ]
6e40bd0ba9e26e31111ed693a9a807353ec39a0c
650
cpp
C++
src/bin/main.cpp
BenjaminIsaac0111/neworder
354849b37f1594c252cfa0c79aa33f5af5bb05f7
[ "MIT" ]
2
2019-10-21T14:36:55.000Z
2020-02-17T09:44:29.000Z
src/bin/main.cpp
BenjaminIsaac0111/neworder
354849b37f1594c252cfa0c79aa33f5af5bb05f7
[ "MIT" ]
null
null
null
src/bin/main.cpp
BenjaminIsaac0111/neworder
354849b37f1594c252cfa0c79aa33f5af5bb05f7
[ "MIT" ]
null
null
null
#include "run.h" #include <iostream> int main(int argc, const char* argv[]) { // Directory containing model (config.py, etc) is specified on the command line // It's added to PYTHONPATH if (argc < 2) { std::cerr << "usage: neworder <model-path> [<extra_path>...]\n" << "where <model-path> is a directory containing the model config (config.py) plus the model definition python files\n" << "and <extra-path> is an option directory containing any other modules required by the model." << std::endl; exit(1); } append_model_paths(&argv[1], argc-1); // single-process return run(0, 1, true); }
28.26087
134
0.64
[ "model" ]
6e4148f1a718f133246fb1ee87eb4450f7de655e
4,202
cpp
C++
Trash/sandbox/qt_webkit/qt-qtwebkit-examples/examples/webkitwidgets/browser/.moc/moc_browserapplication.cpp
ruslankuzmin/julia
2ad5bfb9c9684b1c800e96732a9e2f1e844b856f
[ "BSD-3-Clause" ]
null
null
null
Trash/sandbox/qt_webkit/qt-qtwebkit-examples/examples/webkitwidgets/browser/.moc/moc_browserapplication.cpp
ruslankuzmin/julia
2ad5bfb9c9684b1c800e96732a9e2f1e844b856f
[ "BSD-3-Clause" ]
null
null
null
Trash/sandbox/qt_webkit/qt-qtwebkit-examples/examples/webkitwidgets/browser/.moc/moc_browserapplication.cpp
ruslankuzmin/julia
2ad5bfb9c9684b1c800e96732a9e2f1e844b856f
[ "BSD-3-Clause" ]
1
2020-08-30T20:40:25.000Z
2020-08-30T20:40:25.000Z
/**************************************************************************** ** Meta object code from reading C++ file 'browserapplication.h' ** ** Created by: The Qt Meta Object Compiler version 67 (Qt 5.2.1) ** ** WARNING! All changes made in this file will be lost! *****************************************************************************/ #include "../browserapplication.h" #include <QtCore/qbytearray.h> #include <QtCore/qmetatype.h> #if !defined(Q_MOC_OUTPUT_REVISION) #error "The header file 'browserapplication.h' doesn't include <QObject>." #elif Q_MOC_OUTPUT_REVISION != 67 #error "This file was generated using the moc from 5.2.1. It" #error "cannot be used with the include files from this version of Qt." #error "(The moc has changed too much.)" #endif QT_BEGIN_MOC_NAMESPACE struct qt_meta_stringdata_BrowserApplication_t { QByteArrayData data[9]; char stringdata[121]; }; #define QT_MOC_LITERAL(idx, ofs, len) \ Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \ offsetof(qt_meta_stringdata_BrowserApplication_t, stringdata) + ofs \ - idx * sizeof(QByteArrayData) \ ) static const qt_meta_stringdata_BrowserApplication_t qt_meta_stringdata_BrowserApplication = { { QT_MOC_LITERAL(0, 0, 18), QT_MOC_LITERAL(1, 19, 13), QT_MOC_LITERAL(2, 33, 18), QT_MOC_LITERAL(3, 52, 0), QT_MOC_LITERAL(4, 53, 18), QT_MOC_LITERAL(5, 72, 10), QT_MOC_LITERAL(6, 83, 7), QT_MOC_LITERAL(7, 91, 3), QT_MOC_LITERAL(8, 95, 24) }, "BrowserApplication\0newMainWindow\0" "BrowserMainWindow*\0\0restoreLastSession\0" "postLaunch\0openUrl\0url\0newLocalSocketConnection\0" }; #undef QT_MOC_LITERAL static const uint qt_meta_data_BrowserApplication[] = { // content: 7, // revision 0, // classname 0, 0, // classinfo 5, 14, // methods 0, 0, // properties 0, 0, // enums/sets 0, 0, // constructors 0, // flags 0, // signalCount // slots: name, argc, parameters, tag, flags 1, 0, 39, 3, 0x0a, 4, 0, 40, 3, 0x0a, 5, 0, 41, 3, 0x08, 6, 1, 42, 3, 0x08, 8, 0, 45, 3, 0x08, // slots: parameters 0x80000000 | 2, QMetaType::Void, QMetaType::Void, QMetaType::Void, QMetaType::QUrl, 7, QMetaType::Void, 0 // eod }; void BrowserApplication::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a) { if (_c == QMetaObject::InvokeMetaMethod) { BrowserApplication *_t = static_cast<BrowserApplication *>(_o); switch (_id) { case 0: { BrowserMainWindow* _r = _t->newMainWindow(); if (_a[0]) *reinterpret_cast< BrowserMainWindow**>(_a[0]) = _r; } break; case 1: _t->restoreLastSession(); break; case 2: _t->postLaunch(); break; case 3: _t->openUrl((*reinterpret_cast< const QUrl(*)>(_a[1]))); break; case 4: _t->newLocalSocketConnection(); break; default: ; } } } const QMetaObject BrowserApplication::staticMetaObject = { { &QApplication::staticMetaObject, qt_meta_stringdata_BrowserApplication.data, qt_meta_data_BrowserApplication, qt_static_metacall, 0, 0} }; const QMetaObject *BrowserApplication::metaObject() const { return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject; } void *BrowserApplication::qt_metacast(const char *_clname) { if (!_clname) return 0; if (!strcmp(_clname, qt_meta_stringdata_BrowserApplication.stringdata)) return static_cast<void*>(const_cast< BrowserApplication*>(this)); return QApplication::qt_metacast(_clname); } int BrowserApplication::qt_metacall(QMetaObject::Call _c, int _id, void **_a) { _id = QApplication::qt_metacall(_c, _id, _a); if (_id < 0) return _id; if (_c == QMetaObject::InvokeMetaMethod) { if (_id < 5) qt_static_metacall(this, _c, _id, _a); _id -= 5; } else if (_c == QMetaObject::RegisterMethodArgumentMetaType) { if (_id < 5) *reinterpret_cast<int*>(_a[0]) = -1; _id -= 5; } return _id; } QT_END_MOC_NAMESPACE
32.323077
98
0.627558
[ "object" ]
6e418f057ef08aee748aa362a999220a234d4cfd
4,380
cpp
C++
src/wardialer.cpp
hackner-security/swd
52376221afbe1968cf269ab5d08d18ffad41fba1
[ "MIT" ]
4
2020-09-26T12:35:28.000Z
2021-06-13T12:22:03.000Z
src/wardialer.cpp
hackner-security/swd
52376221afbe1968cf269ab5d08d18ffad41fba1
[ "MIT" ]
null
null
null
src/wardialer.cpp
hackner-security/swd
52376221afbe1968cf269ab5d08d18ffad41fba1
[ "MIT" ]
1
2020-10-27T12:11:46.000Z
2020-10-27T12:11:46.000Z
// Copyright 2020 Barger M., Knoll M., Kofler L. #include "wardialer.hpp" Argparser* args = Argparser::GetArgparser(); int thread_counter = 0; int call_counter = 0; std::atomic<int> id_ctr = 0; DBClient db = DBClient("wardialing.db"); std::vector<std::thread> calls; std::atomic<bool> stop_swd = false; struct call_data { std::string id; std::vector<int8_t> alaw_samples; }; std::vector<call_data> call_data_vector; void signal_handler(int signal) { if (stop_swd == false) { Logger::GetLogger()->Log("Caught signal '" + std::to_string(signal) + "', finishing up calls and exiting.", LOG_LVL_STATUS); stop_swd = true; } } void segfault_handler(int signal) { Logger::GetLogger()->Log("Received SIGFAULT(" + std::to_string(signal) + "), trying to stop other threads...", LOG_LVL_ERROR); if (stop_swd == false) { stop_swd = true; } } void WardialThread(std::vector<std::string> numbers, int thread_id) { SIPClient *client = new SIPClient(args->GetUsername(), args->GetPassword(), args->GetServer(), 4242 + thread_id, thread_id); for ( auto number : numbers ) { std::string id = number + "_" + std::to_string(id_ctr++); db.InsertData(id, number, "Ready", ""); if ( client->Register() == true ) { db.UpdateEntry(id, "Calling", ""); int call_duration = 0; if ( client->Invite(number, 25000.f, args->GetDebugStatus(), &call_duration) == true ) { call_data data; data.id = id; data.alaw_samples = client->GetCallData(); call_data_vector.push_back(data); db.UpdateDuration(id, call_duration); db.UpdateEntry(id, "Call Finished", ""); } else { db.UpdateEntry(id, "Call Failed", ""); } } else { return; } if (stop_swd == true) { break; } } delete client; return; } void AnalyzeCallData() { for ( auto data : call_data_vector ) { db.UpdateEntry(data.id, "Analyzing", ""); Wav wav; AudioAnalyzer audio_analyzer; if (wav.Read(data.alaw_samples) != false) { audio_analyzer.Analyze(&wav); std::string number = data.id.substr(0, data.id.find("_")); Logger::GetLogger()->Log("Detected device: " + audio_analyzer.GetReadableLineType(), LOG_LVL_STATUS, 0, number); db.UpdateEntry(data.id, "Finished", audio_analyzer.GetReadableLineType()); } else { Logger::GetLogger()->Log("Analyzing failed", LOG_LVL_STATUS, 0); db.UpdateEntry(data.id, "Analyzing failed", ""); } } } int Wardialer() { std::vector<std::string> numbers = args->GetNumbers(); std::signal(SIGINT, signal_handler); std::signal(SIGHUP, signal_handler); std::signal(SIGSEGV, segfault_handler); int max_threads = args->GetThreads(); // handle case if more threads are specified than numbers if (static_cast<int>(numbers.size()) < max_threads) { max_threads = numbers.size(); } // caclulate how much numbers should be wardialed by each thread int numbers_per_thread = static_cast<int>(numbers.size()) / max_threads; int numbers_last_thread = numbers_per_thread; if (static_cast<int>(numbers.size()) != (numbers_per_thread * max_threads)) { numbers_last_thread = numbers.size() - (numbers_per_thread * (max_threads - 1)); } // split the numbers vector that each thread has the same amount of numbers // to wardial int number_counter; std::vector<std::vector<std::string>> numbers_for_threads; std::vector<std::string>::const_iterator first; std::vector<std::string>::const_iterator last; int gap; for (int i = 0; i < max_threads; i++) { number_counter = i * numbers_per_thread; first = numbers.begin() + number_counter; gap = number_counter + numbers_per_thread; if ( i == max_threads-1 ) { gap = number_counter + numbers_last_thread; } last = numbers.begin() + gap; std::vector<std::string> number_range(first, last); numbers_for_threads.push_back(number_range); } // Create threads with unique id and their number range int i = 1; for ( std::vector<std::string> number_range : numbers_for_threads ) { calls.push_back(std::thread(WardialThread, number_range, i)); i++; } for (auto & call : calls) { if (call.joinable()) { call.join(); } } // After all calls are finished analyze the call data if (stop_swd == false) { AnalyzeCallData(); } return 0; }
31.73913
118
0.656621
[ "vector" ]
6e4263308179f2a85ec871715fb28253a48501cb
1,109
cpp
C++
Codeforces/Round #702 (div3)/D.cpp
biyotte/Code_of_gunwookim
b8b679ea56b8684ec44a7911211edee1fb558a96
[ "MIT" ]
4
2021-01-27T11:51:30.000Z
2021-01-30T17:02:55.000Z
Codeforces/Round #702 (div3)/D.cpp
biyotte/Code_of_gunwookim
b8b679ea56b8684ec44a7911211edee1fb558a96
[ "MIT" ]
null
null
null
Codeforces/Round #702 (div3)/D.cpp
biyotte/Code_of_gunwookim
b8b679ea56b8684ec44a7911211edee1fb558a96
[ "MIT" ]
5
2021-01-27T11:46:12.000Z
2021-05-06T05:37:47.000Z
#include <bits/stdc++.h> #define x first #define y second #define pb push_back #define all(v) v.begin(),v.end() #pragma gcc optimize("O3") #pragma gcc optimize("Ofast") #pragma gcc optimize("unroll-loops") using namespace std; const int INF = 1e9; const int TMX = 1 << 18; const long long llINF = 2e18; const long long mod = 1e9+7; const long long hashmod = 100003; const int MAXN = 20000; const int MAXM = 4000000; typedef long long ll; typedef long double ld; typedef pair <int,int> pl; typedef pair <ll,ll> pi; typedef vector <int> vec; typedef vector <pi> vecpi; typedef long long ll; int a[105]; int n,ans[105]; void dfs(int l,int r,int dep) { if(l > r) return; int idx = l; for(int i = l;i <= r;i++) { if(a[idx] < a[i]) idx = i; } ans[idx] = dep; dfs(l,idx-1,dep+1), dfs(idx+1,r,dep+1); } int main() { ios_base::sync_with_stdio(false); cin.tie(0); int T; cin >> T; while(T--) { cin >> n; for(int i = 1;i <= n;i++) cin >> a[i]; dfs(1,n,0); for(int i = 1;i <= n;i++) cout << ans[i] << ' '; cout << '\n'; } } for(int i = 0;i < 21;i++) { for(int j = 0;j < 20;j++) arr[i][j] = 0; }
21.745098
50
0.60505
[ "vector" ]
6e43132721ae7014995b19073ad67d21238c5574
6,243
hpp
C++
QuantExt/qle/models/linkablecalibratedmodel.hpp
PiotrSiejda/Engine
8360b5de32408f2a37da5ac3ca7b4e913bf67e9f
[ "BSD-3-Clause" ]
null
null
null
QuantExt/qle/models/linkablecalibratedmodel.hpp
PiotrSiejda/Engine
8360b5de32408f2a37da5ac3ca7b4e913bf67e9f
[ "BSD-3-Clause" ]
null
null
null
QuantExt/qle/models/linkablecalibratedmodel.hpp
PiotrSiejda/Engine
8360b5de32408f2a37da5ac3ca7b4e913bf67e9f
[ "BSD-3-Clause" ]
1
2022-02-07T02:04:10.000Z
2022-02-07T02:04:10.000Z
/* Copyright (C) 2016 Quaternion Risk Management Ltd All rights reserved. This file is part of ORE, a free-software/open-source library for transparent pricing and risk analysis - http://opensourcerisk.org ORE is free software: you can redistribute it and/or modify it under the terms of the Modified BSD License. You should have received a copy of the license along with this program. The license is also available online at <http://opensourcerisk.org> This program is distributed on the basis that it will form a useful contribution to risk analytics and model standardisation, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the license for more details. */ /*! \file linkablecalibratedmodel.hpp \brief calibrated model class with linkable parameters \ingroup models */ #ifndef quantext_calibrated_model_hpp #define quantext_calibrated_model_hpp #include <ql/math/optimization/endcriteria.hpp> #include <ql/math/optimization/method.hpp> #include <ql/models/calibrationhelper.hpp> #include <ql/models/parameter.hpp> #include <ql/option.hpp> #include <ql/patterns/observable.hpp> namespace QuantExt { using namespace QuantLib; //! Calibrated model class with linkable parameters /*! \ingroup models */ class LinkableCalibratedModel : public virtual Observer, public virtual Observable { public: LinkableCalibratedModel(); void update() { generateArguments(); notifyObservers(); } //! Calibrate to a set of market instruments (usually caps/swaptions) /*! An additional constraint can be passed which must be satisfied in addition to the constraints of the model. */ virtual void calibrate(const std::vector<boost::shared_ptr<CalibrationHelperBase> >&, OptimizationMethod& method, const EndCriteria& endCriteria, const Constraint& constraint = Constraint(), const std::vector<Real>& weights = std::vector<Real>(), const std::vector<bool>& fixParameters = std::vector<bool>()); //! for backward compatibility virtual void calibrate(const std::vector<boost::shared_ptr<BlackCalibrationHelper> >&, OptimizationMethod& method, const EndCriteria& endCriteria, const Constraint& constraint = Constraint(), const std::vector<Real>& weights = std::vector<Real>(), const std::vector<bool>& fixParameters = std::vector<bool>()); Real value(const Array& params, const std::vector<boost::shared_ptr<CalibrationHelperBase> >&); //! for backward compatibility Real value(const Array& params, const std::vector<boost::shared_ptr<BlackCalibrationHelper> >&); const boost::shared_ptr<Constraint>& constraint() const; //! Returns end criteria result EndCriteria::Type endCriteria() const { return endCriteria_; } //! Returns the problem values const Array& problemValues() const { return problemValues_; } //! Returns array of arguments on which calibration is done Disposable<Array> params() const; virtual void setParams(const Array& params); protected: virtual void generateArguments() {} std::vector<boost::shared_ptr<Parameter> > arguments_; boost::shared_ptr<Constraint> constraint_; EndCriteria::Type endCriteria_; Array problemValues_; private: //! Constraint imposed on arguments class PrivateConstraint; //! Calibration cost function class class CalibrationFunction; friend class CalibrationFunction; }; //! Linkable Calibrated Model /*! \ingroup models */ class LinkableCalibratedModel::PrivateConstraint : public Constraint { private: class Impl : public Constraint::Impl { public: Impl(const std::vector<boost::shared_ptr<Parameter> >& arguments) : arguments_(arguments) {} bool test(const Array& params) const { Size k = 0; for (Size i = 0; i < arguments_.size(); i++) { Size size = arguments_[i]->size(); Array testParams(size); for (Size j = 0; j < size; j++, k++) testParams[j] = params[k]; if (!arguments_[i]->testParams(testParams)) return false; } return true; } Array upperBound(const Array& params) const { Size k = 0, k2 = 0; Size totalSize = 0; for (Size i = 0; i < arguments_.size(); i++) { totalSize += arguments_[i]->size(); } Array result(totalSize); for (Size i = 0; i < arguments_.size(); i++) { Size size = arguments_[i]->size(); Array partialParams(size); for (Size j = 0; j < size; j++, k++) partialParams[j] = params[k]; Array tmpBound = arguments_[i]->constraint().upperBound(partialParams); for (Size j = 0; j < size; j++, k2++) result[k2] = tmpBound[j]; } return result; } Array lowerBound(const Array& params) const { Size k = 0, k2 = 0; Size totalSize = 0; for (Size i = 0; i < arguments_.size(); i++) { totalSize += arguments_[i]->size(); } Array result(totalSize); for (Size i = 0; i < arguments_.size(); i++) { Size size = arguments_[i]->size(); Array partialParams(size); for (Size j = 0; j < size; j++, k++) partialParams[j] = params[k]; Array tmpBound = arguments_[i]->constraint().lowerBound(partialParams); for (Size j = 0; j < size; j++, k2++) result[k2] = tmpBound[j]; } return result; } private: const std::vector<boost::shared_ptr<Parameter> >& arguments_; }; public: PrivateConstraint(const std::vector<boost::shared_ptr<Parameter> >& arguments) : Constraint(boost::shared_ptr<Constraint::Impl>(new PrivateConstraint::Impl(arguments))) {} }; } // namespace QuantExt #endif
36.940828
118
0.621977
[ "vector", "model" ]
6e492d799a971566bb8637234b67f841138ff2f5
34,970
cpp
C++
source/emulator/src/Network.cpp
InoriRus/Kyty
1aa7cf72ce598ee4ca31edc63f5b9708d629c69d
[ "MIT" ]
76
2021-11-13T13:07:59.000Z
2022-03-22T11:35:29.000Z
source/emulator/src/Network.cpp
InoriRus/Kyty
1aa7cf72ce598ee4ca31edc63f5b9708d629c69d
[ "MIT" ]
7
2021-12-01T18:45:13.000Z
2022-03-26T18:34:33.000Z
source/emulator/src/Network.cpp
InoriRus/Kyty
1aa7cf72ce598ee4ca31edc63f5b9708d629c69d
[ "MIT" ]
9
2021-11-24T08:38:13.000Z
2022-03-24T13:25:04.000Z
#include "Emulator/Network.h" #include "Kyty/Core/ByteBuffer.h" #include "Kyty/Core/Common.h" #include "Kyty/Core/DbgAssert.h" #include "Kyty/Core/String.h" #include "Kyty/Core/Threads.h" #include "Kyty/Core/Vector.h" #include "Emulator/Kernel/Pthread.h" #include "Emulator/Libs/Errno.h" #include "Emulator/Libs/Libs.h" #include <atomic> #ifdef KYTY_EMU_ENABLED namespace Kyty::Libs::Network { class Network { public: class Id { public: static constexpr int MAX_ID = 65536; enum class Type : uint32_t { Invalid = 0, Http = 1, Ssl = 2, Template = 3, Connection = 4, Request = 5, }; explicit Id(int id): m_id(static_cast<uint32_t>(id) & 0xffffu), m_type(static_cast<uint32_t>(id) >> 16u) {} [[nodiscard]] int ToInt() const { return static_cast<int>(m_id + (static_cast<uint32_t>(m_type) << 16u)); } [[nodiscard]] bool IsValid() const { return GetType() != Type::Invalid; } [[nodiscard]] Type GetType() const { switch (m_type) { case static_cast<uint32_t>(Type::Http): return Type::Http; break; case static_cast<uint32_t>(Type::Ssl): return Type::Ssl; break; case static_cast<uint32_t>(Type::Template): return Type::Template; break; case static_cast<uint32_t>(Type::Connection): return Type::Connection; break; case static_cast<uint32_t>(Type::Request): return Type::Request; break; default: return Type::Invalid; } } friend class Network; private: Id() = default; static Id Invalid() { return {}; } static Id Create(int net_id, Type type) { Id r; r.m_id = net_id; r.m_type = static_cast<uint32_t>(type); return r; } [[nodiscard]] int GetId() const { return static_cast<int>(m_id); } uint32_t m_id = 0; uint32_t m_type = static_cast<uint32_t>(Type::Invalid); }; using HttpsCallback = KYTY_SYSV_ABI int (*)(int, unsigned int, void* const*, int, void*); Network() = default; virtual ~Network() = default; KYTY_CLASS_NO_COPY(Network); int PoolCreate(const char* name, int size); bool PoolDestroy(int memid); Id SslInit(uint64_t pool_size); bool SslTerm(Id ssl_ctx_id); Id HttpInit(int memid, Id ssl_ctx_id, uint64_t pool_size); bool HttpTerm(Id http_ctx_id); Id HttpCreateTemplate(Id http_ctx_id, const char* user_agent, int http_ver, bool is_auto_proxy_conf); bool HttpDeleteTemplate(Id tmpl_id); bool HttpSetNonblock(Id id, bool enable); bool HttpsSetSslCallback(Id id, HttpsCallback cbfunc, void* user_arg); bool HttpsDisableOption(Id id, uint32_t ssl_flags); bool HttpAddRequestHeader(Id id, const char* name, const char* value, bool add); bool HttpValid(Id http_ctx_id); bool HttpValidTemplate(Id tmpl_id); bool HttpValidConnection(Id conn_id); bool HttpValidRequest(Id req_id); Id HttpCreateConnectionWithURL(Id tmpl_id, const char* url, bool enable_keep_alive); bool HttpDeleteConnection(Id conn_id); Id HttpCreateRequestWithURL2(Id conn_id, const char* method, const char* url, uint64_t content_length); bool HttpDeleteRequest(Id req_id); bool HttpSetResolveTimeOut(Id id, uint32_t usec); bool HttpSetResolveRetry(Id id, int32_t retry); bool HttpSetConnectTimeOut(Id id, uint32_t usec); bool HttpSetSendTimeOut(Id id, uint32_t usec); bool HttpSetRecvTimeOut(Id id, uint32_t usec); bool HttpSetAutoRedirect(Id id, int enable); bool HttpSetAuthEnabled(Id id, int enable); private: struct Pool { bool used = false; String name; int size = 0; }; struct Ssl { bool used = false; uint64_t size = 0; }; struct Http { bool used = false; uint64_t size = 0; int memid = 0; int ssl_ctx_id = 0; }; struct HttpHeader { String name; String value; }; struct HttpBase { Vector<HttpHeader> headers; bool used = false; bool nonblock = false; bool auto_redirect = true; bool auth_enabled = true; HttpsCallback ssl_cbfunc = nullptr; void* ssl_user_arg = nullptr; uint32_t ssl_flags = 0xA7; int http_ctx_id = 0; uint32_t resolve_timeout = 1'000000; int32_t resolve_retry = 4; uint32_t connect_timeout = 30'000000; uint32_t send_timeout = 120'000000; uint32_t recv_timeout = 120'000000; }; struct HttpTemplate: public HttpBase { String user_agent; int http_ver = 0; bool is_auto_proxy_conf = true; }; struct HttpConnection: public HttpTemplate { explicit HttpConnection(const HttpTemplate& tmpl): HttpTemplate(tmpl) {} // int tmpl_id = 0; String url; bool enable_keep_alive = false; }; struct HttpRequest: public HttpConnection { explicit HttpRequest(HttpConnection& conn): HttpConnection(conn) {} // int conn_id = 0; String method; String url; uint64_t content_length = 0; }; static constexpr int POOLS_MAX = 32; static constexpr int SSL_MAX = 32; static constexpr int HTTP_MAX = 32; Core::Mutex m_mutex; Pool m_pools[POOLS_MAX]; Ssl m_ssl[SSL_MAX]; Http m_http[HTTP_MAX]; Vector<HttpTemplate> m_templates; Vector<HttpConnection> m_connections; Vector<HttpRequest> m_requests; }; static Network* g_net = nullptr; KYTY_SUBSYSTEM_INIT(Network) { EXIT_IF(g_net != nullptr); g_net = new Network; } KYTY_SUBSYSTEM_UNEXPECTED_SHUTDOWN(Network) {} KYTY_SUBSYSTEM_DESTROY(Network) {} int Network::PoolCreate(const char* name, int size) { Core::LockGuard lock(m_mutex); for (int id = 0; id < POOLS_MAX; id++) { if (!m_pools[id].used) { m_pools[id].used = true; m_pools[id].size = size; m_pools[id].name = String::FromUtf8(name); return id; } } return -1; } bool Network::PoolDestroy(int memid) { Core::LockGuard lock(m_mutex); if (memid >= 0 && memid < POOLS_MAX && m_pools[memid].used) { m_pools[memid].used = false; return true; } return false; } Network::Id Network::SslInit(uint64_t pool_size) { Core::LockGuard lock(m_mutex); for (int id = 0; id < SSL_MAX; id++) { if (!m_ssl[id].used) { m_ssl[id].used = true; m_ssl[id].size = pool_size; return Id::Create(id, Id::Type::Ssl); } } return Id::Invalid(); } bool Network::SslTerm(Id ssl_ctx_id) { Core::LockGuard lock(m_mutex); if (ssl_ctx_id.GetType() == Id::Type::Ssl && ssl_ctx_id.GetId() >= 0 && ssl_ctx_id.GetId() < SSL_MAX && m_ssl[ssl_ctx_id.GetId()].used) { m_ssl[ssl_ctx_id.GetId()].used = false; return true; } return false; } Network::Id Network::HttpInit(int memid, Id ssl_ctx_id, uint64_t pool_size) { Core::LockGuard lock(m_mutex); if (ssl_ctx_id.GetType() == Id::Type::Ssl && ssl_ctx_id.GetId() >= 0 && ssl_ctx_id.GetId() < SSL_MAX && m_ssl[ssl_ctx_id.GetId()].used && memid >= 0 && memid < POOLS_MAX && m_pools[memid].used) { for (int id = 0; id < HTTP_MAX; id++) { if (!m_http[id].used) { m_http[id].used = true; m_http[id].size = pool_size; m_http[id].ssl_ctx_id = ssl_ctx_id.GetId(); m_http[id].memid = memid; return Id::Create(id, Id::Type::Http); } } } return Id::Invalid(); } bool Network::HttpValid(Id http_ctx_id) { Core::LockGuard lock(m_mutex); return (http_ctx_id.GetType() == Id::Type::Http && http_ctx_id.GetId() >= 0 && http_ctx_id.GetId() < HTTP_MAX && m_http[http_ctx_id.GetId()].used); } bool Network::HttpValidTemplate(Id tmpl_id) { Core::LockGuard lock(m_mutex); return (tmpl_id.GetType() == Id::Type::Template && m_templates.IndexValid(tmpl_id.GetId()) && m_templates.At(tmpl_id.GetId()).used); } bool Network::HttpValidConnection(Id conn_id) { Core::LockGuard lock(m_mutex); return (conn_id.GetType() == Id::Type::Connection && m_connections.IndexValid(conn_id.GetId()) && m_connections.At(conn_id.GetId()).used); } bool Network::HttpValidRequest(Id req_id) { Core::LockGuard lock(m_mutex); return (req_id.GetType() == Id::Type::Request && m_requests.IndexValid(req_id.GetId()) && m_requests.At(req_id.GetId()).used); } bool Network::HttpTerm(Id http_ctx_id) { Core::LockGuard lock(m_mutex); if (HttpValid(http_ctx_id)) { m_http[http_ctx_id.GetId()].used = false; return true; } return false; } Network::Id Network::HttpCreateTemplate(Id http_ctx_id, const char* user_agent, int http_ver, bool is_auto_proxy_conf) { Core::LockGuard lock(m_mutex); if (HttpValid(http_ctx_id)) { HttpTemplate tn {}; tn.used = true; tn.http_ver = http_ver; tn.user_agent = String::FromUtf8(user_agent); tn.is_auto_proxy_conf = is_auto_proxy_conf; tn.http_ctx_id = http_ctx_id.GetId(); tn.nonblock = false; int index = 0; for (auto& t: m_templates) { if (!t.used) { t = tn; return Id::Create(index, Id::Type::Template); } index++; } if (index < Id::MAX_ID) { m_templates.Add(tn); return Id::Create(index, Id::Type::Template); } } return Id::Invalid(); } Network::Id Network::HttpCreateConnectionWithURL(Id tmpl_id, const char* url, bool enable_keep_alive) { Core::LockGuard lock(m_mutex); if (HttpValidTemplate(tmpl_id)) { HttpConnection cn(m_templates[tmpl_id.GetId()]); cn.used = true; cn.enable_keep_alive = enable_keep_alive; cn.url = String::FromUtf8(url); // cn.tmpl_id = tmpl_id.ToInt(); int index = 0; for (auto& t: m_connections) { if (!t.used) { t = cn; return Id::Create(index, Id::Type::Connection); } index++; } if (index < Id::MAX_ID) { m_connections.Add(cn); return Id::Create(index, Id::Type::Connection); } } return Id::Invalid(); } bool Network::HttpDeleteConnection(Id conn_id) { Core::LockGuard lock(m_mutex); if (HttpValidConnection(conn_id)) { m_connections[conn_id.GetId()].used = false; return true; } return false; } Network::Id Network::HttpCreateRequestWithURL2(Id conn_id, const char* method, const char* url, uint64_t content_length) { Core::LockGuard lock(m_mutex); if (HttpValidConnection(conn_id)) { HttpRequest cn(m_connections[conn_id.GetId()]); cn.used = true; cn.method = String::FromUtf8(method); cn.url = String::FromUtf8(url); // cn.conn_id = conn_id.ToInt(); cn.content_length = content_length; int index = 0; for (auto& t: m_requests) { if (!t.used) { t = cn; return Id::Create(index, Id::Type::Request); } index++; } if (index < Id::MAX_ID) { m_requests.Add(cn); return Id::Create(index, Id::Type::Request); } } return Id::Invalid(); } bool Network::HttpDeleteRequest(Id req_id) { Core::LockGuard lock(m_mutex); if (HttpValidRequest(req_id)) { m_requests[req_id.GetId()].used = false; return true; } return false; } bool Network::HttpDeleteTemplate(Id tmpl_id) { Core::LockGuard lock(m_mutex); if (HttpValidTemplate(tmpl_id)) { m_templates[tmpl_id.GetId()].used = false; return true; } return false; } bool Network::HttpSetNonblock(Id id, bool enable) { Core::LockGuard lock(m_mutex); HttpBase* base = nullptr; if (HttpValidTemplate(id)) { base = &m_templates[id.GetId()]; } else if (HttpValidConnection(id)) { base = &m_connections[id.GetId()]; } else if (HttpValidRequest(id)) { base = &m_requests[id.GetId()]; } if (base != nullptr) { base->nonblock = enable; return true; } return false; } bool Network::HttpsSetSslCallback(Id id, HttpsCallback cbfunc, void* user_arg) { Core::LockGuard lock(m_mutex); HttpBase* base = nullptr; if (HttpValidTemplate(id)) { base = &m_templates[id.GetId()]; } else if (HttpValidConnection(id)) { base = &m_connections[id.GetId()]; } else if (HttpValidRequest(id)) { base = &m_requests[id.GetId()]; } if (base != nullptr) { base->ssl_cbfunc = cbfunc; base->ssl_user_arg = user_arg; return true; } return false; } bool Network::HttpsDisableOption(Id id, uint32_t ssl_flags) { Core::LockGuard lock(m_mutex); HttpBase* base = nullptr; if (HttpValidTemplate(id)) { base = &m_templates[id.GetId()]; } else if (HttpValidConnection(id)) { base = &m_connections[id.GetId()]; } else if (HttpValidRequest(id)) { base = &m_requests[id.GetId()]; } if (base != nullptr) { base->ssl_flags &= ~ssl_flags; return true; } return false; } bool Network::HttpAddRequestHeader(Id id, const char* name, const char* value, bool add) { Core::LockGuard lock(m_mutex); HttpBase* base = nullptr; if (HttpValidTemplate(id)) { base = &m_templates[id.GetId()]; } else if (HttpValidConnection(id)) { base = &m_connections[id.GetId()]; } else if (HttpValidRequest(id)) { base = &m_requests[id.GetId()]; } if (base != nullptr) { HttpHeader nh({String::FromUtf8(name), String::FromUtf8(value)}); if (add) { base->headers.Add(nh); } else { for (auto& h: base->headers) { if (h.name == nh.name) { h.value = nh.value; } } } return true; } return false; } bool Network::HttpSetResolveTimeOut(Id id, uint32_t usec) { Core::LockGuard lock(m_mutex); HttpBase* base = nullptr; if (HttpValidTemplate(id)) { base = &m_templates[id.GetId()]; } else if (HttpValidConnection(id)) { base = &m_connections[id.GetId()]; } if (base != nullptr) { base->resolve_timeout = usec; return true; } return false; } bool Network::HttpSetResolveRetry(Id id, int32_t retry) { Core::LockGuard lock(m_mutex); HttpBase* base = nullptr; if (HttpValidTemplate(id)) { base = &m_templates[id.GetId()]; } else if (HttpValidConnection(id)) { base = &m_connections[id.GetId()]; } if (base != nullptr) { base->resolve_retry = retry; return true; } return false; } bool Network::HttpSetConnectTimeOut(Id id, uint32_t usec) { Core::LockGuard lock(m_mutex); HttpBase* base = nullptr; if (HttpValidTemplate(id)) { base = &m_templates[id.GetId()]; } else if (HttpValidConnection(id)) { base = &m_connections[id.GetId()]; } else if (HttpValidRequest(id)) { base = &m_requests[id.GetId()]; } if (base != nullptr) { base->connect_timeout = usec; return true; } return false; } bool Network::HttpSetSendTimeOut(Id id, uint32_t usec) { Core::LockGuard lock(m_mutex); HttpBase* base = nullptr; if (HttpValidTemplate(id)) { base = &m_templates[id.GetId()]; } else if (HttpValidConnection(id)) { base = &m_connections[id.GetId()]; } else if (HttpValidRequest(id)) { base = &m_requests[id.GetId()]; } if (base != nullptr) { base->send_timeout = usec; return true; } return false; } bool Network::HttpSetRecvTimeOut(Id id, uint32_t usec) { Core::LockGuard lock(m_mutex); HttpBase* base = nullptr; if (HttpValidTemplate(id)) { base = &m_templates[id.GetId()]; } else if (HttpValidConnection(id)) { base = &m_connections[id.GetId()]; } else if (HttpValidRequest(id)) { base = &m_requests[id.GetId()]; } if (base != nullptr) { base->recv_timeout = usec; return true; } return false; } bool Network::HttpSetAutoRedirect(Id id, int enable) { Core::LockGuard lock(m_mutex); HttpBase* base = nullptr; if (HttpValidTemplate(id)) { base = &m_templates[id.GetId()]; } else if (HttpValidConnection(id)) { base = &m_connections[id.GetId()]; } else if (HttpValidRequest(id)) { base = &m_requests[id.GetId()]; } if (base != nullptr) { base->auto_redirect = (enable != 0); return true; } return false; } bool Network::HttpSetAuthEnabled(Id id, int enable) { Core::LockGuard lock(m_mutex); HttpBase* base = nullptr; if (HttpValidTemplate(id)) { base = &m_templates[id.GetId()]; } else if (HttpValidConnection(id)) { base = &m_connections[id.GetId()]; } else if (HttpValidRequest(id)) { base = &m_requests[id.GetId()]; } if (base != nullptr) { base->auth_enabled = (enable != 0); return true; } return false; } namespace Net { LIB_NAME("Net", "Net"); struct NetEtherAddr { uint8_t data[6] = {0}; }; int KYTY_SYSV_ABI NetInit() { PRINT_NAME(); return OK; } int KYTY_SYSV_ABI NetTerm() { PRINT_NAME(); return OK; } int KYTY_SYSV_ABI NetPoolCreate(const char* name, int size, int flags) { PRINT_NAME(); printf("\t name = %s\n", name); printf("\t size = %d\n", size); printf("\t flags = %d\n", flags); EXIT_IF(g_net == nullptr); EXIT_NOT_IMPLEMENTED(flags != 0); EXIT_NOT_IMPLEMENTED(size == 0); int id = g_net->PoolCreate(name, size); if (id < 0) { return NET_ERROR_ENFILE; } return id; } int KYTY_SYSV_ABI NetPoolDestroy(int memid) { PRINT_NAME(); EXIT_IF(g_net == nullptr); if (!g_net->PoolDestroy(memid)) { return NET_ERROR_EBADF; } return OK; } int KYTY_SYSV_ABI NetInetPton(int af, const char* src, void* dst) { PRINT_NAME(); EXIT_NOT_IMPLEMENTED(af != 2); EXIT_NOT_IMPLEMENTED(src == nullptr); EXIT_NOT_IMPLEMENTED(dst == nullptr); EXIT_NOT_IMPLEMENTED(strcmp(src, "127.0.0.1") != 0); printf("\t src = %.16s\n", src); *static_cast<uint32_t*>(dst) = 0x7f000001; return OK; } int KYTY_SYSV_ABI NetEtherNtostr(const NetEtherAddr* n, char* str, size_t len) { PRINT_NAME(); NetEtherAddr zero {}; EXIT_NOT_IMPLEMENTED(len != 18); EXIT_NOT_IMPLEMENTED(n == nullptr); EXIT_NOT_IMPLEMENTED(str == nullptr); EXIT_NOT_IMPLEMENTED(memcmp(n->data, zero.data, sizeof(zero.data)) != 0); strcpy(str, "00:00:00:00:00:00"); // NOLINT return OK; } int KYTY_SYSV_ABI NetGetMacAddress(NetEtherAddr* addr, int flags) { PRINT_NAME(); EXIT_NOT_IMPLEMENTED(addr == nullptr); EXIT_NOT_IMPLEMENTED(flags != 0); memset(addr->data, 0, sizeof(addr->data)); return OK; } } // namespace Net namespace Ssl { LIB_NAME("Ssl", "Ssl"); int KYTY_SYSV_ABI SslInit(uint64_t pool_size) { PRINT_NAME(); printf("\t size = %" PRIu64 "\n", pool_size); EXIT_IF(g_net == nullptr); EXIT_NOT_IMPLEMENTED(pool_size == 0); auto id = g_net->SslInit(pool_size); if (!id.IsValid()) { return SSL_ERROR_OUT_OF_SIZE; } return id.ToInt(); } int KYTY_SYSV_ABI SslTerm(int ssl_ctx_id) { PRINT_NAME(); EXIT_IF(g_net == nullptr); if (!g_net->SslTerm(Network::Id(ssl_ctx_id))) { return SSL_ERROR_INVALID_ID; } return OK; } } // namespace Ssl namespace Http { struct HttpEpoll { Network::Id http_ctx_id = Network::Id(0); Network::Id request_id = Network::Id(0); void* user_arg = nullptr; }; LIB_NAME("Http", "Http"); int KYTY_SYSV_ABI HttpInit(int memid, int ssl_ctx_id, uint64_t pool_size) { PRINT_NAME(); printf("\t memid = %d\n", memid); printf("\t ssl_ctx_id = %d\n", ssl_ctx_id); printf("\t size = %" PRIu64 "\n", pool_size); EXIT_IF(g_net == nullptr); EXIT_NOT_IMPLEMENTED(pool_size == 0); auto id = g_net->HttpInit(memid, Network::Id(ssl_ctx_id), pool_size); if (!id.IsValid()) { return HTTP_ERROR_OUT_OF_MEMORY; } return id.ToInt(); } int KYTY_SYSV_ABI HttpTerm(int http_ctx_id) { PRINT_NAME(); EXIT_IF(g_net == nullptr); if (!g_net->HttpTerm(Network::Id(http_ctx_id))) { return HTTP_ERROR_INVALID_ID; } return OK; } int KYTY_SYSV_ABI HttpCreateTemplate(int http_ctx_id, const char* user_agent, int http_ver, int is_auto_proxy_conf) { PRINT_NAME(); printf("\t http_ctx_id = %d\n", http_ctx_id); printf("\t user_agent = %s\n", user_agent); printf("\t http_ver = %d\n", http_ver); printf("\t is_auto_proxy_conf = %d\n", is_auto_proxy_conf); EXIT_IF(g_net == nullptr); auto id = g_net->HttpCreateTemplate(Network::Id(http_ctx_id), user_agent, http_ver, is_auto_proxy_conf != 0); if (!id.IsValid()) { return HTTP_ERROR_OUT_OF_MEMORY; } return id.ToInt(); } int KYTY_SYSV_ABI HttpDeleteTemplate(int tmpl_id) { PRINT_NAME(); EXIT_IF(g_net == nullptr); if (!g_net->HttpDeleteTemplate(Network::Id(tmpl_id))) { return HTTP_ERROR_INVALID_ID; } return OK; } int KYTY_SYSV_ABI HttpSetNonblock(int id, int enable) { PRINT_NAME(); printf("\t id = %d\n", id); printf("\t enable = %d\n", enable); if (!g_net->HttpSetNonblock(Network::Id(id), enable != 0)) { return HTTP_ERROR_INVALID_ID; } return OK; } int KYTY_SYSV_ABI HttpsSetSslCallback(int id, HttpsCallback cbfunc, void* user_arg) { PRINT_NAME(); printf("\t id = %d\n", id); if (!g_net->HttpsSetSslCallback(Network::Id(id), cbfunc, user_arg)) { return HTTP_ERROR_INVALID_ID; } return OK; } int KYTY_SYSV_ABI HttpsDisableOption(int id, uint32_t ssl_flags) { PRINT_NAME(); printf("\t id = %d\n", id); printf("\t ssl_flags = %u\n", ssl_flags); if (!g_net->HttpsDisableOption(Network::Id(id), ssl_flags)) { return HTTP_ERROR_INVALID_ID; } return OK; } int KYTY_SYSV_ABI HttpSetResolveTimeOut(int id, uint32_t usec) { PRINT_NAME(); printf("\t id = %d\n", id); printf("\t usec = %u\n", usec); if (!g_net->HttpSetResolveTimeOut(Network::Id(id), usec)) { return HTTP_ERROR_INVALID_ID; } return OK; } int KYTY_SYSV_ABI HttpSetResolveRetry(int id, int32_t retry) { PRINT_NAME(); printf("\t id = %d\n", id); printf("\t retry = %d\n", retry); if (!g_net->HttpSetResolveRetry(Network::Id(id), retry)) { return HTTP_ERROR_INVALID_ID; } return OK; } int KYTY_SYSV_ABI HttpSetConnectTimeOut(int id, uint32_t usec) { PRINT_NAME(); printf("\t id = %d\n", id); printf("\t usec = %u\n", usec); if (!g_net->HttpSetConnectTimeOut(Network::Id(id), usec)) { return HTTP_ERROR_INVALID_ID; } return OK; } int KYTY_SYSV_ABI HttpSetSendTimeOut(int id, uint32_t usec) { PRINT_NAME(); printf("\t id = %d\n", id); printf("\t usec = %u\n", usec); if (!g_net->HttpSetSendTimeOut(Network::Id(id), usec)) { return HTTP_ERROR_INVALID_ID; } return OK; } int KYTY_SYSV_ABI HttpSetRecvTimeOut(int id, uint32_t usec) { PRINT_NAME(); printf("\t id = %d\n", id); printf("\t usec = %u\n", usec); if (!g_net->HttpSetRecvTimeOut(Network::Id(id), usec)) { return HTTP_ERROR_INVALID_ID; } return OK; } int KYTY_SYSV_ABI HttpSetAutoRedirect(int id, int enable) { PRINT_NAME(); printf("\t id = %d\n", id); printf("\t enable = %d\n", enable); if (!g_net->HttpSetAutoRedirect(Network::Id(id), enable)) { return HTTP_ERROR_INVALID_ID; } return OK; } int KYTY_SYSV_ABI HttpSetAuthEnabled(int id, int enable) { PRINT_NAME(); printf("\t id = %d\n", id); printf("\t enable = %d\n", enable); if (!g_net->HttpSetAuthEnabled(Network::Id(id), enable)) { return HTTP_ERROR_INVALID_ID; } return OK; } int KYTY_SYSV_ABI HttpAddRequestHeader(int id, const char* name, const char* value, uint32_t mode) { PRINT_NAME(); printf("\t id = %d\n", id); printf("\t name = %s\n", name); printf("\t value = %s\n", value); printf("\t mode = %u\n", mode); EXIT_NOT_IMPLEMENTED(mode != 0 && mode != 1); if (!g_net->HttpAddRequestHeader(Network::Id(id), name, value, mode == 1)) { return HTTP_ERROR_INVALID_ID; } return OK; } int KYTY_SYSV_ABI HttpCreateEpoll(int http_ctx_id, HttpEpollHandle* eh) { PRINT_NAME(); printf("\t http_ctx_id = %d\n", http_ctx_id); EXIT_IF(g_net == nullptr); EXIT_NOT_IMPLEMENTED(eh == nullptr); EXIT_NOT_IMPLEMENTED(!g_net->HttpValid(Network::Id(http_ctx_id))); *eh = new HttpEpoll; (*eh)->http_ctx_id = Network::Id(http_ctx_id); return OK; } int KYTY_SYSV_ABI HttpDestroyEpoll(int http_ctx_id, HttpEpollHandle eh) { PRINT_NAME(); printf("\t http_ctx_id = %d\n", http_ctx_id); EXIT_IF(g_net == nullptr); EXIT_NOT_IMPLEMENTED(eh == nullptr); EXIT_NOT_IMPLEMENTED(!g_net->HttpValid(Network::Id(http_ctx_id))); delete eh; return OK; } int KYTY_SYSV_ABI HttpSetEpoll(int id, HttpEpollHandle eh, void* user_arg) { PRINT_NAME(); printf("\t id = %d\n", id); EXIT_NOT_IMPLEMENTED(eh == nullptr); EXIT_NOT_IMPLEMENTED(!g_net->HttpValidRequest(Network::Id(id))); eh->request_id = Network::Id(id); eh->user_arg = user_arg; return OK; } int KYTY_SYSV_ABI HttpUnsetEpoll(int id) { PRINT_NAME(); printf("\t id = %d\n", id); EXIT_NOT_IMPLEMENTED(!g_net->HttpValidRequest(Network::Id(id))); return OK; } int KYTY_SYSV_ABI HttpSendRequest(int request_id, const void* /*post_data*/, size_t /*size*/) { PRINT_NAME(); printf("\t request_id = %d\n", request_id); return HTTP_ERROR_TIMEOUT; } int KYTY_SYSV_ABI HttpCreateConnectionWithURL(int tmpl_id, const char* url, int enable_keep_alive) { PRINT_NAME(); printf("\t tmpl_id = %d\n", tmpl_id); printf("\t url = %s\n", url); printf("\t enable_keep_alive = %d\n", enable_keep_alive); EXIT_IF(g_net == nullptr); auto id = g_net->HttpCreateConnectionWithURL(Network::Id(tmpl_id), url, enable_keep_alive != 0); if (!id.IsValid()) { return HTTP_ERROR_OUT_OF_MEMORY; } return id.ToInt(); } int KYTY_SYSV_ABI HttpDeleteConnection(int conn_id) { PRINT_NAME(); printf("\t conn_id = %d\n", conn_id); EXIT_IF(g_net == nullptr); if (!g_net->HttpDeleteConnection(Network::Id(conn_id))) { return HTTP_ERROR_INVALID_ID; } return OK; } int KYTY_SYSV_ABI HttpCreateRequestWithURL2(int conn_id, const char* method, const char* url, uint64_t content_length) { PRINT_NAME(); printf("\t conn_id = %d\n", conn_id); printf("\t url = %s\n", url); printf("\t method = %s\n", method); printf("\t content_length = %" PRIu64 "\n", content_length); EXIT_IF(g_net == nullptr); auto id = g_net->HttpCreateRequestWithURL2(Network::Id(conn_id), method, url, content_length); if (!id.IsValid()) { return HTTP_ERROR_OUT_OF_MEMORY; } return id.ToInt(); } int KYTY_SYSV_ABI HttpDeleteRequest(int req_id) { PRINT_NAME(); printf("\t req_id = %d\n", req_id); EXIT_IF(g_net == nullptr); if (!g_net->HttpDeleteRequest(Network::Id(req_id))) { return HTTP_ERROR_INVALID_ID; } return OK; } } // namespace Http namespace NetCtl { LIB_NAME("NetCtl", "NetCtl"); struct NetInAddr { uint32_t s_addr = 0; }; struct NetEtherAddr { uint8_t data[6]; }; struct NetCtlNatInfo { unsigned int size = sizeof(NetCtlNatInfo); int stunStatus = 0; int natType = 0; NetInAddr mappedAddr; }; union NetCtlInfo { uint32_t device; NetEtherAddr ether_addr; uint32_t mtu; uint32_t link; NetEtherAddr bssid; char ssid[32 + 1]; uint32_t wifi_security; uint8_t rssi_dbm; uint8_t rssi_percentage; uint8_t channel; uint32_t ip_config; char dhcp_hostname[255 + 1]; char pppoe_auth_name[127 + 1]; char ip_address[16]; char netmask[16]; char default_route[16]; char primary_dns[16]; char secondary_dns[16]; uint32_t http_proxy_config; char http_proxy_server[255 + 1]; uint16_t http_proxy_port; }; int KYTY_SYSV_ABI NetCtlInit() { PRINT_NAME(); return OK; } void KYTY_SYSV_ABI NetCtlTerm() { PRINT_NAME(); } int KYTY_SYSV_ABI NetCtlGetNatInfo(NetCtlNatInfo* nat_info) { PRINT_NAME(); EXIT_NOT_IMPLEMENTED(nat_info == nullptr); EXIT_NOT_IMPLEMENTED(nat_info->size != sizeof(NetCtlNatInfo)); nat_info->stunStatus = 1; nat_info->natType = 3; nat_info->mappedAddr.s_addr = 0x7f000001; return OK; } int KYTY_SYSV_ABI NetCtlCheckCallback() { PRINT_NAME(); return OK; } int KYTY_SYSV_ABI NetCtlGetState(int* state) { PRINT_NAME(); EXIT_NOT_IMPLEMENTED(state == nullptr); *state = 0; // Disconnected return OK; } int KYTY_SYSV_ABI NetCtlRegisterCallback(NetCtlCallback func, void* /*arg*/, int* cid) { PRINT_NAME(); EXIT_NOT_IMPLEMENTED(func == nullptr); EXIT_NOT_IMPLEMENTED(cid == nullptr); *cid = 1; return OK; } int KYTY_SYSV_ABI NetCtlGetInfo(int code, NetCtlInfo* info) { PRINT_NAME(); EXIT_NOT_IMPLEMENTED(info == nullptr); printf("\t code = %d\n", code); switch (code) { case 2: memset(info->ether_addr.data, 0, sizeof(info->ether_addr.data)); break; case 11: info->ip_config = 0; break; case 14: strcpy(info->ip_address, "127.0.0.1"); break; default: EXIT("unknown code: %d\n", code); } return OK; } } // namespace NetCtl namespace NpManager { LIB_NAME("NpManager", "NpManager"); struct NpTitleId { char id[12 + 1]; uint8_t padding[3]; }; struct NpTitleSecret { uint8_t data[128]; }; struct NpCountryCode { char data[2]; char term; char padding[1]; }; struct NpAgeRestriction { NpCountryCode country_code; int8_t age; uint8_t padding[3]; }; struct NpContentRestriction { size_t size; int8_t default_age_restriction; char padding[3]; int32_t age_restriction_count; const NpAgeRestriction* age_restriction; }; struct NpOnlineId { char data[16]; char term; char dummy[3]; }; struct NpId { NpOnlineId handle; uint8_t opt[8]; uint8_t reserved[8]; }; struct NpCreateAsyncRequestParameter { size_t size; LibKernel::KernelCpumask cpu_affinity_mask; int thread_priority; uint8_t padding[4]; }; int KYTY_SYSV_ABI NpCheckCallback() { PRINT_NAME(); return OK; } int KYTY_SYSV_ABI NpSetNpTitleId(const NpTitleId* title_id, const NpTitleSecret* title_secret) { PRINT_NAME(); EXIT_NOT_IMPLEMENTED(title_id == nullptr); EXIT_NOT_IMPLEMENTED(title_secret == nullptr); printf("\t title_id = %.12s\n", title_id->id); printf("\t title_secret = %s\n", String::HexFromBin(Core::ByteBuffer(title_secret->data, 128)).C_Str()); return OK; } int KYTY_SYSV_ABI NpSetContentRestriction(const NpContentRestriction* restriction) { PRINT_NAME(); EXIT_NOT_IMPLEMENTED(restriction == nullptr); EXIT_NOT_IMPLEMENTED(restriction->size != sizeof(NpContentRestriction)); printf("\t default_age_restriction = %" PRIi8 "\n", restriction->default_age_restriction); printf("\t age_restriction_count = %" PRIi32 "\n", restriction->age_restriction_count); for (int i = 0; i < restriction->age_restriction_count; i++) { printf("\t age_restriction[%d].age = %" PRIi8 "\n", i, restriction->age_restriction[i].age); printf("\t age_restriction[%d].country_code.data = %.2s\n", i, restriction->age_restriction[i].country_code.data); } return OK; } int KYTY_SYSV_ABI NpRegisterStateCallback(void* /*callback*/, void* /*userdata*/) { PRINT_NAME(); return OK; } void KYTY_SYSV_ABI NpRegisterGamePresenceCallback(void* /*callback*/, void* /*userdata*/) { PRINT_NAME(); } int KYTY_SYSV_ABI NpRegisterPlusEventCallback(void* /*callback*/, void* /*userdata*/) { PRINT_NAME(); return OK; } int KYTY_SYSV_ABI NpRegisterNpReachabilityStateCallback(void* /*callback*/, void* /*userdata*/) { PRINT_NAME(); return OK; } int KYTY_SYSV_ABI NpGetNpId(int user_id, NpId* np_id) { PRINT_NAME(); printf("\t user_id = %d\n", user_id); EXIT_NOT_IMPLEMENTED(np_id == nullptr); int s = snprintf(np_id->handle.data, 16, "Kyty"); EXIT_NOT_IMPLEMENTED(s >= 16); np_id->handle.term = 0; return OK; } int KYTY_SYSV_ABI NpGetOnlineId(int user_id, NpOnlineId* online_id) { PRINT_NAME(); printf("\t user_id = %d\n", user_id); EXIT_NOT_IMPLEMENTED(online_id == nullptr); int s = snprintf(online_id->data, 16, "Kyty"); EXIT_NOT_IMPLEMENTED(s >= 16); online_id->term = 0; return OK; } int KYTY_SYSV_ABI NpCreateAsyncRequest(const NpCreateAsyncRequestParameter* param) { PRINT_NAME(); EXIT_NOT_IMPLEMENTED(param == nullptr); printf("\t size = %" PRIu64 "\n", param->size); printf("\t cpu_affinity_mask = %" PRIu64 "\n", param->cpu_affinity_mask); printf("\t thread_priority = %d\n", param->thread_priority); static std::atomic_int id = 0; EXIT_NOT_IMPLEMENTED(id >= 1); return ++id; } int KYTY_SYSV_ABI NpDeleteRequest(int req_id) { PRINT_NAME(); EXIT_NOT_IMPLEMENTED(req_id != 1); printf("\t req_id = %d\n", req_id); return OK; } int KYTY_SYSV_ABI NpCheckNpAvailability(int req_id, const char* user, void* result) { PRINT_NAME(); EXIT_NOT_IMPLEMENTED(req_id != 1); EXIT_NOT_IMPLEMENTED(user == nullptr); EXIT_NOT_IMPLEMENTED(result != nullptr); printf("\t req_id = %d\n", req_id); printf("\t user = %s\n", user); return OK; } int KYTY_SYSV_ABI NpPollAsync(int req_id, int* result) { PRINT_NAME(); EXIT_NOT_IMPLEMENTED(req_id != 1); EXIT_NOT_IMPLEMENTED(result == nullptr); printf("\t req_id = %d\n", req_id); *result = 0; return 0; } int KYTY_SYSV_ABI NpGetState(int user_id, uint32_t* state) { PRINT_NAME(); EXIT_NOT_IMPLEMENTED(state == nullptr); printf("\t user_id = %d\n", user_id); *state = 1; // Signed out return OK; } } // namespace NpManager namespace NpManagerForToolkit { LIB_NAME("NpManagerForToolkit", "NpManager"); int KYTY_SYSV_ABI NpRegisterStateCallbackForToolkit(void* /*callback*/, void* /*userdata*/) { PRINT_NAME(); return OK; } int KYTY_SYSV_ABI NpCheckCallbackForLib() { PRINT_NAME(); return OK; } } // namespace NpManagerForToolkit namespace NpTrophy { LIB_NAME("NpTrophy", "NpTrophy"); struct NpTrophyFlagArray { uint32_t flag_bits[4]; }; int KYTY_SYSV_ABI NpTrophyCreateHandle(int* handle) { PRINT_NAME(); EXIT_NOT_IMPLEMENTED(handle == nullptr); *handle = 1; return OK; } int KYTY_SYSV_ABI NpTrophyCreateContext(int* context, int user_id, uint32_t service_label, uint64_t options) { PRINT_NAME(); EXIT_NOT_IMPLEMENTED(context == nullptr); EXIT_NOT_IMPLEMENTED(options != 0); *context = 1; printf("\t user_id = %d\n", user_id); printf("\t service_label = %u\n", service_label); return OK; } int KYTY_SYSV_ABI NpTrophyRegisterContext(int context, int handle, uint64_t options) { PRINT_NAME(); EXIT_NOT_IMPLEMENTED(options != 0); EXIT_NOT_IMPLEMENTED(context != 1); EXIT_NOT_IMPLEMENTED(handle != 1); printf("\t context = %d\n", context); printf("\t handle = %d\n", handle); return OK; } int KYTY_SYSV_ABI NpTrophyDestroyHandle(int handle) { PRINT_NAME(); EXIT_NOT_IMPLEMENTED(handle != 1); printf("\t handle = %d\n", handle); return OK; } int KYTY_SYSV_ABI NpTrophyGetTrophyUnlockState(int context, int handle, NpTrophyFlagArray* flags, uint32_t* count) { PRINT_NAME(); EXIT_NOT_IMPLEMENTED(flags == nullptr); EXIT_NOT_IMPLEMENTED(count == nullptr); EXIT_NOT_IMPLEMENTED(context != 1); EXIT_NOT_IMPLEMENTED(handle != 1); printf("\t context = %d\n", context); printf("\t handle = %d\n", handle); flags->flag_bits[0] = 0; flags->flag_bits[1] = 0; flags->flag_bits[2] = 0; flags->flag_bits[3] = 0; *count = 0; return OK; } } // namespace NpTrophy namespace NpWebApi { LIB_NAME("NpWebApi", "NpWebApi"); int KYTY_SYSV_ABI NpWebApiInitialize(int http_ctx_id, size_t pool_size) { PRINT_NAME(); EXIT_IF(g_net == nullptr); printf("\t http_ctx_id = %d\n", http_ctx_id); printf("\t pool_size = %" PRIu64 "\n", pool_size); EXIT_NOT_IMPLEMENTED(!g_net->HttpValid(Network::Id(http_ctx_id))); static int id = 0; return ++id; } int KYTY_SYSV_ABI NpWebApiTerminate(int lib_ctx_id) { PRINT_NAME(); printf("\t lib_ctx_id = %d\n", lib_ctx_id); return OK; } } // namespace NpWebApi } // namespace Kyty::Libs::Network #endif // KYTY_EMU_ENABLED
19.309774
136
0.671232
[ "vector" ]
6e4a8fc382bc0844fe5d9f578e205857cef00a1b
2,417
cpp
C++
src/model/World.cpp
joelseverin/Johannebergsrallyt
40932fe1b8bca88274d909bc2d5ee78d19560d10
[ "MIT" ]
null
null
null
src/model/World.cpp
joelseverin/Johannebergsrallyt
40932fe1b8bca88274d909bc2d5ee78d19560d10
[ "MIT" ]
null
null
null
src/model/World.cpp
joelseverin/Johannebergsrallyt
40932fe1b8bca88274d909bc2d5ee78d19560d10
[ "MIT" ]
null
null
null
#include "model/World.h" #include "model/PhysicsWorld.h" #include <fstream> #include <iostream> #include <sstream> namespace Rally { namespace Model { World::World() : physicsWorld(), playerCar(physicsWorld), finish(physicsWorld), start(physicsWorld), tunnelTeleport(physicsWorld) { } World::~World() { } void World::initialize(const std::string & bulletFile) { physicsWorld.initialize(bulletFile); playerCar.attachToWorld(); finish.attachToWorld(btVector3(-1.3f, 0.f, -1.1f), btVector3(0.1f, 6.f, 3.2f)); start.attachToWorld(btVector3(113.0f, 0.f, 183.0f), btVector3(10.f, 10.f, 10.f)); tunnelTeleport.attachToWorld(btVector3(90.0f, 1.5f, -134.0f), btVector3(3.f, 3.f, 3.f)); finishTimer.reset(); start.collide(); highScore = 200; lastTime = 0; } void World::update(float deltaTime) { physicsWorld.update(deltaTime); Rally::Vector3 playerCarPosition = playerCar.getPosition(); if(playerCarPosition.y < -20.0f) { playerCar.teleport(Rally::Vector3(playerCarPosition.x, 30.0f, playerCarPosition.z), playerCar.getOrientation(), false); } // TODO: Removed until the tunnelTeleport.isEnabled/.hasCollided methods are fixed. /*if(tunnelTeleport.hasCollided()) { playerCar.teleport(Rally::Vector3(-126.0f, -4.0f, -52.0f), Rally::Quaternion(1.0f, 0.0f, 0.0f, 0.0f), true); tunnelTeleport.setEnabled(false); }*/ printFinishedTime(); } void World::printFinishedTime(){ if(!start.hasCollided()) finish.reset(); if(start.hasCollided() && finish.hasCollided() && finish.isEnabled()){ //finish.setEnabled(false); if(finishTimer.getElapsedSeconds() > 2) std::cout << "Finished after: " << finishTimer.getElapsedSeconds() << " seconds!" << std::endl; lastTime = finishTimer.getElapsedSeconds(); if(highScore == 200) highScore = 199; else if(lastTime < highScore) highScore = lastTime; finish.reset(); start.reset(); finishTimer.reset(); } } float World::getElapsedSeconds(){ return finishTimer.getElapsedSeconds(); } float World::getLastTime(){ return lastTime; } float World::getHighScore(){ return highScore; } void World::resetHighScore(){ highScore = 200; } } }
25.712766
100
0.625569
[ "model" ]
6e4d4c4ad18de46d3ac199d2ffef1102f8144cd5
5,459
cpp
C++
infer_server/src/util/thread_pool.cpp
YJessicaGao/easydk
e62eecde91886c2679def95edafb48f97650edfa
[ "Apache-2.0" ]
null
null
null
infer_server/src/util/thread_pool.cpp
YJessicaGao/easydk
e62eecde91886c2679def95edafb48f97650edfa
[ "Apache-2.0" ]
null
null
null
infer_server/src/util/thread_pool.cpp
YJessicaGao/easydk
e62eecde91886c2679def95edafb48f97650edfa
[ "Apache-2.0" ]
null
null
null
/************************************************************************* * Copyright (C) 2020 by Cambricon, Inc. All rights reserved * * This source code is licensed under the Apache-2.0 license found in the * LICENSE file in the root directory of this source tree. * * A part of this source code is referenced from ctpl project. * https://github.com/vit-vit/CTPL/blob/master/ctpl_stl.h * * Copyright (C) 2014 by Vitaliy Vitsentiy * * This source code is licensed under the Apache-2.0 license found in the * LICENSE file in the root directory of this source tree. * *************************************************************************/ #include "util/thread_pool.h" #include <memory> #include <mutex> #include <queue> #include <thread> #include <vector> namespace infer_server { /* ----------------- Implement --------------------- */ template <typename Q, typename T> void ThreadPool<Q, T>::Resize(size_t n_threads) noexcept { if (!is_stop_ && !is_done_) { size_t old_n_threads = threads_.size(); if (old_n_threads <= n_threads) { // if the number of threads is increased VLOG(1) << "[EasyDK InferServer] [ThreadPool] Add " << n_threads - old_n_threads << " threads into threadpool, total " << n_threads << " threads"; threads_.resize(n_threads); flags_.resize(n_threads); for (size_t i = old_n_threads; i < n_threads; ++i) { flags_[i] = std::make_shared<std::atomic<bool>>(false); SetThread(i); } } else { // the number of threads is decreased VLOG(1) << "[EasyDK InferServer] [ThreadPool] Remove " << old_n_threads - n_threads << " threads in threadpool, remain " << n_threads << " threads"; for (size_t i = n_threads; i < old_n_threads; ++i) { // this thread will finish flags_[i]->store(true); threads_[i]->detach(); } // stop the detached threads that were waiting cv_.notify_all(); // safe to delete because the threads are detached threads_.resize(n_threads); // safe to delete because the threads have copies of shared_ptr of the flags, not originals flags_.resize(n_threads); } } } template <typename Q, typename T> void ThreadPool<Q, T>::Stop(bool wait_all_task_done) noexcept { VLOG(2) << "[EasyDK InferServer] [ThreadPool] Before stop threadpool ----- Task number in queue: " << task_q_.Size() << ", thread number: " << threads_.size() << ", idle number: " << IdleNumber(); if (!wait_all_task_done) { if (is_stop_) return; VLOG(1) << "[EasyDK InferServer] [ThreadPool] Stop all the thread without waiting for remained task done"; is_stop_.store(true); for (size_t i = 0, n = this->Size(); i < n; ++i) { // command the threads to stop flags_[i]->store(true); } // empty the queue this->ClearQueue(); } else { if (is_done_ || is_stop_) return; VLOG(1) << "[EasyDK InferServer] [ThreadPool] Waiting for remained task done before stop all the thread"; // give the waiting threads a command to finish is_done_.store(true); } { // may stuck on thread::join if no lock here std::unique_lock<std::mutex> lock(mutex_); cv_.notify_all(); // stop all waiting threads } // wait for the computing threads to finish for (size_t i = 0; i < threads_.size(); ++i) { if (threads_[i]->joinable()) threads_[i]->join(); } // if there were no threads in the pool but some functors in the queue, the functors are not deleted by the threads // therefore delete them here this->ClearQueue(); threads_.clear(); flags_.clear(); } template <typename Q, typename T> void ThreadPool<Q, T>::SetThread(int i) noexcept { std::shared_ptr<std::atomic<bool>> tmp(flags_[i]); auto f = [this, i, tmp]() { std::atomic<bool> &flag = *tmp; // init params that bind with thread if (thread_init_func_) { if (thread_init_func_()) { VLOG(3) << "[EasyDK InferServer] [ThreadPool] Init thread context success, thread index: " << i; } else { LOG(ERROR) << "[EasyDK InferServer] [ThreadPool] Init thread context failed, but program will continue. " "Program cannot work correctly maybe."; } } task_type t; bool have_task = task_q_.TryPop(t); while (true) { // if there is anything in the queue while (have_task) { t(); // params encapsulated in std::function need destruct at once t.func = nullptr; if (flag.load()) { // the thread is wanted to stop, return even if the queue is not empty yet return; } else { have_task = task_q_.TryPop(t); } } // the queue is empty here, wait for the next command std::unique_lock<std::mutex> lock(mutex_); ++n_waiting_; cv_.wait(lock, [this, &t, &have_task, &flag]() { have_task = task_q_.TryPop(t); return have_task || is_done_ || flag.load(); }); --n_waiting_; // if the queue is empty and is_done_ == true or *flag then return if (!have_task) return; } }; threads_[i].reset(new std::thread(f)); } /* ----------------- Implement END --------------------- */ // instantiate thread pool template class ThreadPool<TSQueue<Task>>; template class ThreadPool<ThreadSafeQueue<Task, std::priority_queue<Task, std::vector<Task>, Task::Compare>>>; } // namespace infer_server
34.770701
118
0.606521
[ "vector" ]
6e4d65f51d0a3668d4ba90ccf9c61759bb3ee438
12,777
hpp
C++
src/task_list/task_list.hpp
PinghuiHuang/athena-pp-dustfluids
fce21992cc107aa553e83dd76b8d03ae90e990c7
[ "BSD-3-Clause" ]
2
2020-07-02T09:48:49.000Z
2020-08-25T02:37:21.000Z
src/task_list/task_list.hpp
PinghuiHuang/athena-pp-dustfluids
fce21992cc107aa553e83dd76b8d03ae90e990c7
[ "BSD-3-Clause" ]
null
null
null
src/task_list/task_list.hpp
PinghuiHuang/athena-pp-dustfluids
fce21992cc107aa553e83dd76b8d03ae90e990c7
[ "BSD-3-Clause" ]
1
2021-11-12T13:39:48.000Z
2021-11-12T13:39:48.000Z
#ifndef TASK_LIST_TASK_LIST_HPP_ #define TASK_LIST_TASK_LIST_HPP_ //======================================================================================== // Athena++ astrophysical MHD code // Copyright(C) 2014 James M. Stone <jmstone@princeton.edu> and other code contributors // Licensed under the 3-clause BSD License, see LICENSE file for details //======================================================================================== //! \file task_list.hpp //! \brief provides functionality to control dynamic execution using tasks // C headers // C++ headers #include <cstdint> // std::uint64_t #include <string> // std::string #include <vector> // std::vector // Athena++ headers #include "../athena.hpp" // forward declarations class Mesh; class MeshBlock; class TaskList; class FFTGravitySolverTaskList; class TaskID; //! \todo (felker): //! - these 4x declarations can be nested in TaskList if MGTaskList is derived // constants = return codes for functions working on individual Tasks and TaskList enum class TaskStatus {fail, success, next}; enum class TaskListStatus {running, stuck, complete, nothing_to_do}; //---------------------------------------------------------------------------------------- //! \class TaskID //! \brief generalization of bit fields for Task IDs, status, and dependencies. class TaskID { // POD but not aggregate (there is a user-provided ctor) public: TaskID() = default; explicit TaskID(unsigned int id); void Clear(); bool IsUnfinished(const TaskID& id) const; bool CheckDependencies(const TaskID& dep) const; void SetFinished(const TaskID& id); bool operator== (const TaskID& rhs) const; TaskID operator| (const TaskID& rhs) const; private: constexpr static int kNField_ = 2; std::uint64_t bitfld_[kNField_]; friend class TaskList; friend class MultigridTaskList; }; //---------------------------------------------------------------------------------------- //! \struct Task //! \brief data and function pointer for an individual Task struct Task { // aggregate and POD TaskID task_id; //!> encodes task with bit positions in HydroIntegratorTaskNames TaskID dependency; //!> encodes dependencies to other tasks using //!> HydroIntegratorTaskNames TaskStatus (TaskList::*TaskFunc)(MeshBlock*, int); //!> ptr to member function bool lb_time; //!> flag for automatic load balancing based on timing }; //--------------------------------------------------------------------------------------- //! \struct TaskStates //! \brief container for task states on a single MeshBlock struct TaskStates { // aggregate and POD TaskID finished_tasks; int indx_first_task, num_tasks_left; void Reset(int ntasks) { indx_first_task = 0; num_tasks_left = ntasks; finished_tasks.Clear(); } }; //---------------------------------------------------------------------------------------- //! \class TaskList //! \brief data and function definitions for task list base class class TaskList { public: TaskList() : ntasks(0), nstages(0), task_list_{} {} // 2x direct + zero initialization // rule of five: virtual ~TaskList() = default; // data int ntasks; //!> number of tasks in this list int nstages; //!> number of times the tasklist is repeated per each full timestep // functions TaskListStatus DoAllAvailableTasks(MeshBlock *pmb, int stage, TaskStates &ts); void DoTaskListOneStage(Mesh *pmesh, int stage); protected: //! \todo (felker): rename to avoid confusion with class name Task task_list_[64*TaskID::kNField_]; private: virtual void AddTask(const TaskID& id, const TaskID& dep) = 0; virtual void StartupTaskList(MeshBlock *pmb, int stage) = 0; }; //---------------------------------------------------------------------------------------- //! \class TimeIntegratorTaskList //! \brief data and function definitions for TimeIntegratorTaskList derived class class TimeIntegratorTaskList : public TaskList { public: TimeIntegratorTaskList(ParameterInput *pin, Mesh *pm); //-------------------------------------------------------------------------------------- //! \struct IntegratorWeight //! \brief weights used in time integrator tasks struct IntegratorWeight { // 2S or 3S* low-storage RK coefficients, Ketchenson (2010) Real delta; //!> low-storage coefficients to avoid double F() evaluation per substage Real gamma_1, gamma_2, gamma_3; // low-storage coeff for weighted ave of registers Real beta; // coeff. from bidiagonal Shu-Osher form Beta matrix, -1 diagonal terms Real sbeta, ebeta; // time coeff describing start/end time of each stage bool main_stage, orbital_stage; // flag for whether the main calculation is done }; // data std::string integrator; Real cfl_limit; // dt stability limit for the particular time integrator + spatial order int nstages_main; // number of stages labeled main_stage // functions TaskStatus ClearAllBoundary(MeshBlock *pmb, int stage); TaskStatus CalculateHydroFlux(MeshBlock *pmb, int stage); TaskStatus CalculateEMF(MeshBlock *pmb, int stage); TaskStatus SendHydroFlux(MeshBlock *pmb, int stage); TaskStatus SendEMF(MeshBlock *pmb, int stage); TaskStatus ReceiveAndCorrectHydroFlux(MeshBlock *pmb, int stage); TaskStatus ReceiveAndCorrectEMF(MeshBlock *pmb, int stage); TaskStatus IntegrateHydro(MeshBlock *pmb, int stage); TaskStatus IntegrateField(MeshBlock *pmb, int stage); TaskStatus AddSourceTermsHydro(MeshBlock *pmb, int stage); TaskStatus DiffuseHydro(MeshBlock *pmb, int stage); TaskStatus DiffuseField(MeshBlock *pmb, int stage); TaskStatus SendHydro(MeshBlock *pmb, int stage); TaskStatus SendField(MeshBlock *pmb, int stage); TaskStatus ReceiveHydro(MeshBlock *pmb, int stage); TaskStatus ReceiveField(MeshBlock *pmb, int stage); TaskStatus SetBoundariesHydro(MeshBlock *pmb, int stage); TaskStatus SetBoundariesField(MeshBlock *pmb, int stage); TaskStatus SendHydroShear(MeshBlock *pmb, int stage); TaskStatus ReceiveHydroShear(MeshBlock *pmb, int stage); TaskStatus SendHydroFluxShear(MeshBlock *pmb, int stage); TaskStatus ReceiveHydroFluxShear(MeshBlock *pmb, int stage); TaskStatus SendFieldShear(MeshBlock *pmb, int stage); TaskStatus ReceiveFieldShear(MeshBlock *pmb, int stage); TaskStatus SendEMFShear(MeshBlock *pmb, int stage); TaskStatus ReceiveEMFShear(MeshBlock *pmb, int stage); TaskStatus Prolongation(MeshBlock *pmb, int stage); TaskStatus Primitives(MeshBlock *pmb, int stage); TaskStatus PhysicalBoundary(MeshBlock *pmb, int stage); TaskStatus UserWork(MeshBlock *pmb, int stage); TaskStatus NewBlockTimeStep(MeshBlock *pmb, int stage); TaskStatus CheckRefinement(MeshBlock *pmb, int stage); TaskStatus CalculateDustFluidsFlux(MeshBlock *pmb, int stage); TaskStatus SendDustFluidsFlux(MeshBlock *pmb, int stage); TaskStatus ReceiveAndCorrectDustFluidsFlux(MeshBlock *pmb, int stage); TaskStatus IntegrateDustFluids(MeshBlock *pmb, int stage); TaskStatus AddSourceTermsDustFluids(MeshBlock *pmb, int stage); TaskStatus SendDustFluids(MeshBlock *pmb, int stage); TaskStatus ReceiveDustFluids(MeshBlock *pmb, int stage); TaskStatus SetBoundariesDustFluids(MeshBlock *pmb, int stage); TaskStatus SendDustFluidsShear(MeshBlock *pmb, int stage); TaskStatus ReceiveDustFluidsShear(MeshBlock *pmb, int stage); TaskStatus SendDustFluidsFluxShear(MeshBlock *pmb, int stage); TaskStatus ReceiveDustFluidsFluxShear(MeshBlock *pmb, int stage); TaskStatus DiffuseDustFluids(MeshBlock *pmb, int stage); TaskStatus DustGasDrag(MeshBlock *pmb, int stage); TaskStatus SendHydroOrbital(MeshBlock *pmb, int stage); TaskStatus ReceiveHydroOrbital(MeshBlock *pmb, int stage); TaskStatus CalculateHydroOrbital(MeshBlock *pmb, int stage); TaskStatus SendFieldOrbital(MeshBlock *pmb, int stage); //TaskStatus SendDustFluidsOrbital(MeshBlock *pmb, int stage); //TaskStatus ReceiveDustFluidsOrbital(MeshBlock *pmb, int stage); //TaskStatus CalculateDustFluidsOrbital(MeshBlock *pmb, int stage); TaskStatus ReceiveFieldOrbital(MeshBlock *pmb, int stage); TaskStatus CalculateFieldOrbital(MeshBlock *pmb, int stage); bool CheckNextMainStage(int stage) const {return stage_wghts[stage%nstages].main_stage;} private: bool ORBITAL_ADVECTION; // flag for orbital advection (true w/ , false w/o) bool SHEAR_PERIODIC; // flag for shear periodic boundary (true w/ , false w/o) IntegratorWeight stage_wghts[MAX_NSTAGE]; void AddTask(const TaskID& id, const TaskID& dep) override; void StartupTaskList(MeshBlock *pmb, int stage) override; }; //---------------------------------------------------------------------------------------- //! \class SuperTimeStepTaskList //! \brief data and function definitions for SuperTimeStepTaskList derived class class SuperTimeStepTaskList : public TaskList { public: SuperTimeStepTaskList(ParameterInput *pin, Mesh *pm, TimeIntegratorTaskList *ptlist); const Real sts_max_dt_ratio; // subset of NHYDRO indices bool do_sts_hydro; bool do_sts_field; bool do_sts_dustfluids; std::vector<int> sts_idx_subset; // functions TaskStatus ClearAllBoundary_STS(MeshBlock *pmb, int stage); TaskStatus CalculateHydroFlux_STS(MeshBlock *pmb, int stage); TaskStatus CalculateEMF_STS(MeshBlock *pmb, int stage); TaskStatus CalculateDustFluidsFlux_STS(MeshBlock *pmb, int stage); TaskStatus IntegrateHydro_STS(MeshBlock *pmb, int stage); TaskStatus IntegrateField_STS(MeshBlock *pmb, int stage); TaskStatus IntegrateDustFluids_STS(MeshBlock *pmb, int stage); TaskStatus Prolongation_STS(MeshBlock *pmb, int stage); TaskStatus Primitives_STS(MeshBlock *pmb, int stage); TaskStatus PhysicalBoundary_STS(MeshBlock *pmb, int stage); TaskStatus UserWork_STS(MeshBlock *pmb, int stage); TaskStatus NewBlockTimeStep_STS(MeshBlock *pmb, int stage); TaskStatus CheckRefinement_STS(MeshBlock *pmb, int stage); private: bool SHEAR_PERIODIC; // flag for shear periodic boundary (true w/ , false w/o) // currently intiialized but unused. May use it for direct calls to TimeIntegrator fns: TimeIntegratorTaskList *ptlist_; void AddTask(const TaskID&, const TaskID& dep) override; void StartupTaskList(MeshBlock *pmb, int stage) override; }; //---------------------------------------------------------------------------------------- //! 64-bit integers with "1" in different bit positions used to ID each hydro task. //! //! \todo (felker): //! - uncomment the reserved TASK_NAMES once the features are merged to master namespace HydroIntegratorTaskNames { const TaskID NONE(0); const TaskID CLEAR_ALLBND(1); const TaskID CALC_HYDFLX(2); const TaskID CALC_FLDFLX(3); const TaskID CALC_RADFLX(4); const TaskID CALC_CHMFLX(5); const TaskID CALC_DFSFLX(6); const TaskID SEND_HYDFLX(7); const TaskID SEND_FLDFLX(8); // const TaskID SEND_RADFLX(9); // const TaskID SEND_CHMFLX(10); const TaskID SEND_DFSFLX(11); const TaskID RECV_HYDFLX(12); const TaskID RECV_FLDFLX(13); // const TaskID RECV_RADFLX(14); // const TaskID RECV_CHMFLX(15); const TaskID RECV_DFSFLX(16); const TaskID SRCTERM_HYD(17); // const TaskID SRCTERM_FLD(18); // const TaskID SRCTERM_RAD(19); // const TaskID SRCTERM_CHM(20); const TaskID SRCTERM_DFS(21); const TaskID DRAG_DUSTGAS(22); const TaskID INT_HYD(23); const TaskID INT_FLD(24); // const TaskID INT_RAD(25); // const TaskID INT_CHM(26); const TaskID INT_DFS(27); const TaskID SEND_HYD(28); const TaskID SEND_FLD(29); // const TaskID SEND_RAD(30); // const TaskID SEND_CHM(31); const TaskID SEND_DFS(32); const TaskID RECV_HYD(33); const TaskID RECV_FLD(34); // const TaskID RECV_RAD(35); // const TaskID RECV_CHM(36); const TaskID RECV_DFS(37); const TaskID SETB_HYD(38); const TaskID SETB_FLD(39); // const TaskID SETB_RAD(40); // const TaskID SETB_CHM(41); const TaskID SETB_DFS(42); const TaskID PROLONG(43); const TaskID CONS2PRIM(44); const TaskID PHY_BVAL(45); const TaskID USERWORK(46); const TaskID NEW_DT(47); const TaskID FLAG_AMR(48); const TaskID SEND_HYDFLXSH(49); const TaskID SEND_HYDSH(50); const TaskID SEND_EMFSH(51); const TaskID SEND_FLDSH(52); const TaskID SEND_DFSSH(53); const TaskID SEND_DFSFLXSH(54); const TaskID RECV_HYDFLXSH(55); const TaskID RECV_HYDSH(56); const TaskID RECV_EMFSH(57); const TaskID RECV_FLDSH(58); const TaskID RECV_DFSSH(59); const TaskID RECV_DFSFLXSH(60); const TaskID DIFFUSE_HYD(61); const TaskID DIFFUSE_FLD(62); const TaskID DIFFUSE_DFS(63); const TaskID SEND_HYDORB(64); const TaskID RECV_HYDORB(65); const TaskID CALC_HYDORB(66); const TaskID SEND_FLDORB(67); const TaskID RECV_FLDORB(68); const TaskID CALC_FLDORB(69); } // namespace HydroIntegratorTaskNames #endif // TASK_LIST_TASK_LIST_HPP_
35.890449
90
0.70666
[ "mesh", "vector" ]
6e4f08791bc3f21a6409987828a98891e34c9d41
8,237
cpp
C++
AADC/src/aadcUser/AltarDriverModule/DriverModuleWidget.cpp
AimiHat/AADC-2018---Team-Altar
857fb79d52a5a428f6fbd96ca11fe6a758cdc780
[ "MIT" ]
5
2018-11-13T01:40:20.000Z
2019-10-22T12:25:38.000Z
AADC/src/aadcUser/AltarDriverModule/DriverModuleWidget.cpp
AimiHat/AADC-2018---Team-Altar
857fb79d52a5a428f6fbd96ca11fe6a758cdc780
[ "MIT" ]
null
null
null
AADC/src/aadcUser/AltarDriverModule/DriverModuleWidget.cpp
AimiHat/AADC-2018---Team-Altar
857fb79d52a5a428f6fbd96ca11fe6a758cdc780
[ "MIT" ]
1
2019-12-28T02:19:44.000Z
2019-12-28T02:19:44.000Z
/********************************************************************* Copyright (c) 2018 Audi Autonomous Driving Cup. 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. All advertising materials mentioning features or use of this software must display the following acknowledgement: ?This product includes software developed by the Audi AG and its contributors for Audi Autonomous Driving Cup.? 4. Neither the name of Audi 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 AUDI AG 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 AUDI AG OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. **********************************************************************/ #include "stdafx.h" #include "DriverModuleWidget.h" using namespace aadc::jury; DisplayWidgetDriver::DisplayWidgetDriver(QWidget* parent) : QWidget(parent) { m_pWidget = new QWidget(this); m_pWidget->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed); // create the elements QFont font; font.setPointSize(20); QLabel *toplabel = new QLabel(this); toplabel->setText("AADC - Driver Module"); toplabel->setAlignment(Qt::AlignCenter | Qt::AlignCenter); toplabel->setFont(font); QHBoxLayout *hboxManeuverList = new QHBoxLayout(); m_comboBox = new QComboBox(this); m_comboBox->setMaximumWidth(150); hboxManeuverList->addWidget(new QLabel(QString("Maneuver Index"))); hboxManeuverList->addWidget(m_comboBox); m_pSendStartupButton = new QPushButton(this); m_pSendStartupButton->setText("Startup"); m_pSendStartupButton->setFixedWidth(100); m_pSendReadyResponseButton = new QPushButton(this); m_pSendReadyResponseButton->setText("Ready to Start"); m_pSendReadyResponseButton->setFixedWidth(100); m_pSendStateErrorButton = new QPushButton(this); m_pSendStateErrorButton->setText("Error"); m_pSendStateErrorButton->setFixedWidth(100); m_pSendStateRunButton = new QPushButton(this); m_pSendStateRunButton->setText("Running"); m_pSendStateRunButton->setFixedWidth(100); m_pSendStateCompleteButton = new QPushButton(this); m_pSendStateCompleteButton->setText("Complete"); m_pSendStateCompleteButton->setFixedWidth(100); m_logField = new QTextEdit(this); m_logField->setReadOnly(true); m_logField->setFixedSize(240,180); //create the controls for the sections QVBoxLayout *vboxManeuverControl = new QVBoxLayout(); vboxManeuverControl->addLayout(hboxManeuverList); vboxManeuverControl->addWidget(m_pSendStartupButton,0, Qt::AlignCenter); vboxManeuverControl->addWidget(m_pSendReadyResponseButton,0, Qt::AlignCenter); vboxManeuverControl->addWidget(m_pSendStateRunButton,0, Qt::AlignCenter); vboxManeuverControl->addWidget(m_pSendStateErrorButton,0, Qt::AlignCenter); vboxManeuverControl->addWidget(m_pSendStateCompleteButton,0, Qt::AlignCenter); m_pManeuverGroupBox = new QGroupBox(tr("Maneuver Control"),this); m_pManeuverGroupBox->setLayout(vboxManeuverControl); m_pManeuverGroupBox->setFixedWidth(280); QLabel *jurylabel = new QLabel(this); jurylabel->setText("Jury Module:"); jurylabel->setAlignment(Qt::AlignCenter); m_JuryInfo = new QLabel(this); m_JuryInfo->setFixedSize(100,30); m_JuryInfo->setAutoFillBackground(true); m_JuryInfo->setAlignment(Qt::AlignCenter); QHBoxLayout *vboxJuryInfo = new QHBoxLayout(); vboxJuryInfo->addWidget(jurylabel); vboxJuryInfo->addWidget(m_JuryInfo); // set the main layout m_mainLayout = new QVBoxLayout(); m_mainLayout->addWidget(toplabel,0,Qt::AlignCenter); m_mainLayout->addWidget(m_pManeuverGroupBox, 0,Qt::AlignCenter); m_mainLayout->addLayout(vboxJuryInfo); m_mainLayout->addWidget(m_logField,0, Qt::AlignCenter); setLayout(m_mainLayout); //connect the buttons to the slots connect(m_pSendStateErrorButton, SIGNAL(clicked()), this, SLOT(OnStateErrorClicked())); connect(m_pSendStateRunButton, SIGNAL(clicked()), this, SLOT(OnStateRunClicked())); connect(m_pSendStartupButton, SIGNAL(clicked()), this, SLOT(OnStartupClicked())); connect(m_pSendReadyResponseButton, SIGNAL(clicked()), this, SLOT(OnResponseReadyClicked())); connect(m_pSendStateCompleteButton, SIGNAL(clicked()), this, SLOT(OnStateCompleteClicked())); } void DisplayWidgetDriver::OnStateRunClicked() { emit sendStruct(statecar_running,tInt16(m_comboBox->currentIndex())); } void DisplayWidgetDriver::OnStateErrorClicked() { emit sendStruct(statecar_error,tInt16(m_comboBox->currentIndex())); } void DisplayWidgetDriver::OnResponseReadyClicked() { emit sendStruct(statecar_ready,tInt16(m_comboBox->currentIndex())); } void DisplayWidgetDriver::OnStateCompleteClicked() { emit sendStruct(statecar_complete,tInt16(m_comboBox->currentIndex())); } void DisplayWidgetDriver::OnStartupClicked() { emit sendStruct(statecar_startup,tInt16(m_comboBox->currentIndex())); } void DisplayWidgetDriver::OnDriverGo(int entryId) { m_JuryInfo->setStyleSheet("background-color: rgb(0,255,0);"); m_JuryInfo->setText(QString("Start ") + QString::number(entryId)); } void DisplayWidgetDriver::OnDriverStop(int entryId) { m_JuryInfo->setStyleSheet("background-color: rgb(255,0,0);"); m_JuryInfo->setText(QString("Stop ") + QString::number(entryId));; } void DisplayWidgetDriver::OnDriverRequestReady(int entryId) { m_JuryInfo->setStyleSheet("background-color: rgb(255,255,0);"); m_JuryInfo->setText(QString("Request Ready ") + QString::number(entryId) + QString(" ?")); } void DisplayWidgetDriver::OnAppendText(QString text) { m_logField->append(text); } void DisplayWidgetDriver::SetManeuverList(std::vector<tSector>& sectorList) { m_sectorList = sectorList; } void DisplayWidgetDriver::EnableManeuverGroupBox(bool bEnable) { m_pManeuverGroupBox->setEnabled(bEnable); } void DisplayWidgetDriver::ShowManeuverList() { for(unsigned int i = 0; i < m_sectorList.size(); i++) { OnAppendText(QString(cString::Format("Driver Module: Sector ID %d",m_sectorList[i].id).GetPtr())); for(unsigned int j = 0; j < m_sectorList[i].sector.size(); j++) { OnAppendText(QString(cString::Format(" Maneuver ID: %d", m_sectorList[i].sector.at(j).id).GetPtr())); OnAppendText(QString(cString::Format(" Maneuver action: %s", maneuverToString(m_sectorList[i].sector.at(j).action).c_str()).GetPtr())); } } } void DisplayWidgetDriver::FillComboBox() { m_comboBox->clear(); int lastActionId = 0; std::vector<cString> vecManeuverNames; //get the last action id for(unsigned int i = 0; i < m_sectorList.size(); i++) { for(unsigned int j = 0; j < m_sectorList[i].sector.size(); j++) { lastActionId++; vecManeuverNames.push_back(maneuverToString(m_sectorList[i].sector[j].action).c_str()); } } for(int i = 0; i < lastActionId; i++) { m_comboBox->addItem(QString::number(i) + QString(" - ") + QString(vecManeuverNames[i])); } }
38.490654
726
0.729513
[ "vector" ]
6e544b69d238696b34abecd660e9eaf21a80b172
22,329
cpp
C++
frameworks/net/extensions/native/dmzNetExtPacketCodecEventNative.cpp
tongli/dmz
f2242027a17ea804259f9412b07d69f719a527c5
[ "MIT" ]
1
2016-05-08T22:02:35.000Z
2016-05-08T22:02:35.000Z
frameworks/net/extensions/native/dmzNetExtPacketCodecEventNative.cpp
ashok/dmz
2f8d4bced646f25abf2e98bdc0d378dafb4b32ed
[ "MIT" ]
null
null
null
frameworks/net/extensions/native/dmzNetExtPacketCodecEventNative.cpp
ashok/dmz
2f8d4bced646f25abf2e98bdc0d378dafb4b32ed
[ "MIT" ]
null
null
null
#include <dmzEventConsts.h> #include "dmzNetExtPacketCodecEventNative.h" #include <dmzObjectModule.h> #include <dmzRuntimeConfig.h> #include <dmzRuntimeConfigToTypesBase.h> #include <dmzRuntimeDefinitions.h> #include <dmzRuntimeEventType.h> #include <dmzRuntimeObjectType.h> #include <dmzRuntimePluginFactoryLinkSymbol.h> #include <dmzRuntimePluginInfo.h> #include <dmzRuntimeUUID.h> #include <dmzSystemMarshal.h> #include <dmzSystemUnmarshal.h> #include <dmzTypesArrays.h> #include <dmzTypesHandleContainer.h> #include <dmzTypesMask.h> #include <dmzTypesMatrix.h> #include <dmzTypesUUID.h> #include <dmzTypesVector.h> /*! \class dmz::NetExtPacketCodecEventNative \ingroup Net \brief Encodes and decodes events for the network. \details \code <local-scope> <adapter type="Adapter Type" attribute="Attribute Name" /> ... </local-scope> \endcode Possible types are: id, object-type, state, position, orientation, velocity, acceleration, scale, vector, scalar, timestamp, and text. Data object are not currently supported. */ //! \cond dmz::NetExtPacketCodecEventNative::NetExtPacketCodecEventNative ( const PluginInfo &Info, Config &local) : Plugin (Info), NetExtPacketCodecEvent (Info), _SysID (get_runtime_uuid (Info)), _log (Info), _time (Info), _defaultHandle (0), _lnvHandle (0), _eventMod (0), _attrMod (0), _adapterList (0) { _init (local); } dmz::NetExtPacketCodecEventNative::~NetExtPacketCodecEventNative () { if (_adapterList) { delete _adapterList; _adapterList = 0; } } // Plugin Interface void dmz::NetExtPacketCodecEventNative::update_plugin_state ( const PluginStateEnum State, const UInt32 Level) { if (State == PluginStateInit) { } else if (State == PluginStateStart) { } else if (State == PluginStateStop) { } else if (State == PluginStateShutdown) { } } void dmz::NetExtPacketCodecEventNative::discover_plugin ( const PluginDiscoverEnum Mode, const Plugin *PluginPtr) { if (Mode == PluginDiscoverAdd) { if (!_eventMod) { _eventMod = EventModule::cast (PluginPtr); } if (!_attrMod) { _attrMod = NetModuleAttributeMap::cast (PluginPtr); } } else if (Mode == PluginDiscoverRemove) { if (_eventMod && (_eventMod == EventModule::cast (PluginPtr))) { _eventMod = 0; } if (_attrMod && (_attrMod == NetModuleAttributeMap::cast (PluginPtr))) { _attrMod = 0; } } EventAttributeAdapter *current (_adapterList); while (current) { current->discover_plugin (Mode, PluginPtr); current = current->next; } } // NetExtPacketCodecEvent Interface dmz::Boolean dmz::NetExtPacketCodecEventNative::decode (Unmarshal &data, Boolean &isLoopback) { Boolean result (False); UUID uuid; data.get_next_uuid (uuid); isLoopback = (uuid == _SysID); if (!isLoopback && _eventMod) { const Int32 TypeSize (Int32 (data.get_next_int8 ())); ArrayUInt32 typeArray (TypeSize); for (Int32 ix = 0; ix < TypeSize; ix++) { typeArray.set (ix, UInt32 (data.get_next_uint8 ())); } Handle eventHandle (0); EventType type; _attrMod->to_internal_event_type (typeArray, type); if (type) { eventHandle = _eventMod->create_event (type, EventRemote); } if (eventHandle) { result = True; EventAttributeAdapter *current (_adapterList); while (current) { current->decode (eventHandle, data, *_eventMod); current = current->next; } _eventMod->close_event (eventHandle); } } return result; } dmz::Boolean dmz::NetExtPacketCodecEventNative::encode_event ( const Handle EventHandle, Marshal &data) { Boolean result (False); if (_attrMod && _eventMod) { data.set_next_uuid (_SysID); EventType type; ArrayUInt32 typeArray; _eventMod->lookup_event_type (EventHandle, type); if (_attrMod->to_net_event_type (type, typeArray)) { const Int32 TypeSize (typeArray.get_size ()); data.set_next_int8 (Int8 (TypeSize)); for (Int32 ix = 0; ix < TypeSize; ix++) { data.set_next_uint8 (UInt8 (typeArray.get (ix))); } EventAttributeAdapter *current (_adapterList); while (current) { current->encode (EventHandle, *_eventMod, data); current = current->next; } result = True; } } return result; } void dmz::NetExtPacketCodecEventNative::_init (Config &local) { RuntimeContext *context (get_plugin_runtime_context ()); Definitions defs (context, &_log); _defaultHandle = defs.create_named_handle (EventAttributeDefaultName); Config adapters; EventAttributeAdapter *current (0); if (local.lookup_all_config ("adapter", adapters)) { ConfigIterator it; Config data; while (adapters.get_next_config (it, data)) { EventAttributeAdapter *next (create_event_adapter (data, context, _log)); if (next) { if (current) { current->next = next; current = next; } else { _adapterList = current = next; } } } } } extern "C" { DMZ_PLUGIN_FACTORY_LINK_SYMBOL dmz::Plugin * create_dmzNetExtPacketCodecEventNative ( const dmz::PluginInfo &Info, dmz::Config &local, dmz::Config &global) { return new dmz::NetExtPacketCodecEventNative (Info, local); } }; namespace { typedef dmz::NetExtPacketCodecEventNative::EventAttributeAdapter Adapter; static dmz::Handle local_create_attribute_handle (dmz::Config &local, dmz::RuntimeContext *context) { return dmz::Definitions (context).create_named_handle ( config_to_string ("attribute", local, dmz::EventAttributeDefaultName)); } class ObjectID : public Adapter { public: ObjectID (dmz::Config &local, dmz::RuntimeContext *context); virtual void discover_plugin ( const dmz::PluginDiscoverEnum Mode, const dmz::Plugin *PluginPtr); virtual void decode ( const dmz::Handle EventHandle, dmz::Unmarshal &data, dmz::EventModule &eventMod); virtual void encode ( const dmz::Handle EventHandle, dmz::EventModule &eventMod, dmz::Marshal &data); protected: dmz::ObjectModule *_objMod; }; ObjectID::ObjectID (dmz::Config &local, dmz::RuntimeContext *context) : Adapter (local, context), _objMod (0) {;} void ObjectID::discover_plugin ( const dmz::PluginDiscoverEnum Mode, const dmz::Plugin *PluginPtr) { if (Mode == dmz::PluginDiscoverAdd) { if (!_objMod) { _objMod = dmz::ObjectModule::cast (PluginPtr); } } else if (Mode == dmz::PluginDiscoverRemove) { if (_objMod && (_objMod == dmz::ObjectModule::cast (PluginPtr))) { _objMod = 0; } } } void ObjectID::decode ( const dmz::Handle EventHandle, dmz::Unmarshal &data, dmz::EventModule &eventMod) { dmz::UUID objectID; data.get_next_uuid (objectID); if (_objMod) { const dmz::Handle Value (_objMod->lookup_handle_from_uuid (objectID)); eventMod.store_object_handle (EventHandle, _AttributeHandle, Value); } } void ObjectID::encode ( const dmz::Handle EventHandle, dmz::EventModule &eventMod, dmz::Marshal &data) { dmz::Handle value (0); eventMod.lookup_object_handle (EventHandle, _AttributeHandle, value); dmz::UUID objectID; if (_objMod) { _objMod->lookup_uuid (value, objectID); } data.set_next_uuid (objectID); } class ObjectTypeAttr : public Adapter { public: ObjectTypeAttr (dmz::Config &local, dmz::RuntimeContext *context); virtual void discover_plugin ( const dmz::PluginDiscoverEnum Mode, const dmz::Plugin *PluginPtr); virtual void decode ( const dmz::Handle EventHandle, dmz::Unmarshal &data, dmz::EventModule &eventMod); virtual void encode ( const dmz::Handle EventHandle, dmz::EventModule &eventMod, dmz::Marshal &data); protected: dmz::NetModuleAttributeMap *_attrMod; }; ObjectTypeAttr::ObjectTypeAttr (dmz::Config &local, dmz::RuntimeContext *context) : Adapter (local, context), _attrMod (0) {;} void ObjectTypeAttr::discover_plugin ( const dmz::PluginDiscoverEnum Mode, const dmz::Plugin *PluginPtr) { if (Mode == dmz::PluginDiscoverAdd) { if (!_attrMod) { _attrMod = dmz::NetModuleAttributeMap::cast (PluginPtr); } } else if (Mode == dmz::PluginDiscoverRemove) { if (_attrMod && (_attrMod == dmz::NetModuleAttributeMap::cast (PluginPtr))) { _attrMod = 0; } } } void ObjectTypeAttr::decode ( const dmz::Handle EventHandle, dmz::Unmarshal &data, dmz::EventModule &eventMod) { const dmz::Int32 Size (data.get_next_int8 ()); dmz::ArrayUInt32 typeArray (Size); for (dmz::Int32 ix = 0; ix < Size; ix++) { typeArray.set (ix, data.get_next_uint8 ()); } if (_attrMod) { dmz::ObjectType type; _attrMod->to_internal_object_type (typeArray, type); eventMod.store_object_type (EventHandle, _AttributeHandle, type); } } void ObjectTypeAttr::encode ( const dmz::Handle EventHandle, dmz::EventModule &eventMod, dmz::Marshal &data) { dmz::ArrayUInt32 typeArray; if (_attrMod) { dmz::ObjectType type; eventMod.lookup_object_type (EventHandle, _AttributeHandle, type); _attrMod->to_net_object_type (type, typeArray); } const dmz::Int32 Size (typeArray.get_size ()); data.set_next_int8 (dmz::Int8 (Size)); for (dmz::Int32 ix = 0; ix < Size; ix++) { data.set_next_uint8 (dmz::UInt8 (typeArray.get (ix))); } } class State : public Adapter { public: State (dmz::Config &local, dmz::RuntimeContext *context); virtual void discover_plugin ( const dmz::PluginDiscoverEnum Mode, const dmz::Plugin *PluginPtr); virtual void decode ( const dmz::Handle EventHandle, dmz::Unmarshal &data, dmz::EventModule &eventMod); virtual void encode ( const dmz::Handle EventHandle, dmz::EventModule &eventMod, dmz::Marshal &data); protected: dmz::NetModuleAttributeMap *_attrMod; }; State::State (dmz::Config &local, dmz::RuntimeContext *context) : Adapter (local, context), _attrMod (0) {;} void State::discover_plugin ( const dmz::PluginDiscoverEnum Mode, const dmz::Plugin *PluginPtr) { if (Mode == dmz::PluginDiscoverAdd) { if (!_attrMod) { _attrMod = dmz::NetModuleAttributeMap::cast (PluginPtr); } } else if (Mode == dmz::PluginDiscoverRemove) { if (_attrMod && (_attrMod == dmz::NetModuleAttributeMap::cast (PluginPtr))) { _attrMod = 0; } } } void State::decode ( const dmz::Handle EventHandle, dmz::Unmarshal &data, dmz::EventModule &eventMod) { const dmz::Int32 Size (data.get_next_int8 ()); dmz::ArrayUInt32 stateArray (Size); for (dmz::Int32 ix = 0; ix < Size; ix++) { stateArray.set (ix, data.get_next_uint32 ()); } if (_attrMod) { dmz::EventType type; eventMod.lookup_event_type (EventHandle, type); dmz::Mask value; _attrMod->to_internal_event_mask (type, stateArray, value); eventMod.store_state (EventHandle, _AttributeHandle, value); } } void State::encode ( const dmz::Handle EventHandle, dmz::EventModule &eventMod, dmz::Marshal &data) { dmz::ArrayUInt32 stateArray; if (_attrMod) { dmz::EventType type; eventMod.lookup_event_type (EventHandle, type); dmz::Mask value; eventMod.lookup_state (EventHandle, _AttributeHandle, value); _attrMod->to_net_event_mask (type, value, stateArray); } const dmz::Int32 Size (stateArray.get_size ()); data.set_next_int8 (dmz::Int8 (Size)); for (dmz::Int32 ix = 0; ix < Size; ix++) { data.set_next_uint32 (stateArray.get (ix)); } } class TimeStamp : public Adapter { public: TimeStamp (dmz::Config &local, dmz::RuntimeContext *context) : Adapter (local, context) {;} virtual void decode ( const dmz::Handle EventHandle, dmz::Unmarshal &data, dmz::EventModule &eventMod); virtual void encode ( const dmz::Handle EventHandle, dmz::EventModule &eventMod, dmz::Marshal &data); }; void TimeStamp::decode ( const dmz::Handle EventHandle, dmz::Unmarshal &data, dmz::EventModule &eventMod) { const dmz::Float64 Value (data.get_next_float64 ()); eventMod.store_time_stamp (EventHandle, _AttributeHandle, Value); } void TimeStamp::encode ( const dmz::Handle EventHandle, dmz::EventModule &eventMod, dmz::Marshal &data) { dmz::Float64 value (0.0); eventMod.lookup_time_stamp (EventHandle, _AttributeHandle, value); data.set_next_float64 (value); } class Position : public Adapter { public: Position (dmz::Config &local, dmz::RuntimeContext *context) : Adapter (local, context) {;} virtual void decode ( const dmz::Handle EventHandle, dmz::Unmarshal &data, dmz::EventModule &eventMod); virtual void encode ( const dmz::Handle EventHandle, dmz::EventModule &eventMod, dmz::Marshal &data); }; void Position::decode ( const dmz::Handle EventHandle, dmz::Unmarshal &data, dmz::EventModule &eventMod) { dmz::Vector value; data.get_next_vector (value); eventMod.store_position (EventHandle, _AttributeHandle, value); } void Position::encode ( const dmz::Handle EventHandle, dmz::EventModule &eventMod, dmz::Marshal &data) { dmz::Vector value; eventMod.lookup_position (EventHandle, _AttributeHandle, value); data.set_next_vector (value); } class Orientation : public Adapter { public: Orientation (dmz::Config &local, dmz::RuntimeContext *context) : Adapter (local, context) {;} virtual void decode ( const dmz::Handle EventHandle, dmz::Unmarshal &data, dmz::EventModule &eventMod); virtual void encode ( const dmz::Handle EventHandle, dmz::EventModule &eventMod, dmz::Marshal &data); }; void Orientation::decode ( const dmz::Handle EventHandle, dmz::Unmarshal &data, dmz::EventModule &eventMod) { dmz::Matrix value; data.get_next_matrix (value); eventMod.store_orientation (EventHandle, _AttributeHandle, value); } void Orientation::encode ( const dmz::Handle EventHandle, dmz::EventModule &eventMod, dmz::Marshal &data) { dmz::Matrix value; eventMod.lookup_orientation (EventHandle, _AttributeHandle, value); data.set_next_matrix (value); } class Velocity : public Adapter { public: Velocity (dmz::Config &local, dmz::RuntimeContext *context) : Adapter (local, context) {;} virtual void decode ( const dmz::Handle EventHandle, dmz::Unmarshal &data, dmz::EventModule &eventMod); virtual void encode ( const dmz::Handle EventHandle, dmz::EventModule &eventMod, dmz::Marshal &data); }; void Velocity::decode ( const dmz::Handle EventHandle, dmz::Unmarshal &data, dmz::EventModule &eventMod) { dmz::Vector value; data.get_next_vector (value); eventMod.store_velocity (EventHandle, _AttributeHandle, value); } void Velocity::encode ( const dmz::Handle EventHandle, dmz::EventModule &eventMod, dmz::Marshal &data) { dmz::Vector value; eventMod.lookup_velocity (EventHandle, _AttributeHandle, value); data.set_next_vector (value); } class Acceleration : public Adapter { public: Acceleration (dmz::Config &local, dmz::RuntimeContext *context) : Adapter (local, context) {;} virtual void decode ( const dmz::Handle EventHandle, dmz::Unmarshal &data, dmz::EventModule &eventMod); virtual void encode ( const dmz::Handle EventHandle, dmz::EventModule &eventMod, dmz::Marshal &data); }; void Acceleration::decode ( const dmz::Handle EventHandle, dmz::Unmarshal &data, dmz::EventModule &eventMod) { dmz::Vector value; data.get_next_vector (value); eventMod.store_acceleration (EventHandle, _AttributeHandle, value); } void Acceleration::encode ( const dmz::Handle EventHandle, dmz::EventModule &eventMod, dmz::Marshal &data) { dmz::Vector value; eventMod.lookup_acceleration (EventHandle, _AttributeHandle, value); data.set_next_vector (value); } class Scale : public Adapter { public: Scale (dmz::Config &local, dmz::RuntimeContext *context) : Adapter (local, context) {;} virtual void decode ( const dmz::Handle EventHandle, dmz::Unmarshal &data, dmz::EventModule &eventMod); virtual void encode ( const dmz::Handle EventHandle, dmz::EventModule &eventMod, dmz::Marshal &data); }; void Scale::decode ( const dmz::Handle EventHandle, dmz::Unmarshal &data, dmz::EventModule &eventMod) { dmz::Vector value; data.get_next_vector (value); eventMod.store_scale (EventHandle, _AttributeHandle, value); } void Scale::encode ( const dmz::Handle EventHandle, dmz::EventModule &eventMod, dmz::Marshal &data) { dmz::Vector value; eventMod.lookup_scale (EventHandle, _AttributeHandle, value); data.set_next_vector (value); } class VectorAttr : public Adapter { public: VectorAttr (dmz::Config &local, dmz::RuntimeContext *context) : Adapter (local, context) {;} virtual void decode ( const dmz::Handle EventHandle, dmz::Unmarshal &data, dmz::EventModule &eventMod); virtual void encode ( const dmz::Handle EventHandle, dmz::EventModule &eventMod, dmz::Marshal &data); }; void VectorAttr::decode ( const dmz::Handle EventHandle, dmz::Unmarshal &data, dmz::EventModule &eventMod) { dmz::Vector value; data.get_next_vector (value); eventMod.store_vector (EventHandle, _AttributeHandle, value); } void VectorAttr::encode ( const dmz::Handle EventHandle, dmz::EventModule &eventMod, dmz::Marshal &data) { dmz::Vector value; eventMod.lookup_vector (EventHandle, _AttributeHandle, value); data.set_next_vector (value); } class Scalar : public Adapter { public: Scalar (dmz::Config &local, dmz::RuntimeContext *context) : Adapter (local, context) {;} virtual void decode ( const dmz::Handle EventHandle, dmz::Unmarshal &data, dmz::EventModule &eventMod); virtual void encode ( const dmz::Handle EventHandle, dmz::EventModule &eventMod, dmz::Marshal &data); }; void Scalar::decode ( const dmz::Handle EventHandle, dmz::Unmarshal &data, dmz::EventModule &eventMod) { const dmz::Float64 Value (data.get_next_float64 ()); eventMod.store_scalar (EventHandle, _AttributeHandle, Value); } void Scalar::encode ( const dmz::Handle EventHandle, dmz::EventModule &eventMod, dmz::Marshal &data) { dmz::Float64 value (0.0); eventMod.lookup_scalar (EventHandle, _AttributeHandle, value); data.set_next_float64 (value); } class Text : public Adapter { public: Text (dmz::Config &local, dmz::RuntimeContext *context) : Adapter (local, context) {;} virtual void decode ( const dmz::Handle EventHandle, dmz::Unmarshal &data, dmz::EventModule &eventMod); virtual void encode ( const dmz::Handle EventHandle, dmz::EventModule &eventMod, dmz::Marshal &data); }; void Text::decode ( const dmz::Handle EventHandle, dmz::Unmarshal &data, dmz::EventModule &eventMod) { dmz::String value; data.get_next_string (value); eventMod.store_text (EventHandle, _AttributeHandle, value); } void Text::encode ( const dmz::Handle EventHandle, dmz::EventModule &eventMod, dmz::Marshal &data) { dmz::String value; eventMod.lookup_text (EventHandle, _AttributeHandle, value); data.set_next_string (value); } // TODO Still need a Data Adapter }; dmz::NetExtPacketCodecEventNative::EventAttributeAdapter::EventAttributeAdapter ( Config &local, RuntimeContext *context) : next (0), _AttributeHandle (local_create_attribute_handle (local, context)) {;} dmz::NetExtPacketCodecEventNative::EventAttributeAdapter::~EventAttributeAdapter () { if (next) { delete next; next = 0; } } dmz::NetExtPacketCodecEventNative::EventAttributeAdapter * dmz::NetExtPacketCodecEventNative::create_event_adapter ( Config &local, RuntimeContext *context, Log &log) { Adapter *result (0); const String Type = config_to_string ("type", local).to_lower (); if (Type == "id") { result = new ObjectID (local, context); } else if (Type == "object-type") { result = new ObjectTypeAttr (local, context); } else if (Type == "state") { result = new State (local, context); } else if (Type == "position") { result = new Position (local, context); } else if (Type == "orientation") { result = new Orientation (local, context); } else if (Type == "velocity") { result = new Velocity (local, context); } else if (Type == "acceleration") { result = new Acceleration (local, context); } else if (Type == "scale") { result = new Scale (local, context); } else if (Type == "vector") { result = new VectorAttr (local, context); } else if (Type == "scalar") { result = new Scalar(local, context); } else if (Type == "timestamp") { result = new TimeStamp (local, context); } else if (Type == "text") { result = new Text (local, context); } else { log.error << "Unknown event attribute adapter type: " << Type << endl; } return result; } //! \endcond
22.925051
175
0.645036
[ "object", "vector" ]
6e560ff2701dd7909566e6cde99bd1d0206d613a
95,342
cpp
C++
apps/mysql-5.1.65/storage/ndb/src/mgmsrv/ConfigInfo.cpp
vusec/firestarter
2048c1f731b8f3c5570a920757f9d7730d5f716a
[ "Apache-2.0" ]
3
2021-04-29T07:59:16.000Z
2021-12-10T02:23:05.000Z
apps/mysql-5.1.65/storage/ndb/src/mgmsrv/ConfigInfo.cpp
vusec/firestarter
2048c1f731b8f3c5570a920757f9d7730d5f716a
[ "Apache-2.0" ]
null
null
null
apps/mysql-5.1.65/storage/ndb/src/mgmsrv/ConfigInfo.cpp
vusec/firestarter
2048c1f731b8f3c5570a920757f9d7730d5f716a
[ "Apache-2.0" ]
null
null
null
/* Copyright (C) 2003 MySQL AB This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include <ndb_global.h> #ifndef NDB_MGMAPI #include <ndb_opt_defaults.h> #include <NdbTCP.h> #include "ConfigInfo.hpp" #include <mgmapi_config_parameters.h> #include <ndb_limits.h> #include "InitConfigFileParser.hpp" #include <m_string.h> extern my_bool opt_ndb_shm; extern my_bool opt_core; #else #include "ConfigInfo.hpp" #include <mgmapi_config_parameters.h> #endif /* NDB_MGMAPI */ #define MAX_LINE_LENGTH 255 #define KEY_INTERNAL 0 #define MAX_INT_RNIL 0xfffffeff #define MAX_PORT_NO 65535 #define _STR_VALUE(x) #x #define STR_VALUE(x) _STR_VALUE(x) /**************************************************************************** * Section names ****************************************************************************/ #define DB_TOKEN_PRINT "ndbd(DB)" #define MGM_TOKEN_PRINT "ndb_mgmd(MGM)" #define API_TOKEN_PRINT "mysqld(API)" #define DB_TOKEN "DB" #define MGM_TOKEN "MGM" #define API_TOKEN "API" #ifndef NDB_MGMAPI const ConfigInfo::AliasPair ConfigInfo::m_sectionNameAliases[]={ {API_TOKEN, "MYSQLD"}, {DB_TOKEN, "NDBD"}, {MGM_TOKEN, "NDB_MGMD"}, {0, 0} }; const char* ConfigInfo::m_sectionNames[]={ "SYSTEM", "COMPUTER", DB_TOKEN, MGM_TOKEN, API_TOKEN, "TCP", "SCI", "SHM" }; const int ConfigInfo::m_noOfSectionNames = sizeof(m_sectionNames)/sizeof(char*); /**************************************************************************** * Section Rules declarations ****************************************************************************/ static bool transformComputer(InitConfigFileParser::Context & ctx, const char *); static bool transformSystem(InitConfigFileParser::Context & ctx, const char *); static bool transformNode(InitConfigFileParser::Context & ctx, const char *); static bool checkConnectionSupport(InitConfigFileParser::Context & ctx, const char *); static bool transformConnection(InitConfigFileParser::Context & ctx, const char *); static bool applyDefaultValues(InitConfigFileParser::Context & ctx, const char *); static bool checkMandatory(InitConfigFileParser::Context & ctx, const char *); static bool fixPortNumber(InitConfigFileParser::Context & ctx, const char *); static bool fixShmKey(InitConfigFileParser::Context & ctx, const char *); static bool checkDbConstraints(InitConfigFileParser::Context & ctx, const char *); static bool checkConnectionConstraints(InitConfigFileParser::Context &, const char *); static bool checkTCPConstraints(InitConfigFileParser::Context &, const char *); static bool fixNodeHostname(InitConfigFileParser::Context & ctx, const char * data); static bool fixHostname(InitConfigFileParser::Context & ctx, const char * data); static bool fixNodeId(InitConfigFileParser::Context & ctx, const char * data); static bool fixDepricated(InitConfigFileParser::Context & ctx, const char *); static bool saveInConfigValues(InitConfigFileParser::Context & ctx, const char *); static bool fixFileSystemPath(InitConfigFileParser::Context & ctx, const char * data); static bool fixBackupDataDir(InitConfigFileParser::Context & ctx, const char * data); static bool fixShmUniqueId(InitConfigFileParser::Context & ctx, const char * data); static bool checkLocalhostHostnameMix(InitConfigFileParser::Context & ctx, const char * data); const ConfigInfo::SectionRule ConfigInfo::m_SectionRules[] = { { "SYSTEM", transformSystem, 0 }, { "COMPUTER", transformComputer, 0 }, { DB_TOKEN, transformNode, 0 }, { API_TOKEN, transformNode, 0 }, { MGM_TOKEN, transformNode, 0 }, { MGM_TOKEN, fixShmUniqueId, 0 }, { "TCP", checkConnectionSupport, 0 }, { "SHM", checkConnectionSupport, 0 }, { "SCI", checkConnectionSupport, 0 }, { "TCP", transformConnection, 0 }, { "SHM", transformConnection, 0 }, { "SCI", transformConnection, 0 }, { DB_TOKEN, fixNodeHostname, 0 }, { API_TOKEN, fixNodeHostname, 0 }, { MGM_TOKEN, fixNodeHostname, 0 }, { "TCP", fixNodeId, "NodeId1" }, { "TCP", fixNodeId, "NodeId2" }, { "SHM", fixNodeId, "NodeId1" }, { "SHM", fixNodeId, "NodeId2" }, { "SCI", fixNodeId, "NodeId1" }, { "SCI", fixNodeId, "NodeId2" }, { "TCP", fixHostname, "HostName1" }, { "TCP", fixHostname, "HostName2" }, { "SHM", fixHostname, "HostName1" }, { "SHM", fixHostname, "HostName2" }, { "SCI", fixHostname, "HostName1" }, { "SCI", fixHostname, "HostName2" }, { "SHM", fixHostname, "HostName1" }, { "SHM", fixHostname, "HostName2" }, { "TCP", fixPortNumber, 0 }, // has to come after fixHostName { "SHM", fixPortNumber, 0 }, // has to come after fixHostName { "SCI", fixPortNumber, 0 }, // has to come after fixHostName { "*", applyDefaultValues, "user" }, { "*", fixDepricated, 0 }, { "*", applyDefaultValues, "system" }, { "SHM", fixShmKey, 0 }, // has to come after apply default values { DB_TOKEN, checkLocalhostHostnameMix, 0 }, { API_TOKEN, checkLocalhostHostnameMix, 0 }, { MGM_TOKEN, checkLocalhostHostnameMix, 0 }, { DB_TOKEN, fixFileSystemPath, 0 }, { DB_TOKEN, fixBackupDataDir, 0 }, { DB_TOKEN, checkDbConstraints, 0 }, { "TCP", checkConnectionConstraints, 0 }, { "SHM", checkConnectionConstraints, 0 }, { "SCI", checkConnectionConstraints, 0 }, { "TCP", checkTCPConstraints, "HostName1" }, { "TCP", checkTCPConstraints, "HostName2" }, { "SCI", checkTCPConstraints, "HostName1" }, { "SCI", checkTCPConstraints, "HostName2" }, { "SHM", checkTCPConstraints, "HostName1" }, { "SHM", checkTCPConstraints, "HostName2" }, { "*", checkMandatory, 0 }, { DB_TOKEN, saveInConfigValues, 0 }, { API_TOKEN, saveInConfigValues, 0 }, { MGM_TOKEN, saveInConfigValues, 0 }, { "TCP", saveInConfigValues, 0 }, { "SHM", saveInConfigValues, 0 }, { "SCI", saveInConfigValues, 0 } }; const int ConfigInfo::m_NoOfRules = sizeof(m_SectionRules)/sizeof(SectionRule); /**************************************************************************** * Config Rules declarations ****************************************************************************/ static bool sanity_checks(Vector<ConfigInfo::ConfigRuleSection>&sections, struct InitConfigFileParser::Context &ctx, const char * rule_data); static bool add_node_connections(Vector<ConfigInfo::ConfigRuleSection>&sections, struct InitConfigFileParser::Context &ctx, const char * rule_data); static bool set_connection_priorities(Vector<ConfigInfo::ConfigRuleSection>&sections, struct InitConfigFileParser::Context &ctx, const char * rule_data); static bool check_node_vs_replicas(Vector<ConfigInfo::ConfigRuleSection>&sections, struct InitConfigFileParser::Context &ctx, const char * rule_data); const ConfigInfo::ConfigRule ConfigInfo::m_ConfigRules[] = { { sanity_checks, 0 }, { add_node_connections, 0 }, { set_connection_priorities, 0 }, { check_node_vs_replicas, 0 }, { 0, 0 } }; struct DepricationTransform { const char * m_section; const char * m_oldName; const char * m_newName; double m_add; double m_mul; }; static const DepricationTransform f_deprication[] = { { DB_TOKEN, "Discless", "Diskless", 0, 1 }, { DB_TOKEN, "Id", "NodeId", 0, 1 }, { API_TOKEN, "Id", "NodeId", 0, 1 }, { MGM_TOKEN, "Id", "NodeId", 0, 1 }, { 0, 0, 0, 0, 0} }; #endif /* NDB_MGMAPI */ /** * The default constructors create objects with suitable values for the * configuration parameters. * * Some are however given the value MANDATORY which means that the value * must be specified in the configuration file. * * Min and max values are also given for some parameters. * - Attr1: Name in file (initial config file) * - Attr2: Name in prop (properties object) * - Attr3: Name of Section (in init config file) * - Attr4: Updateable * - Attr5: Type of parameter (INT or BOOL) * - Attr6: Default Value (number only) * - Attr7: Min value * - Attr8: Max value * * Parameter constraints are coded in file Config.cpp. * * ******************************************************************* * Parameters used under development should be marked "NOTIMPLEMENTED" * ******************************************************************* */ const ConfigInfo::ParamInfo ConfigInfo::m_ParamInfo[] = { /**************************************************************************** * COMPUTER ***************************************************************************/ { KEY_INTERNAL, "COMPUTER", "COMPUTER", "Computer section", ConfigInfo::CI_INTERNAL, false, ConfigInfo::CI_SECTION, 0, 0, 0 }, { KEY_INTERNAL, "Id", "COMPUTER", "Name of computer", ConfigInfo::CI_USED, false, ConfigInfo::CI_STRING, MANDATORY, 0, 0 }, { KEY_INTERNAL, "HostName", "COMPUTER", "Hostname of computer (e.g. mysql.com)", ConfigInfo::CI_USED, false, ConfigInfo::CI_STRING, MANDATORY, 0, 0 }, { KEY_INTERNAL, "ByteOrder", "COMPUTER", 0, ConfigInfo::CI_DEPRICATED, false, ConfigInfo::CI_STRING, UNDEFINED, 0, 0 }, /**************************************************************************** * SYSTEM ***************************************************************************/ { CFG_SECTION_SYSTEM, "SYSTEM", "SYSTEM", "System section", ConfigInfo::CI_USED, false, ConfigInfo::CI_SECTION, (const char *)CFG_SECTION_SYSTEM, 0, 0 }, { CFG_SYS_NAME, "Name", "SYSTEM", "Name of system (NDB Cluster)", ConfigInfo::CI_USED, false, ConfigInfo::CI_STRING, MANDATORY, 0, 0 }, { CFG_SYS_PRIMARY_MGM_NODE, "PrimaryMGMNode", "SYSTEM", "Node id of Primary "MGM_TOKEN_PRINT" node", ConfigInfo::CI_USED, false, ConfigInfo::CI_INT, "0", "0", STR_VALUE(MAX_INT_RNIL) }, { CFG_SYS_CONFIG_GENERATION, "ConfigGenerationNumber", "SYSTEM", "Configuration generation number", ConfigInfo::CI_USED, false, ConfigInfo::CI_INT, "0", "0", STR_VALUE(MAX_INT_RNIL) }, /*************************************************************************** * DB ***************************************************************************/ { CFG_SECTION_NODE, DB_TOKEN, DB_TOKEN, "Node section", ConfigInfo::CI_USED, false, ConfigInfo::CI_SECTION, (const char *)NODE_TYPE_DB, 0, 0 }, { CFG_NODE_HOST, "HostName", DB_TOKEN, "Name of computer for this node", ConfigInfo::CI_INTERNAL, false, ConfigInfo::CI_STRING, "localhost", 0, 0 }, { CFG_NODE_SYSTEM, "System", DB_TOKEN, "Name of system for this node", ConfigInfo::CI_INTERNAL, false, ConfigInfo::CI_STRING, UNDEFINED, 0, 0 }, { KEY_INTERNAL, "Id", DB_TOKEN, "", ConfigInfo::CI_DEPRICATED, false, ConfigInfo::CI_INT, MANDATORY, "1", STR_VALUE(MAX_DATA_NODE_ID) }, { CFG_NODE_ID, "NodeId", DB_TOKEN, "Number identifying the database node ("DB_TOKEN_PRINT")", ConfigInfo::CI_USED, false, ConfigInfo::CI_INT, MANDATORY, "1", STR_VALUE(MAX_DATA_NODE_ID) }, { KEY_INTERNAL, "ServerPort", DB_TOKEN, "Port used to setup transporter", ConfigInfo::CI_USED, false, ConfigInfo::CI_INT, UNDEFINED, "1", STR_VALUE(MAX_PORT_NO) }, { CFG_DB_NO_REPLICAS, "NoOfReplicas", DB_TOKEN, "Number of copies of all data in the database (1-4)", ConfigInfo::CI_USED, false, ConfigInfo::CI_INT, MANDATORY, "1", "4" }, { CFG_DB_NO_ATTRIBUTES, "MaxNoOfAttributes", DB_TOKEN, "Total number of attributes stored in database. I.e. sum over all tables", ConfigInfo::CI_USED, false, ConfigInfo::CI_INT, "1000", "32", STR_VALUE(MAX_INT_RNIL) }, { CFG_DB_NO_TABLES, "MaxNoOfTables", DB_TOKEN, "Total number of tables stored in the database", ConfigInfo::CI_USED, false, ConfigInfo::CI_INT, "128", "8", STR_VALUE(MAX_TABLES) }, { CFG_DB_NO_ORDERED_INDEXES, "MaxNoOfOrderedIndexes", DB_TOKEN, "Total number of ordered indexes that can be defined in the system", ConfigInfo::CI_USED, false, ConfigInfo::CI_INT, "128", "0", STR_VALUE(MAX_INT_RNIL) }, { CFG_DB_NO_UNIQUE_HASH_INDEXES, "MaxNoOfUniqueHashIndexes", DB_TOKEN, "Total number of unique hash indexes that can be defined in the system", ConfigInfo::CI_USED, false, ConfigInfo::CI_INT, "64", "0", STR_VALUE(MAX_INT_RNIL) }, { CFG_DB_NO_INDEXES, "MaxNoOfIndexes", DB_TOKEN, "Total number of indexes that can be defined in the system", ConfigInfo::CI_DEPRICATED, false, ConfigInfo::CI_INT, "128", "0", STR_VALUE(MAX_INT_RNIL) }, { CFG_DB_NO_INDEX_OPS, "MaxNoOfConcurrentIndexOperations", DB_TOKEN, "Total number of index operations that can execute simultaneously on one "DB_TOKEN_PRINT" node", ConfigInfo::CI_USED, false, ConfigInfo::CI_INT, "8K", "0", STR_VALUE(MAX_INT_RNIL) }, { CFG_DB_NO_TRIGGERS, "MaxNoOfTriggers", DB_TOKEN, "Total number of triggers that can be defined in the system", ConfigInfo::CI_USED, false, ConfigInfo::CI_INT, "768", "0", STR_VALUE(MAX_INT_RNIL) }, { CFG_DB_NO_TRIGGER_OPS, "MaxNoOfFiredTriggers", DB_TOKEN, "Total number of triggers that can fire simultaneously in one "DB_TOKEN_PRINT" node", ConfigInfo::CI_USED, false, ConfigInfo::CI_INT, "4000", "0", STR_VALUE(MAX_INT_RNIL) }, { KEY_INTERNAL, "ExecuteOnComputer", DB_TOKEN, "String referencing an earlier defined COMPUTER", ConfigInfo::CI_USED, false, ConfigInfo::CI_STRING, UNDEFINED, 0, 0 }, { CFG_DB_NO_SAVE_MSGS, "MaxNoOfSavedMessages", DB_TOKEN, "Max number of error messages in error log and max number of trace files", ConfigInfo::CI_USED, true, ConfigInfo::CI_INT, "25", "0", STR_VALUE(MAX_INT_RNIL) }, { CFG_DB_MEMLOCK, "LockPagesInMainMemory", DB_TOKEN, "If set to yes, then NDB Cluster data will not be swapped out to disk", ConfigInfo::CI_USED, true, ConfigInfo::CI_INT, "0", "0", "2" }, { CFG_DB_WATCHDOG_INTERVAL, "TimeBetweenWatchDogCheck", DB_TOKEN, "Time between execution checks inside a database node", ConfigInfo::CI_USED, true, ConfigInfo::CI_INT, "6000", "70", STR_VALUE(MAX_INT_RNIL) }, { CFG_DB_WATCHDOG_INTERVAL_INITIAL, "TimeBetweenWatchDogCheckInitial", DB_TOKEN, "Time between execution checks inside a database node in the early start phases when memory is allocated", ConfigInfo::CI_USED, true, ConfigInfo::CI_INT, "6000", "70", STR_VALUE(MAX_INT_RNIL) }, { CFG_DB_STOP_ON_ERROR, "StopOnError", DB_TOKEN, "If set to N, "DB_TOKEN_PRINT" automatically restarts/recovers in case of node failure", ConfigInfo::CI_USED, true, ConfigInfo::CI_BOOL, "true", "false", "true" }, { CFG_DB_STOP_ON_ERROR_INSERT, "RestartOnErrorInsert", DB_TOKEN, "See src/kernel/vm/Emulator.hpp NdbRestartType for details", ConfigInfo::CI_INTERNAL, true, ConfigInfo::CI_INT, "2", "0", "4" }, { CFG_DB_NO_OPS, "MaxNoOfConcurrentOperations", DB_TOKEN, "Max number of operation records in transaction coordinator", ConfigInfo::CI_USED, false, ConfigInfo::CI_INT, "32k", "32", STR_VALUE(MAX_INT_RNIL) }, { CFG_DB_NO_LOCAL_OPS, "MaxNoOfLocalOperations", DB_TOKEN, "Max number of operation records defined in the local storage node", ConfigInfo::CI_USED, false, ConfigInfo::CI_INT, UNDEFINED, "32", STR_VALUE(MAX_INT_RNIL) }, { CFG_DB_NO_LOCAL_SCANS, "MaxNoOfLocalScans", DB_TOKEN, "Max number of fragment scans in parallel in the local storage node", ConfigInfo::CI_USED, false, ConfigInfo::CI_INT, UNDEFINED, "32", STR_VALUE(MAX_INT_RNIL) }, { CFG_DB_BATCH_SIZE, "BatchSizePerLocalScan", DB_TOKEN, "Used to calculate the number of lock records for scan with hold lock", ConfigInfo::CI_USED, false, ConfigInfo::CI_INT, STR_VALUE(DEF_BATCH_SIZE), "1", STR_VALUE(MAX_PARALLEL_OP_PER_SCAN) }, { CFG_DB_NO_TRANSACTIONS, "MaxNoOfConcurrentTransactions", DB_TOKEN, "Max number of transaction executing concurrently on the "DB_TOKEN_PRINT" node", ConfigInfo::CI_USED, false, ConfigInfo::CI_INT, "4096", "32", STR_VALUE(MAX_INT_RNIL) }, { CFG_DB_NO_SCANS, "MaxNoOfConcurrentScans", DB_TOKEN, "Max number of scans executing concurrently on the "DB_TOKEN_PRINT" node", ConfigInfo::CI_USED, false, ConfigInfo::CI_INT, "256", "2", "500" }, { CFG_DB_TRANS_BUFFER_MEM, "TransactionBufferMemory", DB_TOKEN, "Dynamic buffer space (in bytes) for key and attribute data allocated for each "DB_TOKEN_PRINT" node", ConfigInfo::CI_USED, false, ConfigInfo::CI_INT, "1M", "1K", STR_VALUE(MAX_INT_RNIL) }, { CFG_DB_INDEX_MEM, "IndexMemory", DB_TOKEN, "Number bytes on each "DB_TOKEN_PRINT" node allocated for storing indexes", ConfigInfo::CI_USED, false, ConfigInfo::CI_INT64, "18M", "1M", "1024G" }, { CFG_DB_DATA_MEM, "DataMemory", DB_TOKEN, "Number bytes on each "DB_TOKEN_PRINT" node allocated for storing data", ConfigInfo::CI_USED, false, ConfigInfo::CI_INT64, "80M", "1M", "1024G" }, { CFG_DB_UNDO_INDEX_BUFFER, "UndoIndexBuffer", DB_TOKEN, "Number bytes on each "DB_TOKEN_PRINT" node allocated for writing UNDO logs for index part", ConfigInfo::CI_USED, false, ConfigInfo::CI_INT, "2M", "1M", STR_VALUE(MAX_INT_RNIL)}, { CFG_DB_UNDO_DATA_BUFFER, "UndoDataBuffer", DB_TOKEN, "Number bytes on each "DB_TOKEN_PRINT" node allocated for writing UNDO logs for data part", ConfigInfo::CI_USED, false, ConfigInfo::CI_INT, "16M", "1M", STR_VALUE(MAX_INT_RNIL)}, { CFG_DB_REDO_BUFFER, "RedoBuffer", DB_TOKEN, "Number bytes on each "DB_TOKEN_PRINT" node allocated for writing REDO logs", ConfigInfo::CI_USED, false, ConfigInfo::CI_INT, "8M", "1M", STR_VALUE(MAX_INT_RNIL)}, { CFG_DB_LONG_SIGNAL_BUFFER, "LongMessageBuffer", DB_TOKEN, "Number bytes on each "DB_TOKEN_PRINT" node allocated for internal long messages", ConfigInfo::CI_USED, false, ConfigInfo::CI_INT, "1M", "512k", STR_VALUE(MAX_INT_RNIL)}, { CFG_DB_DISK_PAGE_BUFFER_MEMORY, "DiskPageBufferMemory", DB_TOKEN, "Number bytes on each "DB_TOKEN_PRINT" node allocated for disk page buffer cache", ConfigInfo::CI_USED, false, ConfigInfo::CI_INT64, "64M", "4M", "1024G" }, { CFG_DB_SGA, "SharedGlobalMemory", DB_TOKEN, "Total number bytes on each "DB_TOKEN_PRINT" node allocated for any use", ConfigInfo::CI_USED, false, ConfigInfo::CI_INT64, "20M", "0", "65536G" }, // 32k pages * 32-bit i value { CFG_DB_START_PARTIAL_TIMEOUT, "StartPartialTimeout", DB_TOKEN, "Time to wait before trying to start wo/ all nodes. 0=Wait forever", ConfigInfo::CI_USED, true, ConfigInfo::CI_INT, "30000", "0", STR_VALUE(MAX_INT_RNIL) }, { CFG_DB_START_PARTITION_TIMEOUT, "StartPartitionedTimeout", DB_TOKEN, "Time to wait before trying to start partitioned. 0=Wait forever", ConfigInfo::CI_USED, true, ConfigInfo::CI_INT, "60000", "0", STR_VALUE(MAX_INT_RNIL) }, { CFG_DB_START_FAILURE_TIMEOUT, "StartFailureTimeout", DB_TOKEN, "Time to wait before terminating. 0=Wait forever", ConfigInfo::CI_USED, true, ConfigInfo::CI_INT, "0", "0", STR_VALUE(MAX_INT_RNIL) }, { CFG_DB_HEARTBEAT_INTERVAL, "HeartbeatIntervalDbDb", DB_TOKEN, "Time between "DB_TOKEN_PRINT"-"DB_TOKEN_PRINT" heartbeats. "DB_TOKEN_PRINT" considered dead after 3 missed HBs", ConfigInfo::CI_USED, true, ConfigInfo::CI_INT, "1500", "10", STR_VALUE(MAX_INT_RNIL) }, { CFG_DB_API_HEARTBEAT_INTERVAL, "HeartbeatIntervalDbApi", DB_TOKEN, "Time between "API_TOKEN_PRINT"-"DB_TOKEN_PRINT" heartbeats. "API_TOKEN_PRINT" connection closed after 3 missed HBs", ConfigInfo::CI_USED, true, ConfigInfo::CI_INT, "1500", "100", STR_VALUE(MAX_INT_RNIL) }, { CFG_DB_LCP_INTERVAL, "TimeBetweenLocalCheckpoints", DB_TOKEN, "Time between taking snapshots of the database (expressed in 2log of bytes)", ConfigInfo::CI_USED, true, ConfigInfo::CI_INT, "20", "0", "31" }, { CFG_DB_GCP_INTERVAL, "TimeBetweenGlobalCheckpoints", DB_TOKEN, "Time between doing group commit of transactions to disk", ConfigInfo::CI_USED, true, ConfigInfo::CI_INT, "2000", "10", "32000" }, { CFG_DB_NO_REDOLOG_FILES, "NoOfFragmentLogFiles", DB_TOKEN, "No of 16 Mbyte Redo log files in each of 4 file sets belonging to "DB_TOKEN_PRINT" node", ConfigInfo::CI_USED, false, ConfigInfo::CI_INT, "16", "3", STR_VALUE(MAX_INT_RNIL) }, { CFG_DB_REDOLOG_FILE_SIZE, "FragmentLogFileSize", DB_TOKEN, "Size of each Redo log file", ConfigInfo::CI_USED, false, ConfigInfo::CI_INT, "16M", "4M", "1G" }, { CFG_DB_MAX_OPEN_FILES, "MaxNoOfOpenFiles", DB_TOKEN, "Max number of files open per "DB_TOKEN_PRINT" node.(One thread is created per file)", ConfigInfo::CI_USED, false, ConfigInfo::CI_INT, "0", "20", STR_VALUE(MAX_INT_RNIL) }, { CFG_DB_INITIAL_OPEN_FILES, "InitialNoOfOpenFiles", DB_TOKEN, "Initial number of files open per "DB_TOKEN_PRINT" node.(One thread is created per file)", ConfigInfo::CI_USED, false, ConfigInfo::CI_INT, "27", "20", STR_VALUE(MAX_INT_RNIL) }, { CFG_DB_TRANSACTION_CHECK_INTERVAL, "TimeBetweenInactiveTransactionAbortCheck", DB_TOKEN, "Time between inactive transaction checks", ConfigInfo::CI_USED, true, ConfigInfo::CI_INT, "1000", "1000", STR_VALUE(MAX_INT_RNIL) }, { CFG_DB_TRANSACTION_INACTIVE_TIMEOUT, "TransactionInactiveTimeout", DB_TOKEN, "Time application can wait before executing another transaction part (ms).\n" "This is the time the transaction coordinator waits for the application\n" "to execute or send another part (query, statement) of the transaction.\n" "If the application takes too long time, the transaction gets aborted.\n" "Timeout set to 0 means that we don't timeout at all on application wait.", ConfigInfo::CI_USED, true, ConfigInfo::CI_INT, STR_VALUE(MAX_INT_RNIL), "0", STR_VALUE(MAX_INT_RNIL) }, { CFG_DB_TRANSACTION_DEADLOCK_TIMEOUT, "TransactionDeadlockDetectionTimeout", DB_TOKEN, "Time transaction can be executing in a DB node (ms).\n" "This is the time the transaction coordinator waits for each database node\n" "of the transaction to execute a request. If the database node takes too\n" "long time, the transaction gets aborted.", ConfigInfo::CI_USED, true, ConfigInfo::CI_INT, "1200", "50", STR_VALUE(MAX_INT_RNIL) }, { CFG_DB_LCP_DISC_PAGES_TUP_SR, "NoOfDiskPagesToDiskDuringRestartTUP", DB_TOKEN, "DiskCheckpointSpeedSr", ConfigInfo::CI_DEPRICATED, true, ConfigInfo::CI_INT, "40", "1", STR_VALUE(MAX_INT_RNIL) }, { CFG_DB_LCP_DISC_PAGES_TUP, "NoOfDiskPagesToDiskAfterRestartTUP", DB_TOKEN, "DiskCheckpointSpeed", ConfigInfo::CI_DEPRICATED, true, ConfigInfo::CI_INT, "40", "1", STR_VALUE(MAX_INT_RNIL) }, { CFG_DB_LCP_DISC_PAGES_ACC_SR, "NoOfDiskPagesToDiskDuringRestartACC", DB_TOKEN, "DiskCheckpointSpeedSr", ConfigInfo::CI_DEPRICATED, true, ConfigInfo::CI_INT, "20", "1", STR_VALUE(MAX_INT_RNIL) }, { CFG_DB_LCP_DISC_PAGES_ACC, "NoOfDiskPagesToDiskAfterRestartACC", DB_TOKEN, "DiskCheckpointSpeed", ConfigInfo::CI_DEPRICATED, true, ConfigInfo::CI_INT, "20", "1", STR_VALUE(MAX_INT_RNIL) }, { CFG_DB_DISCLESS, "Diskless", DB_TOKEN, "Run wo/ disk", ConfigInfo::CI_USED, true, ConfigInfo::CI_BOOL, "false", "false", "true"}, { KEY_INTERNAL, "Discless", DB_TOKEN, "Diskless", ConfigInfo::CI_DEPRICATED, true, ConfigInfo::CI_BOOL, "false", "false", "true"}, { CFG_DB_ARBIT_TIMEOUT, "ArbitrationTimeout", DB_TOKEN, "Max time (milliseconds) database partion waits for arbitration signal", ConfigInfo::CI_USED, false, ConfigInfo::CI_INT, "3000", "10", STR_VALUE(MAX_INT_RNIL) }, { CFG_NODE_DATADIR, "DataDir", DB_TOKEN, "Data directory for this node", ConfigInfo::CI_USED, false, ConfigInfo::CI_STRING, MYSQLCLUSTERDIR, 0, 0 }, { CFG_DB_FILESYSTEM_PATH, "FileSystemPath", DB_TOKEN, "Path to directory where the "DB_TOKEN_PRINT" node stores its data (directory must exist)", ConfigInfo::CI_USED, false, ConfigInfo::CI_STRING, UNDEFINED, 0, 0 }, { CFG_LOGLEVEL_STARTUP, "LogLevelStartup", DB_TOKEN, "Node startup info printed on stdout", ConfigInfo::CI_USED, false, ConfigInfo::CI_INT, "1", "0", "15" }, { CFG_LOGLEVEL_SHUTDOWN, "LogLevelShutdown", DB_TOKEN, "Node shutdown info printed on stdout", ConfigInfo::CI_USED, false, ConfigInfo::CI_INT, "0", "0", "15" }, { CFG_LOGLEVEL_STATISTICS, "LogLevelStatistic", DB_TOKEN, "Transaction, operation, transporter info printed on stdout", ConfigInfo::CI_USED, false, ConfigInfo::CI_INT, "0", "0", "15" }, { CFG_LOGLEVEL_CHECKPOINT, "LogLevelCheckpoint", DB_TOKEN, "Local and Global checkpoint info printed on stdout", ConfigInfo::CI_USED, false, ConfigInfo::CI_INT, "0", "0", "15" }, { CFG_LOGLEVEL_NODERESTART, "LogLevelNodeRestart", DB_TOKEN, "Node restart, node failure info printed on stdout", ConfigInfo::CI_USED, false, ConfigInfo::CI_INT, "0", "0", "15" }, { CFG_LOGLEVEL_CONNECTION, "LogLevelConnection", DB_TOKEN, "Node connect/disconnect info printed on stdout", ConfigInfo::CI_USED, false, ConfigInfo::CI_INT, "0", "0", "15" }, { CFG_LOGLEVEL_CONGESTION, "LogLevelCongestion", DB_TOKEN, "Congestion info printed on stdout", ConfigInfo::CI_USED, false, ConfigInfo::CI_INT, "0", "0", "15" }, { CFG_LOGLEVEL_ERROR, "LogLevelError", DB_TOKEN, "Transporter, heartbeat errors printed on stdout", ConfigInfo::CI_USED, false, ConfigInfo::CI_INT, "0", "0", "15" }, { CFG_LOGLEVEL_INFO, "LogLevelInfo", DB_TOKEN, "Heartbeat and log info printed on stdout", ConfigInfo::CI_USED, false, ConfigInfo::CI_INT, "0", "0", "15" }, /** * Backup */ { CFG_DB_PARALLEL_BACKUPS, "ParallelBackups", DB_TOKEN, "Maximum number of parallel backups", ConfigInfo::CI_NOTIMPLEMENTED, false, ConfigInfo::CI_INT, "1", "1", "1" }, { CFG_DB_BACKUP_DATADIR, "BackupDataDir", DB_TOKEN, "Path to where to store backups", ConfigInfo::CI_USED, false, ConfigInfo::CI_STRING, UNDEFINED, 0, 0 }, { CFG_DB_DISK_SYNCH_SIZE, "DiskSyncSize", DB_TOKEN, "Data written to a file before a synch is forced", ConfigInfo::CI_USED, false, ConfigInfo::CI_INT, "4M", "32k", STR_VALUE(MAX_INT_RNIL) }, { CFG_DB_CHECKPOINT_SPEED, "DiskCheckpointSpeed", DB_TOKEN, "Bytes per second allowed to be written by checkpoint", ConfigInfo::CI_USED, false, ConfigInfo::CI_INT, "10M", "1M", STR_VALUE(MAX_INT_RNIL) }, { CFG_DB_CHECKPOINT_SPEED_SR, "DiskCheckpointSpeedInRestart", DB_TOKEN, "Bytes per second allowed to be written by checkpoint during restart", ConfigInfo::CI_USED, false, ConfigInfo::CI_INT, "100M", "1M", STR_VALUE(MAX_INT_RNIL) }, { CFG_DB_BACKUP_MEM, "BackupMemory", DB_TOKEN, "Total memory allocated for backups per node (in bytes)", ConfigInfo::CI_USED, false, ConfigInfo::CI_INT, "4M", // sum of BackupDataBufferSize and BackupLogBufferSize "0", STR_VALUE(MAX_INT_RNIL) }, { CFG_DB_BACKUP_DATA_BUFFER_MEM, "BackupDataBufferSize", DB_TOKEN, "Default size of databuffer for a backup (in bytes)", ConfigInfo::CI_USED, false, ConfigInfo::CI_INT, "2M", // remember to change BackupMemory "0", STR_VALUE(MAX_INT_RNIL) }, { CFG_DB_BACKUP_LOG_BUFFER_MEM, "BackupLogBufferSize", DB_TOKEN, "Default size of logbuffer for a backup (in bytes)", ConfigInfo::CI_USED, false, ConfigInfo::CI_INT, "2M", // remember to change BackupMemory "0", STR_VALUE(MAX_INT_RNIL) }, { CFG_DB_BACKUP_WRITE_SIZE, "BackupWriteSize", DB_TOKEN, "Default size of filesystem writes made by backup (in bytes)", ConfigInfo::CI_USED, false, ConfigInfo::CI_INT, "32K", "2K", STR_VALUE(MAX_INT_RNIL) }, { CFG_DB_BACKUP_MAX_WRITE_SIZE, "BackupMaxWriteSize", DB_TOKEN, "Max size of filesystem writes made by backup (in bytes)", ConfigInfo::CI_USED, false, ConfigInfo::CI_INT, "256K", "2K", STR_VALUE(MAX_INT_RNIL) }, { CFG_DB_STRING_MEMORY, "StringMemory", DB_TOKEN, "Default size of string memory (0 -> 5% of max 1-100 -> %of max, >100 -> actual bytes)", ConfigInfo::CI_USED, false, ConfigInfo::CI_INT, "0", "0", STR_VALUE(MAX_INT_RNIL) }, { CFG_DB_MAX_ALLOCATE, "MaxAllocate", DB_TOKEN, "Maximum size of allocation to use when allocating memory for tables", ConfigInfo::CI_USED, false, ConfigInfo::CI_INT, "32M", "1M", "1G" }, { CFG_DB_MEMREPORT_FREQUENCY, "MemReportFrequency", DB_TOKEN, "Frequency of mem reports in seconds, 0 = only when passing %-limits", ConfigInfo::CI_USED, false, ConfigInfo::CI_INT, "0", "0", STR_VALUE(MAX_INT_RNIL) }, { CFG_DB_O_DIRECT, "ODirect", DB_TOKEN, "Use O_DIRECT file write/read when possible", ConfigInfo::CI_USED, true, ConfigInfo::CI_BOOL, "false", "false", "true"}, /*************************************************************************** * API ***************************************************************************/ { CFG_SECTION_NODE, API_TOKEN, API_TOKEN, "Node section", ConfigInfo::CI_USED, false, ConfigInfo::CI_SECTION, (const char *)NODE_TYPE_API, 0, 0 }, { CFG_NODE_HOST, "HostName", API_TOKEN, "Name of computer for this node", ConfigInfo::CI_INTERNAL, false, ConfigInfo::CI_STRING, "", 0, 0 }, { CFG_NODE_SYSTEM, "System", API_TOKEN, "Name of system for this node", ConfigInfo::CI_INTERNAL, false, ConfigInfo::CI_STRING, UNDEFINED, 0, 0 }, { KEY_INTERNAL, "Id", API_TOKEN, "", ConfigInfo::CI_DEPRICATED, false, ConfigInfo::CI_INT, MANDATORY, "1", STR_VALUE(MAX_NODES_ID) }, { CFG_NODE_ID, "NodeId", API_TOKEN, "Number identifying application node ("API_TOKEN_PRINT")", ConfigInfo::CI_USED, false, ConfigInfo::CI_INT, MANDATORY, "1", STR_VALUE(MAX_NODES_ID) }, { KEY_INTERNAL, "ExecuteOnComputer", API_TOKEN, "String referencing an earlier defined COMPUTER", ConfigInfo::CI_USED, false, ConfigInfo::CI_STRING, UNDEFINED, 0, 0 }, { CFG_NODE_ARBIT_RANK, "ArbitrationRank", API_TOKEN, "If 0, then "API_TOKEN_PRINT" is not arbitrator. Kernel selects arbitrators in order 1, 2", ConfigInfo::CI_USED, false, ConfigInfo::CI_INT, "0", "0", "2" }, { CFG_NODE_ARBIT_DELAY, "ArbitrationDelay", API_TOKEN, "When asked to arbitrate, arbitrator waits this long before voting (msec)", ConfigInfo::CI_USED, false, ConfigInfo::CI_INT, "0", "0", STR_VALUE(MAX_INT_RNIL) }, { CFG_MAX_SCAN_BATCH_SIZE, "MaxScanBatchSize", "API", "The maximum collective batch size for one scan", ConfigInfo::CI_USED, false, ConfigInfo::CI_INT, STR_VALUE(MAX_SCAN_BATCH_SIZE), "32k", "16M" }, { CFG_BATCH_BYTE_SIZE, "BatchByteSize", "API", "The default batch size in bytes", ConfigInfo::CI_USED, false, ConfigInfo::CI_INT, STR_VALUE(SCAN_BATCH_SIZE), "1k", "1M" }, { CFG_BATCH_SIZE, "BatchSize", "API", "The default batch size in number of records", ConfigInfo::CI_USED, false, ConfigInfo::CI_INT, STR_VALUE(DEF_BATCH_SIZE), "1", STR_VALUE(MAX_PARALLEL_OP_PER_SCAN) }, /**************************************************************************** * MGM ***************************************************************************/ { CFG_SECTION_NODE, MGM_TOKEN, MGM_TOKEN, "Node section", ConfigInfo::CI_USED, false, ConfigInfo::CI_SECTION, (const char *)NODE_TYPE_MGM, 0, 0 }, { CFG_NODE_HOST, "HostName", MGM_TOKEN, "Name of computer for this node", ConfigInfo::CI_INTERNAL, false, ConfigInfo::CI_STRING, "", 0, 0 }, { CFG_NODE_DATADIR, "DataDir", MGM_TOKEN, "Data directory for this node", ConfigInfo::CI_USED, false, ConfigInfo::CI_STRING, MYSQLCLUSTERDIR, 0, 0 }, { CFG_NODE_SYSTEM, "System", MGM_TOKEN, "Name of system for this node", ConfigInfo::CI_INTERNAL, false, ConfigInfo::CI_STRING, UNDEFINED, 0, 0 }, { KEY_INTERNAL, "Id", MGM_TOKEN, "", ConfigInfo::CI_DEPRICATED, false, ConfigInfo::CI_INT, MANDATORY, "1", STR_VALUE(MAX_NODES_ID) }, { CFG_NODE_ID, "NodeId", MGM_TOKEN, "Number identifying the management server node ("MGM_TOKEN_PRINT")", ConfigInfo::CI_USED, false, ConfigInfo::CI_INT, MANDATORY, "1", STR_VALUE(MAX_NODES_ID) }, { CFG_LOG_DESTINATION, "LogDestination", MGM_TOKEN, "String describing where logmessages are sent", ConfigInfo::CI_USED, false, ConfigInfo::CI_STRING, 0, 0, 0 }, { KEY_INTERNAL, "ExecuteOnComputer", MGM_TOKEN, "String referencing an earlier defined COMPUTER", ConfigInfo::CI_USED, false, ConfigInfo::CI_STRING, 0, 0, 0 }, { KEY_INTERNAL, "MaxNoOfSavedEvents", MGM_TOKEN, "", ConfigInfo::CI_USED, false, ConfigInfo::CI_INT, "100", "0", STR_VALUE(MAX_INT_RNIL) }, { CFG_MGM_PORT, "PortNumber", MGM_TOKEN, "Port number to give commands to/fetch configurations from management server", ConfigInfo::CI_USED, false, ConfigInfo::CI_INT, NDB_PORT, "0", STR_VALUE(MAX_PORT_NO) }, { KEY_INTERNAL, "PortNumberStats", MGM_TOKEN, "Port number used to get statistical information from a management server", ConfigInfo::CI_USED, false, ConfigInfo::CI_INT, UNDEFINED, "0", STR_VALUE(MAX_PORT_NO) }, { CFG_NODE_ARBIT_RANK, "ArbitrationRank", MGM_TOKEN, "If 0, then "MGM_TOKEN_PRINT" is not arbitrator. Kernel selects arbitrators in order 1, 2", ConfigInfo::CI_USED, false, ConfigInfo::CI_INT, "1", "0", "2" }, { CFG_NODE_ARBIT_DELAY, "ArbitrationDelay", MGM_TOKEN, "", ConfigInfo::CI_USED, false, ConfigInfo::CI_INT, "0", "0", STR_VALUE(MAX_INT_RNIL) }, /**************************************************************************** * TCP ***************************************************************************/ { CFG_SECTION_CONNECTION, "TCP", "TCP", "Connection section", ConfigInfo::CI_USED, false, ConfigInfo::CI_SECTION, (const char *)CONNECTION_TYPE_TCP, 0, 0 }, { CFG_CONNECTION_HOSTNAME_1, "HostName1", "TCP", "Name/IP of computer on one side of the connection", ConfigInfo::CI_INTERNAL, false, ConfigInfo::CI_STRING, UNDEFINED, 0, 0 }, { CFG_CONNECTION_HOSTNAME_2, "HostName2", "TCP", "Name/IP of computer on one side of the connection", ConfigInfo::CI_INTERNAL, false, ConfigInfo::CI_STRING, UNDEFINED, 0, 0 }, { CFG_CONNECTION_NODE_1, "NodeId1", "TCP", "Id of node ("DB_TOKEN_PRINT", "API_TOKEN_PRINT" or "MGM_TOKEN_PRINT") on one side of the connection", ConfigInfo::CI_USED, false, ConfigInfo::CI_STRING, MANDATORY, 0, 0 }, { CFG_CONNECTION_NODE_2, "NodeId2", "TCP", "Id of node ("DB_TOKEN_PRINT", "API_TOKEN_PRINT" or "MGM_TOKEN_PRINT") on one side of the connection", ConfigInfo::CI_USED, false, ConfigInfo::CI_STRING, MANDATORY, 0, 0 }, { CFG_CONNECTION_GROUP, "Group", "TCP", "", ConfigInfo::CI_USED, false, ConfigInfo::CI_INT, "55", "0", "200" }, { CFG_CONNECTION_NODE_ID_SERVER, "NodeIdServer", "TCP", "", ConfigInfo::CI_USED, false, ConfigInfo::CI_INT, MANDATORY, "1", "63" }, { CFG_CONNECTION_SEND_SIGNAL_ID, "SendSignalId", "TCP", "Sends id in each signal. Used in trace files.", ConfigInfo::CI_USED, false, ConfigInfo::CI_BOOL, "true", "false", "true" }, { CFG_CONNECTION_CHECKSUM, "Checksum", "TCP", "If checksum is enabled, all signals between nodes are checked for errors", ConfigInfo::CI_USED, false, ConfigInfo::CI_BOOL, "false", "false", "true" }, { CFG_CONNECTION_SERVER_PORT, "PortNumber", "TCP", "Port used for this transporter", ConfigInfo::CI_USED, false, ConfigInfo::CI_INT, MANDATORY, "0", STR_VALUE(MAX_PORT_NO) }, { CFG_TCP_SEND_BUFFER_SIZE, "SendBufferMemory", "TCP", "Bytes of buffer for signals sent from this node", ConfigInfo::CI_USED, false, ConfigInfo::CI_INT, "256K", "64K", STR_VALUE(MAX_INT_RNIL) }, { CFG_TCP_RECEIVE_BUFFER_SIZE, "ReceiveBufferMemory", "TCP", "Bytes of buffer for signals received by this node", ConfigInfo::CI_USED, false, ConfigInfo::CI_INT, "64K", "16K", STR_VALUE(MAX_INT_RNIL) }, { CFG_TCP_PROXY, "Proxy", "TCP", "", ConfigInfo::CI_USED, false, ConfigInfo::CI_STRING, UNDEFINED, 0, 0 }, { CFG_CONNECTION_NODE_1_SYSTEM, "NodeId1_System", "TCP", "System for node 1 in connection", ConfigInfo::CI_INTERNAL, false, ConfigInfo::CI_STRING, UNDEFINED, 0, 0 }, { CFG_CONNECTION_NODE_2_SYSTEM, "NodeId2_System", "TCP", "System for node 2 in connection", ConfigInfo::CI_INTERNAL, false, ConfigInfo::CI_STRING, UNDEFINED, 0, 0 }, /**************************************************************************** * SHM ***************************************************************************/ { CFG_SECTION_CONNECTION, "SHM", "SHM", "Connection section", ConfigInfo::CI_USED, false, ConfigInfo::CI_SECTION, (const char *)CONNECTION_TYPE_SHM, 0, 0 }, { CFG_CONNECTION_HOSTNAME_1, "HostName1", "SHM", "Name/IP of computer on one side of the connection", ConfigInfo::CI_INTERNAL, false, ConfigInfo::CI_STRING, UNDEFINED, 0, 0 }, { CFG_CONNECTION_HOSTNAME_2, "HostName2", "SHM", "Name/IP of computer on one side of the connection", ConfigInfo::CI_INTERNAL, false, ConfigInfo::CI_STRING, UNDEFINED, 0, 0 }, { CFG_CONNECTION_SERVER_PORT, "PortNumber", "SHM", "Port used for this transporter", ConfigInfo::CI_USED, false, ConfigInfo::CI_INT, MANDATORY, "0", STR_VALUE(MAX_PORT_NO) }, { CFG_SHM_SIGNUM, "Signum", "SHM", "Signum to be used for signalling", ConfigInfo::CI_USED, false, ConfigInfo::CI_INT, UNDEFINED, "0", STR_VALUE(MAX_INT_RNIL) }, { CFG_CONNECTION_NODE_1, "NodeId1", "SHM", "Id of node ("DB_TOKEN_PRINT", "API_TOKEN_PRINT" or "MGM_TOKEN_PRINT") on one side of the connection", ConfigInfo::CI_USED, false, ConfigInfo::CI_STRING, MANDATORY, 0, 0 }, { CFG_CONNECTION_NODE_2, "NodeId2", "SHM", "Id of node ("DB_TOKEN_PRINT", "API_TOKEN_PRINT" or "MGM_TOKEN_PRINT") on one side of the connection", ConfigInfo::CI_USED, false, ConfigInfo::CI_STRING, MANDATORY, 0, 0 }, { CFG_CONNECTION_GROUP, "Group", "SHM", "", ConfigInfo::CI_USED, false, ConfigInfo::CI_INT, "35", "0", "200" }, { CFG_CONNECTION_NODE_ID_SERVER, "NodeIdServer", "SHM", "", ConfigInfo::CI_USED, false, ConfigInfo::CI_INT, MANDATORY, "1", "63" }, { CFG_CONNECTION_SEND_SIGNAL_ID, "SendSignalId", "SHM", "Sends id in each signal. Used in trace files.", ConfigInfo::CI_USED, false, ConfigInfo::CI_BOOL, "false", "false", "true" }, { CFG_CONNECTION_CHECKSUM, "Checksum", "SHM", "If checksum is enabled, all signals between nodes are checked for errors", ConfigInfo::CI_USED, false, ConfigInfo::CI_BOOL, "true", "false", "true" }, { CFG_SHM_KEY, "ShmKey", "SHM", "A shared memory key", ConfigInfo::CI_USED, false, ConfigInfo::CI_INT, UNDEFINED, "0", STR_VALUE(MAX_INT_RNIL) }, { CFG_SHM_BUFFER_MEM, "ShmSize", "SHM", "Size of shared memory segment", ConfigInfo::CI_USED, false, ConfigInfo::CI_INT, "1M", "64K", STR_VALUE(MAX_INT_RNIL) }, { CFG_CONNECTION_NODE_1_SYSTEM, "NodeId1_System", "SHM", "System for node 1 in connection", ConfigInfo::CI_INTERNAL, false, ConfigInfo::CI_STRING, UNDEFINED, 0, 0 }, { CFG_CONNECTION_NODE_2_SYSTEM, "NodeId2_System", "SHM", "System for node 2 in connection", ConfigInfo::CI_INTERNAL, false, ConfigInfo::CI_STRING, UNDEFINED, 0, 0 }, /**************************************************************************** * SCI ***************************************************************************/ { CFG_SECTION_CONNECTION, "SCI", "SCI", "Connection section", ConfigInfo::CI_USED, false, ConfigInfo::CI_SECTION, (const char *)CONNECTION_TYPE_SCI, 0, 0 }, { CFG_CONNECTION_NODE_1, "NodeId1", "SCI", "Id of node ("DB_TOKEN_PRINT", "API_TOKEN_PRINT" or "MGM_TOKEN_PRINT") on one side of the connection", ConfigInfo::CI_USED, false, ConfigInfo::CI_STRING, MANDATORY, "0", STR_VALUE(MAX_INT_RNIL) }, { CFG_CONNECTION_NODE_2, "NodeId2", "SCI", "Id of node ("DB_TOKEN_PRINT", "API_TOKEN_PRINT" or "MGM_TOKEN_PRINT") on one side of the connection", ConfigInfo::CI_USED, false, ConfigInfo::CI_STRING, MANDATORY, "0", STR_VALUE(MAX_INT_RNIL) }, { CFG_CONNECTION_GROUP, "Group", "SCI", "", ConfigInfo::CI_USED, false, ConfigInfo::CI_INT, "15", "0", "200" }, { CFG_CONNECTION_NODE_ID_SERVER, "NodeIdServer", "SCI", "", ConfigInfo::CI_USED, false, ConfigInfo::CI_INT, MANDATORY, "1", "63" }, { CFG_CONNECTION_HOSTNAME_1, "HostName1", "SCI", "Name/IP of computer on one side of the connection", ConfigInfo::CI_INTERNAL, false, ConfigInfo::CI_STRING, UNDEFINED, 0, 0 }, { CFG_CONNECTION_HOSTNAME_2, "HostName2", "SCI", "Name/IP of computer on one side of the connection", ConfigInfo::CI_INTERNAL, false, ConfigInfo::CI_STRING, UNDEFINED, 0, 0 }, { CFG_CONNECTION_SERVER_PORT, "PortNumber", "SCI", "Port used for this transporter", ConfigInfo::CI_USED, false, ConfigInfo::CI_INT, MANDATORY, "0", STR_VALUE(MAX_PORT_NO) }, { CFG_SCI_HOST1_ID_0, "Host1SciId0", "SCI", "SCI-node id for adapter 0 on Host1 (a computer can have two adapters)", ConfigInfo::CI_USED, false, ConfigInfo::CI_INT, MANDATORY, "0", STR_VALUE(MAX_INT_RNIL) }, { CFG_SCI_HOST1_ID_1, "Host1SciId1", "SCI", "SCI-node id for adapter 1 on Host1 (a computer can have two adapters)", ConfigInfo::CI_USED, false, ConfigInfo::CI_INT, "0", "0", STR_VALUE(MAX_INT_RNIL) }, { CFG_SCI_HOST2_ID_0, "Host2SciId0", "SCI", "SCI-node id for adapter 0 on Host2 (a computer can have two adapters)", ConfigInfo::CI_USED, false, ConfigInfo::CI_INT, MANDATORY, "0", STR_VALUE(MAX_INT_RNIL) }, { CFG_SCI_HOST2_ID_1, "Host2SciId1", "SCI", "SCI-node id for adapter 1 on Host2 (a computer can have two adapters)", ConfigInfo::CI_USED, false, ConfigInfo::CI_INT, "0", "0", STR_VALUE(MAX_INT_RNIL) }, { CFG_CONNECTION_SEND_SIGNAL_ID, "SendSignalId", "SCI", "Sends id in each signal. Used in trace files.", ConfigInfo::CI_USED, false, ConfigInfo::CI_BOOL, "true", "false", "true" }, { CFG_CONNECTION_CHECKSUM, "Checksum", "SCI", "If checksum is enabled, all signals between nodes are checked for errors", ConfigInfo::CI_USED, false, ConfigInfo::CI_BOOL, "false", "false", "true" }, { CFG_SCI_SEND_LIMIT, "SendLimit", "SCI", "Transporter send buffer contents are sent when this no of bytes is buffered", ConfigInfo::CI_USED, false, ConfigInfo::CI_INT, "8K", "128", "32K" }, { CFG_SCI_BUFFER_MEM, "SharedBufferSize", "SCI", "Size of shared memory segment", ConfigInfo::CI_USED, false, ConfigInfo::CI_INT, "1M", "64K", STR_VALUE(MAX_INT_RNIL) }, { CFG_CONNECTION_NODE_1_SYSTEM, "NodeId1_System", "SCI", "System for node 1 in connection", ConfigInfo::CI_INTERNAL, false, ConfigInfo::CI_STRING, UNDEFINED, 0, 0 }, { CFG_CONNECTION_NODE_2_SYSTEM, "NodeId2_System", "SCI", "System for node 2 in connection", ConfigInfo::CI_INTERNAL, false, ConfigInfo::CI_STRING, UNDEFINED, 0, 0 } }; const int ConfigInfo::m_NoOfParams = sizeof(m_ParamInfo) / sizeof(ParamInfo); #ifndef NDB_MGMAPI /**************************************************************************** * Ctor ****************************************************************************/ static void require(bool v) { if(!v) { if (opt_core) abort(); else exit(-1); } } ConfigInfo::ConfigInfo() : m_info(true), m_systemDefaults(true) { int i; Properties *section; const Properties *oldpinfo; for (i=0; i<m_NoOfParams; i++) { const ParamInfo & param = m_ParamInfo[i]; Uint64 default_uint64; bool default_bool; // Create new section if it did not exist if (!m_info.getCopy(param._section, &section)) { Properties newsection(true); m_info.put(param._section, &newsection); // Get copy of section m_info.getCopy(param._section, &section); } // Create pinfo (parameter info) entry Properties pinfo(true); pinfo.put("Id", param._paramId); pinfo.put("Fname", param._fname); pinfo.put("Description", param._description); pinfo.put("Updateable", param._updateable); pinfo.put("Type", param._type); pinfo.put("Status", param._status); if(param._default == MANDATORY){ pinfo.put("Mandatory", (Uint32)1); } switch (param._type) { case CI_BOOL: { bool tmp_bool; require(InitConfigFileParser::convertStringToBool(param._min, tmp_bool)); pinfo.put64("Min", tmp_bool); require(InitConfigFileParser::convertStringToBool(param._max, tmp_bool)); pinfo.put64("Max", tmp_bool); break; } case CI_INT: case CI_INT64: { Uint64 tmp_uint64; require(InitConfigFileParser::convertStringToUint64(param._min, tmp_uint64)); pinfo.put64("Min", tmp_uint64); require(InitConfigFileParser::convertStringToUint64(param._max, tmp_uint64)); pinfo.put64("Max", tmp_uint64); break; } case CI_SECTION: pinfo.put("SectionType", (Uint32)UintPtr(param._default)); break; case CI_STRING: break; } // Check that pinfo is really new if (section->get(param._fname, &oldpinfo)) { ndbout << "Error: Parameter " << param._fname << " defined twice in section " << param._section << "." << endl; require(false); } // Add new pinfo to section section->put(param._fname, &pinfo); // Replace section with modified section m_info.put(param._section, section, true); delete section; if(param._type != ConfigInfo::CI_SECTION){ Properties * p; if(!m_systemDefaults.getCopy(param._section, &p)){ p = new Properties(true); } if(param._default != UNDEFINED && param._default != MANDATORY){ switch (param._type) { case CI_SECTION: break; case CI_STRING: require(p->put(param._fname, param._default)); break; case CI_BOOL: { require(InitConfigFileParser::convertStringToBool(param._default, default_bool)); require(p->put(param._fname, default_bool)); break; } case CI_INT: case CI_INT64: { require(InitConfigFileParser::convertStringToUint64(param._default, default_uint64)); require(p->put(param._fname, default_uint64)); break; } } } require(m_systemDefaults.put(param._section, p, true)); delete p; } } for (i=0; i<m_NoOfParams; i++) { if(m_ParamInfo[i]._section == NULL){ ndbout << "Check that each entry has a section failed." << endl; ndbout << "Parameter \"" << m_ParamInfo[i]._fname << endl; ndbout << "Edit file " << __FILE__ << "." << endl; require(false); } if(m_ParamInfo[i]._type == ConfigInfo::CI_SECTION) continue; const Properties * p = getInfo(m_ParamInfo[i]._section); if (!p || !p->contains(m_ParamInfo[i]._fname)) { ndbout << "Check that each pname has an fname failed." << endl; ndbout << "Parameter \"" << m_ParamInfo[i]._fname << "\" does not exist in section \"" << m_ParamInfo[i]._section << "\"." << endl; ndbout << "Edit file " << __FILE__ << "." << endl; require(false); } } } /**************************************************************************** * Getters ****************************************************************************/ inline void warning(const char * src, const char * arg){ ndbout << "Illegal call to ConfigInfo::" << src << "() - " << arg << endl; require(false); } const Properties * ConfigInfo::getInfo(const char * section) const { const Properties * p; if(!m_info.get(section, &p)){ return 0; // warning("getInfo", section); } return p; } const Properties * ConfigInfo::getDefaults(const char * section) const { const Properties * p; if(!m_systemDefaults.get(section, &p)){ return 0; //warning("getDefaults", section); } return p; } static Uint64 getInfoInt(const Properties * section, const char* fname, const char * type){ Uint32 val32; const Properties * p; if (section->get(fname, &p) && p->get(type, &val32)) { return val32; } Uint64 val64; if(p && p->get(type, &val64)){ return val64; } section->print(); if(section->get(fname, &p)){ p->print(); } warning(type, fname); return 0; } static const char * getInfoString(const Properties * section, const char* fname, const char * type){ const char* val; const Properties * p; if (section->get(fname, &p) && p->get(type, &val)) { return val; } warning(type, fname); return val; } Uint64 ConfigInfo::getMax(const Properties * section, const char* fname) const { return getInfoInt(section, fname, "Max"); } Uint64 ConfigInfo::getMin(const Properties * section, const char* fname) const { return getInfoInt(section, fname, "Min"); } Uint64 ConfigInfo::getDefault(const Properties * section, const char* fname) const { return getInfoInt(section, fname, "Default"); } const char* ConfigInfo::getDescription(const Properties * section, const char* fname) const { return getInfoString(section, fname, "Description"); } bool ConfigInfo::isSection(const char * section) const { for (int i = 0; i<m_noOfSectionNames; i++) { if(!strcasecmp(section, m_sectionNames[i])) return true; } return false; } const char* ConfigInfo::nameToAlias(const char * name) { for (int i = 0; m_sectionNameAliases[i].name != 0; i++) if(!strcasecmp(name, m_sectionNameAliases[i].name)) return m_sectionNameAliases[i].alias; return 0; } const char* ConfigInfo::getAlias(const char * section) { for (int i = 0; m_sectionNameAliases[i].name != 0; i++) if(!strcasecmp(section, m_sectionNameAliases[i].alias)) return m_sectionNameAliases[i].name; return 0; } bool ConfigInfo::verify(const Properties * section, const char* fname, Uint64 value) const { Uint64 min, max; min = getInfoInt(section, fname, "Min"); max = getInfoInt(section, fname, "Max"); if(min > max){ warning("verify", fname); } if (value >= min && value <= max) return true; else return false; } ConfigInfo::Type ConfigInfo::getType(const Properties * section, const char* fname) const { return (ConfigInfo::Type) getInfoInt(section, fname, "Type"); } ConfigInfo::Status ConfigInfo::getStatus(const Properties * section, const char* fname) const { return (ConfigInfo::Status) getInfoInt(section, fname, "Status"); } /**************************************************************************** * Printers ****************************************************************************/ void ConfigInfo::print() const { Properties::Iterator it(&m_info); for (const char* n = it.first(); n != NULL; n = it.next()) { print(n); } } void ConfigInfo::print(const char* section) const { ndbout << "****** " << section << " ******" << endl << endl; const Properties * sec = getInfo(section); Properties::Iterator it(sec); for (const char* n = it.first(); n != NULL; n = it.next()) { // Skip entries with different F- and P-names if (getStatus(sec, n) == ConfigInfo::CI_INTERNAL) continue; if (getStatus(sec, n) == ConfigInfo::CI_DEPRICATED) continue; if (getStatus(sec, n) == ConfigInfo::CI_NOTIMPLEMENTED) continue; print(sec, n); } } void ConfigInfo::print(const Properties * section, const char* parameter) const { ndbout << parameter; // ndbout << getDescription(section, parameter) << endl; switch (getType(section, parameter)) { case ConfigInfo::CI_BOOL: ndbout << " (Boolean value)" << endl; ndbout << getDescription(section, parameter) << endl; if (getDefault(section, parameter) == false) { ndbout << "Default: N (Legal values: Y, N)" << endl; } else if (getDefault(section, parameter) == true) { ndbout << "Default: Y (Legal values: Y, N)" << endl; } else if (getDefault(section, parameter) == (UintPtr)MANDATORY) { ndbout << "MANDATORY (Legal values: Y, N)" << endl; } else { ndbout << "UNKNOWN" << endl; } ndbout << endl; break; case ConfigInfo::CI_INT: case ConfigInfo::CI_INT64: ndbout << " (Non-negative Integer)" << endl; ndbout << getDescription(section, parameter) << endl; if (getDefault(section, parameter) == (UintPtr)MANDATORY) { ndbout << "MANDATORY ("; } else if (getDefault(section, parameter) == (UintPtr)UNDEFINED) { ndbout << "UNDEFINED ("; } else { ndbout << "Default: " << getDefault(section, parameter) << " ("; } ndbout << "Min: " << getMin(section, parameter) << ", "; ndbout << "Max: " << getMax(section, parameter) << ")" << endl; ndbout << endl; break; case ConfigInfo::CI_STRING: ndbout << " (String)" << endl; ndbout << getDescription(section, parameter) << endl; if (getDefault(section, parameter) == (UintPtr)MANDATORY) { ndbout << "MANDATORY" << endl; } else { ndbout << "No default value" << endl; } ndbout << endl; break; case ConfigInfo::CI_SECTION: break; } } /**************************************************************************** * Section Rules ****************************************************************************/ /** * Node rule: Add "Type" and update "NoOfNodes" */ bool transformNode(InitConfigFileParser::Context & ctx, const char * data){ Uint32 id, line; if(!ctx.m_currentSection->get("NodeId", &id) && !ctx.m_currentSection->get("Id", &id)){ Uint32 nextNodeId= 1; ctx.m_userProperties.get("NextNodeId", &nextNodeId); id= nextNodeId; while (ctx.m_userProperties.get("AllocatedNodeId_", id, &line)) id++; if (id != nextNodeId) { fprintf(stderr,"Cluster configuration warning line %d: " "Could not use next node id %d for section [%s], " "using next unused node id %d.\n", ctx.m_sectionLineno, nextNodeId, ctx.fname, id); } ctx.m_currentSection->put("NodeId", id); } else if(ctx.m_userProperties.get("AllocatedNodeId_", id, &line)) { ctx.reportError("Duplicate nodeid in section " "[%s] starting at line: %d. Previously used on line %d.", ctx.fname, ctx.m_sectionLineno, line); return false; } if(id >= MAX_NODES) { ctx.reportError("too many nodes configured, only up to %d nodes supported.", MAX_NODES); return false; } // next node id _always_ next numbers after last used id ctx.m_userProperties.put("NextNodeId", id+1, true); ctx.m_userProperties.put("AllocatedNodeId_", id, ctx.m_sectionLineno); BaseString::snprintf(ctx.pname, sizeof(ctx.pname), "Node_%d", id); ctx.m_currentSection->put("Type", ctx.fname); Uint32 nodes = 0; ctx.m_userProperties.get("NoOfNodes", &nodes); ctx.m_userProperties.put("NoOfNodes", ++nodes, true); /** * Update count (per type) */ nodes = 0; ctx.m_userProperties.get(ctx.fname, &nodes); ctx.m_userProperties.put(ctx.fname, ++nodes, true); return true; } static bool checkLocalhostHostnameMix(InitConfigFileParser::Context & ctx, const char * data) { DBUG_ENTER("checkLocalhostHostnameMix"); const char * hostname= 0; ctx.m_currentSection->get("HostName", &hostname); if (hostname == 0 || hostname[0] == 0) DBUG_RETURN(true); Uint32 localhost_used= 0; if(!strcmp(hostname, "localhost") || !strcmp(hostname, "127.0.0.1")){ localhost_used= 1; ctx.m_userProperties.put("$computer-localhost-used", localhost_used); if(!ctx.m_userProperties.get("$computer-localhost", &hostname)) DBUG_RETURN(true); } else { ctx.m_userProperties.get("$computer-localhost-used", &localhost_used); ctx.m_userProperties.put("$computer-localhost", hostname); } if (localhost_used) { ctx.reportError("Mixing of localhost (default for [NDBD]HostName) with other hostname(%s) is illegal", hostname); DBUG_RETURN(false); } DBUG_RETURN(true); } bool fixNodeHostname(InitConfigFileParser::Context & ctx, const char * data) { const char * hostname; DBUG_ENTER("fixNodeHostname"); if (ctx.m_currentSection->get("HostName", &hostname)) DBUG_RETURN(checkLocalhostHostnameMix(ctx,0)); const char * compId; if(!ctx.m_currentSection->get("ExecuteOnComputer", &compId)) DBUG_RETURN(true); const Properties * computer; char tmp[255]; BaseString::snprintf(tmp, sizeof(tmp), "Computer_%s", compId); if(!ctx.m_config->get(tmp, &computer)){ ctx.reportError("Computer \"%s\" not declared" "- [%s] starting at line: %d", compId, ctx.fname, ctx.m_sectionLineno); DBUG_RETURN(false); } if(!computer->get("HostName", &hostname)){ ctx.reportError("HostName missing in [COMPUTER] (Id: %d) " " - [%s] starting at line: %d", compId, ctx.fname, ctx.m_sectionLineno); DBUG_RETURN(false); } require(ctx.m_currentSection->put("HostName", hostname)); DBUG_RETURN(checkLocalhostHostnameMix(ctx,0)); } bool fixFileSystemPath(InitConfigFileParser::Context & ctx, const char * data){ DBUG_ENTER("fixFileSystemPath"); const char * path; if (ctx.m_currentSection->get("FileSystemPath", &path)) DBUG_RETURN(true); if (ctx.m_currentSection->get("DataDir", &path)) { require(ctx.m_currentSection->put("FileSystemPath", path)); DBUG_RETURN(true); } require(false); DBUG_RETURN(false); } bool fixBackupDataDir(InitConfigFileParser::Context & ctx, const char * data){ const char * path; if (ctx.m_currentSection->get("BackupDataDir", &path)) return true; if (ctx.m_currentSection->get("FileSystemPath", &path)) { require(ctx.m_currentSection->put("BackupDataDir", path)); return true; } require(false); return false; } /** * Connection rule: Check support of connection */ bool checkConnectionSupport(InitConfigFileParser::Context & ctx, const char * data) { int error= 0; if (strcasecmp("TCP",ctx.fname) == 0) { // always enabled } else if (strcasecmp("SHM",ctx.fname) == 0) { #ifndef NDB_SHM_TRANSPORTER error= 1; #endif } else if (strcasecmp("SCI",ctx.fname) == 0) { #ifndef NDB_SCI_TRANSPORTER error= 1; #endif } if (error) { ctx.reportError("Binary not compiled with this connection support, " "[%s] starting at line: %d", ctx.fname, ctx.m_sectionLineno); return false; } return true; } /** * Connection rule: Update "NoOfConnections" */ bool transformConnection(InitConfigFileParser::Context & ctx, const char * data) { Uint32 connections = 0; ctx.m_userProperties.get("NoOfConnections", &connections); BaseString::snprintf(ctx.pname, sizeof(ctx.pname), "Connection_%d", connections); ctx.m_userProperties.put("NoOfConnections", ++connections, true); ctx.m_currentSection->put("Type", ctx.fname); return true; } /** * System rule: Just add it */ bool transformSystem(InitConfigFileParser::Context & ctx, const char * data){ const char * name; if(!ctx.m_currentSection->get("Name", &name)){ ctx.reportError("Mandatory parameter Name missing from section " "[%s] starting at line: %d", ctx.fname, ctx.m_sectionLineno); return false; } ndbout << "transformSystem " << name << endl; BaseString::snprintf(ctx.pname, sizeof(ctx.pname), "SYSTEM_%s", name); return true; } /** * Computer rule: Update "NoOfComputers", add "Type" */ bool transformComputer(InitConfigFileParser::Context & ctx, const char * data){ const char * id; if(!ctx.m_currentSection->get("Id", &id)){ ctx.reportError("Mandatory parameter Id missing from section " "[%s] starting at line: %d", ctx.fname, ctx.m_sectionLineno); return false; } BaseString::snprintf(ctx.pname, sizeof(ctx.pname), "Computer_%s", id); Uint32 computers = 0; ctx.m_userProperties.get("NoOfComputers", &computers); ctx.m_userProperties.put("NoOfComputers", ++computers, true); const char * hostname = 0; ctx.m_currentSection->get("HostName", &hostname); if(!hostname){ return true; } return checkLocalhostHostnameMix(ctx,0); } /** * Apply default values */ void applyDefaultValues(InitConfigFileParser::Context & ctx, const Properties * defaults) { DBUG_ENTER("applyDefaultValues"); if(defaults != NULL){ Properties::Iterator it(defaults); for(const char * name = it.first(); name != NULL; name = it.next()){ (void) ctx.m_info->getStatus(ctx.m_currentInfo, name); if(!ctx.m_currentSection->contains(name)){ switch (ctx.m_info->getType(ctx.m_currentInfo, name)){ case ConfigInfo::CI_INT: case ConfigInfo::CI_BOOL:{ Uint32 val = 0; ::require(defaults->get(name, &val)); ctx.m_currentSection->put(name, val); DBUG_PRINT("info",("%s=%d #default",name,val)); break; } case ConfigInfo::CI_INT64:{ Uint64 val = 0; ::require(defaults->get(name, &val)); ctx.m_currentSection->put64(name, val); DBUG_PRINT("info",("%s=%lld #default",name,val)); break; } case ConfigInfo::CI_STRING:{ const char * val; ::require(defaults->get(name, &val)); ctx.m_currentSection->put(name, val); DBUG_PRINT("info",("%s=%s #default",name,val)); break; } case ConfigInfo::CI_SECTION: break; } } #ifndef DBUG_OFF else { switch (ctx.m_info->getType(ctx.m_currentInfo, name)){ case ConfigInfo::CI_INT: case ConfigInfo::CI_BOOL:{ Uint32 val = 0; ::require(ctx.m_currentSection->get(name, &val)); DBUG_PRINT("info",("%s=%d",name,val)); break; } case ConfigInfo::CI_INT64:{ Uint64 val = 0; ::require(ctx.m_currentSection->get(name, &val)); DBUG_PRINT("info",("%s=%lld",name,val)); break; } case ConfigInfo::CI_STRING:{ const char * val; ::require(ctx.m_currentSection->get(name, &val)); DBUG_PRINT("info",("%s=%s",name,val)); break; } case ConfigInfo::CI_SECTION: break; } } #endif } } DBUG_VOID_RETURN; } bool applyDefaultValues(InitConfigFileParser::Context & ctx, const char * data){ if(strcmp(data, "user") == 0) applyDefaultValues(ctx, ctx.m_userDefaults); else if (strcmp(data, "system") == 0) applyDefaultValues(ctx, ctx.m_systemDefaults); else return false; return true; } /** * Check that a section contains all MANDATORY parameters */ bool checkMandatory(InitConfigFileParser::Context & ctx, const char * data){ Properties::Iterator it(ctx.m_currentInfo); for(const char * name = it.first(); name != NULL; name = it.next()){ const Properties * info = NULL; ::require(ctx.m_currentInfo->get(name, &info)); Uint32 val; if(info->get("Mandatory", &val)){ const char * fname; ::require(info->get("Fname", &fname)); if(!ctx.m_currentSection->contains(fname)){ ctx.reportError("Mandatory parameter %s missing from section " "[%s] starting at line: %d", fname, ctx.fname, ctx.m_sectionLineno); return false; } } } return true; } /** * Connection rule: Fix node id * * Transform a string "NodeidX" (e.g. "uppsala.32") * into a Uint32 "NodeIdX" (e.g. 32) and a string "SystemX" (e.g. "uppsala"). */ static bool fixNodeId(InitConfigFileParser::Context & ctx, const char * data) { char buf[] = "NodeIdX"; buf[6] = data[sizeof("NodeI")]; char sysbuf[] = "SystemX"; sysbuf[6] = data[sizeof("NodeI")]; const char* nodeId; if(!ctx.m_currentSection->get(buf, &nodeId)) { ctx.reportError("Mandatory parameter %s missing from section" "[%s] starting at line: %d", buf, ctx.fname, ctx.m_sectionLineno); return false; } char tmpLine[MAX_LINE_LENGTH]; strncpy(tmpLine, nodeId, MAX_LINE_LENGTH); char* token1 = strtok(tmpLine, "."); char* token2 = strtok(NULL, "."); Uint32 id; if(!token1) { ctx.reportError("Value for mandatory parameter %s missing from section " "[%s] starting at line: %d", buf, ctx.fname, ctx.m_sectionLineno); return false; } if (token2 == NULL) { // Only a number given errno = 0; char* p; id = strtol(token1, &p, 10); if (errno != 0 || id <= 0x0 || id > MAX_NODES) { ctx.reportError("Illegal value for mandatory parameter %s from section " "[%s] starting at line: %d", buf, ctx.fname, ctx.m_sectionLineno); return false; } require(ctx.m_currentSection->put(buf, id, true)); } else { // A pair given (e.g. "uppsala.32") errno = 0; char* p; id = strtol(token2, &p, 10); if (errno != 0 || id <= 0x0 || id > MAX_NODES) { ctx.reportError("Illegal value for mandatory parameter %s from section " "[%s] starting at line: %d", buf, ctx.fname, ctx.m_sectionLineno); return false; } require(ctx.m_currentSection->put(buf, id, true)); require(ctx.m_currentSection->put(sysbuf, token1)); } return true; } /** * Connection rule: Fix hostname * * Unless Hostname is not already specified, do steps: * -# Via Connection's NodeId lookup Node * -# Via Node's ExecuteOnComputer lookup Hostname * -# Add HostName to Connection */ static bool fixHostname(InitConfigFileParser::Context & ctx, const char * data){ char buf[] = "NodeIdX"; buf[6] = data[sizeof("HostNam")]; char sysbuf[] = "SystemX"; sysbuf[6] = data[sizeof("HostNam")]; if(!ctx.m_currentSection->contains(data)){ Uint32 id = 0; require(ctx.m_currentSection->get(buf, &id)); const Properties * node; if(!ctx.m_config->get("Node", id, &node)) { ctx.reportError("Unknown node: \"%d\" specified in connection " "[%s] starting at line: %d", id, ctx.fname, ctx.m_sectionLineno); return false; } const char * hostname; require(node->get("HostName", &hostname)); require(ctx.m_currentSection->put(data, hostname)); } return true; } /** * Connection rule: Fix port number (using a port number adder) */ static bool fixPortNumber(InitConfigFileParser::Context & ctx, const char * data){ DBUG_ENTER("fixPortNumber"); Uint32 id1, id2; const char *hostName1; const char *hostName2; require(ctx.m_currentSection->get("NodeId1", &id1)); require(ctx.m_currentSection->get("NodeId2", &id2)); require(ctx.m_currentSection->get("HostName1", &hostName1)); require(ctx.m_currentSection->get("HostName2", &hostName2)); DBUG_PRINT("info",("NodeId1=%d HostName1=\"%s\"",id1,hostName1)); DBUG_PRINT("info",("NodeId2=%d HostName2=\"%s\"",id2,hostName2)); const Properties *node1, *node2; require(ctx.m_config->get("Node", id1, &node1)); require(ctx.m_config->get("Node", id2, &node2)); const char *type1, *type2; require(node1->get("Type", &type1)); require(node2->get("Type", &type2)); /* add NodeIdServer info */ { Uint32 nodeIdServer = id1 < id2 ? id1 : id2; if(strcmp(type1, API_TOKEN) == 0 || strcmp(type2, MGM_TOKEN) == 0) nodeIdServer = id2; else if(strcmp(type2, API_TOKEN) == 0 || strcmp(type1, MGM_TOKEN) == 0) nodeIdServer = id1; ctx.m_currentSection->put("NodeIdServer", nodeIdServer); if (id2 == nodeIdServer) { { const char *tmp= hostName1; hostName1= hostName2; hostName2= tmp; } { Uint32 tmp= id1; id1= id2; id2= tmp; } { const Properties *tmp= node1; node1= node2; node2= tmp; } { const char *tmp= type1; type1= type2; type2= tmp; } } } BaseString hostname(hostName1); if (hostname.c_str()[0] == 0) { ctx.reportError("Hostname required on nodeid %d since it will " "act as server.", id1); DBUG_RETURN(false); } Uint32 port= 0; if(strcmp(type1, MGM_TOKEN)==0) node1->get("PortNumber",&port); else if(strcmp(type2, MGM_TOKEN)==0) node2->get("PortNumber",&port); if (!port && !node1->get("ServerPort", &port) && !ctx.m_userProperties.get("ServerPort_", id1, &port)) { Uint32 base= 0; /* * If the connection doesn't involve an mgm server, * and a default port number has been set, behave the old * way of allocating port numbers for transporters. */ if(ctx.m_userDefaults && ctx.m_userDefaults->get("PortNumber", &base)) { Uint32 adder= 0; { BaseString server_port_adder(hostname); server_port_adder.append("_ServerPortAdder"); ctx.m_userProperties.get(server_port_adder.c_str(), &adder); ctx.m_userProperties.put(server_port_adder.c_str(), adder+1, true); } if (!ctx.m_userProperties.get("ServerPortBase", &base)){ if(!(ctx.m_userDefaults && ctx.m_userDefaults->get("PortNumber", &base)) && !ctx.m_systemDefaults->get("PortNumber", &base)) { base= strtoll(NDB_TCP_BASE_PORT,0,0); } ctx.m_userProperties.put("ServerPortBase", base); } port= base + adder; ctx.m_userProperties.put("ServerPort_", id1, port); } } if(ctx.m_currentSection->contains("PortNumber")) { ndbout << "PortNumber should no longer be specificied " << "per connection, please remove from config. " << "Will be changed to " << port << endl; ctx.m_currentSection->put("PortNumber", port, true); } else { ctx.m_currentSection->put("PortNumber", port); } DBUG_PRINT("info", ("connection %d-%d port %d host %s", id1, id2, port, hostname.c_str())); DBUG_RETURN(true); } static bool fixShmUniqueId(InitConfigFileParser::Context & ctx, const char * data) { DBUG_ENTER("fixShmUniqueId"); Uint32 nodes= 0; ctx.m_userProperties.get(ctx.fname, &nodes); if (nodes == 1) // first management server { Uint32 portno= atoi(NDB_PORT); ctx.m_currentSection->get("PortNumber", &portno); ctx.m_userProperties.put("ShmUniqueId", portno); } DBUG_RETURN(true); } static bool fixShmKey(InitConfigFileParser::Context & ctx, const char *) { DBUG_ENTER("fixShmKey"); { static int last_signum= -1; Uint32 signum; if(!ctx.m_currentSection->get("Signum", &signum)) { signum= OPT_NDB_SHM_SIGNUM_DEFAULT; if (signum <= 0) { ctx.reportError("Unable to set default parameter for [SHM]Signum" " please specify [SHM DEFAULT]Signum"); return false; } ctx.m_currentSection->put("Signum", signum); DBUG_PRINT("info",("Added Signum=%u", signum)); } if ( last_signum != (int)signum && last_signum >= 0 ) { ctx.reportError("All shared memory transporters must have same [SHM]Signum defined." " Use [SHM DEFAULT]Signum"); return false; } last_signum= (int)signum; } { Uint32 id1= 0, id2= 0, key= 0; require(ctx.m_currentSection->get("NodeId1", &id1)); require(ctx.m_currentSection->get("NodeId2", &id2)); if(!ctx.m_currentSection->get("ShmKey", &key)) { require(ctx.m_userProperties.get("ShmUniqueId", &key)); key= key << 16 | (id1 > id2 ? id1 << 8 | id2 : id2 << 8 | id1); ctx.m_currentSection->put("ShmKey", key); DBUG_PRINT("info",("Added ShmKey=0x%x", key)); } } DBUG_RETURN(true); } /** * DB Node rule: Check various constraints */ static bool checkDbConstraints(InitConfigFileParser::Context & ctx, const char *){ Uint32 t1 = 0, t2 = 0; ctx.m_currentSection->get("MaxNoOfConcurrentOperations", &t1); ctx.m_currentSection->get("MaxNoOfConcurrentTransactions", &t2); if (t1 < t2) { ctx.reportError("MaxNoOfConcurrentOperations must be greater than " "MaxNoOfConcurrentTransactions - [%s] starting at line: %d", ctx.fname, ctx.m_sectionLineno); return false; } Uint32 replicas = 0, otherReplicas; ctx.m_currentSection->get("NoOfReplicas", &replicas); if(ctx.m_userProperties.get("NoOfReplicas", &otherReplicas)){ if(replicas != otherReplicas){ ctx.reportError("NoOfReplicas defined differently on different nodes" " - [%s] starting at line: %d", ctx.fname, ctx.m_sectionLineno); return false; } } else { ctx.m_userProperties.put("NoOfReplicas", replicas); } /** * In kernel, will calculate the MaxNoOfMeataTables use the following sum: * Uint32 noOfMetaTables = noOfTables + noOfOrderedIndexes + * noOfUniqueHashIndexes + 2 * 2 is the number of the SysTables. * So must check that the sum does't exceed the max value of Uint32. */ Uint32 noOfTables = 0, noOfOrderedIndexes = 0, noOfUniqueHashIndexes = 0; ctx.m_currentSection->get("MaxNoOfTables", &noOfTables); ctx.m_currentSection->get("MaxNoOfOrderedIndexes", &noOfOrderedIndexes); ctx.m_currentSection->get("MaxNoOfUniqueHashIndexes", &noOfUniqueHashIndexes); Uint64 sum= (Uint64)noOfTables + noOfOrderedIndexes + noOfUniqueHashIndexes; if (sum > ((Uint32)~0 - 2)) { ctx.reportError("The sum of MaxNoOfTables, MaxNoOfOrderedIndexes and" " MaxNoOfUniqueHashIndexes must not exceed %u - [%s]" " starting at line: %d", ((Uint32)~0 - 2), ctx.fname, ctx.m_sectionLineno); return false; } return true; } /** * Connection rule: Check varius constraints */ static bool checkConnectionConstraints(InitConfigFileParser::Context & ctx, const char *){ Uint32 id1 = 0, id2 = 0; ctx.m_currentSection->get("NodeId1", &id1); ctx.m_currentSection->get("NodeId2", &id2); if(id1 == id2){ ctx.reportError("Illegal connection from node to itself" " - [%s] starting at line: %d", ctx.fname, ctx.m_sectionLineno); return false; } const Properties * node1; if(!ctx.m_config->get("Node", id1, &node1)){ ctx.reportError("Connection refering to undefined node: %d" " - [%s] starting at line: %d", id1, ctx.fname, ctx.m_sectionLineno); return false; } const Properties * node2; if(!ctx.m_config->get("Node", id2, &node2)){ ctx.reportError("Connection refering to undefined node: %d" " - [%s] starting at line: %d", id2, ctx.fname, ctx.m_sectionLineno); return false; } const char * type1; const char * type2; require(node1->get("Type", &type1)); require(node2->get("Type", &type2)); /** * Report error if the following are true * -# None of the nodes is of type DB * -# Not both of them are MGMs */ if((strcmp(type1, DB_TOKEN) != 0 && strcmp(type2, DB_TOKEN) != 0) && !(strcmp(type1, MGM_TOKEN) == 0 && strcmp(type2, MGM_TOKEN) == 0)) { ctx.reportError("Invalid connection between node %d (%s) and node %d (%s)" " - [%s] starting at line: %d", id1, type1, id2, type2, ctx.fname, ctx.m_sectionLineno); return false; } return true; } static bool checkTCPConstraints(InitConfigFileParser::Context & ctx, const char * data){ const char * host; struct in_addr addr; if(ctx.m_currentSection->get(data, &host) && strlen(host) && Ndb_getInAddr(&addr, host)){ ctx.reportError("Unable to lookup/illegal hostname %s" " - [%s] starting at line: %d", host, ctx.fname, ctx.m_sectionLineno); return false; } return true; } static bool transform(InitConfigFileParser::Context & ctx, Properties & dst, const char * oldName, const char * newName, double add, double mul){ if(ctx.m_currentSection->contains(newName)){ ctx.reportError("Both %s and %s specified" " - [%s] starting at line: %d", oldName, newName, ctx.fname, ctx.m_sectionLineno); return false; } PropertiesType oldType; require(ctx.m_currentSection->getTypeOf(oldName, &oldType)); ConfigInfo::Type newType = ctx.m_info->getType(ctx.m_currentInfo, newName); if(!((oldType == PropertiesType_Uint32 || oldType == PropertiesType_Uint64) && (newType == ConfigInfo::CI_INT || newType == ConfigInfo::CI_INT64 || newType == ConfigInfo::CI_BOOL))){ ndbout << "oldType: " << (int)oldType << ", newType: " << (int)newType << endl; ctx.reportError("Unable to handle type conversion w.r.t deprication %s %s" "- [%s] starting at line: %d", oldName, newName, ctx.fname, ctx.m_sectionLineno); return false; } Uint64 oldVal; require(ctx.m_currentSection->get(oldName, &oldVal)); Uint64 newVal = (Uint64)((Int64)oldVal * mul + add); if(!ctx.m_info->verify(ctx.m_currentInfo, newName, newVal)){ ctx.reportError("Unable to handle deprication, new value not within bounds" "%s %s - [%s] starting at line: %d", oldName, newName, ctx.fname, ctx.m_sectionLineno); return false; } if(newType == ConfigInfo::CI_INT || newType == ConfigInfo::CI_BOOL){ require(dst.put(newName, (Uint32)newVal)); } else if(newType == ConfigInfo::CI_INT64) { require(dst.put64(newName, newVal)); } return true; } static bool fixDepricated(InitConfigFileParser::Context & ctx, const char * data){ const char * name; /** * Transform old values to new values * Transform new values to old values (backward compatible) */ Properties tmp(true); Properties::Iterator it(ctx.m_currentSection); for (name = it.first(); name != NULL; name = it.next()) { const DepricationTransform * p = &f_deprication[0]; while(p->m_section != 0){ if(strcmp(p->m_section, ctx.fname) == 0){ double mul = p->m_mul; double add = p->m_add; if(strcasecmp(name, p->m_oldName) == 0){ if(!transform(ctx, tmp, name, p->m_newName, add, mul)){ return false; } } else if(strcasecmp(name, p->m_newName) == 0) { if(!transform(ctx, tmp, name, p->m_oldName, -add/mul,1.0/mul)){ return false; } } } p++; } } Properties::Iterator it2(&tmp); for (name = it2.first(); name != NULL; name = it2.next()) { PropertiesType type; require(tmp.getTypeOf(name, &type)); switch(type){ case PropertiesType_Uint32:{ Uint32 val; require(tmp.get(name, &val)); ::require(ctx.m_currentSection->put(name, val)); break; } case PropertiesType_char:{ const char * val; require(tmp.get(name, &val)); ::require(ctx.m_currentSection->put(name, val)); break; } case PropertiesType_Uint64:{ Uint64 val; require(tmp.get(name, &val)); ::require(ctx.m_currentSection->put64(name, val)); break; } case PropertiesType_Properties: default: ::require(false); } } return true; } extern int g_print_full_config; static bool saveInConfigValues(InitConfigFileParser::Context & ctx, const char * data){ const Properties * sec; if(!ctx.m_currentInfo->get(ctx.fname, &sec)){ require(false); return false; } do { const char *secName; Uint32 id, status, typeVal; require(sec->get("Fname", &secName)); require(sec->get("Id", &id)); require(sec->get("Status", &status)); require(sec->get("SectionType", &typeVal)); if(id == KEY_INTERNAL || status == ConfigInfo::CI_INTERNAL){ ndbout_c("skipping section %s", ctx.fname); break; } if (g_print_full_config) { const char *alias= ConfigInfo::nameToAlias(ctx.fname); printf("[%s]\n", alias ? alias : ctx.fname); } Uint32 no = 0; ctx.m_userProperties.get("$Section", id, &no); ctx.m_userProperties.put("$Section", id, no+1, true); ctx.m_configValues.openSection(id, no); ctx.m_configValues.put(CFG_TYPE_OF_SECTION, typeVal); Properties::Iterator it(ctx.m_currentSection); for (const char* n = it.first(); n != NULL; n = it.next()) { const Properties * info; if(!ctx.m_currentInfo->get(n, &info)) continue; id = 0; info->get("Id", &id); if(id == KEY_INTERNAL) continue; bool ok = true; PropertiesType type; require(ctx.m_currentSection->getTypeOf(n, &type)); switch(type){ case PropertiesType_Uint32:{ Uint32 val; require(ctx.m_currentSection->get(n, &val)); ok = ctx.m_configValues.put(id, val); if (g_print_full_config) printf("%s=%u\n", n, val); break; } case PropertiesType_Uint64:{ Uint64 val; require(ctx.m_currentSection->get(n, &val)); ok = ctx.m_configValues.put64(id, val); if (g_print_full_config) printf("%s=%llu\n", n, val); break; } case PropertiesType_char:{ const char * val; require(ctx.m_currentSection->get(n, &val)); ok = ctx.m_configValues.put(id, val); if (g_print_full_config) printf("%s=%s\n", n, val); break; } default: require(false); } require(ok); } ctx.m_configValues.closeSection(); } while(0); return true; } static bool sanity_checks(Vector<ConfigInfo::ConfigRuleSection>&sections, struct InitConfigFileParser::Context &ctx, const char * rule_data) { Uint32 db_nodes = 0; Uint32 mgm_nodes = 0; Uint32 api_nodes = 0; if (!ctx.m_userProperties.get("DB", &db_nodes)) { ctx.reportError("At least one database node (ndbd) should be defined in config file"); return false; } if (!ctx.m_userProperties.get("MGM", &mgm_nodes)) { ctx.reportError("At least one management server node (ndb_mgmd) should be defined in config file"); return false; } if (!ctx.m_userProperties.get("API", &api_nodes)) { ctx.reportError("At least one application node (for the mysqld) should be defined in config file"); return false; } return true; } static void add_a_connection(Vector<ConfigInfo::ConfigRuleSection>&sections, struct InitConfigFileParser::Context &ctx, Uint32 nodeId1, Uint32 nodeId2, bool use_shm) { ConfigInfo::ConfigRuleSection s; const char *hostname1= 0, *hostname2= 0; const Properties *tmp; require(ctx.m_config->get("Node", nodeId1, &tmp)); tmp->get("HostName", &hostname1); require(ctx.m_config->get("Node", nodeId2, &tmp)); tmp->get("HostName", &hostname2); char buf[16]; s.m_sectionData= new Properties(true); BaseString::snprintf(buf, sizeof(buf), "%u", nodeId1); s.m_sectionData->put("NodeId1", buf); BaseString::snprintf(buf, sizeof(buf), "%u", nodeId2); s.m_sectionData->put("NodeId2", buf); if (use_shm && hostname1 && hostname1[0] && hostname2 && hostname2[0] && strcmp(hostname1,hostname2) == 0) { s.m_sectionType= BaseString("SHM"); DBUG_PRINT("info",("adding SHM connection %d %d",nodeId1,nodeId2)); } else { s.m_sectionType= BaseString("TCP"); DBUG_PRINT("info",("adding TCP connection %d %d",nodeId1,nodeId2)); } sections.push_back(s); } static bool add_node_connections(Vector<ConfigInfo::ConfigRuleSection>&sections, struct InitConfigFileParser::Context &ctx, const char * rule_data) { DBUG_ENTER("add_node_connections"); Uint32 i; Properties * props= ctx.m_config; Properties p_connections(true); Properties p_connections2(true); for (i = 0;; i++){ const Properties * tmp; Uint32 nodeId1, nodeId2; if(!props->get("Connection", i, &tmp)) break; if(!tmp->get("NodeId1", &nodeId1)) continue; p_connections.put("", nodeId1, nodeId1); if(!tmp->get("NodeId2", &nodeId2)) continue; p_connections.put("", nodeId2, nodeId2); p_connections2.put("", nodeId1 + nodeId2<<16, nodeId1); p_connections2.put("", nodeId2 + nodeId1<<16, nodeId2); } Uint32 nNodes; ctx.m_userProperties.get("NoOfNodes", &nNodes); Properties p_db_nodes(true); Properties p_api_nodes(true); Properties p_mgm_nodes(true); Uint32 i_db= 0, i_api= 0, i_mgm= 0, n; for (i= 0, n= 0; n < nNodes; i++){ const Properties * tmp; if(!props->get("Node", i, &tmp)) continue; n++; const char * type; if(!tmp->get("Type", &type)) continue; if (strcmp(type,DB_TOKEN) == 0) p_db_nodes.put("", i_db++, i); else if (strcmp(type,API_TOKEN) == 0) p_api_nodes.put("", i_api++, i); else if (strcmp(type,MGM_TOKEN) == 0) p_mgm_nodes.put("", i_mgm++, i); } Uint32 nodeId1, nodeId2, dummy; for (i= 0; p_db_nodes.get("", i, &nodeId1); i++){ for (Uint32 j= i+1;; j++){ if(!p_db_nodes.get("", j, &nodeId2)) break; if(!p_connections2.get("", nodeId1+nodeId2<<16, &dummy)) { add_a_connection(sections,ctx,nodeId1,nodeId2,opt_ndb_shm); } } } for (i= 0; p_api_nodes.get("", i, &nodeId1); i++){ if(!p_connections.get("", nodeId1, &dummy)) { for (Uint32 j= 0;; j++){ if(!p_db_nodes.get("", j, &nodeId2)) break; add_a_connection(sections,ctx,nodeId1,nodeId2,opt_ndb_shm); } } } for (i= 0; p_mgm_nodes.get("", i, &nodeId1); i++){ if(!p_connections.get("", nodeId1, &dummy)) { for (Uint32 j= 0;; j++){ if(!p_db_nodes.get("", j, &nodeId2)) break; add_a_connection(sections,ctx,nodeId1,nodeId2,0); } } } DBUG_RETURN(true); } static bool set_connection_priorities(Vector<ConfigInfo::ConfigRuleSection>&sections, struct InitConfigFileParser::Context &ctx, const char * rule_data) { DBUG_ENTER("set_connection_priorities"); DBUG_RETURN(true); } static bool check_node_vs_replicas(Vector<ConfigInfo::ConfigRuleSection>&sections, struct InitConfigFileParser::Context &ctx, const char * rule_data) { Uint32 db_nodes= 0; Uint32 replicas= 0; Uint32 db_host_count= 0; bool with_arbitration_rank= false; ctx.m_userProperties.get(DB_TOKEN, &db_nodes); ctx.m_userProperties.get("NoOfReplicas", &replicas); if((db_nodes % replicas) != 0){ ctx.reportError("Invalid no of db nodes wrt no of replicas.\n" "No of nodes must be dividable with no or replicas"); return false; } // check that node groups and arbitrators are ok // just issue warning if not if(replicas > 1){ Properties * props= ctx.m_config; Properties p_db_hosts(true); // store hosts which db nodes run on Properties p_arbitrators(true); // store hosts which arbitrators run on // arbitrator should not run together with db node on same host Uint32 i, n, group= 0, i_group= 0; Uint32 n_nodes; BaseString node_group_warning, arbitration_warning; const char *arbit_warn_fmt= "\n arbitrator with id %d and db node with id %d on same host %s"; const char *arbit_warn_fmt2= "\n arbitrator with id %d has no hostname specified"; ctx.m_userProperties.get("NoOfNodes", &n_nodes); for (i= 0, n= 0; n < n_nodes; i++){ const Properties * tmp; if(!props->get("Node", i, &tmp)) continue; n++; const char * type; if(!tmp->get("Type", &type)) continue; const char* host= 0; tmp->get("HostName", &host); if (strcmp(type,DB_TOKEN) == 0) { { Uint32 ii; if (!p_db_hosts.get(host,&ii)) db_host_count++; p_db_hosts.put(host,i); if (p_arbitrators.get(host,&ii)) { arbitration_warning.appfmt(arbit_warn_fmt, ii, i, host); p_arbitrators.remove(host); // only one warning per db node } } { unsigned j; BaseString str, str2; str.assfmt("#group%d_",group); p_db_hosts.put(str.c_str(),i_group,host); str2.assfmt("##group%d_",group); p_db_hosts.put(str2.c_str(),i_group,i); for (j= 0; j < i_group; j++) { const char *other_host; p_db_hosts.get(str.c_str(),j,&other_host); if (strcmp(host,other_host) == 0) { unsigned int other_i, c= 0; p_db_hosts.get(str2.c_str(),j,&other_i); p_db_hosts.get(str.c_str(),&c); if (c == 0) // first warning in this node group node_group_warning.appfmt(" Node group %d", group); c|= 1 << j; p_db_hosts.put(str.c_str(),c); node_group_warning.appfmt(",\n db node with id %d and id %d " "on same host %s", other_i, i, host); } } i_group++; DBUG_ASSERT(i_group <= replicas); if (i_group == replicas) { unsigned c= 0; p_db_hosts.get(str.c_str(),&c); if (c+1 == (1u << (replicas-1))) // all nodes on same machine node_group_warning.append(".\n Host failure will " "cause complete cluster shutdown."); else if (c > 0) node_group_warning.append(".\n Host failure may " "cause complete cluster shutdown."); group++; i_group= 0; } } } else if (strcmp(type,API_TOKEN) == 0 || strcmp(type,MGM_TOKEN) == 0) { Uint32 rank; if(tmp->get("ArbitrationRank", &rank) && rank > 0) { with_arbitration_rank = true; //check whether MGM or API node configured with rank >0 if(host && host[0] != 0) { Uint32 ii; p_arbitrators.put(host,i); if (p_db_hosts.get(host,&ii)) { arbitration_warning.appfmt(arbit_warn_fmt, i, ii, host); } } else { arbitration_warning.appfmt(arbit_warn_fmt2, i); } } } } if (db_host_count > 1 && node_group_warning.length() > 0) ctx.reportWarning("Cluster configuration warning:\n%s",node_group_warning.c_str()); if (!with_arbitration_rank) { ctx.reportWarning("Cluster configuration warning:" "\n Neither %s nor %s nodes are configured with arbitrator," "\n may cause complete cluster shutdown in case of host failure.", MGM_TOKEN, API_TOKEN); } if (db_host_count > 1 && arbitration_warning.length() > 0) ctx.reportWarning("Cluster configuration warning:%s%s",arbitration_warning.c_str(), "\n Running arbitrator on the same host as a database node may" "\n cause complete cluster shutdown in case of host failure."); } return true; } template class Vector<ConfigInfo::ConfigRuleSection>; #endif /* NDB_MGMAPI */
24.912987
121
0.614997
[ "object", "vector", "transform" ]
6e5616fcdbb18da4358e347973968657e527bbe1
8,064
cpp
C++
cachelib/allocator/tests/MemoryTiersTest.cpp
victoria-mcgrath/CacheLib
e206608e818012a150470fc85a626de282dc1b03
[ "Apache-2.0" ]
null
null
null
cachelib/allocator/tests/MemoryTiersTest.cpp
victoria-mcgrath/CacheLib
e206608e818012a150470fc85a626de282dc1b03
[ "Apache-2.0" ]
null
null
null
cachelib/allocator/tests/MemoryTiersTest.cpp
victoria-mcgrath/CacheLib
e206608e818012a150470fc85a626de282dc1b03
[ "Apache-2.0" ]
null
null
null
/* * Copyright (c) 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. */ #include <numeric> #include "cachelib/allocator/CacheAllocator.h" #include "cachelib/allocator/tests/TestBase.h" namespace facebook { namespace cachelib { namespace tests { using LruAllocatorConfig = CacheAllocatorConfig<LruAllocator>; using LruMemoryTierConfigs = LruAllocatorConfig::MemoryTierConfigs; using Strings = std::vector<std::string>; using SizePair = std::tuple<size_t, size_t>; using SizePairs = std::vector<SizePair>; const size_t defaultTotalCacheSize{1 * 1024 * 1024 * 1024}; const std::string defaultCacheDir{"/var/metadataDir"}; const std::string defaultPmemPath{"/dev/shm/p1"}; const std::string defaultDaxPath{"/dev/dax0.0"}; template <typename Allocator> class MemoryTiersTest: public AllocatorTest<Allocator> { public: void basicCheck( LruAllocatorConfig& actualConfig, const Strings& expectedPaths = {defaultPmemPath}, size_t expectedTotalCacheSize = defaultTotalCacheSize, const std::string& expectedCacheDir = defaultCacheDir) { EXPECT_EQ(actualConfig.getCacheSize(), expectedTotalCacheSize); EXPECT_EQ(actualConfig.getMemoryTierConfigs().size(), expectedPaths.size()); EXPECT_EQ(actualConfig.getCacheDir(), expectedCacheDir); auto configs = actualConfig.getMemoryTierConfigs(); size_t sum_sizes = std::accumulate(configs.begin(), configs.end(), 0, [](const size_t i, const MemoryTierCacheConfig& config) { return i + config.getSize();}); size_t sum_ratios = std::accumulate(configs.begin(), configs.end(), 0, [](const size_t i, const MemoryTierCacheConfig& config) { return i + config.getRatio();}); EXPECT_EQ(sum_sizes, expectedTotalCacheSize); size_t partition_size = 0, remaining_capacity = actualConfig.getCacheSize(); if (sum_ratios) { partition_size = actualConfig.getCacheSize() / sum_ratios; } for(auto i = 0; i < configs.size(); ++i) { auto &opt = std::get<FileShmSegmentOpts>(configs[i].getShmTypeOpts()); EXPECT_EQ(opt.path, expectedPaths[i]); EXPECT_GT(configs[i].getSize(), 0); if (configs[i].getRatio() && (i < configs.size() - 1)) { EXPECT_EQ(configs[i].getSize(), partition_size * configs[i].getRatio()); } remaining_capacity -= configs[i].getSize(); } EXPECT_EQ(remaining_capacity, 0); } LruAllocatorConfig createTestCacheConfig( const Strings& tierPaths = {defaultPmemPath}, const SizePairs& sizePairs = {std::make_tuple(1 /* ratio */, 0 /* size */)}, bool setPosixForShm = true, size_t cacheSize = defaultTotalCacheSize, const std::string& cacheDir = defaultCacheDir) { LruAllocatorConfig cfg; cfg.setCacheSize(cacheSize) .enableCachePersistence(cacheDir); if (setPosixForShm) cfg.usePosixForShm(); LruMemoryTierConfigs tierConfigs; tierConfigs.reserve(tierPaths.size()); for(auto i = 0; i < tierPaths.size(); ++i) { tierConfigs.push_back(MemoryTierCacheConfig::fromFile(tierPaths[i]) .setRatio(std::get<0>(sizePairs[i])) .setSize(std::get<1>(sizePairs[i]))); } cfg.configureMemoryTiers(tierConfigs); return cfg; } }; using LruMemoryTiersTest = MemoryTiersTest<LruAllocator>; TEST_F(LruMemoryTiersTest, TestValid1TierPmemRatioConfig) { LruAllocatorConfig cfg = createTestCacheConfig({defaultPmemPath}); basicCheck(cfg); } TEST_F(LruMemoryTiersTest, TestValid1TierDaxRatioConfig) { LruAllocatorConfig cfg = createTestCacheConfig({defaultDaxPath}); basicCheck(cfg, {defaultDaxPath}); } TEST_F(LruMemoryTiersTest, TestValid1TierDaxSizeConfig) { LruAllocatorConfig cfg = createTestCacheConfig({defaultDaxPath}, {std::make_tuple(0, defaultTotalCacheSize)}, /* setPosixShm */ true, /* cacheSize */ 0); basicCheck(cfg, {defaultDaxPath}); // Setting size after conifguringMemoryTiers with sizes is not allowed. EXPECT_THROW(cfg.setCacheSize(defaultTotalCacheSize + 1), std::invalid_argument); } TEST_F(LruMemoryTiersTest, TestValid2TierDaxPmemConfig) { LruAllocatorConfig cfg = createTestCacheConfig({defaultDaxPath, defaultPmemPath}, {std::make_tuple(1, 0), std::make_tuple(1, 0)}); basicCheck(cfg, {defaultDaxPath, defaultPmemPath}); } TEST_F(LruMemoryTiersTest, TestValid2TierDaxPmemRatioConfig) { LruAllocatorConfig cfg = createTestCacheConfig({defaultDaxPath, defaultPmemPath}, {std::make_tuple(5, 0), std::make_tuple(2, 0)}); basicCheck(cfg, {defaultDaxPath, defaultPmemPath}); } TEST_F(LruMemoryTiersTest, TestValid2TierDaxPmemSizeConfig) { size_t size_1 = 4321, size_2 = 1234; LruAllocatorConfig cfg = createTestCacheConfig({defaultDaxPath, defaultPmemPath}, {std::make_tuple(0, size_1), std::make_tuple(0, size_2)}, true, 0); basicCheck(cfg, {defaultDaxPath, defaultPmemPath}, size_1 + size_2); // Setting size after conifguringMemoryTiers with sizes is not allowed. EXPECT_THROW(cfg.setCacheSize(size_1 + size_2 + 1), std::invalid_argument); } TEST_F(LruMemoryTiersTest, TestInvalid2TierConfigPosixShmNotSet) { LruAllocatorConfig cfg = createTestCacheConfig({defaultDaxPath, defaultPmemPath}, {std::make_tuple(1, 0), std::make_tuple(1, 0)}, /* setPosixShm */ false); } TEST_F(LruMemoryTiersTest, TestInvalid2TierConfigNumberOfPartitionsTooLarge) { EXPECT_THROW(createTestCacheConfig({defaultDaxPath, defaultPmemPath}, {std::make_tuple(defaultTotalCacheSize, 0), std::make_tuple(1, 0)}).validate(), std::invalid_argument); } TEST_F(LruMemoryTiersTest, TestInvalid2TierConfigSizesAndRatiosMixed) { EXPECT_THROW(createTestCacheConfig({defaultDaxPath, defaultPmemPath}, {std::make_tuple(1, 0), std::make_tuple(1, 1)}), std::invalid_argument); EXPECT_THROW(createTestCacheConfig({defaultDaxPath, defaultPmemPath}, {std::make_tuple(1, 1), std::make_tuple(0, 1)}), std::invalid_argument); } TEST_F(LruMemoryTiersTest, TestInvalid2TierConfigSizesAndRatioNotSet) { EXPECT_THROW(createTestCacheConfig({defaultDaxPath, defaultPmemPath}, {std::make_tuple(1, 0), std::make_tuple(0, 0)}), std::invalid_argument); } TEST_F(LruMemoryTiersTest, TestInvalid2TierConfigRatiosCacheSizeNotSet) { EXPECT_THROW(createTestCacheConfig({defaultDaxPath, defaultPmemPath}, {std::make_tuple(1, 0), std::make_tuple(1, 0)}, /* setPosixShm */ true, /* cacheSize */ 0).validate(), std::invalid_argument); } TEST_F(LruMemoryTiersTest, TestInvalid2TierConfigSizesNeCacheSize) { EXPECT_THROW(createTestCacheConfig({defaultDaxPath, defaultPmemPath}, {std::make_tuple(0, 1), std::make_tuple(0, 1)}), std::invalid_argument); } } // namespace tests } // namespace cachelib } // namespace facebook
42.893617
116
0.660094
[ "vector" ]
6e5c8056d7d87e30cbfd656626fae84d5d3582e2
2,284
cpp
C++
Enforcer.cpp
cps-sei/cps-synth-resolultion
3834bcd566d5fc4ce3f2c107d5ee3b7d06caf31f
[ "MIT" ]
1
2020-10-01T13:56:35.000Z
2020-10-01T13:56:35.000Z
Enforcer.cpp
cps-sei/cps-synth-resolultion
3834bcd566d5fc4ce3f2c107d5ee3b7d06caf31f
[ "MIT" ]
null
null
null
Enforcer.cpp
cps-sei/cps-synth-resolultion
3834bcd566d5fc4ce3f2c107d5ee3b7d06caf31f
[ "MIT" ]
1
2021-06-03T00:09:30.000Z
2021-06-03T00:09:30.000Z
/* * Synthesis-based resolution of features/enforcers interactions in CPS * Copyright 2020 Carnegie Mellon University. * NO WARRANTY. THIS CARNEGIE MELLON UNIVERSITY AND SOFTWARE ENGINEERING * INSTITUTE MATERIAL IS FURNISHED ON AN "AS-IS" BASIS. CARNEGIE MELLON * UNIVERSITY MAKES NO WARRANTIES OF ANY KIND, EITHER EXPRESSED OR IMPLIED, * AS TO ANY MATTER INCLUDING, BUT NOT LIMITED TO, WARRANTY OF FITNESS FOR * PURPOSE OR MERCHANTABILITY, EXCLUSIVITY, OR RESULTS OBTAINED FROM USE OF * THE MATERIAL. CARNEGIE MELLON UNIVERSITY DOES NOT MAKE ANY WARRANTY OF ANY * KIND WITH RESPECT TO FREEDOM FROM PATENT, TRADEMARK, OR COPYRIGHT * INFRINGEMENT. * Released under a BSD (SEI)-style license, please see license.txt or contact * permission@sei.cmu.edu for full terms. * [DISTRIBUTION STATEMENT A] This material has been approved for public * release and unlimited distribution. Please see Copyright notice for * non-US Government use and distribution. * This Software includes and/or makes use of the following Third-Party Software * subject to its own license: * 1. JsonCpp * (https://github.com/open-source-parsers/jsoncpp/blob/master/LICENSE) * Copyright 2010 Baptiste Lepilleur and The JsonCpp Authors. * DM20-0762 */ #include "Enforcer.h" #include "DroneUtil.h" #include <cmath> #include <dronecode_sdk/dronecode_sdk.h> #include <chrono> #include <set> using namespace dronecode_sdk; using std::chrono::steady_clock; namespace cdra { Enforcer::Enforcer(std::shared_ptr<dronecode_sdk::Offboard> offboard, std::shared_ptr<dronecode_sdk::Telemetry> telemetry, std::shared_ptr<StateStore> store) : offboard(offboard), telemetry(telemetry), store(store), enforcerName("Null Enforcer") { } Enforcer::~Enforcer() { // TODO Auto-generated destructor stub } const char* Enforcer::getName() const { return enforcerName.c_str(); } void Enforcer::send(const dronecode_sdk::Offboard::VelocityNEDYaw& velocity_ned_yaw) { offboard->send_velocity_ned(velocity_ned_yaw); } std::vector<dronecode_sdk::Offboard::VelocityNEDYaw> Enforcer::enforce( const dronecode_sdk::Offboard::VelocityNEDYaw &velocity_ned_yaw) { std::vector<dronecode_sdk::Offboard::VelocityNEDYaw> newNEDs; newNEDs.push_back(velocity_ned_yaw); return newNEDs; } } /* namespace cdra */
35.6875
88
0.774081
[ "vector" ]
6e6314565726b7e22a795185a60b8afb89df5228
21,393
cpp
C++
Source/WebCore/platform/network/qt/QNetworkReplyHandler.cpp
VincentWei/mdolphin-core
48ffdcf587a48a7bb4345ae469a45c5b64ffad0e
[ "Apache-2.0" ]
6
2017-05-31T01:46:45.000Z
2018-06-12T10:53:30.000Z
Source/WebCore/platform/network/qt/QNetworkReplyHandler.cpp
FMSoftCN/mdolphin-core
48ffdcf587a48a7bb4345ae469a45c5b64ffad0e
[ "Apache-2.0" ]
null
null
null
Source/WebCore/platform/network/qt/QNetworkReplyHandler.cpp
FMSoftCN/mdolphin-core
48ffdcf587a48a7bb4345ae469a45c5b64ffad0e
[ "Apache-2.0" ]
2
2017-07-17T06:02:42.000Z
2018-09-19T10:08:38.000Z
/* Copyright (C) 2008 Nokia Corporation and/or its subsidiary(-ies) Copyright (C) 2007 Staikos Computing Services Inc. <info@staikos.net> Copyright (C) 2008 Holger Hans Peter Freyther This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 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 Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "config.h" #include "QNetworkReplyHandler.h" #include "HTTPParsers.h" #include "MIMETypeRegistry.h" #include "ResourceHandle.h" #include "ResourceHandleClient.h" #include "ResourceHandleInternal.h" #include "ResourceResponse.h" #include "ResourceRequest.h" #include <QDateTime> #include <QFile> #include <QFileInfo> #include <QNetworkReply> #include <QNetworkCookie> #include <qwebframe.h> #include <qwebpage.h> #include <wtf/text/CString.h> #include <QDebug> #include <QCoreApplication> // In Qt 4.8, the attribute for sending a request synchronously will be made public, // for now, use this hackish solution for setting the internal attribute. const QNetworkRequest::Attribute gSynchronousNetworkRequestAttribute = static_cast<QNetworkRequest::Attribute>(QNetworkRequest::HttpPipeliningWasUsedAttribute + 7); static const int gMaxRedirections = 10; namespace WebCore { // Take a deep copy of the FormDataElement FormDataIODevice::FormDataIODevice(FormData* data) : m_formElements(data ? data->elements() : Vector<FormDataElement>()) , m_currentFile(0) , m_currentDelta(0) , m_fileSize(0) , m_dataSize(0) { setOpenMode(FormDataIODevice::ReadOnly); if (!m_formElements.isEmpty() && m_formElements[0].m_type == FormDataElement::encodedFile) openFileForCurrentElement(); computeSize(); } FormDataIODevice::~FormDataIODevice() { delete m_currentFile; } qint64 FormDataIODevice::computeSize() { for (int i = 0; i < m_formElements.size(); ++i) { const FormDataElement& element = m_formElements[i]; if (element.m_type == FormDataElement::data) m_dataSize += element.m_data.size(); else { QFileInfo fi(element.m_filename); m_fileSize += fi.size(); } } return m_dataSize + m_fileSize; } void FormDataIODevice::moveToNextElement() { if (m_currentFile) m_currentFile->close(); m_currentDelta = 0; m_formElements.remove(0); if (m_formElements.isEmpty() || m_formElements[0].m_type == FormDataElement::data) return; openFileForCurrentElement(); } void FormDataIODevice::openFileForCurrentElement() { if (!m_currentFile) m_currentFile = new QFile; m_currentFile->setFileName(m_formElements[0].m_filename); m_currentFile->open(QFile::ReadOnly); } // m_formElements[0] is the current item. If the destination buffer is // big enough we are going to read from more than one FormDataElement qint64 FormDataIODevice::readData(char* destination, qint64 size) { if (m_formElements.isEmpty()) return -1; qint64 copied = 0; while (copied < size && !m_formElements.isEmpty()) { const FormDataElement& element = m_formElements[0]; const qint64 available = size-copied; if (element.m_type == FormDataElement::data) { const qint64 toCopy = qMin<qint64>(available, element.m_data.size() - m_currentDelta); memcpy(destination+copied, element.m_data.data()+m_currentDelta, toCopy); m_currentDelta += toCopy; copied += toCopy; if (m_currentDelta == element.m_data.size()) moveToNextElement(); } else { const QByteArray data = m_currentFile->read(available); memcpy(destination+copied, data.constData(), data.size()); copied += data.size(); if (m_currentFile->atEnd() || !m_currentFile->isOpen()) moveToNextElement(); } } return copied; } qint64 FormDataIODevice::writeData(const char*, qint64) { return -1; } bool FormDataIODevice::isSequential() const { return true; } QNetworkReplyWrapper::QNetworkReplyWrapper(QNetworkReply* reply, QObject* parent) : QObject(parent) , m_reply(reply) { Q_ASSERT(m_reply); connect(m_reply, SIGNAL(metaDataChanged()), this, SLOT(receiveMetaData())); connect(m_reply, SIGNAL(readyRead()), this, SLOT(receiveMetaData())); connect(m_reply, SIGNAL(finished()), this, SLOT(receiveMetaData())); } QNetworkReplyWrapper::~QNetworkReplyWrapper() { if (m_reply) m_reply->deleteLater(); } QNetworkReply* QNetworkReplyWrapper::release() { if (!m_reply) return 0; resetConnections(); QNetworkReply* reply = m_reply; m_reply = 0; reply->setParent(0); return reply; } void QNetworkReplyWrapper::resetConnections() { if (m_reply) m_reply->disconnect(this); QCoreApplication::removePostedEvents(this, QEvent::MetaCall); } void QNetworkReplyWrapper::receiveMetaData() { // This slot is only used to receive the first signal from the QNetworkReply object. resetConnections(); m_redirectionTargetUrl = m_reply->attribute(QNetworkRequest::RedirectionTargetAttribute).toUrl(); if (m_redirectionTargetUrl.isValid()) { emit metaDataChanged(); emit finished(); return; } WTF::String contentType = m_reply->header(QNetworkRequest::ContentTypeHeader).toString(); m_encoding = extractCharsetFromMediaType(contentType); m_advertisedMimeType = extractMIMETypeFromMediaType(contentType); bool hasData = m_reply->bytesAvailable(); bool isFinished = m_reply->isFinished(); if (!isFinished) { // If not finished, connect to the slots that will be used from this point on. connect(m_reply, SIGNAL(readyRead()), this, SIGNAL(readyRead())); connect(m_reply, SIGNAL(finished()), this, SLOT(didReceiveFinished())); } emit metaDataChanged(); if (hasData) emit readyRead(); if (isFinished) { emit finished(); return; } } void QNetworkReplyWrapper::didReceiveFinished() { // Disconnecting will make sure that nothing will happen after emitting the finished signal. resetConnections(); emit finished(); } String QNetworkReplyHandler::httpMethod() const { switch (m_method) { case QNetworkAccessManager::GetOperation: return "GET"; case QNetworkAccessManager::HeadOperation: return "HEAD"; case QNetworkAccessManager::PostOperation: return "POST"; case QNetworkAccessManager::PutOperation: return "PUT"; case QNetworkAccessManager::DeleteOperation: return "DELETE"; case QNetworkAccessManager::CustomOperation: return m_resourceHandle->firstRequest().httpMethod(); default: ASSERT_NOT_REACHED(); return "GET"; } } QNetworkReplyHandler::QNetworkReplyHandler(ResourceHandle* handle, LoadType loadType, bool deferred) : QObject(0) , m_replyWrapper(0) , m_resourceHandle(handle) , m_loadType(loadType) , m_deferred(deferred) , m_redirectionTries(gMaxRedirections) { resetState(); const ResourceRequest &r = m_resourceHandle->firstRequest(); if (r.httpMethod() == "GET") m_method = QNetworkAccessManager::GetOperation; else if (r.httpMethod() == "HEAD") m_method = QNetworkAccessManager::HeadOperation; else if (r.httpMethod() == "POST") m_method = QNetworkAccessManager::PostOperation; else if (r.httpMethod() == "PUT") m_method = QNetworkAccessManager::PutOperation; else if (r.httpMethod() == "DELETE") m_method = QNetworkAccessManager::DeleteOperation; else m_method = QNetworkAccessManager::CustomOperation; QObject* originatingObject = 0; if (m_resourceHandle->getInternal()->m_context) originatingObject = m_resourceHandle->getInternal()->m_context->originatingObject(); m_request = r.toNetworkRequest(originatingObject); if (!m_deferred) start(); } void QNetworkReplyHandler::resetState() { m_redirected = false; m_responseSent = false; m_responseContainsData = false; m_hasStarted = false; m_callFinishOnResume = false; m_callSendResponseIfNeededOnResume = false; m_callForwardDataOnResume = false; if (m_replyWrapper) { m_replyWrapper->deleteLater(); m_replyWrapper = 0; } } void QNetworkReplyHandler::setLoadingDeferred(bool deferred) { m_deferred = deferred; if (!deferred) resumeDeferredLoad(); } void QNetworkReplyHandler::resumeDeferredLoad() { if (!m_hasStarted) { ASSERT(!m_callSendResponseIfNeededOnResume); ASSERT(!m_callForwardDataOnResume); ASSERT(!m_callFinishOnResume); start(); return; } if (m_callSendResponseIfNeededOnResume) sendResponseIfNeeded(); if (m_callForwardDataOnResume) forwardData(); if (m_callFinishOnResume) finish(); } void QNetworkReplyHandler::abort() { m_resourceHandle = 0; if (QNetworkReply* reply = release()) { reply->abort(); reply->deleteLater(); } deleteLater(); } QNetworkReply* QNetworkReplyHandler::release() { if (!m_replyWrapper) return 0; QNetworkReply* reply = m_replyWrapper->release(); m_replyWrapper->deleteLater(); m_replyWrapper = 0; return reply; } static bool shouldIgnoreHttpError(QNetworkReply* reply, bool receivedData) { int httpStatusCode = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt(); if (httpStatusCode == 401 || httpStatusCode == 407) return true; if (receivedData && (httpStatusCode >= 400 && httpStatusCode < 600)) return true; return false; } void QNetworkReplyHandler::finish() { ASSERT(m_hasStarted); m_callFinishOnResume = m_deferred; if (m_deferred) return; if (!m_replyWrapper || !m_replyWrapper->reply()) return; sendResponseIfNeeded(); if (wasAborted()) return; ResourceHandleClient* client = m_resourceHandle->client(); if (!client) { m_replyWrapper->deleteLater(); m_replyWrapper = 0; return; } if (m_redirected) { resetState(); start(); return; } if (!m_replyWrapper->reply()->error() || shouldIgnoreHttpError(m_replyWrapper->reply(), m_responseContainsData)) client->didFinishLoading(m_resourceHandle, 0); else { QUrl url = m_replyWrapper->reply()->url(); int httpStatusCode = m_replyWrapper->reply()->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt(); if (httpStatusCode) { ResourceError error("HTTP", httpStatusCode, url.toString(), m_replyWrapper->reply()->attribute(QNetworkRequest::HttpReasonPhraseAttribute).toString()); client->didFail(m_resourceHandle, error); } else { ResourceError error("QtNetwork", m_replyWrapper->reply()->error(), url.toString(), m_replyWrapper->reply()->errorString()); client->didFail(m_resourceHandle, error); } } if (m_replyWrapper) { m_replyWrapper->deleteLater(); m_replyWrapper = 0; } } void QNetworkReplyHandler::sendResponseIfNeeded() { ASSERT(m_hasStarted); m_callSendResponseIfNeededOnResume = m_deferred; if (m_deferred) return; if (!m_replyWrapper || !m_replyWrapper->reply()) return; if (m_replyWrapper->reply()->error() && !shouldIgnoreHttpError(m_replyWrapper->reply(), m_responseContainsData)) return; if (wasAborted()) return; if (m_responseSent) return; m_responseSent = true; ResourceHandleClient* client = m_resourceHandle->client(); if (!client) return; WTF::String contentType = m_replyWrapper->reply()->header(QNetworkRequest::ContentTypeHeader).toString(); WTF::String encoding = extractCharsetFromMediaType(contentType); WTF::String mimeType = extractMIMETypeFromMediaType(contentType); if (mimeType.isEmpty()) { // let's try to guess from the extension mimeType = MIMETypeRegistry::getMIMETypeForPath(m_replyWrapper->reply()->url().path()); } KURL url(m_replyWrapper->reply()->url()); ResourceResponse response(url, mimeType.lower(), m_replyWrapper->reply()->header(QNetworkRequest::ContentLengthHeader).toLongLong(), encoding, String()); if (url.isLocalFile()) { client->didReceiveResponse(m_resourceHandle, response); return; } // The status code is equal to 0 for protocols not in the HTTP family. int statusCode = m_replyWrapper->reply()->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt(); if (url.protocolInHTTPFamily()) { String suggestedFilename = filenameFromHTTPContentDisposition(QString::fromLatin1(m_replyWrapper->reply()->rawHeader("Content-Disposition"))); if (!suggestedFilename.isEmpty()) response.setSuggestedFilename(suggestedFilename); else response.setSuggestedFilename(url.lastPathComponent()); response.setHTTPStatusCode(statusCode); response.setHTTPStatusText(m_replyWrapper->reply()->attribute(QNetworkRequest::HttpReasonPhraseAttribute).toByteArray().constData()); // Add remaining headers. foreach (const QNetworkReply::RawHeaderPair& pair, m_replyWrapper->reply()->rawHeaderPairs()) response.setHTTPHeaderField(QString::fromLatin1(pair.first), QString::fromLatin1(pair.second)); } QUrl redirection = m_replyWrapper->reply()->attribute(QNetworkRequest::RedirectionTargetAttribute).toUrl(); if (redirection.isValid()) { redirect(response, redirection); return; } client->didReceiveResponse(m_resourceHandle, response); } void QNetworkReplyHandler::redirect(ResourceResponse& response, const QUrl& redirection) { QUrl newUrl = m_replyWrapper->reply()->url().resolved(redirection); ResourceHandleClient* client = m_resourceHandle->client(); ASSERT(client); int statusCode = m_replyWrapper->reply()->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt(); m_redirectionTries--; if (!m_redirectionTries) { ResourceError error(newUrl.host(), 400 /*bad request*/, newUrl.toString(), QCoreApplication::translate("QWebPage", "Redirection limit reached")); client->didFail(m_resourceHandle, error); return; } m_redirected = true; // Status Code 301 (Moved Permanently), 302 (Moved Temporarily), 303 (See Other): // - If original request is POST convert to GET and redirect automatically // Status Code 307 (Temporary Redirect) and all other redirect status codes: // - Use the HTTP method from the previous request if ((statusCode >= 301 && statusCode <= 303) && m_resourceHandle->firstRequest().httpMethod() == "POST") m_method = QNetworkAccessManager::GetOperation; ResourceRequest newRequest = m_resourceHandle->firstRequest(); newRequest.setHTTPMethod(httpMethod()); newRequest.setURL(newUrl); // Should not set Referer after a redirect from a secure resource to non-secure one. if (!newRequest.url().protocolIs("https") && protocolIs(newRequest.httpReferrer(), "https")) newRequest.clearHTTPReferrer(); client->willSendRequest(m_resourceHandle, newRequest, response); if (wasAborted()) // Network error cancelled the request. return; QObject* originatingObject = 0; if (m_resourceHandle->getInternal()->m_context) originatingObject = m_resourceHandle->getInternal()->m_context->originatingObject(); m_request = newRequest.toNetworkRequest(originatingObject); } void QNetworkReplyHandler::forwardData() { ASSERT(m_hasStarted); m_callForwardDataOnResume = m_deferred; if (m_deferred) return; if (!m_replyWrapper || !m_replyWrapper->reply()) return; if (m_replyWrapper->reply()->bytesAvailable()) m_responseContainsData = true; sendResponseIfNeeded(); // don't emit the "Document has moved here" type of HTML if (m_redirected) return; if (wasAborted()) return; QByteArray data = m_replyWrapper->reply()->read(m_replyWrapper->reply()->bytesAvailable()); ResourceHandleClient* client = m_resourceHandle->client(); if (!client) return; // FIXME: https://bugs.webkit.org/show_bug.cgi?id=19793 // -1 means we do not provide any data about transfer size to inspector so it would use // Content-Length headers or content size to show transfer size. if (!data.isEmpty()) client->didReceiveData(m_resourceHandle, data.constData(), data.length(), -1); } void QNetworkReplyHandler::uploadProgress(qint64 bytesSent, qint64 bytesTotal) { if (wasAborted()) return; ResourceHandleClient* client = m_resourceHandle->client(); if (!client) return; client->didSendData(m_resourceHandle, bytesSent, bytesTotal); } QNetworkReply* QNetworkReplyHandler::sendNetworkRequest() { if (m_loadType == SynchronousLoad) m_request.setAttribute(gSynchronousNetworkRequestAttribute, true); ResourceHandleInternal* d = m_resourceHandle->getInternal(); QNetworkAccessManager* manager = 0; if (d->m_context) manager = d->m_context->networkAccessManager(); if (!manager) return 0; const QUrl url = m_request.url(); const QString scheme = url.scheme(); // Post requests on files and data don't really make sense, but for // fast/forms/form-post-urlencoded.html and for fast/forms/button-state-restore.html // we still need to retrieve the file/data, which means we map it to a Get instead. if (m_method == QNetworkAccessManager::PostOperation && (!url.toLocalFile().isEmpty() || url.scheme() == QLatin1String("data"))) m_method = QNetworkAccessManager::GetOperation; switch (m_method) { case QNetworkAccessManager::GetOperation: return manager->get(m_request); case QNetworkAccessManager::PostOperation: { FormDataIODevice* postDevice = new FormDataIODevice(d->m_firstRequest.httpBody()); // We may be uploading files so prevent QNR from buffering data m_request.setHeader(QNetworkRequest::ContentLengthHeader, postDevice->getFormDataSize()); m_request.setAttribute(QNetworkRequest::DoNotBufferUploadDataAttribute, QVariant(true)); QNetworkReply* result = manager->post(m_request, postDevice); postDevice->setParent(result); return result; } case QNetworkAccessManager::HeadOperation: return manager->head(m_request); case QNetworkAccessManager::PutOperation: { FormDataIODevice* putDevice = new FormDataIODevice(d->m_firstRequest.httpBody()); // We may be uploading files so prevent QNR from buffering data m_request.setHeader(QNetworkRequest::ContentLengthHeader, putDevice->getFormDataSize()); m_request.setAttribute(QNetworkRequest::DoNotBufferUploadDataAttribute, QVariant(true)); QNetworkReply* result = manager->put(m_request, putDevice); putDevice->setParent(result); return result; } case QNetworkAccessManager::DeleteOperation: { return manager->deleteResource(m_request); } case QNetworkAccessManager::CustomOperation: return manager->sendCustomRequest(m_request, m_resourceHandle->firstRequest().httpMethod().latin1().data()); case QNetworkAccessManager::UnknownOperation: ASSERT_NOT_REACHED(); return 0; } return 0; } void QNetworkReplyHandler::start() { ASSERT(!m_hasStarted); m_hasStarted = true; QNetworkReply* reply = sendNetworkRequest(); if (!reply) return; m_replyWrapper = new QNetworkReplyWrapper(reply, this); if (m_loadType == SynchronousLoad && m_replyWrapper->reply()->isFinished()) { // If supported, a synchronous request will be finished at this point, no need to hook up the signals. return; } connect(m_replyWrapper, SIGNAL(finished()), this, SLOT(finish())); connect(m_replyWrapper, SIGNAL(metaDataChanged()), this, SLOT(sendResponseIfNeeded())); connect(m_replyWrapper, SIGNAL(readyRead()), this, SLOT(forwardData())); if (m_resourceHandle->firstRequest().reportUploadProgress()) connect(m_replyWrapper->reply(), SIGNAL(uploadProgress(qint64, qint64)), this, SLOT(uploadProgress(qint64, qint64))); } } #include "moc_QNetworkReplyHandler.cpp"
32.073463
164
0.6827
[ "object", "vector" ]
6e6819333cd492d528a216d8ace8b2ef2029e1fc
1,476
cpp
C++
2017/day19/main.cpp
batduck27/Advent_of_code
6b2dadf28bebd2301464c864f5112dccede9762b
[ "MIT" ]
null
null
null
2017/day19/main.cpp
batduck27/Advent_of_code
6b2dadf28bebd2301464c864f5112dccede9762b
[ "MIT" ]
null
null
null
2017/day19/main.cpp
batduck27/Advent_of_code
6b2dadf28bebd2301464c864f5112dccede9762b
[ "MIT" ]
null
null
null
#include <iostream> #include <fstream> #include <stdlib.h> #include <vector> #define UP 0 #define RIGHT 1 #define DOWN 2 #define LEFT 3 static const int vert[] = {-1, 0, 1, 0}; static const int oriz[] = {0, 1, 0, -1}; void changeDirection(const std::vector<std::string>& maze, int i, int j, int& dir) { for (int k = 0; k < 4; ++ k) { // ignore the opposite direction if (abs(k - dir) == 2) { continue; } int newI = i + vert[k]; int newJ = j + oriz[k]; if (maze[newI][newJ] != ' ') { dir = k; return; } } } int main() { std::ifstream fin("data.in"); std::vector<std::string> maze; std::string line; std::string order; int dir = DOWN; int steps = 0; size_t i = 0, j = 0; while (std::getline(fin, line)) { maze.push_back(line); } fin.close(); j = maze[0].find_first_of("|"); while (i >= 0 && i < maze.size() && j >= 0 && j < maze[i].size()) { if (maze[i][j] >= 'A' && maze[i][j] <= 'Z') { order.push_back(maze[i][j]); } else if (maze[i][j] == '+') { changeDirection(maze, i, j, dir); } else if (maze[i][j] == ' ') { break; } i += vert[dir]; j += oriz[dir]; ++ steps; } std::cout << "The answer for part1 is: " << order << "\n"; std::cout << "The answer for part2 is: " << steps << "\n"; return 0; }
21.705882
82
0.466125
[ "vector" ]
6e70ac0af0f6e37b2772405ba1c0a599dc5fe2c7
161
inl
C++
clove/components/core/graphics/include/Clove/Graphics/Metal/MetalGraphicsCommandBuffer.inl
mondoo/Clove
3989dc3fea0d886a69005c1e0bb4396501f336f2
[ "MIT" ]
33
2020-01-09T04:57:29.000Z
2021-08-14T08:02:43.000Z
clove/components/core/graphics/include/Clove/Graphics/Metal/MetalGraphicsCommandBuffer.inl
mondoo/Clove
3989dc3fea0d886a69005c1e0bb4396501f336f2
[ "MIT" ]
234
2019-10-25T06:04:35.000Z
2021-08-18T05:47:41.000Z
clove/components/core/graphics/include/Clove/Graphics/Metal/MetalGraphicsCommandBuffer.inl
mondoo/Clove
3989dc3fea0d886a69005c1e0bb4396501f336f2
[ "MIT" ]
4
2020-02-11T15:28:42.000Z
2020-09-07T16:22:58.000Z
namespace clove { std::vector<MetalGraphicsCommandBuffer::RenderPass> const &MetalGraphicsCommandBuffer::getEncodedRenderPasses() const { return passes; } }
26.833333
120
0.801242
[ "vector" ]
6e70e9c2c16c51bc42a0a29a0874c3b455edf518
347
hpp
C++
llarp/util/status.hpp
da4089/llarp
e223f5d023b1794638b9e9b47a86ed03c8c25306
[ "Zlib" ]
28
2018-01-25T17:39:25.000Z
2022-03-26T15:23:12.000Z
llarp/util/status.hpp
gjyoung1974/loki-network
6559bb8f9e80095b4a7462ccb8fdf12e8ce19527
[ "Zlib" ]
1
2021-05-05T12:20:41.000Z
2021-05-05T13:21:38.000Z
llarp/util/status.hpp
gjyoung1974/loki-network
6559bb8f9e80095b4a7462ccb8fdf12e8ce19527
[ "Zlib" ]
7
2018-05-21T12:34:50.000Z
2021-05-05T11:57:50.000Z
#ifndef LLARP_UTIL_STATUS_HPP #define LLARP_UTIL_STATUS_HPP #include <util/string_view.hpp> #include <nlohmann/json.hpp> #include <vector> #include <string> #include <algorithm> #include <absl/types/variant.h> namespace llarp { namespace util { using StatusObject = nlohmann::json; } // namespace util } // namespace llarp #endif
15.772727
40
0.73487
[ "vector" ]
6e75533840c3f12974102251de121e85a357ebee
1,321
cpp
C++
test/utest.cpp
Marcos-Seafloor/udp_bridge
4acd257f7da3b6d591f4091fc0dbfadb53d038dd
[ "BSD-2-Clause" ]
6
2018-12-22T15:32:29.000Z
2022-03-07T14:56:44.000Z
test/utest.cpp
Marcos-Seafloor/udp_bridge
4acd257f7da3b6d591f4091fc0dbfadb53d038dd
[ "BSD-2-Clause" ]
null
null
null
test/utest.cpp
Marcos-Seafloor/udp_bridge
4acd257f7da3b6d591f4091fc0dbfadb53d038dd
[ "BSD-2-Clause" ]
8
2018-04-05T19:57:36.000Z
2022-02-07T15:49:41.000Z
#include "udp_bridge/packet.h" #include <gtest/gtest.h> #include "ros/ros.h" TEST(UDPBridge_Packet, compressionTest) { std::string test_in {"foobar foobar foobar foobar"}; std::vector<uint8_t> data_in(test_in.begin(),test_in.end()); auto compressed_data = udp_bridge::compress(data_in); udp_bridge::CompressedPacket *compressed_packet = reinterpret_cast<udp_bridge::CompressedPacket*>(compressed_data.data()); EXPECT_EQ(compressed_packet->type, udp_bridge::PacketType::Compressed); EXPECT_LE(compressed_packet->uncompressed_size, test_in.size()); EXPECT_LT(compressed_data.size(), data_in.size()); auto decompressed_data = udp_bridge::uncompress(compressed_data); EXPECT_EQ(data_in.size(), decompressed_data.size()); EXPECT_EQ(data_in, decompressed_data); std::string decompressed_string(decompressed_data.begin(), decompressed_data.end()); EXPECT_EQ(test_in, decompressed_string); } TEST(UDPBridge_Packet, addressToDottedTest) { sockaddr_in address {}; address.sin_addr.s_addr = htonl(0x7f000001); EXPECT_EQ(udp_bridge::addressToDotted(address),"127.0.0.1"); } int main(int argc, char **argv){ testing::InitGoogleTest(&argc, argv); ros::init(argc, argv, "udp_bridge_tester"); ros::NodeHandle nh; return RUN_ALL_TESTS(); }
33.025
126
0.733535
[ "vector" ]
6e7aa09c2b3dfcb96b186f9423194288f6fed28b
606
cpp
C++
ch04/src/student_info.cpp
Julia-Run/Accelerated-Cpp
602b2f824fe605f3beb81f1ad4b8bde31d923bb5
[ "MIT" ]
null
null
null
ch04/src/student_info.cpp
Julia-Run/Accelerated-Cpp
602b2f824fe605f3beb81f1ad4b8bde31d923bb5
[ "MIT" ]
null
null
null
ch04/src/student_info.cpp
Julia-Run/Accelerated-Cpp
602b2f824fe605f3beb81f1ad4b8bde31d923bb5
[ "MIT" ]
null
null
null
// // Created by dora on 22/2/2022. // #include "student _info.h" using namespace std; istream &read_hw(istream &hwIn, vector<double> &hw) { if (hwIn) { hw.clear(); double x; while (hwIn >> x) { hw.push_back(x); } hwIn.clear(); } return hwIn; } istream &read_inf(istream &infoIn, student_info &oneStudent) { infoIn >> oneStudent.name >> oneStudent.midterm >> oneStudent.final; read_hw(infoIn, oneStudent.homework); return infoIn; } bool compare(const student_info &s1, const student_info &s2) { return s1.name < s2.name; }
21.642857
72
0.612211
[ "vector" ]
6e7ce60e11505abea80d101aaaa0c3bb483362d5
730
hpp
C++
engine/src/VertexBufferObject.hpp
skryabiin/core
13bcdd0c9f3ebcc4954b9ee05ea95db0f77e16f7
[ "MIT" ]
null
null
null
engine/src/VertexBufferObject.hpp
skryabiin/core
13bcdd0c9f3ebcc4954b9ee05ea95db0f77e16f7
[ "MIT" ]
null
null
null
engine/src/VertexBufferObject.hpp
skryabiin/core
13bcdd0c9f3ebcc4954b9ee05ea95db0f77e16f7
[ "MIT" ]
null
null
null
#ifndef CORE_VERTEX_BUFFER_OBJECT_HPP #define CORE_VERTEX_BUFFER_OBJECT_HPP #include "BufferObject.hpp" namespace core { template<typename T> class VertexBufferObject : public BufferObject<T, GL_ARRAY_BUFFER> { public: bool setVertexAttributePointer(GLuint index) { return setVertexAttributePointer(index, GL_FALSE, 0); } bool setVertexAttributePointer(GLuint index, GLboolean normalized, GLuint stride) { if (_isBound) { glVertexAttribPointer(index, _vertexDimension, getTypeEnum<T>() , normalized, 0, NULL); return true; } else { error("Error attempting to set vertex attribute pointer: buffer object is not bound."); return false; } } }; } //end namespace core #endif
20.857143
93
0.732877
[ "object" ]
6e7e6ea7acca886b864d2e5b2c48a365b5748cc9
1,968
cpp
C++
src/Maths/MatrixSolver.cpp
OliverBenz/PhysicsEngine
e2a0b3dcbb42c7513bd49628e5fae5fd7906c977
[ "MIT" ]
3
2021-06-17T18:48:24.000Z
2021-07-19T09:14:12.000Z
src/Maths/MatrixSolver.cpp
OliverBenz/PhysEn
e2a0b3dcbb42c7513bd49628e5fae5fd7906c977
[ "MIT" ]
28
2021-05-23T15:36:32.000Z
2022-02-11T14:42:20.000Z
src/Maths/MatrixSolver.cpp
OliverBenz/PhysicsEngine
e2a0b3dcbb42c7513bd49628e5fae5fd7906c977
[ "MIT" ]
null
null
null
#include "MatrixSolver.hpp" namespace PhysEn { namespace Maths { // TODO: Append to not require square matrix bool makeUpperTriangle(Matrix& matrix){ if (!matrix.getSize().isSquare()) return false; double diagonal; size_t rowCount = matrix.getSize().rows; for (size_t i = 0; i < rowCount; i++){ // Divide the i-th row by the diagonal element diagonal = matrix.at(i, i); for(size_t j = i; j < rowCount; j++){ matrix.at(i, j) /= diagonal; } // Subtract the normalized equation from all the other rowCount of the matrix for(size_t k = i + 1; k < rowCount; k++){ diagonal = matrix.at(k, i); for(size_t j = i; j < rowCount; j++) matrix.at(k, j) -= matrix.at(i, j) * diagonal; } } return true; } Maths::Vector solveEquation(Matrix& components, Vector& result){ if (components.getSize().rows != result.getSize()) throw std::invalid_argument("Result vector dimension does not line up with component row count!"); double diagonal; size_t rowCount = components.getSize().rows; for (size_t i = 0; i < rowCount; i++){ // Divide the i-th row by the diagonal element diagonal = components.at(i, i); for(size_t j = i; j < rowCount; j++){ components.at(i, j) /= diagonal; } // Divide the i-th known term by the diagonal element result[i] /= diagonal; // Subtract the normalized equation from all the other rowCount of the components for(size_t k = i + 1; k < rowCount; k++){ diagonal = components.at(k, i); for(size_t j = i; j < rowCount; j++) components.at(k, j) -= components.at(i, j) * diagonal; // Do the same also for the known terms result[k] -= diagonal * result[i]; } } Maths::Vector x(result.getSize()); double sum = 0; // Index k is incremented for nested loop and will be -1 in the end! for (int k = (int)rowCount - 1; k >= 0; k--) { sum = 0; for (size_t i = k + 1; i < rowCount; i++) sum += components.at(k, i) * x[i]; x[k] = result[k] - sum; } return x; } } }
25.558442
100
0.637703
[ "vector" ]
6e8533f81c940d840af4e7ef82d6b96693ca30aa
2,049
cpp
C++
src/process.cpp
EricHodgins/CppND-System-Monitor-Project
aacee19d2d7d13c56dd4c0fb1ae20ea74411ca22
[ "MIT" ]
null
null
null
src/process.cpp
EricHodgins/CppND-System-Monitor-Project
aacee19d2d7d13c56dd4c0fb1ae20ea74411ca22
[ "MIT" ]
null
null
null
src/process.cpp
EricHodgins/CppND-System-Monitor-Project
aacee19d2d7d13c56dd4c0fb1ae20ea74411ca22
[ "MIT" ]
null
null
null
#include <unistd.h> #include <cctype> #include <sstream> #include <string> #include <vector> #include "process.h" using std::string; using std::to_string; using std::vector; void Process::setPid(const int pid) { pid_ = pid; } // TODO: Return this process's ID int Process::Pid() { return pid_; } // TODO: Return this process's CPU utilization float Process::CpuUtilization() { long int upTime = LinuxParser::UpTime(pid_); vector<string> cpuInfo = LinuxParser::ProcessorUtilization(pid_); long int utime = std::stol(cpuInfo[13]); long int stime = std::stol(cpuInfo[14]); long int cutime = std::stol(cpuInfo[15]); long int cstime = std::stol(cpuInfo[16]); long int startime = std::stol(cpuInfo[21]); int long totalTime = utime + stime; totalTime += cutime + cstime; float seconds = (float)upTime - ((float)startime / sysconf(_SC_CLK_TCK)); float cpuUsage = (((float)totalTime / sysconf(_SC_CLK_TCK)) / seconds); cpu_ = cpuUsage; return cpuUsage; } // TODO: Return the command that generated this process string Process::Command() { return LinuxParser::Command(pid_); } // TODO: Return this process's memory utilization string Process::Ram() { string ramstring = LinuxParser::Ram(pid_); try { ram_ = std::stol(ramstring) / 1024; } catch(...) { ram_ = 0; } return std::to_string(ram_); } // TODO: Return the user (name) that generated this process string Process::User() { return LinuxParser::User(pid_); } // TODO: Return the age of this process (in seconds) long int Process::UpTime() { return LinuxParser::UpTime(pid_); } // TODO: Overload the "less than" comparison operator for Process objects // REMOVE: [[maybe_unused]] once you define the function bool Process::operator<(Process const& a) const { return ram_ > a.ram_; //return cpu_ < a.cpu_; } void Process::setRam() { string ramStr = LinuxParser::Ram(pid_); try { ram_ = std::stol(ramStr) / 1024; } catch (...) { ram_ = 0; } }
26.960526
77
0.654954
[ "vector" ]
6e896e350cd6298fc6ba51fef30826e4cae7c02e
895
cpp
C++
class_polymorphism.cpp
zhichengMLE/Cplusplus
525d80550c2460b0504926a26beaa67ca91bb848
[ "MIT" ]
1
2019-03-29T21:07:37.000Z
2019-03-29T21:07:37.000Z
class_polymorphism.cpp
zhichengMLE/Cplusplus
525d80550c2460b0504926a26beaa67ca91bb848
[ "MIT" ]
null
null
null
class_polymorphism.cpp
zhichengMLE/Cplusplus
525d80550c2460b0504926a26beaa67ca91bb848
[ "MIT" ]
null
null
null
#include <iostream> using namespace std; class shape{ protected: int width; int length; public: void setWidth(int newWidth){ width = newWidth; } void setLength(int newLength){ length = newLength; } virtual int getArea() = 0; }; class square : public shape{ public: int getArea(){ return width * length; } }; class rectangle : public shape{ public: int getArea(){ return width * length; } }; int main() { square m; rectangle n; shape *s1 = &m; shape *s2 = &n; s1->setLength(10); s1->setWidth(10); cout << s1->getArea() << endl; cout << m.getArea() << endl; s2->setLength(10); s2->setWidth(5); cout << s2->getArea() << endl; cout << n.getArea() << endl; return 0; } /* 100 100 50 50 */
15.982143
38
0.506145
[ "shape" ]
6e902c75d3212017e26dcb1fd9afab9fb9775ba8
3,921
cpp
C++
Sources/Overload/OvRendering/src/OvRendering/Resources/Mesh.cpp
kmqwerty/Overload
f3b8c751a05815400ed35dd2be20a3900f3454fd
[ "MIT" ]
755
2019-07-10T01:26:39.000Z
2022-03-31T12:43:19.000Z
Sources/Overload/OvRendering/src/OvRendering/Resources/Mesh.cpp
kmqwerty/Overload
f3b8c751a05815400ed35dd2be20a3900f3454fd
[ "MIT" ]
111
2020-02-28T23:30:10.000Z
2022-01-18T13:57:30.000Z
Sources/Overload/OvRendering/src/OvRendering/Resources/Mesh.cpp
kmqwerty/Overload
f3b8c751a05815400ed35dd2be20a3900f3454fd
[ "MIT" ]
97
2019-11-06T15:19:56.000Z
2022-03-25T08:40:04.000Z
/** * @project: Overload * @author: Overload Tech. * @licence: MIT */ #include <algorithm> #include "OvRendering/Resources/Mesh.h" OvRendering::Resources::Mesh::Mesh(const std::vector<Geometry::Vertex>& p_vertices, const std::vector<uint32_t>& p_indices, uint32_t p_materialIndex) : m_vertexCount(static_cast<uint32_t>(p_vertices.size())), m_indicesCount(static_cast<uint32_t>(p_indices.size())), m_materialIndex(p_materialIndex) { CreateBuffers(p_vertices, p_indices); ComputeBoundingSphere(p_vertices); } void OvRendering::Resources::Mesh::Bind() { m_vertexArray.Bind(); } void OvRendering::Resources::Mesh::Unbind() { m_vertexArray.Unbind(); } uint32_t OvRendering::Resources::Mesh::GetVertexCount() { return m_vertexCount; } uint32_t OvRendering::Resources::Mesh::GetIndexCount() { return m_indicesCount; } uint32_t OvRendering::Resources::Mesh::GetMaterialIndex() const { return m_materialIndex; } const OvRendering::Geometry::BoundingSphere& OvRendering::Resources::Mesh::GetBoundingSphere() const { return m_boundingSphere; } void OvRendering::Resources::Mesh::CreateBuffers(const std::vector<Geometry::Vertex>& p_vertices, const std::vector<uint32_t>& p_indices) { std::vector<float> vertexData; std::vector<unsigned int> rawIndices; for (const auto& vertex : p_vertices) { vertexData.push_back(vertex.position[0]); vertexData.push_back(vertex.position[1]); vertexData.push_back(vertex.position[2]); vertexData.push_back(vertex.texCoords[0]); vertexData.push_back(vertex.texCoords[1]); vertexData.push_back(vertex.normals[0]); vertexData.push_back(vertex.normals[1]); vertexData.push_back(vertex.normals[2]); vertexData.push_back(vertex.tangent[0]); vertexData.push_back(vertex.tangent[1]); vertexData.push_back(vertex.tangent[2]); vertexData.push_back(vertex.bitangent[0]); vertexData.push_back(vertex.bitangent[1]); vertexData.push_back(vertex.bitangent[2]); } m_vertexBuffer = std::make_unique<Buffers::VertexBuffer<float>>(vertexData); m_indexBuffer = std::make_unique<Buffers::IndexBuffer>(const_cast<uint32_t*>(p_indices.data()), p_indices.size()); uint64_t vertexSize = sizeof(Geometry::Vertex); m_vertexArray.BindAttribute(0, *m_vertexBuffer, Buffers::EType::FLOAT, 3, vertexSize, 0); m_vertexArray.BindAttribute(1, *m_vertexBuffer, Buffers::EType::FLOAT, 2, vertexSize, sizeof(float) * 3); m_vertexArray.BindAttribute(2, *m_vertexBuffer, Buffers::EType::FLOAT, 3, vertexSize, sizeof(float) * 5); m_vertexArray.BindAttribute(3, *m_vertexBuffer, Buffers::EType::FLOAT, 3, vertexSize, sizeof(float) * 8); m_vertexArray.BindAttribute(4, *m_vertexBuffer, Buffers::EType::FLOAT, 3, vertexSize, sizeof(float) * 11); } void OvRendering::Resources::Mesh::ComputeBoundingSphere(const std::vector<Geometry::Vertex>& p_vertices) { m_boundingSphere.position = OvMaths::FVector3::Zero; m_boundingSphere.radius = 0.0f; if (!p_vertices.empty()) { float minX = std::numeric_limits<float>::max(); float minY = std::numeric_limits<float>::max(); float minZ = std::numeric_limits<float>::max(); float maxX = std::numeric_limits<float>::min(); float maxY = std::numeric_limits<float>::min(); float maxZ = std::numeric_limits<float>::min(); for (const auto& vertex : p_vertices) { minX = std::min(minX, vertex.position[0]); minY = std::min(minY, vertex.position[1]); minZ = std::min(minZ, vertex.position[2]); maxX = std::max(maxX, vertex.position[0]); maxY = std::max(maxY, vertex.position[1]); maxZ = std::max(maxZ, vertex.position[2]); } m_boundingSphere.position = OvMaths::FVector3{ minX + maxX, minY + maxY, minZ + maxZ } / 2.0f; for (const auto& vertex : p_vertices) { const auto& position = reinterpret_cast<const OvMaths::FVector3&>(vertex.position); m_boundingSphere.radius = std::max(m_boundingSphere.radius, OvMaths::FVector3::Distance(m_boundingSphere.position, position)); } } }
31.368
151
0.740372
[ "mesh", "geometry", "vector" ]
6e97849453404c39d36c28a35a2868af94f52fe9
1,084
cpp
C++
main.cpp
Raphire/UTTT-langskonk
a8e404b5c522c4f96d66ca73c5fcd5dea52c0b2c
[ "MIT" ]
null
null
null
main.cpp
Raphire/UTTT-langskonk
a8e404b5c522c4f96d66ca73c5fcd5dea52c0b2c
[ "MIT" ]
null
null
null
main.cpp
Raphire/UTTT-langskonk
a8e404b5c522c4f96d66ca73c5fcd5dea52c0b2c
[ "MIT" ]
null
null
null
// main.cpp // Jeffrey Drost #include "utttbot.h" #include <vector> void test() { UTTTBot bot; std::vector<std::string> input = { "settings player_names player0,player1", "settings your_bot player1", "settings timebank 5000", "settings time_per_move 200", "settings your_botid 1", "update game round 1", "update game field .,.,.,.,.,.,.,.,.,.,.,.,.,.,.,.,.,.,.,.,.,.,.,.,.,.,.,.,.,.,.,.,.,.,.,.,.,.,.,.,.,.,.,.,.,.,.,.,.,.,.,.,.,.,.,.,.,.,.,.,.,.,.,.,.,.,.,.,.,.,.,.,.,.,.,.,.,.,.,.,.", "update game macroboard -1,-1,-1,-1,-1,-1,-1,-1,-1", //"update game field .,.,.,.,.,1,.,.,.,0,.,0,.,.,1,0,.,0,.,.,1,.,.,1,.,.,.,1,.,.,.,0,.,.,0,.,1,.,.,.,.,.,.,.,.,1,0,.,.,1,1,1,1,1,.,0,.,1,0,1,0,.,.,0,.,.,.,.,0,.,0,.,1,0,.,0,1,.,1,0,0", //"update game macroboard .,1,.,1,.,1,-1,.,0", "action move 10000" }; for(int i = 0; i < input.size(); i++) bot.input(input[i]); } int main() { //test(); UTTTBot bot; bot.run(); return 0; }
30.111111
196
0.391144
[ "vector" ]
6e9869a84d4708e813bcbf6e33b6a14d38234d2c
414
hpp
C++
lib/src/include/deskgap/argv.hpp
perjonsson/DeskGap
5e74de37c057de3bac3ac16b3fabdb79b934d21e
[ "MIT" ]
1,910
2019-02-08T05:41:48.000Z
2022-03-24T23:41:33.000Z
lib/src/include/deskgap/argv.hpp
perjonsson/DeskGap
5e74de37c057de3bac3ac16b3fabdb79b934d21e
[ "MIT" ]
73
2019-02-13T02:58:20.000Z
2022-03-02T05:49:34.000Z
lib/src/include/deskgap/argv.hpp
ci010/DeskGap
b3346fea3dd3af7df9a0420131da7f4ac1518092
[ "MIT" ]
88
2019-02-13T12:41:00.000Z
2022-03-25T05:04:31.000Z
// // Created by patr0nus on 2019/11/13. // #ifndef DESKGAP_ARGV_HPP #define DESKGAP_ARGV_HPP #include <vector> #include <string> namespace DeskGap { #ifdef WIN32 std::vector<std::string> Argv(int argc, const wchar_t** argv); #else inline std::vector<std::string> Argv(int argc, const char** argv) { return std::vector<std::string>(argv, argv + argc); } #endif } #endif //DESKGAP_ARGV_HPP
18.818182
71
0.681159
[ "vector" ]
6e9f2802dcf6cea683286d615d97c174a5e757fb
9,514
cpp
C++
FaultyMemory/cpp/representation.cpp
VictorGeebs/FaultyMemory
c82ea3496b5dc193d8cdf6eb08f6cfa1e871c5ff
[ "Apache-2.0" ]
7
2020-06-17T16:44:36.000Z
2021-06-21T17:55:02.000Z
FaultyMemory/cpp/representation.cpp
VictorGeebs/FaultyMemory
c82ea3496b5dc193d8cdf6eb08f6cfa1e871c5ff
[ "Apache-2.0" ]
null
null
null
FaultyMemory/cpp/representation.cpp
VictorGeebs/FaultyMemory
c82ea3496b5dc193d8cdf6eb08f6cfa1e871c5ff
[ "Apache-2.0" ]
1
2020-08-18T19:51:59.000Z
2020-08-18T19:51:59.000Z
#include <torch/extension.h> #include <iostream> #include <vector> #include <time.h> #include <stdlib.h> #include <iomanip> #include <random> #include <bitset> #include <math.h> #include <algorithm> namespace customFunc { float clamp(float v, float lo, float hi) { assert( !(hi < lo) ); return (v < lo) ? lo : (hi < v) ? hi : v; } } //************************************* // Binary Representation //************************************* // Encode std::uint8_t encodeBinary(const float var, const bool isSigned = true) { return var > 0; } torch::Tensor encodeTenBinary(const torch::Tensor& ten, const bool isSigned = true) { at::Tensor boolTen = ten > 0; return boolTen.to(torch::kUInt8); } // Decode float decodeBinary(const std::uint8_t var, const bool isSigned = true) { return var == 0 ? -1*isSigned : 1; } torch::Tensor decodeTenBinary(const torch::Tensor& ten, const bool isSigned = true) { at::Tensor floatTen = ten.to(torch::kFloat32); if(isSigned) { return floatTen*2 - 1; } else { return floatTen; } } // Quantize float quantizeBinary(const float var, const bool isSigned = true) { return var <= 0 ? -1*isSigned : 1; } torch::Tensor quantizeTenBinary(const torch::Tensor& ten, const bool isSigned = true) { at::Tensor boolTen = ten > 0; at::Tensor floatTen = boolTen.to(torch::kFloat32); if(isSigned) { return floatTen*2 - 1; } else { return floatTen; } } //************************************* // Integer Representation //************************************* // Encode std::uint8_t encodeInt(const float var, const std::size_t width, const bool isSigned) { // Finding representation boundaries int low = -(1u << (width - 1)) * isSigned; int high = low + (1u << width) - 1; // Clamping and rounding, then converting to uint8 return static_cast<std::uint8_t>(std::round(customFunc::clamp(var, low, high))); } torch::Tensor encodeTenInt(const torch::Tensor& ten, const std::size_t width, const bool isSigned) { // Finding representation boundaries int low = -(1u << (width - 1)) * isSigned; int high = low + (1u << width) - 1; // Clamping and rounding, then converting to uint8 return ten.clamp(low, high).round().to(torch::kUInt8); } // Decode float decodeInt(std::uint8_t var, const std::size_t width, const bool isSigned) { std::uint8_t repeatingSignMask = std::numeric_limits<std::uint8_t>::max(); for (std::size_t i = 0; i < width; i++) { repeatingSignMask &= ~(1ul << i); } // ex repeatingSignMask: 0b11111000 // if leftmost relevant bit is 1 (if signed) const bool isNegative = (var >> (width - 1) & 1); if (isSigned && isNegative) { var |= repeatingSignMask; // repeat 1 leftwards } else { var &= ~repeatingSignMask; // repeat 0 leftwards } return static_cast<float>(static_cast<int8_t>(var)); } torch::Tensor decodeTenInt(const torch::Tensor& ten, const std::size_t width, const bool isSigned) { std::uint8_t repeatingSignMask = std::numeric_limits<std::uint8_t>::max(); for (std::size_t i = 0; i < width; i++) { repeatingSignMask &= ~(1ul << i); } // ex repeatingSignMask: 0b11111000 torch::Tensor floatTen = ten.to(torch::kFloat32).flatten(); torch::Tensor flat = ten.flatten().to(torch::kInt32); auto access = flat.accessor<int,1>(); for(int i = 0; i < flat.size(0); i++) { std::uint8_t var = static_cast<std::uint8_t>(access[i]); const bool isNegative = (var >> (width - 1) & 1); if (isSigned && isNegative) { var |= repeatingSignMask; // repeat 1 leftwards } else { var &= ~repeatingSignMask; // repeat 0 leftwards } floatTen[i] = static_cast<float>(static_cast<int8_t>(var)); } return floatTen.reshape_as(ten); } // Quantize float quantizeInt(const float var, const std::size_t width, const bool isSigned) { // Finding representation boundaries int low = -(1u << (width - 1)) * isSigned; int high = low + (1u << width) - 1; // Clamping and rounding return std::round(customFunc::clamp(var, low, high)); } at::Tensor quantizeTenInt(const at::Tensor ten, const std::size_t width, const bool isSigned) { // Finding representation boundaries int low = -(1u << (width - 1)) * isSigned; int high = low + (1u << width) - 1; // Clamping and rounding return ten.clamp(low, high).round(); } //************************************* // Fixed-Point Representation //************************************* // Encode std::uint8_t encodeFixedPoint(const float var, const std::size_t width, const std::size_t nbDigits) { float precision = 1.0 / (1u << nbDigits); // Smallest increment with the set number of bits std::size_t wholeWidth = width - nbDigits; // width of the whole part of the number (int(var)) int maxInt = 1u << (wholeWidth); // Max value possible of the whole part with the number of bits specified, assuming unsigned notation float maxVal = maxInt/2; // Max value possible of the whole part with the number of bits specified, assuming signed notation float clamped = customFunc::clamp(var, -1*maxVal, maxVal - precision); // Clamping variable to calculated values clamped *= 1u << nbDigits; clamped = std::round(clamped); return static_cast<std::uint8_t>(clamped); } torch::Tensor encodeTenFixedPoint(const torch::Tensor& ten, const std::size_t width, const std::size_t nbDigits) { float precision = 1.0 / (1u << nbDigits); // Smallest increment with the set number of bits std::size_t wholeWidth = width - nbDigits; // width of the whole part of the number (int(var)) int maxInt = 1u << (wholeWidth); // Max value possible of the whole part with the number of bits specified, assuming unsigned notation float maxVal = maxInt/2.f; // Max value possible of the whole part with the number of bits specified, assuming signed notation torch::Tensor clamped = ten.clamp(-maxVal, maxVal - precision); // Clamping tensor variable to calculated values //std::cerr << precision << '\n'; //std::cerr << maxVal << '\n'; //std::cerr << maxInt << '\n'; unsigned int scale = 1 << nbDigits; clamped = clamped * static_cast<int>(scale); return clamped.round().to(torch::kUInt8); } // Decode float decodeFixedPoint(std::uint8_t var, const std::size_t width, const std::size_t nbDigits) { std::int8_t varInt = static_cast<std::int8_t>(var); float precision = 1.0 / (1u << nbDigits); return precision*varInt; } torch::Tensor decodeTenFixedPoint(const torch::Tensor& ten, const std::size_t width, const std::size_t nbDigits) { torch::Tensor intTen = ten.to(torch::kInt8).to(torch::kFloat32); float precision = 1.0 / (1u << nbDigits); return precision*intTen; } // Quantize float quantizeFixedPoint(float var, const std::size_t width, const std::size_t nbDigits) { float precision = 1.0 / (1u << nbDigits); // Smallest increment with the set number of bits std::size_t wholeWidth = width - nbDigits; // width of the whole part of the number (int(var)) int maxInt = 1u << (wholeWidth-1); // Max value possible of the whole part with the number of bits specified, assuming signed notation float clamped = customFunc::clamp(var, -1*maxInt, maxInt - precision); // Clamping variable to calculated values int f = (1u << nbDigits); clamped *= f; clamped = std::round(clamped); return clamped /= f; } torch::Tensor quantizeTenFixedPoint(const torch::Tensor ten, const std::size_t width, const std::size_t nbDigits) { float precision = 1.0 / (1u << nbDigits); // Smallest increment with the set number of bits std::size_t wholeWidth = width - nbDigits; // width of the whole part of the number (int(var)) int maxInt = 1u << (wholeWidth-1); // Max value possible of the whole part with the number of bits specified, assuming signed notation torch::Tensor clamped = ten.clamp(-1*maxInt, maxInt - precision); // Clamping variable to calculated values int f = (1u << nbDigits); clamped *= f; clamped = clamped.round(); return clamped /= f; } // Binding PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) { m.def("encodeBinary", &encodeBinary, "CPPperturb"); m.def("encodeTenBinary", &encodeTenBinary, "CPPperturb"); m.def("decodeBinary", &decodeBinary, "CPPperturb"); m.def("decodeTenBinary", &decodeTenBinary, "CPPperturb"); m.def("quantizeBinary", &quantizeBinary, "CPPperturb"); m.def("quantizeTenBinary", &quantizeTenBinary, "CPPperturb"); m.def("encodeInt", &encodeInt, "CPPperturb"); m.def("encodeTenInt", &encodeTenInt, "CPPperturb"); m.def("decodeInt", &decodeInt, "CPPperturb"); m.def("decodeTenInt", &decodeTenInt, "CPPperturb"); m.def("quantizeInt", &quantizeInt, "CPPperturb"); m.def("quantizeTenInt", &quantizeTenInt, "CPPperturb"); m.def("encodeFixedPoint", &encodeFixedPoint, "CPPperturb"); m.def("encodeTenFixedPoint", &encodeTenFixedPoint, "CPPperturb"); m.def("decodeFixedPoint", &decodeFixedPoint, "CPPperturb"); m.def("decodeTenFixedPoint", &decodeTenFixedPoint, "CPPperturb"); m.def("quantizeFixedPoint", &quantizeFixedPoint, "CPPperturb"); m.def("quantizeTenFixedPoint", &quantizeTenFixedPoint, "CPPperturb"); }
32.694158
138
0.640214
[ "vector" ]
6ea5bd9578159c2c2bd19360c738459199b1ff3e
12,845
cpp
C++
main.cpp
Ziagl/GeometryClipmaps
3146d54ed4ea3775873219fb068084f3ebe94a28
[ "MIT" ]
null
null
null
main.cpp
Ziagl/GeometryClipmaps
3146d54ed4ea3775873219fb068084f3ebe94a28
[ "MIT" ]
null
null
null
main.cpp
Ziagl/GeometryClipmaps
3146d54ed4ea3775873219fb068084f3ebe94a28
[ "MIT" ]
null
null
null
#include "GLIncludes.h" #include <cstdio> #include <cstdlib> #include <iostream> #include <sstream> #include <iomanip> #include <math.h> // Math things #include "SimpleMath.h" #include "VectorMath.h" #include "Config.h" #include "Terrain.h" #include "Camera.h" // OpenGL Includes #include <GLTools.h> // OpenGL toolkit #pragma comment(lib, "opengl32.lib") #pragma comment(lib, "glew32.lib") // Items in popup menu enum { MENU_LIGHTING = 1, MENU_POLYMODE, MENU_TEXTURING, MENU_FRAMERATE, MENU_EXIT, MENU_BLENDREGIONS }; // Mouse data static bool g_bMouseDrag = false; static int g_iMouseX = 0; static int g_iMouseY = 0; static int g_iMouseDX = 0; static int g_iMouseDY = 0; // Camera data static bool g_bCameraRotLeft = false; static bool g_bCameraRotRight = false; static bool g_bCameraRotUp = false; static bool g_bCameraRotDown = false; static bool g_bCameraMoveForward = false; static bool g_bCameraMoveBackward = false; static bool g_bCameraMoveLeft = false; static bool g_bCameraMoveRight = false; static bool g_bCameraMoveUp = false; static bool g_bCameraMoveDown = false; static bool g_bBlockMoveForward = false; static bool g_bBlockMoveBackward = false; static bool g_bBlockMoveLeft = false; static bool g_bBlockMoveRight = false; static int g_iCameraVelocity = 5; static bool g_bUpdateNeeded = false; // menu callback function void selectFromMenu(int idCommand) { switch (idCommand) { case MENU_FRAMERATE: g_bFrameRate = !g_bFrameRate; break; case MENU_POLYMODE: g_bFillPolygons = !g_bFillPolygons; glPolygonMode (GL_FRONT_AND_BACK, g_bFillPolygons ? GL_FILL : GL_LINE); break; case MENU_BLENDREGIONS: if(g_fBlendRegions<1.0f) g_fBlendRegions = 1.0f; else g_fBlendRegions = 0.0f; break; case MENU_EXIT: printf( "Exiting.\n" ); glutSetKeyRepeat( GLUT_KEY_REPEAT_ON ); exit (0); break; } // redraw at the end of selection glutPostRedisplay(); } // mouse motion function void ActiveMotionFunc(int x, int y) { if( !g_bMouseDrag ) return; g_iMouseDX = x-g_iMouseX; g_iMouseDY = y-g_iMouseY; g_iMouseX = x; g_iMouseY = y; // viewport changed -> update clipmap pyramid g_bUpdateNeeded = true; } // mouse function void MouseFunc(int button, int state, int x, int y) { if( button != GLUT_LEFT_BUTTON ) return; g_iMouseX = x; g_iMouseY = y; g_bMouseDrag = (state==GLUT_DOWN); // viewport changed -> update clipmap pyramid g_bUpdateNeeded = false; } // idle mouse funcion void IdleFunc() { g_iMouseDX = 0; g_iMouseDY = 0; } // keyboard callback function void KeyboardDown(unsigned char key, int, int ) { if( key >= 48 && key <= 57 ) // digits 0-9 for camera speed { g_iCameraVelocity = (key-48) + 5; } else switch (key) { case 'w': g_bCameraMoveForward = true; break; case 's': g_bCameraMoveBackward = true; break; case 'a': g_bCameraMoveLeft = true; break; case 'd': g_bCameraMoveRight = true; break; case 'c': g_bCameraMoveDown = true; break; case 'q': g_bCameraMoveUp = true; break; case 'y': g_bCameraMoveDown = true; break; case 'g': g_bBlockMoveForward = true; break; case 'j': g_bBlockMoveBackward = true; break; case 'z': g_bBlockMoveLeft = true; break; case 'h': g_bBlockMoveRight = true; break; case 27: // ESCAPE key selectFromMenu(MENU_EXIT); break; case 'f': selectFromMenu(MENU_FRAMERATE); break; case 'p': selectFromMenu(MENU_POLYMODE); break; case 'b': selectFromMenu(MENU_BLENDREGIONS); break; } // cameramove leads to change in clipmap pyramid g_bUpdateNeeded = true; } void KeyboardUp(unsigned char key, int, int ) { switch(key) { case 'w': g_bCameraMoveForward = false; break; case 's': g_bCameraMoveBackward = false; break; case 'a': g_bCameraMoveLeft = false; break; case 'd': g_bCameraMoveRight = false; break; case 'c': g_bCameraMoveDown = false; break; case 'q': g_bCameraMoveUp = false; break; case 'y': g_bCameraMoveDown = false; break; case 'g': g_bBlockMoveForward = false; break; case 'j': g_bBlockMoveBackward = false; break; case 'z': g_bBlockMoveLeft = false; break; case 'h': g_bBlockMoveRight = false; break; } g_bUpdateNeeded = false; } // special keys for camera rotation void SpecialFunc(int key, int x, int y) { switch(key) { case GLUT_KEY_LEFT : g_bCameraRotLeft = true; break; case GLUT_KEY_RIGHT : g_bCameraRotRight = true; break; case GLUT_KEY_UP : g_bCameraRotUp = true; break; case GLUT_KEY_DOWN : g_bCameraRotDown = true; break; } g_bUpdateNeeded = true; } void SpecialUpFunc(int key, int x, int y) { switch(key) { case GLUT_KEY_LEFT : g_bCameraRotLeft = false; break; case GLUT_KEY_RIGHT : g_bCameraRotRight = false; break; case GLUT_KEY_UP : g_bCameraRotUp = false; break; case GLUT_KEY_DOWN : g_bCameraRotDown = false; break; } g_bUpdateNeeded = false; } // init popup menu and console output int buildPopupMenu() { printf( "Keys:\n" ); printf( " p - Toggle polygon fill\n" ); printf( " f - Display frame rate\n" ); printf( " b - Toggle blend regions\n"); printf( " a,s,d,w - Move\n" ); printf( " arrow keys - Turn\n" ); printf( " q,y - Camera up/down\n"); printf( " 0..9 - Adjust Speed\n" ); printf( " ESC - Exit\n" ); int menu = glutCreateMenu (selectFromMenu); glutAddMenuEntry ("Toggle polygon fill", MENU_POLYMODE); glutAddMenuEntry ("Display frame rate", MENU_FRAMERATE); glutAddMenuEntry ("Toggle blend regions", MENU_BLENDREGIONS); return menu; } /////////////////////////////////////////////////////////////////////////////// // FPS Timer Class class FPStimer { public: FPStimer(int wait) : wait(wait),t0(0),n(0),fps(1.0) {}; void Frame() { n++; double t = GetTime(); if( t0 <= 0 ) { // init t0 = t; fps = 1.0; n = 0; return; } if( t - t0 > wait ) { fps = float(n)/(float( t-t0 )/1000.0); t0 = t; n = 0; } }; inline float Fps() { return fps; }; inline float DeltaT() { return 1.0/fps; }; private: double wait; double t0; int n; double fps; }; static FPStimer fastFpsTimer(0),slowFpsTimer(250); // String output function void glutString(const char *pstr, int x, int y ) { glMatrixMode( GL_PROJECTION ); glLoadIdentity(); glOrtho( 0,g_Width,0,g_Height,0,1 ); glMatrixMode( GL_MODELVIEW ); glLoadIdentity(); glDisable( GL_DEPTH_TEST ); glDisable( GL_LIGHTING ); glColor3f( 1.0,1.0,1.0 ); float rp[4] = { x, y, 0, 1 }; glRasterPos4fv( rp ); while (*pstr!=char(0)) { if( *pstr=='\n' ) { rp[1] -= 13; glRasterPos4fv( rp ); } else glutBitmapCharacter( GLUT_BITMAP_8_BY_13, int( *pstr )); pstr++; } glEnable( GL_DEPTH_TEST ); } /////////////////////////////////////////////////////////////////////////////// // Window has changed size, or has just been created. In either case, we need // to use the window dimensions to set the viewport and the projection matrix. void ChangeSize(int w, int h) { g_Width = w; g_Height = h; g_bUpdateNeeded = true; } /////////////////////////////////////////////////////////////////////////////// // This function does any needed initialization on the rendering context. // This is the first opportunity to do any OpenGL related tasks. void SetupRC() { glDrawBuffer(GL_BACK); glEnable(GL_DEPTH_TEST); glDepthFunc(GL_LESS); glShadeModel(GL_SMOOTH); glEnable(GL_LIGHTING); glEnable(GL_LIGHT0); glEnable( GL_CULL_FACE ); glCullFace( GL_BACK ); glEnable( GL_NORMALIZE ); glFrontFace( GL_CCW ); glEnable(GL_LIGHTING); TerrainInit(); g_FreeCamera.dist = float3( 0,0, 10.f ); g_FreeCamera.angle = float3( 0 ); g_FreeCamera.angleVel = float3( 0 ); g_FreeCamera.target = float3( 0, g_fHeight, 0 ); g_FreeCamera.Update(); } // timer callback function static void timerCallback(int) { const float fSec = fastFpsTimer.DeltaT(); int iCameraRotHoriz = g_iMouseDX; int iCameraRotVert = g_iMouseDY; // Calculate Rotation Velocities from the keyboard input. // for the Plane float t = 0.f; // Block float blockspeed = 50.0f * g_iCameraVelocity; g_blockPos.x -= g_bBlockMoveForward ? blockspeed : 0.0f; g_blockPos.x += g_bBlockMoveBackward ? blockspeed : 0.0f; g_blockPos.z -= g_bBlockMoveLeft ? blockspeed : 0.0f; g_blockPos.z += g_bBlockMoveRight ? blockspeed : 0.0f; // and for camera t = 0.f; t += g_bCameraRotRight ? -g_fCameraAngleYDefVelocity : 0.f; t += g_bCameraRotLeft ? g_fCameraAngleYDefVelocity : 0.f; t -= iCameraRotHoriz * Rad( 45.0 ); g_FreeCamera.angleVel.y = t; t = 0.f; t += g_bCameraRotUp ? -g_fCameraAngleXDefVelocity : 0.f; t += g_bCameraRotDown ? g_fCameraAngleXDefVelocity : 0.f; t -= iCameraRotVert * Rad( 45.0 ); g_FreeCamera.angleVel.x = t; float3 cameraVel; t = 0.f; t += g_bCameraMoveForward ? 1.f : 0.f; t += g_bCameraMoveBackward ? -1.f : 0.f; cameraVel.z = t; t=0.f; t += g_bCameraMoveLeft ? 1.f : 0.f; t += g_bCameraMoveRight ? -1.f : 0.f; cameraVel.x = t; t=0.f; t += g_bCameraMoveUp ? 1.f : 0.f; t += g_bCameraMoveDown ? -1.f : 0.f; cameraVel.y = t; if( LenSqr(cameraVel) > 1.0e-3 ) cameraVel = Normalize( cameraVel ); // first person shooter style movement const float3 dX( -cosf(-g_FreeCamera.angle.y), 0.f, -sinf(-g_FreeCamera.angle.y) ); const float3 dZ( -dX.z, 0, dX.x ); const float3 dY( 0, 1, 0); const float speed = g_iCameraVelocity * 4.0 + 2.0; const float3 delta = fSec*20.0*speed*speed*(dZ*cameraVel.z + dX*cameraVel.x + dY*cameraVel.y); float3 newPos = g_FreeCamera.target + delta; float h = g_clipmapSystem.CalcHeight( newPos ) + g_minCameraHeight; if( newPos.y-h < g_nearPlane*10.0f ) newPos.y = (h+g_nearPlane*10.0f) + 0.4*(newPos.y-h-g_nearPlane*10.0f); if( newPos.y-h < g_nearPlane*2.0f ) newPos.y = (h+g_nearPlane*2.0f); g_FreeCamera.target = newPos; // Camera Orientation g_FreeCamera.angle += fSec * g_FreeCamera.angleVel; if(g_FreeCamera.angle.x > 0.0f) g_FreeCamera.angle.x = 0.0f; // Update Matrix g_FreeCamera.Update(); // Redraw and restart timer glutPostRedisplay(); glutTimerFunc( g_nTimerDelay, timerCallback, 0); } /********************************************** ********************************************** GL INITIALISATION / WINDOW REDRAWING ********************************************** *********************************************/ void setupCamera() { // Setup projection with field of view of 65 degrees glMatrixMode(GL_PROJECTION); glLoadIdentity(); g_FreeCamera.param.Set(65.0,float(g_Width)/float(g_Height),g_nearPlane,g_farPlane); CameraParams &p = g_FreeCamera.param; glFrustum( p.l,p.r,p.b,p.t,p.n,p.f ); // camera -> world glMatrixMode(GL_MODELVIEW); glLoadIdentity(); // world -> camera MultMatrixToGL( g_FreeCamera.MatWorldView() ); } void renderScene() { //draw the Terrain if(g_bUpdateNeeded) { TerrainUpdateFrame( g_FreeCamera.param, g_FreeCamera.MatWorldView(), g_lightDir ); } TerrainRender(); } /////////////////////////////////////////////////////////////////////////////// // Called to draw scene void RenderScene(void) { fastFpsTimer.Frame(); slowFpsTimer.Frame(); // Clear frame buffer and depth buffer glClearColor( colorSky[0], colorSky[1], colorSky[2], colorSky[3] ); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT); // Setup camera and initialize modelview matrix stack setupCamera(); glViewport(0, 0, g_Width, g_Height); // Render the scene renderScene(); // Display framerate if (g_bFrameRate) { std::stringstream buf; buf << slowFpsTimer.Fps() << " fps" << std::endl; glutString( buf.str().c_str(), 0 ,g_Height-18 ); } glutSwapBuffers(); } /////////////////////////////////////////////////////////////////////////////// // Main entry point for GLUT based programs int main(int argc, char* argv[]) { gltSetWorkingDirectory(argv[0]); glutInit(&argc, argv); glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH | GLUT_STENCIL); glutInitWindowSize(g_Width, g_Height); glutCreateWindow("Geometry Clipmaps"); // Initialice OpenGL and CEUGUI glewInit(); SetupRC(); // Register callbacks: glutDisplayFunc(RenderScene); glutReshapeFunc(ChangeSize); glutSetKeyRepeat( GLUT_KEY_REPEAT_ON ); glutKeyboardFunc(KeyboardDown); glutKeyboardUpFunc(KeyboardUp); glutSpecialFunc(SpecialFunc); glutSpecialUpFunc(SpecialUpFunc); glutMotionFunc(ActiveMotionFunc); glutMouseFunc(MouseFunc); glutIdleFunc(IdleFunc); GLenum err = glewInit(); if (GLEW_OK != err) { fprintf(stderr, "GLEW Error: %s\n", glewGetErrorString(err)); return 1; } // Create popup menu buildPopupMenu(); glutAttachMenu(GLUT_RIGHT_BUTTON); // Start display timer glutTimerFunc( g_nTimerDelay, timerCallback, 0); glutMainLoop(); return 0; }
22.417103
97
0.657844
[ "geometry", "render" ]
6eaa76b4aee7abc05414a1b1743fa06018965a0f
1,921
cpp
C++
EvtGen1_06_00/src/EvtGenModels/EvtMultibody.cpp
klendathu2k/StarGenerator
7dd407c41d4eea059ca96ded80d30bda0bc014a4
[ "MIT" ]
2
2018-12-24T19:37:00.000Z
2022-02-28T06:57:20.000Z
EvtGen1_06_00/src/EvtGenModels/EvtMultibody.cpp
klendathu2k/StarGenerator
7dd407c41d4eea059ca96ded80d30bda0bc014a4
[ "MIT" ]
null
null
null
EvtGen1_06_00/src/EvtGenModels/EvtMultibody.cpp
klendathu2k/StarGenerator
7dd407c41d4eea059ca96ded80d30bda0bc014a4
[ "MIT" ]
null
null
null
#include "EvtGenBase/EvtPatches.hh" #include "EvtGenBase/EvtGenKine.hh" #include "EvtGenBase/EvtPDL.hh" #include "EvtGenBase/EvtReport.hh" #include "EvtGenBase/EvtResonance.hh" #include "EvtGenBase/EvtResonance2.hh" #include "EvtGenModels/EvtMultibody.hh" #include "EvtGenBase/EvtConst.hh" #include "EvtGenBase/EvtdFunction.hh" #include "EvtGenBase/EvtKine.hh" #include "EvtGenBase/EvtParticle.hh" EvtMultibody::~EvtMultibody() { if( _decayTree != NULL ) delete _decayTree; _decayTree=NULL; if( _ilist != NULL ) delete [] _ilist; _ilist=NULL; } std::string EvtMultibody::getName() { return "D_MULTIBODY"; } EvtDecayBase* EvtMultibody::clone() { return new EvtMultibody; } void EvtMultibody::init() { int N = getNArg(); _decayTree = new EvtMTree( getDaugs(), getNDaug() ); _ilist = new int[getNDaug()+1]; for(int i=0; i<N-1; ++i) { if(getArgStr( i )=="RESONANCE") { _decayTree->addtree( getArgStr( ++i ) ); } else { EvtGenReport(EVTGEN_ERROR,"EvtGen") << "Syntax error at " << getArgStr( i ) << std::endl; ::abort(); } } } // Set the maximum probability amplitude - if function is left blank then the // program will search for it. This however is not deterministic and therefore // in the release cannot be in place. void EvtMultibody::initProbMax() { // setProbMax(1.0); } void EvtMultibody::decay( EvtParticle *p ) { // Initialize the phase space before doing anything else! p->initializePhaseSpace(getNDaug(),getDaugs()); EvtSpinAmp amp = _decayTree->amplitude( p ); vector<int> index = amp.iterallowedinit(); vector<unsigned int> spins = amp.dims(); do { for( size_t i=0; i<index.size(); ++i ) { _ilist[i]=index[i]+spins[i]; } vertex( _ilist, amp( index ) ); } while( amp.iterateallowed( index ) ); }
25.276316
79
0.63925
[ "vector" ]
6ec31bbe513172cbedd97ace089485f07776fdc0
2,634
cpp
C++
Competitive Programing Problem Solutions/Graph Theory/MST&DisjointSET/Marathon - 6[2016] [Disjoint Set and MST][01-06-2017]/1123 - Trail Maintenance.cpp
BIJOY-SUST/ACM---ICPC
b382d80d327ddcab15ab15c0e763ccf8a22e0d43
[ "Apache-2.0" ]
1
2022-02-27T12:07:59.000Z
2022-02-27T12:07:59.000Z
Competitive Programing Problem Solutions/Graph Theory/MST&DisjointSET/Marathon - 6[2016] [Disjoint Set and MST][01-06-2017]/1123 - Trail Maintenance.cpp
BIJOY-SUST/Competitive-Programming
b382d80d327ddcab15ab15c0e763ccf8a22e0d43
[ "Apache-2.0" ]
null
null
null
Competitive Programing Problem Solutions/Graph Theory/MST&DisjointSET/Marathon - 6[2016] [Disjoint Set and MST][01-06-2017]/1123 - Trail Maintenance.cpp
BIJOY-SUST/Competitive-Programming
b382d80d327ddcab15ab15c0e763ccf8a22e0d43
[ "Apache-2.0" ]
null
null
null
#include<bits/stdc++.h> //#define pi 2*acos(0.0) //#define valid(tx,ty) tx>=0&&tx<r&&ty>=0&&ty<c //#define p pair<int,int> //#define ll long long int //#define llu unsigned long long int //#define mx 100001 //#define mod 100000007 //const long long inf = 1e15; //----------------------Graph Moves-------------------- //const int fx[]={+1,-1,+0,+0}; //const int fy[]={+0,+0,+1,-1}; //const int fx[]={+0,+0,+1,-1,-1,+1,-1,+1}; //const int fy[]={-1,+1,+0,+0,+1,+1,-1,-1}; //const int fx[]={-2,-2,-1,-1,+1,+1,+2,+2}; //const int fy[]={-1,+1,-2,+2,-2,+2,-1,+1}; //----------------------------------------------------- //-----------------------Bitmask----------------------- //int biton(int n,int pos){return n=n|(1<<pos);} //int bitoff(int n,int pos){return n=n&~(1<<pos);} //bool check(int n,int pos){return (bool)(n&(1<<pos));} //----------------------------------------------------- using namespace std; int parent[210]; class node{ public: int u,v,w; bool operator<(const node &p)const{ return w<p.w; } node(int x,int y,int z){ u=x,v=y,w=z; } }; vector<node>edges; int find_par(int x){ if(parent[x]!=x) return parent[x]=find_par(parent[x]); else return parent[x]; } int MST(int n){ vector<node>edges2; sort(edges.begin(),edges.end()); for(int i=0;i<=n;i++) parent[i]=i; int c=0,ans=0; for(int i=0;i<edges.size();i++){ int pu=find_par(edges[i].u); int pv=find_par(edges[i].v); if(pu!=pv){ c++; parent[pu]=pv; ans+=edges[i].w; edges2.push_back(edges[i]); if(c==n-1) break; } } edges.clear(); edges=edges2; edges2.clear(); if(c==n-1) return ans; else return -1; } int main(){ // freopen("Input.txt","r",stdin); // freopen("Output.txt","w",stdout); int t; scanf("%d",&t); for(int cs=1;cs<=t;cs++){ edges.clear(); //parent.clear(); printf("Case %d:\n",cs); int n,e,c=0; scanf("%d%d",&n,&e); for(int i=1;i<=e;i++){ int a,b,d; scanf("%d%d%d",&a,&b,&d); edges.push_back(node(a,b,d)); c++; if(c<n-1) printf("-1\n"); else{ int ans=MST(n); printf("%d\n",ans); } } } return 0; } /* Sample Input 1 4 6 1 2 10 1 3 8 3 2 3 1 4 3 1 3 6 2 1 2 Output for Sample Input Case 1: -1 -1 -1 14 12 8 */
24.849057
59
0.42407
[ "vector" ]
6ec5b44186f8c8c0b09fcc35181a20029016f364
5,368
cpp
C++
Realistic Camera/realistic.cpp
YungChunLu/Rendering
ffee21cd3bc7b2475d05034b73e3fea6b4dcd4dc
[ "MIT" ]
null
null
null
Realistic Camera/realistic.cpp
YungChunLu/Rendering
ffee21cd3bc7b2475d05034b73e3fea6b4dcd4dc
[ "MIT" ]
null
null
null
Realistic Camera/realistic.cpp
YungChunLu/Rendering
ffee21cd3bc7b2475d05034b73e3fea6b4dcd4dc
[ "MIT" ]
1
2018-05-04T18:12:29.000Z
2018-05-04T18:12:29.000Z
#include "stdafx.h" #include "cameras/realistic.h" #include <fstream> #include <iostream> RealisticCamera::RealisticCamera(const AnimatedTransform &cam2world, float hither, float yon, float sopen, float sclose, float filmdistance, float aperture_diameter, string specfile, float filmdiag, Film *f) : Camera(cam2world, sopen, sclose, f) // pbrt-v2 doesnot specify hither and yon { distance = 0; Hither = hither; Yon = yon; // Parse the Specfile if (!ParseSpec(specfile)) { cerr << "Error in parsing " << specfile << endl; exit(1); } // now, distance represents the true location of film distance -= filmdistance; // build the transform float diag = sqrtf(f->xResolution * f->xResolution + f->yResolution * f->yResolution); float ratio = filmdiag / diag; // X and Y is in the Screen Space coordinate float X = ratio * 0.5 * f->xResolution; float Y = ratio * 0.5 * f->yResolution; RasterToCamera = Translate(Vector(0.f, 0.f, distance)) * Translate(Vector(X, -Y, 0.f)) * Scale(ratio, ratio, 1) * Scale(-1.f, 1.f, 1.f); } float RealisticCamera::GenerateRay(const CameraSample &sample, Ray *ray) const { // Generate raster and camera samples Point Pras(sample.imageX, sample.imageY, 0); Point Pcamera; RasterToCamera(Pras, &Pcamera); // Set the iterator int it = lens.size() - 1; float z, lensU, lensV, lensZ; // Sample point on lens - Method1 //ConcentricSampleDisk(sample.lensU, sample.lensV, &lensU, &lensV); //lensU *= lens[it].aperture; //lensV *= lens[it].aperture; // Sample point on lens - Method2 float r = lens[it].aperture * sqrtf(sample.lensU), theta = 2 * M_PI * sample.lensV; lensU = r * cosf(theta); lensV = r * sinf(theta); z = sqrtf(lens[it].radius * lens[it].radius - lensV * lensV - lensU * lensU); lensZ = lens[it].z - lens[it].radius - ((lens[it].radius < 0) ? z : -z); Point hit = Point(lensU, lensV, lensZ); Vector T = hit - Pcamera; // Tracing the ray for(int i = it; i >= 0; --i){ if (lens[i].isStop) { float deltaZ = lens[i].z - hit.z; T = Normalize(T); float t = deltaZ / T.z; hit = hit + t * T; if (hit.x * hit.x + hit.y * hit.y > lens[i].aperture * lens[i].aperture) return 0.f; } else { float n2 = (i == 0) ? 1 :lens[i-1].n; if (!Propagating(hit, T, lens[i], n2)) return 0.f; } } ray->o = hit; ray->d = Normalize(T); ray->mint = Hither; ray->maxt = (Yon - Hither) / ray->d.z; ray->time = Lerp(sample.time, shutterOpen, shutterClose); CameraToWorld(*ray, ray); // Set exposure weight float weight = Dot(Normalize(hit - Pcamera), Vector(0, 0, 1)); weight *= weight / abs(distance); weight *= weight * (lens[0].aperture * lens[0].aperture * M_PI); return weight; } bool RealisticCamera::ParseSpec(const string &file){ // open file const char* spec = file.c_str(); ifstream in(spec); // handle open error if (!in) return false; // define size of each reading line int size = 256; char* line = new char[size]; in.getline(line, size); // define the parameter we need float radius = 0, axpos = 0, n = 0, aperture = 0; while (!in.eof()){ if(line[0] != '#'){ Len len; sscanf(line, "%f%f%f%f", &radius, &axpos, &n, &aperture); len.isStop = (n == 0); len.z = distance; len.radius = radius; len.n = (n == 0) ? 1 : n; len.aperture = aperture * 0.5; distance -= axpos; lens.push_back(len); }; in.getline(line, size); } in.close(); return true; } bool RealisticCamera::Propagating(Point& O, Vector& D, Len surface, float n2) const{ Vector d = Normalize(D); Point C = Point(0.f, 0.f, surface.z - surface.radius); Vector OC = O - C; float b = Dot(OC, d); float c = OC.LengthSquared() - surface.radius * surface.radius; float determine = b * b - c; float t = 0; if (determine < 0) { return false; } else { float root = sqrtf(determine); t = (surface.radius > 0) ? (-b + root) : (-b - root); } O = O + t * d; if (surface.aperture * surface.aperture < O.y * O.y + O.x * O.x) return false; Vector N = (surface.radius > 0.f) ? Normalize(C - O) : Normalize(O - C); // Heckber's Method float n_ratio = surface.n / n2; float c1 = -Dot(d, N); float c2 = 1.f - n_ratio * n_ratio * (1.f - c1 * c1); if (c2 <= 0.f) return false; else c2 = sqrtf(c2); D = n_ratio * d + (n_ratio * c1 - c2) * N; return true; } RealisticCamera *CreateRealisticCamera(const ParamSet &params, const AnimatedTransform &cam2world, Film *film) { // Extract common camera parameters from \use{ParamSet} float hither = params.FindOneFloat("hither", -1); float yon = params.FindOneFloat("yon", -1); float shutteropen = params.FindOneFloat("shutteropen", -1); float shutterclose = params.FindOneFloat("shutterclose", -1); // Realistic camera-specific parameters string specfile = params.FindOneString("specfile", ""); float filmdistance = params.FindOneFloat("filmdistance", 70.0); // about 70 mm default to film float fstop = params.FindOneFloat("aperture_diameter", 1.0); float filmdiag = params.FindOneFloat("filmdiag", 35.0); Assert(hither != -1 && yon != -1 && shutteropen != -1 && shutterclose != -1 && filmdistance!= -1); if (specfile == "") { Severe( "No lens spec file supplied!\n" ); } return new RealisticCamera(cam2world, hither, yon, shutteropen, shutterclose, filmdistance, fstop, specfile, filmdiag, film); }
31.576471
95
0.639903
[ "vector", "transform" ]
6ec69788ea122e06a83372d57e4de69751efeb68
1,154
hxx
C++
source/code/iceshard/iceshard/private/gfx/iceshard_gfx_context.hxx
iceshard-engine/engine
4f2092af8d2d389ea72addc729d0c2c8d944c95c
[ "BSD-3-Clause-Clear" ]
39
2019-08-17T09:08:51.000Z
2022-02-13T10:14:19.000Z
source/code/iceshard/iceshard/private/gfx/iceshard_gfx_context.hxx
iceshard-engine/engine
4f2092af8d2d389ea72addc729d0c2c8d944c95c
[ "BSD-3-Clause-Clear" ]
63
2020-05-22T16:09:30.000Z
2022-01-21T14:24:05.000Z
source/code/iceshard/iceshard/private/gfx/iceshard_gfx_context.hxx
iceshard-engine/engine
4f2092af8d2d389ea72addc729d0c2c8d944c95c
[ "BSD-3-Clause-Clear" ]
null
null
null
#pragma once #include <ice/gfx/gfx_context.hxx> #include <ice/gfx/gfx_stage.hxx> #include <ice/collections.hxx> namespace ice::gfx { class GfxPass; class GfxTrait; class GfxDevice; struct IceGfxContextStage { ice::gfx::GfxContextStage const* stage; }; class IceGfxContext : public ice::gfx::GfxContext { public: IceGfxContext( ice::Allocator& alloc, ice::gfx::GfxPass const& gfx_pass ) noexcept; ~IceGfxContext() noexcept override = default; void prepare_context( ice::Span<ice::gfx::GfxContextStage const*> stages, ice::gfx::GfxDevice& device ) noexcept; void clear_context( ice::gfx::GfxDevice& device ) noexcept; void record_commands( ice::EngineFrame const& engine_frame, ice::render::CommandBuffer command_buffer, ice::render::RenderCommands& command_api ) noexcept; private: //ice::gfx::GfxPass const& _gfx_pass; ice::pod::Array<ice::gfx::IceGfxContextStage> _cached_stages; }; } // namespace ice::gfx
23.55102
69
0.606586
[ "render" ]
6ec6d1270673bd8ed7e7a37199462bfe4b339061
59,358
cpp
C++
MSpectrum.cpp
mhoopmann/magnum
371865baabef579f65096f366c6033d0fc3c4286
[ "Apache-2.0" ]
null
null
null
MSpectrum.cpp
mhoopmann/magnum
371865baabef579f65096f366c6033d0fc3c4286
[ "Apache-2.0" ]
2
2021-10-05T17:42:55.000Z
2021-11-19T19:54:21.000Z
MSpectrum.cpp
mhoopmann/magnum
371865baabef579f65096f366c6033d0fc3c4286
[ "Apache-2.0" ]
null
null
null
/* Copyright 2018, Michael R. Hoopmann, Institute for Systems Biology 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 "MSpectrum.h" #include <iostream> using namespace std; /*============================ Constructors & Destructors ============================*/ MSpectrum::MSpectrum(const int& i, const double& bs, const double& os, const int& th){ binOffset=os; binSize=bs; instrumentPrecursor=false; invBinSize=1.0/binSize; charge = 0; maxIntensity=0; mz = 0; precursor = new vector<mPrecursor>; singlets = new vector<MTopPeps>; spec = new vector<mSpecPoint>; scanNumber = 0; rTime = 0; xCorrArraySize=0; xCorrSparseArraySize=0; xCorrSparseArray=NULL; bigMonoMass=0; bigZ=0; singletCount=0; singletFirst=NULL; singletLast=NULL; singletMax=i; kojakSparseArray=NULL; kojakBins=0; //singletList=NULL; //singletBins=0; lowScore=0; hpSize=th; hp=new sHistoPep[hpSize]; for(int j=0;j<hpSize;j++){ hp[j].pepIndex=-1; hp[j].topScore=0; } for(int j=0;j<HISTOSZ;j++) histogram[j]=0; histogramCount=0; histoMaxIndex=0; //** temporary //for(int a=0;a<60;a++){ // for (int j = 0; j<HISTOSZ; j++) hX[a][j] = 0; // hXCount[a] = 0; //} //** cc=0; sc=0; } MSpectrum::MSpectrum(mParams& p){ //params->topCount, params->binSize, params->binOffset, params->threads binOffset = p.binOffset; binSize = p.binSize; instrumentPrecursor = false; invBinSize = 1.0 / binSize; charge = 0; maxIntensity = 0; mz = 0; precursor = new vector<mPrecursor>; singlets = new vector<MTopPeps>; spec = new vector<mSpecPoint>; scanNumber = 0; rTime = 0; xCorrArraySize = 0; xCorrSparseArraySize = 0; xCorrSparseArray = NULL; bigMonoMass=0; bigZ=0; singletCount = 0; singletFirst = NULL; singletLast = NULL; singletMax = p.topCount; kojakSparseArray = NULL; kojakBins = 0; lowScore = 0; maxHistogramCount=3000; minAdductMass=p.minAdductMass; maxPepLen=p.maxPepLen; mHisto=new MHistogram*[maxPepLen+1]; for(int j=0;j<p.maxPepLen+1;j++)mHisto[j]=NULL; for(int j=0;j<6;j++) ionSeries[j]=p.ionSeries[j]; hpSize = p.threads; hp = new sHistoPep[hpSize]; for (int j = 0; j<hpSize; j++){ hp[j].pepIndex = -1; hp[j].topScore = 0; } for (int j = 0; j<HISTOSZ; j++) histogram[j] = 0; histogramCount = 0; histoMaxIndex = 0; //** temporary //for (int a = 0; a<60; a++){ // for (int j = 0; j<HISTOSZ; j++) hX[a][j] = 0; // hXCount[a] = 0; //} //** cc = 0; sc = 0; } MSpectrum::MSpectrum(const MSpectrum& p){ unsigned int i; int j; spec = new vector<mSpecPoint>(*p.spec); for(i=0;i<20;i++) topHit[i]=p.topHit[i]; precursor = new vector<mPrecursor>(*p.precursor); singlets = new vector<MTopPeps>(*p.singlets); binOffset = p.binOffset; binSize = p.binSize; instrumentPrecursor = p.instrumentPrecursor; invBinSize = p.invBinSize; charge= p.charge; maxIntensity = p.maxIntensity; mz = p.mz; scanNumber = p.scanNumber; rTime = p.rTime; xCorrArraySize = p.xCorrArraySize; xCorrSparseArraySize = p.xCorrSparseArraySize; lowScore=p.lowScore; for(i = 0; i<HISTOSZ; i++) histogram[i] = p.histogram[i]; histogramCount = p.histogramCount; histoMaxIndex = p.histoMaxIndex; bigMonoMass=p.bigMonoMass; bigZ=p.bigZ; decoys=p.decoys; maxHistogramCount = p.maxHistogramCount; minAdductMass = p.minAdductMass; maxPepLen = p.maxPepLen; mHisto = new MHistogram*[maxPepLen+1]; for (int j = 0; j<p.maxPepLen+1; j++)mHisto[j] = NULL; for (int j = 0; j<6; j++) ionSeries[j] = p.ionSeries[j]; cc=p.cc; sc=p.sc; hpSize=p.hpSize; hp=new sHistoPep[hpSize]; for(j=0;j<hpSize;j++)hp[j]=p.hp[j]; singletCount=p.singletCount; singletMax=p.singletMax; singletFirst=NULL; singletLast=NULL; mScoreCard* sc=NULL; mScoreCard* tmp=p.singletFirst; if(tmp!=NULL) { singletFirst=new mScoreCard(*tmp); sc=singletFirst; tmp=tmp->next; while(tmp!=NULL){ sc->next=new mScoreCard(*tmp); sc->next->prev=sc; sc=sc->next; tmp=tmp->next; } singletLast=sc; } if(p.xCorrSparseArray==NULL){ xCorrSparseArray=NULL; } else { xCorrSparseArray = (mSparseMatrix *)calloc((size_t)xCorrSparseArraySize, (size_t)sizeof(mSparseMatrix)); for(j=0;j<xCorrSparseArraySize;j++) xCorrSparseArray[j]=p.xCorrSparseArray[j]; } kojakBins=p.kojakBins; if(p.kojakSparseArray==NULL){ kojakSparseArray=NULL; } else { for(j=0;j<kojakBins;j++){ if(p.kojakSparseArray[j]==NULL){ kojakSparseArray[j]=NULL; } else { kojakSparseArray[j] = new char[(int)invBinSize+1]; for(i=0;i<(unsigned int)invBinSize+1;i++) kojakSparseArray[j][i]=p.kojakSparseArray[j][i]; } } } //** temporary //for (int a = 0; a<60; a++){ // for (int j = 0; j<HISTOSZ; j++) hX[a][j] = p.hX[a][j]; // hXCount[a] = p.hXCount[a]; //} //** } MSpectrum::~MSpectrum(){ delete spec; delete precursor; delete singlets; if(xCorrSparseArray!=NULL) free(xCorrSparseArray); while(singletFirst!=NULL){ mScoreCard* tmp=singletFirst; singletFirst=singletFirst->next; delete tmp; } singletLast=NULL; int j; if(kojakSparseArray!=NULL){ for(j=0;j<kojakBins;j++){ if(kojakSparseArray[j]!=NULL) delete [] kojakSparseArray[j]; } delete [] kojakSparseArray; } delete [] hp; for (j = 0; j<maxPepLen+1; j++){ if (mHisto[j] != NULL) delete mHisto[j]; } delete[] mHisto; decoys=NULL; } /*============================ Operators ============================*/ MSpectrum& MSpectrum::operator=(const MSpectrum& p){ if(this!=&p){ unsigned int i; int j; delete spec; spec = new vector<mSpecPoint>(*p.spec); for(i=0;i<20;i++) topHit[i]=p.topHit[i]; delete precursor; precursor = new vector<mPrecursor>(*p.precursor); delete singlets; singlets = new vector<MTopPeps>(*p.singlets); binOffset = p.binOffset; binSize = p.binSize; instrumentPrecursor = p.instrumentPrecursor; invBinSize = p.invBinSize; charge = p.charge; maxIntensity = p.maxIntensity; mz = p.charge; scanNumber = p.scanNumber; rTime = p.rTime; xCorrArraySize = p.xCorrArraySize; xCorrSparseArraySize = p.xCorrSparseArraySize; lowScore = p.lowScore; bigMonoMass = p.bigMonoMass; bigZ=p.bigZ; for (i = 0; i<HISTOSZ; i++) histogram[i] = p.histogram[i]; histogramCount = p.histogramCount; histoMaxIndex = p.histoMaxIndex; for(i=0;i<maxPepLen+1;i++){ if(mHisto[i]!=NULL) delete mHisto[i]; } delete [] mHisto; decoys = p.decoys; maxHistogramCount = p.maxHistogramCount; minAdductMass = p.minAdductMass; maxPepLen = p.maxPepLen; mHisto = new MHistogram*[maxPepLen+1]; for (int j = 0; j<p.maxPepLen+1; j++)mHisto[j] = NULL; for (int j = 0; j<6; j++) ionSeries[j] = p.ionSeries[j]; cc = p.cc; sc = p.sc; delete [] hp; hpSize = p.hpSize; hp = new sHistoPep[hpSize]; for (j = 0; j<hpSize; j++)hp[j] = p.hp[j]; singletCount=p.singletCount; singletMax=p.singletMax; singletFirst=NULL; singletLast=NULL; mScoreCard* sc=NULL; mScoreCard* tmp=p.singletFirst; if(tmp!=NULL) { singletFirst=new mScoreCard(*tmp); sc=singletFirst; tmp=tmp->next; while(tmp!=NULL){ sc->next=new mScoreCard(*tmp); sc->next->prev=sc; sc=sc->next; tmp=tmp->next; } singletLast=sc; } if(xCorrSparseArray!=NULL) free(xCorrSparseArray); if(p.xCorrSparseArray==NULL){ xCorrSparseArray=NULL; } else { xCorrSparseArray = (mSparseMatrix *)calloc((size_t)xCorrSparseArraySize, (size_t)sizeof(mSparseMatrix)); for(j=0;j<xCorrSparseArraySize;j++) xCorrSparseArray[j]=p.xCorrSparseArray[j]; } if(kojakSparseArray!=NULL){ for(j=0;j<kojakBins;j++){ if(kojakSparseArray[j]!=NULL) delete [] kojakSparseArray[j]; } delete [] kojakSparseArray; } kojakBins=p.kojakBins; if(p.kojakSparseArray==NULL){ kojakSparseArray=NULL; } else { for(j=0;j<kojakBins;j++){ if(p.kojakSparseArray[j]==NULL){ kojakSparseArray[j]=NULL; } else { kojakSparseArray[j] = new char[(int)invBinSize+1]; for(i=0;i<(unsigned int)invBinSize+1;i++) kojakSparseArray[j][i]=p.kojakSparseArray[j][i]; } } } } return *this; } mSpecPoint& MSpectrum::operator [](const int &i){ return spec->at(i); } /*============================ Accessors ============================*/ double MSpectrum::getBinOffset(){ return binOffset; } int MSpectrum::getCharge(){ return charge; } bool MSpectrum::getInstrumentPrecursor(){ return instrumentPrecursor; } double MSpectrum::getInvBinSize(){ return invBinSize; } float MSpectrum::getMaxIntensity(){ return maxIntensity; } double MSpectrum::getMZ(){ return mz; } mPrecursor& MSpectrum::getPrecursor(int i){ return precursor->at(i); } mPrecursor* MSpectrum::getPrecursor2(int i){ return &precursor->at(i); } float MSpectrum::getRTime(){ return rTime; } int MSpectrum::getScanNumber(){ return scanNumber; } mScoreCard& MSpectrum::getScoreCard(int i){ return topHit[i]; } int MSpectrum::getSingletCount(){ return singletCount; } mScoreCard& MSpectrum::getSingletScoreCard(int i){ if(i>=singletCount) return *singletLast; mScoreCard* sc=singletFirst; int j=0; while(j<i){ if(sc->next==NULL) break; sc=sc->next; j++; } return *sc; } MTopPeps* MSpectrum::getTopPeps(int i){ return &singlets->at(i); } int MSpectrum::size(){ return (int)spec->size(); } int MSpectrum::sizePrecursor(){ return (int)precursor->size(); } /*============================ Modifiers ============================*/ void MSpectrum::addPoint(mSpecPoint& s){ spec->push_back(s); } void MSpectrum::addPrecursor(mPrecursor& p, int sz){ precursor->push_back(p); MTopPeps tp; tp.peptideMax=sz; //tp.resetSingletList(p.monoMass); singlets->push_back(tp); if(p.monoMass>bigMonoMass) { bigMonoMass=p.monoMass; bigZ=p.charge; } } void MSpectrum::clear(){ spec->clear(); precursor->clear(); singlets->clear(); bigMonoMass=0; bigZ=0; } void MSpectrum::erasePrecursor(int i){ precursor->erase(precursor->begin()+i); singlets->erase(singlets->begin()+i); } void MSpectrum::setCharge(int i){ charge=i; } void MSpectrum::setInstrumentPrecursor(bool b){ instrumentPrecursor=b; } void MSpectrum::setMaxIntensity(float f){ maxIntensity=f; } void MSpectrum::setMZ(double d){ mz=d; } void MSpectrum::setRTime(float f){ rTime=f; } void MSpectrum::setScanNumber(int i){ scanNumber=i; } /*============================ Functions ============================*/ bool MSpectrum::checkReporterIon(double mz, mParams* params){ int key = (int)mz; if (key >= kojakBins) return false; if (kojakSparseArray[key] == NULL) return false; int pos = (int)((mz - key)*invBinSize); if(kojakSparseArray[key][pos]>params->rIonThreshold) return true; return false; } void MSpectrum::checkScore(mScoreCard& s, int th){ unsigned int i; unsigned int j; //edge case for "reversible" cross-links: check if already matches top hit identically //note that such duplications still occur below the top score, but shouldn't influence the final result to the user int k=0; while(k<20 && s.eVal==topHit[k].eVal){ if(s.pep==topHit[k].pep && s.site==topHit[k].site){ if(s.mods->size()==topHit[k].mods->size()){ for(i=0;i<s.mods->size();i++){ if(s.mods->at(i).mass!=topHit[k].mods->at(i).mass || s.mods->at(i).pos!=topHit[k].mods->at(i).pos) break; } if(i==s.mods->size()) return; } } k++; } for(i=0;i<20;i++){ if(s.eVal < topHit[i].eVal) { for(j=19;j>i;j--) { topHit[j]=topHit[j-1]; } topHit[i] = s; lowScore=topHit[19].eVal; return; } } } void MSpectrum::checkSingletScore(mScoreCard& s){ mScoreCard* sc; mScoreCard* cur; //If list is empty, add the score card if(singletCount==0){ singletFirst=new mScoreCard(s); singletLast=singletFirst; singletCount++; return; } //check if we can just add to the end if(s.simpleScore<singletLast->simpleScore){ //check if we need to store the singlet if(singletCount==singletMax) return; singletLast->next=new mScoreCard(s); singletLast->next->prev=singletLast; singletLast=singletLast->next; singletCount++; return; } //check if it goes in the front if(s.simpleScore>=singletFirst->simpleScore){ singletFirst->prev=new mScoreCard(s); singletFirst->prev->next=singletFirst; singletFirst=singletFirst->prev; //add to singlet list if(singletCount<singletMax) { singletCount++; } else { cur=singletLast; singletLast=singletLast->prev; singletLast->next=NULL; delete cur; } return; } //scan to find insertion point cur = singletFirst->next; int i=1; while(s.simpleScore < cur->simpleScore){ i++; cur=cur->next; } sc=new mScoreCard(s); sc->prev=cur->prev; sc->next=cur; cur->prev->next=sc; cur->prev=sc; if(sc->prev==NULL) singletFirst=sc; if(singletCount<singletMax) { singletCount++; } else { cur=singletLast; singletLast=singletLast->prev; singletLast->next=NULL; delete cur; } } double MSpectrum::computeE(double score, int len){ //if we haven't computed a histogram yet, do it now if(mHisto[len]==NULL){ //cout << "Compute Histo: " << scanNumber << "\t" << len << endl; //Clear histogram for (int j = 0; j<HISTOSZ; j++) histogram[j] = 0; histogramCount = 0; if (!generateXcorrDecoys2(len)) { //handle failure cout << "Fail genXCorr2: " << scanNumber << "\t" << len << endl; exit(1); } mHisto[len]=new MHistogram(); linearRegression3(mHisto[len]->slope, mHisto[len]->intercept, mHisto[len]->rSq); //cout << "linReg3 success" << endl; mHisto[len]->slope*=10; //** temporary //cout << "\nDecoy Histogram: " << len << "\t" << histogramCount << endl; //for(int i=0;i<HISTOSZ;i++) cout << i << "\t" << histogram[i] << endl; //cout << mHisto[len]->slope << "\t" << mHisto[len]->intercept << "\t" << mHisto[len]->rSq << endl; //** } if (mHisto[len]->slope>=0){ //handle bad slopes //cout << "Fail regression: " << scanNumber << "\t" << len << endl; //cout << histogramCount << endl; //for (int j = 0; j<HISTOSZ; j++) cout << j << "\t" << histogram[j] << endl; //cout << score << "\t" << len << "\tslope=" << mHisto[len]->slope << endl; return 1000; //exit(1); } //cout << "Compute E: " << scanNumber << "\t" << len << endl; return pow(10.0, mHisto[len]->slope * score + mHisto[len]->intercept); } void MSpectrum::resetSingletList(){ /* size_t j; double max; if (singletList != NULL){ for (j = 0; j<singletBins; j++){ if (singletList[j] != NULL) delete singletList[j]; } delete[] singletList; } max=precursor->at(0).monoMass; for(j=1;j<precursor->size();j++){ if (precursor->at(j).monoMass>max) max = precursor->at(j).monoMass; } singletBins=(int)(max/10+1); singletList = new list<mSingletScoreCard*>*[singletBins]; for (j = 0; j<singletBins; j++) singletList[j] = NULL; */ } void MSpectrum::sortMZ(){ qsort(&spec->at(0),spec->size(),sizeof(mSpecPoint),compareMZ); } void MSpectrum::xCorrScore(){ kojakXCorr(); } /*============================ Private Functions ============================*/ void MSpectrum::kojakXCorr(){ int i; int j; int iTmp; double dTmp; double dSum; double *pdTempRawData; double *pdTmpFastXcorrData; float *pfFastXcorrData; mPreprocessStruct pPre; pPre.iHighestIon = 0; pPre.dHighestIntensity = 0; BinIons(&pPre); //cout << scanNumber << ": " << kojakBins << "\t" << xCorrArraySize << "\t" << invBinSize << "\t" << (int)invBinSize+1 << endl; kojakSparseArray=new char*[kojakBins]; for(i=0;i<kojakBins;i++) kojakSparseArray[i]=NULL; pdTempRawData = (double *)calloc((size_t)xCorrArraySize, (size_t)sizeof(double)); if (pdTempRawData == NULL) { fprintf(stderr, " Error - calloc(pdTempRawData[%d]).\n\n", xCorrArraySize); exit(1); } pdTmpFastXcorrData = (double *)calloc((size_t)xCorrArraySize, (size_t)sizeof(double)); if (pdTmpFastXcorrData == NULL) { fprintf(stderr, " Error - calloc(pdTmpFastXcorrData[%d]).\n\n", xCorrArraySize); exit(1); } pfFastXcorrData = (float *)calloc((size_t)xCorrArraySize, (size_t)sizeof(float)); if (pfFastXcorrData == NULL) { fprintf(stderr, " Error - calloc(pfFastXcorrData[%d]).\n\n", xCorrArraySize); exit(1); } // Create data for correlation analysis. MakeCorrData(pdTempRawData, &pPre, 50.0); // Make fast xcorr spectrum. dSum=0.0; for (i=0; i<75; i++) dSum += pPre.pdCorrelationData[i].intensity; for (i=75; i < xCorrArraySize +75; i++) { if (i<xCorrArraySize) dSum += pPre.pdCorrelationData[i].intensity; if (i>=151) dSum -= pPre.pdCorrelationData[i-151].intensity; pdTmpFastXcorrData[i-75] = (dSum - pPre.pdCorrelationData[i-75].intensity)* 0.0066666667; } xCorrSparseArraySize=1; for (i=0; i<xCorrArraySize; i++) { dTmp = pPre.pdCorrelationData[i].intensity - pdTmpFastXcorrData[i]; pfFastXcorrData[i] = (float)dTmp; // Add flanking peaks if used iTmp = i-1; if (iTmp >= 0) pfFastXcorrData[i] += (float) ((pPre.pdCorrelationData[iTmp].intensity - pdTmpFastXcorrData[iTmp])*0.5); iTmp = i+1; if (iTmp < xCorrArraySize) pfFastXcorrData[i] += (float) ((pPre.pdCorrelationData[iTmp].intensity - pdTmpFastXcorrData[iTmp])*0.5); } free(pdTmpFastXcorrData); //MH: Fill sparse matrix for(i=0;i<xCorrArraySize;i++){ if(pfFastXcorrData[i]>0.5 || pfFastXcorrData[i]<-0.5){ //Fill in missing masses as a result of adding flanking peaks if(pPre.pdCorrelationData[i].mass==0){ j=1; while(true){ if( (i+j)<xCorrArraySize){ if(pPre.pdCorrelationData[i+j].mass>0){ pPre.pdCorrelationData[i].mass=pPre.pdCorrelationData[i+j].mass-j*binSize; break; } } if( (i-j)>-1){ if(pPre.pdCorrelationData[i-j].mass>0){ pPre.pdCorrelationData[i].mass=pPre.pdCorrelationData[i-j].mass+j*binSize; break; } } j++; } } //convert i to sparse array key //dTmp=pPre.pdCorrelationData[i].mass+binSize*binOffset; dTmp=binSize*i; iTmp=(int)dTmp; //cout << i << "\t" << pfFastXcorrData[i] << "\t" << dTmp << "\t" << iTmp << endl; if(kojakSparseArray[iTmp]==NULL) { kojakSparseArray[iTmp]=new char[(int)invBinSize+1]; for(j=0;j<(int)invBinSize+1;j++) kojakSparseArray[iTmp][j]=0; } j=(int)((dTmp-iTmp)*invBinSize/*+0.5*/); //cout << (dTmp-iTmp) << "\t" << (dTmp-iTmp)*invBinSize/*+0.5*/ << endl; //cout << j << endl; //if( j>(int)invBinSize) { // cout << "ERROR!" << endl; // exit(0); //} if(pfFastXcorrData[i]>127) kojakSparseArray[iTmp][j]=127; else if(pfFastXcorrData[i]<-128) kojakSparseArray[iTmp][j]=-128; else if(pfFastXcorrData[i]>0) kojakSparseArray[iTmp][j]=(char)(pfFastXcorrData[i]+0.5); else kojakSparseArray[iTmp][j]=(char)(pfFastXcorrData[i]-0.5); //cout << i << "\t" << iTmp << "\t" << j << "\t" << (int)kojakSparseArray[iTmp][j] << endl; } } /* if(scanNumber==11368){ for(i=0;i<kojakBins;i++){ if(kojakSparseArray[i]==NULL) { cout << i << "\tNULL" << endl; continue; } for(j=0;j<(int)invBinSize+1;j++){ cout << i << "\t" << j << "\t" << (int)kojakSparseArray[i][j] << endl; } } } */ //exit(1); free(pPre.pdCorrelationData); free(pfFastXcorrData); free(pdTempRawData); } void MSpectrum::BinIons(mPreprocessStruct *pPre) { int i; unsigned int j; double dPrecursor; double dIon; double dIntensity; // Just need to pad iArraySize by 75. dPrecursor=0; for(j=0;j<precursor->size();j++){ if(precursor->at(j).monoMass>dPrecursor) dPrecursor=precursor->at(j).monoMass; } xCorrArraySize = (int)((dPrecursor + 100.0) / binSize); kojakBins = (int)(spec->at(spec->size()-1).mass+100.0); pPre->pdCorrelationData = (mSpecPoint *)calloc(xCorrArraySize, (size_t)sizeof(mSpecPoint)); if (pPre->pdCorrelationData == NULL) { fprintf(stderr, " Error - calloc(pdCorrelationData[%d]).\n\n", xCorrArraySize); exit(1); } i = 0; while(true) { if (i >= (int)spec->size()) break; dIon = spec->at(i).mass; dIntensity = spec->at(i).intensity; i++; if (dIntensity > 0.0) { if (dIon < (dPrecursor + 50.0)) { //#define BIN(dMass) (int)(dMass*invBinSize + binOffset) int iBinIon = (int)(dIon*invBinSize+binOffset); dIntensity = sqrt(dIntensity); if (iBinIon > pPre->iHighestIon) pPre->iHighestIon = iBinIon; if ((iBinIon < xCorrArraySize) && (dIntensity > pPre->pdCorrelationData[iBinIon].intensity)) { if (dIntensity > pPre->pdCorrelationData[iBinIon].intensity) { pPre->pdCorrelationData[iBinIon].intensity = (float)dIntensity; pPre->pdCorrelationData[iBinIon].mass = dIon; } if (pPre->pdCorrelationData[iBinIon].intensity > pPre->dHighestIntensity) pPre->dHighestIntensity = pPre->pdCorrelationData[iBinIon].intensity; } } } } //Clear spectrum data that we no longer need spec->clear(); } // pdTempRawData now holds raw data, pdCorrelationData is windowed data. void MSpectrum::MakeCorrData(double *pdTempRawData, mPreprocessStruct *pPre, double scale){ int i; int ii; int iBin; int iWindowSize; int iNumWindows=10; double dMaxWindowInten; double dMaxOverallInten; double dTmp1; double dTmp2; dMaxOverallInten = 0.0; // Normalize maximum intensity to 100. dTmp1 = 1.0; if (pPre->dHighestIntensity > 0.000001) dTmp1 = 100.0 / pPre->dHighestIntensity; for (i=0; i < xCorrArraySize; i++) { pdTempRawData[i] = pPre->pdCorrelationData[i].intensity*dTmp1; pPre->pdCorrelationData[i].intensity=0.0; if (dMaxOverallInten < pdTempRawData[i]) dMaxOverallInten = pdTempRawData[i]; } iWindowSize = (int) ceil( (double)(pPre->iHighestIon)/iNumWindows); for (i=0; i<iNumWindows; i++){ dMaxWindowInten = 0.0; for (ii=0; ii<iWindowSize; ii++) { // Find max inten. in window. iBin = i*iWindowSize+ii; if (iBin < xCorrArraySize) { if (pdTempRawData[iBin] > dMaxWindowInten)dMaxWindowInten = pdTempRawData[iBin]; } } if (dMaxWindowInten > 0.0) { dTmp1 = scale / dMaxWindowInten; dTmp2 = 0.05 * dMaxOverallInten; for (ii=0; ii<iWindowSize; ii++){ // Normalize to max inten. in window. iBin = i*iWindowSize+ii; if (iBin < xCorrArraySize){ if (pdTempRawData[iBin] > dTmp2) pPre->pdCorrelationData[iBin].intensity = (float)(pdTempRawData[iBin]*dTmp1); } } } } } //from Comet bool MSpectrum::calcEValue(mParams* params, MDecoys& decoys) { int i; int iLoopCount; int iMaxCorr; int iStartCorr; int iNextCorr; double dSlope; double dIntercept; double dRSq; if(topHit[0].simpleScore==0) return true; if (histogramCount < DECOY_SIZE) { if (!generateXcorrDecoys(params,decoys)) return false; } //linearRegression(dSlope, dIntercept, iMaxCorr, iStartCorr, iNextCorr); linearRegression2(dSlope, dIntercept, iMaxCorr, iStartCorr, iNextCorr,dRSq); histoMaxIndex = iMaxCorr; dSlope *= 10.0; iLoopCount=20; //score all e-values among top hits? for (i = 0; i<iLoopCount; i++) { if(topHit[i].simpleScore==0) break; //score all e-values among top hits? if (dSlope >= 0.0) { topHit[i].eVal=1e12; } else { topHit[i].eVal = pow(10.0, dSlope * topHit[i].simpleScore + dIntercept); } } return true; } //from Comet // Make synthetic decoy spectra to fill out correlation histogram by going // through each candidate peptide and rotating spectra in m/z space. bool MSpectrum::generateXcorrDecoys(mParams* params, MDecoys& decoys) { int i; int n; int j; int k; int maxZ; int z; size_t r=0; int key; int pos; double dBion; double dYion; double dXcorr; double dFragmentIonMass = 0.0; // DECOY_SIZE is the minimum # of decoys required or else this function isn't // called. So need to generate iLoopMax more xcorr scores for the histogram. int iLoopMax = DECOY_SIZE - histogramCount; int seed = (scanNumber*histogramCount); if (seed<0) seed = -seed; seed = seed % DECOY_SIZE; //don't always start at the top, but not random either; remains reproducible across threads int decoyIndex; j = 0; for (i = 0; i<iLoopMax; i++) { // iterate through required # decoys dXcorr = 0.0; decoyIndex = (seed + i) % DECOY_SIZE; //iterate over precursors r++; if (r >= precursor->size()) r = 0; maxZ = precursor->at(r).charge; if (maxZ>4) maxZ = 4; for (j = 0; j<MAX_DECOY_PEP_LEN; j++) { // iterate through decoy fragment ions dBion = decoys.decoyIons[decoyIndex].pdIonsN[j]; dYion = decoys.decoyIons[decoyIndex].pdIonsC[j]; if(dBion>precursor->at(r).monoMass && dYion>precursor->at(r).monoMass) break; //stop when fragment ion masses exceed precursor mass for (n = 0; n<6; n++) { if(!params->ionSeries[n]) continue; switch (n) { case 0: dFragmentIonMass = dBion - 27.9949141; break; case 1: dFragmentIonMass = dBion; break; case 2: dFragmentIonMass = dBion + 17.026547; break; case 3: dFragmentIonMass = dYion + 25.9792649; break; case 4: dFragmentIonMass = dYion; break; case 5: dFragmentIonMass = dYion - 16.0187224; break; } if(dFragmentIonMass>precursor->at(r).monoMass) continue; for (z=1;z<maxZ;z++) { mz = (dFragmentIonMass + (z - 1)*1.007276466) / z; mz = params->binSize * (int)(mz*invBinSize + params->binOffset); key = (int)mz; if(key>=kojakBins) break; if(kojakSparseArray[key]==NULL) continue; pos = (int)((mz - key)*invBinSize); dXcorr += kojakSparseArray[key][pos]; } } } if(dXcorr<=0.0) dXcorr=0.0; k = (int)(dXcorr*0.05 + 0.5); // 0.05=0.005*10; see MAnalysis::mangnumScoring if (k < 0) k = 0; else if (k >= HISTOSZ) k = HISTOSZ - 1; histogram[k] += 1; histogramCount++; } return true; } //from Comet // Make synthetic decoy spectra to fill out correlation histogram by going // through each candidate peptide and rotating spectra in m/z space. bool MSpectrum::generateXcorrDecoys2(int maxPepLen) { int i; int n; int j; int k; int maxZ; int z; size_t r = 0; int key; int pos; double dBion[3]; //0=N-term, 1=C-term, 2=center double dYion[3]; double dXcorr[3]; double dFragmentIonMass = 0.0; double oMass; bool bAdduct; int ac; // DECOY_SIZE is the minimum # of decoys required or else this function isn't // called. So need to generate iLoopMax more xcorr scores for the histogram. int iLoopMax = DECOY_SIZE; int seed = scanNumber % DECOY_SIZE; //don't always start at the top, but not random either; remains reproducible across threads int decoyIndex; //cout << "generateXcorrDecoys2 " << iLoopMax << "\t" << precursor->size() << endl; j = 0; for (i = 0; i<iLoopMax; i++) { // iterate through required # decoys dXcorr[0]=dXcorr[1]=dXcorr[2] = 0; decoyIndex = (seed + i) % DECOY_SIZE; //iterate over precursors r++; if (r >= precursor->size()) r = 0; maxZ = precursor->at(r).charge; if (maxZ>4) maxZ = 4; //if we need to add an adduct mass, then do so here bAdduct=true; ac=3; oMass=precursor->at(r).monoMass-110.5822*maxPepLen; //cout << "oMass: " << oMass << "\t" << minAdductMass << "\t" << precursor->at(r).monoMass << endl; if(oMass<minAdductMass) { oMass=0; bAdduct=false; ac=1; } for (j = 0; j<MAX_DECOY_PEP_LEN; j++) { // iterate through decoy fragment ions if(j==maxPepLen) break; //stop when fragment ions exceed peptide length dBion[0] = decoys->decoyIons[decoyIndex].pdIonsN[j] + oMass; dYion[0] = decoys->decoyIons[decoyIndex].pdIonsC[j]; if(bAdduct){ dBion[1] = decoys->decoyIons[decoyIndex].pdIonsN[j]; dYion[1] = decoys->decoyIons[decoyIndex].pdIonsC[j] + oMass; if(j<maxPepLen/2) { dBion[2]=dBion[1]; dYion[2]=dYion[0]; } else { dBion[2]=dBion[0]; dYion[2]=dYion[1]; } } for(int x=0;x<ac;x++){ for (n = 0; n<6; n++) { if (!ionSeries[n]) continue; switch (n) { case 0: dFragmentIonMass = dBion[x] - 27.9949141; break; case 1: dFragmentIonMass = dBion[x]; break; case 2: dFragmentIonMass = dBion[x] + 17.026547; break; case 3: dFragmentIonMass = dYion[x] + 25.9792649; break; case 4: dFragmentIonMass = dYion[x]; break; case 5: dFragmentIonMass = dYion[x] - 16.0187224; break; } if (dFragmentIonMass>precursor->at(r).monoMass) continue; for (z = 1; z<maxZ; z++) { mz = (dFragmentIonMass + (z - 1)*1.007276466) / z; mz = binSize * (int)(mz*invBinSize + binOffset); key = (int)mz; if (key >= kojakBins) break; if (key<0 || kojakSparseArray[key] == NULL) continue; pos = (int)((mz - key)*invBinSize); dXcorr[x] += kojakSparseArray[key][pos]; } } } } for(int x=0;x<ac;x++){ if (dXcorr[x] <= 0.0) dXcorr[x] = 0.0; k = (int)(dXcorr[x]*0.05 + 0.5); // 0.05=0.005*10; see MAnalysis::mangnumScoring if (k < 0) k = 0; else if (k >= HISTOSZ) k = HISTOSZ - 1; histogram[k] += 1; histogramCount++; if(histogramCount==maxHistogramCount) break; } if (histogramCount == maxHistogramCount) break; } //cout << "success" << endl; return true; } //from Comet // Make synthetic decoy spectra to fill out correlation histogram by going // through each candidate peptide and rotating spectra in m/z space. bool MSpectrum::generateXcorrDecoys3(int minP, int maxP, int depth) { //int i; //int n; //int j; //int k; //int maxZ; //int z; //size_t r = 0; //int key; //int pos; //double dBion[3]; //0=N-term, 1=C-term, 2=center //double dYion[3]; //double dXcorr[3]; //double dFragmentIonMass = 0.0; //double oMass; //bool bAdduct; //int ac; //iterate from 0 to maxlen //compute yn; //if n>minlen/2, function(n+1 to n*2,+offset) //if n>minlen, function(b+offset); //compute bn; //if n>minlex, function(y+offset); //function(n + 1 to n * 2, +offset) //function( b+offset, upto n); //compute yn+offset //compute bn; <-this is redundant for all lengths int histoXCount[MAX_DECOY_PEP_LEN]; int histoX[MAX_DECOY_PEP_LEN][HISTOSZ]; for(int a=0;a<MAX_DECOY_PEP_LEN;a++){ histoXCount[a]=0; for(int b=0;b<HISTOSZ;b++){ histoX[a][b]=0; } } //int histoXCount[51]; //int histoX[51][HISTOSZ]; //for (int a = 0; a<51; a++){ // histoXCount[a] = 0; // for (int b = 0; b<HISTOSZ; b++){ // histoX[a][b] = 0; // } //} int decoyIndex=0; double monoMass=bigMonoMass; double ionB,ionY; double dFragmentIonMass; double xcorr,xcorr2B, xcorr2Y; double m; int maxZ=bigZ; if (maxZ>4) maxZ = 4; int key,pos; double xcorrY,xcorrB; for(int x=0;x<depth/3;x++){ //cout << "MonoMass: " << monoMass << endl; decoyIndex=x; xcorrY=0; xcorrB=0; for(int a=0;a<maxP-1;a++){ //the unmodified ions ionB = decoys->decoyIons[decoyIndex].pdIonsN[a]; //cout << "B" << a + 1 << "\t" << ionB << endl; ionY = decoys->decoyIons[decoyIndex].pdIonsC[a]; //cout << "Y" << a+1 << "\t" << ionY << endl; for (int b = 3; b<6; b++) { if (!ionSeries[b]) continue; switch (b) { case 0: dFragmentIonMass = ionB - 27.9949141; break; case 1: dFragmentIonMass = ionB; break; case 2: dFragmentIonMass = ionB + 17.026547; break; case 3: dFragmentIonMass = ionY + 25.9792649; break; case 4: dFragmentIonMass = ionY; break; case 5: dFragmentIonMass = ionY - 16.0187224; break; } //if (dFragmentIonMass>monoMass) continue; for (int z = 1; z<maxZ; z++) { m = (dFragmentIonMass + (z - 1)*1.007276466) / z; m = binSize * (int)(m*invBinSize + binOffset); key = (int)m; if (key >= kojakBins) break; if (key<0 || kojakSparseArray[key] == NULL) continue; pos = (int)((m - key)*invBinSize); //cout << (int)kojakSparseArray[key][pos] << endl; if (b<3) xcorrB += kojakSparseArray[key][pos]; else xcorrY += kojakSparseArray[key][pos]; } } if(a>(minP-3)) { //Modification on N-term double massOffsetB = monoMass - decoys->decoyIons[decoyIndex].pdIonsN[a+1]-17.00273965; //17.00328821; //cout << "Start B: " << massOffsetB << "\t" << xcorrY << endl; xcorr2Y=xcorrY; double massOffsetY = monoMass - decoys->decoyIons[decoyIndex].pdIonsC[a + 1] + 1.00782503; //cout << "Start Y: " << massOffsetY << "\t" << xcorrB << endl; xcorr2B = xcorrB; for (int b = 0; b<6; b++) { if (!ionSeries[b]) continue; switch (b) { case 0: dFragmentIonMass = massOffsetB - 27.9949141; break; case 1: dFragmentIonMass = massOffsetB; break; case 2: dFragmentIonMass = massOffsetB + 17.026547; break; case 3: dFragmentIonMass = massOffsetY - 27.9949141; break; case 4: dFragmentIonMass = massOffsetY; break; case 5: dFragmentIonMass = massOffsetY + 17.026547; break; } if(b<3) xcorr2Y += makeXCorrB(decoyIndex, dFragmentIonMass, maxZ, a); else xcorr2B += makeXCorrY(decoyIndex, dFragmentIonMass, maxZ, a); } //get key //cout << "TotY: " << xcorr2Y << "\t" << a+2 << endl; if (xcorr2Y <= 0.0) xcorr2Y = 0.0; int k = (int)(xcorr2Y * 0.05 + 0.5); // 0.05=0.005*10; see MAnalysis::mangnumScoring if (k < 0) k = 0; else if (k >= HISTOSZ) k = HISTOSZ - 1; histoX[a+2][k]++; //N-terminal open mod histoXCount[a+2]++; //cout << "TotB: " << xcorr2B << "\t" << a + 2 << endl; if (xcorr2B <= 0.0) xcorr2B = 0.0; k = (int)(xcorr2B * 0.05 + 0.5); // 0.05=0.005*10; see MAnalysis::mangnumScoring if (k < 0) k = 0; else if (k >= HISTOSZ) k = HISTOSZ - 1; histoX[a + 2][k]++; //N-terminal open mod histoXCount[a + 2]++; } //Middle mod - for all peptides if(a>=(minP-2)/2 && a<=(maxP-2)/2){ xcorr=xcorrB+xcorrY; double massOffsetB = monoMass - decoys->decoyIons[decoyIndex].pdIonsN[a*2 + 1] - 17.00273965; double massOffsetY = monoMass - decoys->decoyIons[decoyIndex].pdIonsC[a*2 + 1] + 1.00782503; for (int b = 0; b<6; b++) { if (!ionSeries[b]) continue; switch (b) { case 0: dFragmentIonMass = massOffsetB - 27.9949141; break; case 1: dFragmentIonMass = massOffsetB; break; case 2: dFragmentIonMass = massOffsetB + 17.026547; break; case 3: dFragmentIonMass = massOffsetY - 27.9949141; break; case 4: dFragmentIonMass = massOffsetY; break; case 5: dFragmentIonMass = massOffsetY + 17.026547; break; } if (b<3) xcorr += makeXCorrB(decoyIndex, dFragmentIonMass, maxZ, a*2,a+1); else xcorr += makeXCorrY(decoyIndex, dFragmentIonMass, maxZ, a*2,a+1); } //cout << "TotM: " << xcorr << "\t" << a*2 + 2 << endl; if (xcorr <= 0.0) xcorr = 0.0; int k = (int)(xcorr * 0.05 + 0.5); // 0.05=0.005*10; see MAnalysis::mangnumScoring if (k < 0) k = 0; else if (k >= HISTOSZ) k = HISTOSZ - 1; histoX[a*2 + 2][k]++; //N-terminal open mod histoXCount[a*2 + 2]++; if((a*2+1)<maxP-1){ xcorr = xcorrB + xcorrY; double massOffsetB = monoMass - decoys->decoyIons[decoyIndex].pdIonsN[a * 2 + 2] - 17.00273965; double massOffsetY = monoMass - decoys->decoyIons[decoyIndex].pdIonsC[a * 2 + 2] + 1.00782503; for (int b = 0; b<6; b++) { if (!ionSeries[b]) continue; switch (b) { case 0: dFragmentIonMass = massOffsetB - 27.9949141; break; case 1: dFragmentIonMass = massOffsetB; break; case 2: dFragmentIonMass = massOffsetB + 17.026547; break; case 3: dFragmentIonMass = massOffsetY - 27.9949141; break; case 4: dFragmentIonMass = massOffsetY; break; case 5: dFragmentIonMass = massOffsetY + 17.026547; break; } if (b<3) xcorr += makeXCorrB(decoyIndex, dFragmentIonMass, maxZ, a * 2+1, a+1); else xcorr += makeXCorrY(decoyIndex, dFragmentIonMass, maxZ, a * 2+1, a+1); } //cout << "TotM: " << xcorr << "\t" << a * 2 + 3 << endl; if (xcorr <= 0.0) xcorr = 0.0; int k = (int)(xcorr * 0.05 + 0.5); // 0.05=0.005*10; see MAnalysis::mangnumScoring if (k < 0) k = 0; else if (k >= HISTOSZ) k = HISTOSZ - 1; histoX[a * 2 + 3][k]++; //N-terminal open mod histoXCount[a * 2 + 3]++; } } } } for(int a=minP;a<maxP+1;a++){ mHisto[a] = new MHistogram(); linearRegression4(histoX[a],histoXCount[a],mHisto[a]->slope, mHisto[a]->intercept, mHisto[a]->rSq); mHisto[a]->slope *= 10; //** temporary //cout << "\nDecoy Histogram: " << a << "\t" << histoXCount[a] << endl; //for (int i = 0; i<HISTOSZ; i++) cout << i << "\t" << histoX[a][i] << endl; //cout << mHisto[a]->slope << "\t" << mHisto[a]->intercept << "\t" << mHisto[a]->rSq << endl; //** } return true; } double MSpectrum::makeXCorrB(int decoyIndex, double modMass, int maxZ, int len, int offset){ double xcorr=0; double m; int key; int pos; double b; for(int a=offset;a<len+1;a++){ b = modMass + decoys->decoyIons[decoyIndex].pdIonsN[a]; if(b<0) continue; //if (b>maxMass) break; //stop when fragment ion masses exceed precursor mass //cout << "xb" << a+1 << "\t" << b << endl; for (int z = 1; z<maxZ; z++) { m = (b + (z - 1)*1.007276466) / z; m = binSize * (int)(m*invBinSize + binOffset); key = (int)m; if (key >= kojakBins) break; if (kojakSparseArray[key] == NULL) continue; pos = (int)((m - key)*invBinSize); xcorr += kojakSparseArray[key][pos]; } } //cout << "xB: " << xcorr << endl; return xcorr; } double MSpectrum::makeXCorrY(int decoyIndex, double modMass, int maxZ, int len, int offset){ double xcorr = 0; double m; int key; int pos; double b; for (int a = offset; a<len + 1; a++){ b = modMass + decoys->decoyIons[decoyIndex].pdIonsC[a]; if(b<0) continue; //cout << "xy" << a+1 << "\t" << b << endl; //if (b>maxMass) break; //stop when fragment ion masses exceed precursor mass for (int z = 1; z<maxZ; z++) { m = (b + (z - 1)*1.007276466) / z; m = binSize * (int)(m*invBinSize + binOffset); key = (int)m; if (key >= kojakBins) break; if (kojakSparseArray[key] == NULL) continue; pos = (int)((m - key)*invBinSize); xcorr += kojakSparseArray[key][pos]; } } //cout << "xY: " << xcorr << endl; return xcorr; } //from Comet void MSpectrum::linearRegression(double& slope, double& intercept, int& iMaxXcorr, int& iStartXcorr, int& iNextXcorr) { double Sx, Sxy; // Sum of square distances. double Mx, My; // means double dx, dy; double b, a; double SumX, SumY; // Sum of X and Y values to calculate mean. double dCummulative[HISTOSZ]; // Cummulative frequency at each xcorr value. int i; int iNextCorr; // 2nd best xcorr index int iMaxCorr = 0; // max xcorr index int iStartCorr; int iNumPoints; // Find maximum correlation score index. for (i = HISTOSZ- 2; i >= 0; i--) { if (histogram[i] > 0) break; } iMaxCorr = i; iNextCorr = 0; for (i = 0; i<iMaxCorr; i++) { if (histogram[i] == 0) { // register iNextCorr if there's a histo value of 0 consecutively if (histogram[i + 1] == 0 || i + 1 == iMaxCorr) { if (i>0) iNextCorr = i - 1; break; } } } if (i == iMaxCorr) { iNextCorr = iMaxCorr; if (iMaxCorr>12) iNextCorr = iMaxCorr - 2; } // Create cummulative distribution function from iNextCorr down, skipping the outliers. dCummulative[iNextCorr] = histogram[iNextCorr]; for (i = iNextCorr - 1; i >= 0; i--) { dCummulative[i] = dCummulative[i + 1] + histogram[i]; if (histogram[i + 1] == 0) dCummulative[i + 1] = 0.0; } // log10 for (i = iNextCorr; i >= 0; i--) { histogram[i] = (int)dCummulative[i]; // First store cummulative in histogram. dCummulative[i] = log10(dCummulative[i]); } iStartCorr = 0; if (iNextCorr >= 30) iStartCorr = (int)(iNextCorr - iNextCorr*0.25); else if (iNextCorr >= 15) iStartCorr = (int)(iNextCorr - iNextCorr*0.5); Mx = My = a = b = 0.0; while (iStartCorr >= 0) { Sx = Sxy = SumX = SumY = 0.0; iNumPoints = 0; // Calculate means. for (i = iStartCorr; i <= iNextCorr; i++) { if (histogram[i] > 0) { SumY += (float)dCummulative[i]; SumX += i; iNumPoints++; } } if (iNumPoints > 0) { Mx = SumX / iNumPoints; My = SumY / iNumPoints; } else { Mx = My = 0.0; } // Calculate sum of squares. for (i = iStartCorr; i <= iNextCorr; i++) { if (dCummulative[i] > 0) { dx = i - Mx; dy = dCummulative[i] - My; Sx += dx*dx; Sxy += dx*dy; } } if (Sx > 0) b = Sxy / Sx; // slope else b = 0; if (b < 0.0) break; else iStartCorr--; } a = My - b*Mx; // y-intercept slope = b; intercept = a; iMaxXcorr = iMaxCorr; iStartXcorr = iStartCorr; iNextXcorr = iNextCorr; } void MSpectrum::linearRegression2(double& slope, double& intercept, int& iMaxXcorr, int& iStartXcorr, int& iNextXcorr, double& rSquared) { double Sx, Sxy; // Sum of square distances. double Mx, My; // means double dx, dy; double b, a; double SumX, SumY; // Sum of X and Y values to calculate mean. double SST, SSR; double rsq; double bestRSQ; double bestSlope; double bestInt; double dCummulative[HISTOSZ]; // Cummulative frequency at each xcorr value. int i; int bestNC; int bestStart; int iNextCorr; // 2nd best xcorr index int iMaxCorr = 0; // max xcorr index int iStartCorr; int iNumPoints; // Find maximum correlation score index. for (i = HISTOSZ - 2; i >= 0; i--) { if (histogram[i] > 0) break; } iMaxCorr = i; //bail now if there is no width to the distribution if (iMaxCorr<3) { slope = 0; intercept = 0; iMaxXcorr = 0; iStartXcorr = 0; iNextXcorr = 0; rSquared = 0; return; } //More aggressive version summing everything below the max dCummulative[iMaxCorr - 1] = histogram[iMaxCorr - 1]; for (i = iMaxCorr - 2; i >= 0; i--) { dCummulative[i] = dCummulative[i + 1] + histogram[i]; } //get middle-ish datapoint as seed. Using count/10. for (i = 0; i<iMaxCorr; i++){ if (dCummulative[i] < histogramCount / 10) break; } if (i >= (iMaxCorr - 1)) iNextCorr = iMaxCorr - 2; else iNextCorr = i; // log10...and stomp all over the original...hard to troubleshoot later for (i = iMaxCorr - 1; i >= 0; i--) { histogram[i] = (int)dCummulative[i]; if(dCummulative[i]>0) dCummulative[i] = log10(dCummulative[i]); } iStartCorr = iNextCorr - 1; iNextCorr++; bool bRight = false; // which direction to add datapoint from bestRSQ = 0; bestNC = 0; bestSlope = 0; bestInt = 0; rsq = Mx = My = a = b = 0.0; while (true) { Sx = Sxy = SumX = SumY = 0.0; iNumPoints = 0; // Calculate means. for (i = iStartCorr; i <= iNextCorr; i++) { if (histogram[i] > 0) { SumY += dCummulative[i]; SumX += i; iNumPoints++; } } if (iNumPoints > 0) { Mx = SumX / iNumPoints; My = SumY / iNumPoints; } else { Mx = My = 0.0; } // Calculate sum of squares. SST = 0; for (i = iStartCorr; i <= iNextCorr; i++) { dx = i - Mx; dy = dCummulative[i] - My; Sx += dx*dx; Sxy += dx*dy; SST += dy*dy; } b = Sxy / Sx; a = My - b*Mx; // y-intercept //MH: compute R2 SSR = 0; for (i = iStartCorr; i <= iNextCorr; i++) { dy = dCummulative[i] - (b*i + a); SSR += (dy*dy); } rsq = 1 - SSR / SST; if (rsq>0.95 || rsq>bestRSQ){ if (rsq>bestRSQ || iNextCorr - iStartCorr + 1<8){ //keep better RSQ only if more than 8 datapoints, otherwise keep every RSQ below 8 datapoints bestRSQ = rsq; bestNC = iNextCorr; bestSlope = b; bestInt = a; bestStart = iStartCorr; } if (bRight){ if (iNextCorr<(iMaxCorr - 1) && dCummulative[iNextCorr]>0) iNextCorr++; else if (iStartCorr>0) iStartCorr--; else break; } else { if (iStartCorr>0) iStartCorr--; else if (iNextCorr<(iMaxCorr - 1) && dCummulative[iNextCorr]>0) iNextCorr++; else break; } bRight = !bRight; } else { break; } } slope = bestSlope; intercept = bestInt; iMaxXcorr = iMaxCorr; iStartXcorr = bestStart; iNextXcorr = bestNC; rSquared = bestRSQ; } void MSpectrum::linearRegression3(double& slope, double& intercept, double& rSquared) { double Sx, Sxy; // Sum of square distances. double Mx, My; // means double dx, dy; double b, a; double SumX, SumY; // Sum of X and Y values to calculate mean. double SST, SSR; double rsq; double bestRSQ; double bestSlope; double bestInt; double dCummulative[HISTOSZ]; // Cummulative frequency at each xcorr value. int i; int iNextCorr; // 2nd best xcorr index int iMaxCorr = 0; // max xcorr index int iStartCorr; int iNumPoints; //cout << "x " << histogramCount << endl; //for(i=0;i<HISTOSZ;i++) cout << "x " << i << "\t" << histogram[i] << endl; // Find maximum correlation score index. for (i = HISTOSZ - 2; i >= 0; i--) { if (histogram[i] > 0) break; } iMaxCorr = i; //bail now if there is no width to the distribution if (iMaxCorr<2) { slope = 0; intercept = 0; rSquared = 0; return; } //More aggressive version summing everything dCummulative[iMaxCorr] = histogram[iMaxCorr]; for (i = iMaxCorr - 1; i >= 0; i--) { dCummulative[i] = dCummulative[i + 1] + histogram[i]; } //get middle-ish datapoint as seed. Using count/10. for (i = 0; i<iMaxCorr; i++){ if (dCummulative[i] < histogramCount / 10) break; } if (i >= (iMaxCorr)) iNextCorr = iMaxCorr - 1; else iNextCorr = i; // log10...and stomp all over the original...hard to troubleshoot later for (i = iMaxCorr; i >= 0; i--) { histogram[i] = (int)dCummulative[i]; if (dCummulative[i]>0) dCummulative[i] = log10(dCummulative[i]); } iStartCorr = iNextCorr - 1; iNextCorr++; bool bRight = false; // which direction to add datapoint from bestRSQ = 0; bestSlope = 0; bestInt = 0; rsq = Mx = My = a = b = 0.0; while (true) { Sx = Sxy = SumX = SumY = 0.0; iNumPoints = 0; // Calculate means. for (i = iStartCorr; i <= iNextCorr; i++) { if (histogram[i] > 0) { SumY += dCummulative[i]; SumX += i; iNumPoints++; } } if (iNumPoints > 0) { Mx = SumX / iNumPoints; My = SumY / iNumPoints; } else { Mx = My = 0.0; } // Calculate sum of squares. SST = 0; for (i = iStartCorr; i <= iNextCorr; i++) { dx = i - Mx; dy = dCummulative[i] - My; Sx += dx*dx; Sxy += dx*dy; SST += dy*dy; } b = Sxy / Sx; a = My - b*Mx; // y-intercept //MH: compute R2 SSR = 0; for (i = iStartCorr; i <= iNextCorr; i++) { dy = dCummulative[i] - (b*i + a); SSR += (dy*dy); } rsq = 1 - SSR / SST; if (rsq>0.95 || rsq>bestRSQ){ if (rsq>bestRSQ || iNextCorr - iStartCorr + 1<8){ //keep better RSQ only if more than 8 datapoints, otherwise keep every RSQ below 8 datapoints bestRSQ = rsq; bestSlope = b; bestInt = a; } if (bRight){ if (iNextCorr<iMaxCorr && dCummulative[iNextCorr]>0) iNextCorr++; else if (iStartCorr>0) iStartCorr--; else break; } else { if (iStartCorr>0) iStartCorr--; else if (iNextCorr<iMaxCorr && dCummulative[iNextCorr]>0) iNextCorr++; else break; } bRight = !bRight; } else { break; } } slope = bestSlope; intercept = bestInt; rSquared = bestRSQ; } void MSpectrum::linearRegression4(int* h, int sz, double& slope, double& intercept, double& rSquared) { double Sx, Sxy; // Sum of square distances. double Mx, My; // means double dx, dy; double b, a; double SumX, SumY; // Sum of X and Y values to calculate mean. double SST, SSR; double rsq; double bestRSQ; double bestSlope; double bestInt; double dCummulative[HISTOSZ]; // Cummulative frequency at each xcorr value. int i; int iNextCorr; // 2nd best xcorr index int iMaxCorr = 0; // max xcorr index int iStartCorr; int iNumPoints; //cout << "x " << histogramCount << endl; //for(i=0;i<HISTOSZ;i++) cout << "x " << i << "\t" << histogram[i] << endl; // Find maximum correlation score index. for (i = HISTOSZ - 2; i >= 0; i--) { if (h[i] > 0) break; } iMaxCorr = i; //bail now if there is no width to the distribution if (iMaxCorr<2) { slope = 0; intercept = 0; rSquared = 0; return; } //More aggressive version summing everything dCummulative[iMaxCorr] = h[iMaxCorr]; for (i = iMaxCorr - 1; i >= 0; i--) { dCummulative[i] = dCummulative[i + 1] + h[i]; } //get middle-ish datapoint as seed. Using count/10. for (i = 0; i<iMaxCorr; i++){ if (dCummulative[i] < sz / 10) break; } if (i >= (iMaxCorr)) iNextCorr = iMaxCorr - 1; else iNextCorr = i; // log10...and stomp all over the original...hard to troubleshoot later for (i = iMaxCorr; i >= 0; i--) { h[i] = (int)dCummulative[i]; if (dCummulative[i]>0) dCummulative[i] = log10(dCummulative[i]); } iStartCorr = iNextCorr - 1; iNextCorr++; bool bRight = false; // which direction to add datapoint from bestRSQ = 0; bestSlope = 0; bestInt = 0; rsq = Mx = My = a = b = 0.0; while (true) { Sx = Sxy = SumX = SumY = 0.0; iNumPoints = 0; // Calculate means. for (i = iStartCorr; i <= iNextCorr; i++) { if (h[i] > 0) { SumY += dCummulative[i]; SumX += i; iNumPoints++; } } if (iNumPoints > 0) { Mx = SumX / iNumPoints; My = SumY / iNumPoints; } else { Mx = My = 0.0; } // Calculate sum of squares. SST = 0; for (i = iStartCorr; i <= iNextCorr; i++) { dx = i - Mx; dy = dCummulative[i] - My; Sx += dx*dx; Sxy += dx*dy; SST += dy*dy; } b = Sxy / Sx; a = My - b*Mx; // y-intercept //MH: compute R2 SSR = 0; for (i = iStartCorr; i <= iNextCorr; i++) { dy = dCummulative[i] - (b*i + a); SSR += (dy*dy); } rsq = 1 - SSR / SST; if (rsq>0.95 || rsq>bestRSQ){ if (rsq>bestRSQ || iNextCorr - iStartCorr + 1<8){ //keep better RSQ only if more than 8 datapoints, otherwise keep every RSQ below 8 datapoints bestRSQ = rsq; bestSlope = b; bestInt = a; } if (bRight){ if (iNextCorr<iMaxCorr && dCummulative[iNextCorr]>0) iNextCorr++; else if (iStartCorr>0) iStartCorr--; else break; } else { if (iStartCorr>0) iStartCorr--; else if (iNextCorr<iMaxCorr && dCummulative[iNextCorr]>0) iNextCorr++; else break; } bRight = !bRight; } else { break; } } slope = bestSlope; intercept = bestInt; rSquared = bestRSQ; } void MSpectrum::shortResults(std::vector<mScoreCard2>& v){ //cout << "shortResults: "; v.clear(); int count=0; int scoreIndex=0; mScoreCard tmpSC = getScoreCard(scoreIndex); //iterate over all results while(tmpSC.simpleScore>0){ count++; //check if this peptide seen in another configuration size_t a; for(a=0;a<v.size();a++){ if(v[a].eVal==tmpSC.eVal && v[a].simpleScore==tmpSC.simpleScore && v[a].pep==tmpSC.pep && v[a].mods.size()==tmpSC.mods->size()){ //size_t b; //for(b=0;b<v[a].mods.size();b++){ // if(v[a].mods[b].mass!=tmpSC.mods->at(b).mass) break; // if (v[a].mods[b].pos != tmpSC.mods->at(b).pos) break; // if (v[a].mods[b].term != tmpSC.mods->at(b).term) break; //} //if(b==v[a].mods.size()){ //identical peptides size_t b; for(b=0;b<v[a].sites.size();b++){ if(tmpSC.site==v[a].sites[b]) break; } if(b==v[a].sites.size()) v[a].sites.push_back(tmpSC.site); /*} else { mScoreCard2 sc; sc.conFrag=tmpSC.conFrag; sc.eVal=tmpSC.eVal; sc.mass=tmpSC.mass; sc.massA=tmpSC.massA; sc.match=tmpSC.match; sc.pep=tmpSC.pep; sc.precursor=tmpSC.precursor; sc.simpleScore=tmpSC.simpleScore; sc.sites.push_back(tmpSC.site); for(size_t c=0; c<tmpSC.mods->size();c++) sc.mods.push_back(tmpSC.mods->at(c)); v.push_back(sc); }*/ break; } } //add unique results if (a==v.size()){ mScoreCard2 sc; sc.conFrag = tmpSC.conFrag; sc.eVal = tmpSC.eVal; sc.mass = tmpSC.mass; sc.massA = tmpSC.massA; sc.match = tmpSC.match; sc.pep = tmpSC.pep; sc.precursor = tmpSC.precursor; sc.simpleScore = tmpSC.simpleScore; sc.sites.push_back(tmpSC.site); for (size_t c = 0; c<tmpSC.mods->size(); c++) sc.mods.push_back(tmpSC.mods->at(c)); v.push_back(sc); } if(++scoreIndex<20) tmpSC = getScoreCard(scoreIndex); else break; } //cout << count << endl; } void MSpectrum::shortResults2(std::vector<mScoreCard3>& v){ //cout << "shortResults: "; v.clear(); int count = 0; int scoreIndex = 0; mScoreCard tmpSC = getScoreCard(scoreIndex); //iterate over all results while (tmpSC.simpleScore>0){ count++; //check if this peptide seen in another configuration size_t a; for (a = 0; a<v.size(); a++){ if (v[a].eVal == tmpSC.eVal && v[a].simpleScore == tmpSC.simpleScore && v[a].pep == tmpSC.pep && v[a].modCount == (int)tmpSC.mods->size()){ //alternate version of existing peptide, so append the novel mod positions mPepMod2 pm; for (size_t c = 0; c<tmpSC.mods->size(); c++) { pm.mods.push_back(tmpSC.mods->at(c)); } v[a].mSet.push_back(pm); v[a].aSites.push_back(tmpSC.site); break; } } //add unique results if (a == v.size()){ mScoreCard3 sc; sc.conFrag = tmpSC.conFrag; sc.eVal = tmpSC.eVal; sc.mass = tmpSC.mass; sc.massA = tmpSC.massA; sc.match = tmpSC.match; sc.pep = tmpSC.pep; sc.precursor = tmpSC.precursor; sc.simpleScore = tmpSC.simpleScore; sc.modCount=(int)tmpSC.mods->size(); sc.aSites.push_back(tmpSC.site); mPepMod2 pm; for (size_t c = 0; c<tmpSC.mods->size(); c++) { pm.mods.push_back(tmpSC.mods->at(c)); } sc.mSet.push_back(pm); v.push_back(sc); } if (++scoreIndex<20) tmpSC = getScoreCard(scoreIndex); else break; } } //void MSpectrum::makeXCorrB(int index, double massOffset, double maxMass, int maxZ, int maxIon){ // double xcorr=0; // double ion; // double m; // int key,pos; // // for (int a = 0; a<maxIon; a++) { // iterate through required # of ions // ion = decoys->decoyIons[index].pdIonsN[a]+massOffset; // if (ion>maxMass) break; //stop when fragment ion masses exceed precursor mass // // for (int z = 1; z<maxZ; z++) { // m = (ion + (z - 1)*1.007276466) / z; // m = binSize * (int)(m*invBinSize + binOffset); // key = (int)m; // if (key >= kojakBins) break; // if (kojakSparseArray[key] == NULL) continue; // pos = (int)((m - key)*invBinSize); // xcorr += kojakSparseArray[key][pos]; // } // } // // // // //iterate from 0 to maxlen // //compute yn; // //if n>minlen/2, function(n+1 to n*2,+offset) // //if n>minlen, function(b+offset); // //compute bn; // //if n>minlex, function(y+offset); // // //function(n + 1 to n * 2, +offset) // //function( b+offset, upto n); // //compute yn+offset // //compute bn; <-this is redundant for all lengths //} /*============================ Utilities ============================*/ int MSpectrum::compareIntensity(const void *p1, const void *p2){ const mSpecPoint d1 = *(mSpecPoint *)p1; const mSpecPoint d2 = *(mSpecPoint *)p2; if(d1.intensity<d2.intensity) return -1; else if(d1.intensity>d2.intensity) return 1; else return 0; } int MSpectrum::compareMZ(const void *p1, const void *p2){ const mSpecPoint d1 = *(mSpecPoint *)p1; const mSpecPoint d2 = *(mSpecPoint *)p2; if(d1.mass<d2.mass) return -1; else if(d1.mass>d2.mass) return 1; else return 0; } //** temporary //void MSpectrum::tHistogram(double score, int len){ // int k = (int)(score * 10 + 0.5); // if (k < 0) k = 0; // else if (k >= HISTOSZ) k = HISTOSZ - 1; // hX[len][k] += 1; // hXCount[len]++; //} // //void MSpectrum::exportHisto(){ // // for(int k=10;k<30;k++){ // for (int j = 0; j<HISTOSZ; j++) histogram[j] = hX[k][j]; // histogramCount = hXCount[k]; // // MHistogram mHistoX; // linearRegression3(mHistoX.slope, mHistoX.intercept, mHistoX.rSq); // cout << "\nReal Histogram: " << k << "\t" << histogramCount << endl; // for (int i = 0; i<HISTOSZ; i++) cout << i << "\t" << histogram[i] << endl; // cout << mHistoX.slope << "\t" << mHistoX.intercept << "\t" << mHistoX.rSq << endl;; // } //} //**
28.118427
157
0.589525
[ "vector" ]
6ed89d65225258c231d22eac778a10e5e69feefd
4,373
cc
C++
apps/obs_history/create_obs_history.cc
OSADP/Pikalert-Vehicle-Data-Translator-
295da604408f6f13af0301b55476a81311459386
[ "Apache-2.0" ]
2
2020-06-03T15:59:50.000Z
2020-12-21T11:11:57.000Z
apps/obs_history/create_obs_history.cc
OSADP/Pikalert-Vehicle-Data-Translator-
295da604408f6f13af0301b55476a81311459386
[ "Apache-2.0" ]
null
null
null
apps/obs_history/create_obs_history.cc
OSADP/Pikalert-Vehicle-Data-Translator-
295da604408f6f13af0301b55476a81311459386
[ "Apache-2.0" ]
2
2019-10-02T06:47:23.000Z
2020-02-02T18:32:23.000Z
// *=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* // ** Copyright UCAR (c) 1992 - 2015 // ** University Corporation for Atmospheric Research(UCAR) // ** National Center for Atmospheric Research(NCAR) // ** Research Applications Laboratory(RAL) // ** P.O.Box 3000, Boulder, Colorado, 80307-3000, USA // ** See LICENCE.TXT if applicable for licence details // ** 2015/02/02 20:22:27 // *=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* #include <math.h> #include <iostream> #include <vector> #include <string.h> #include <nxncf/nxncf.hh> #include <log/log.hh> #include "obs_history.h" extern Log *logfile; int create_obs_history(int num_out_times, char *output_file_name, char *cdl_file_name, ds *data) { int i, ret; char var_name[80]; long *dim = new long[2]; // Create output netcdf file ret = NCF_cdl2nc(cdl_file_name, output_file_name); if (ret != 0) { logfile->write_time("Error: Unable to generate output file %s\n", output_file_name); return (-1); } /* open netcdf file for writing */ NcFile output_file(output_file_name, NcFile::Write); if (!output_file.is_valid()) { logfile->write_time("Error: Unable to open output file %s\n",output_file_name); return (-1); } // Write creation time ret = NXNCF_write_creation_time(output_file); if (ret < 0) { logfile->write_time("Error: Could not put creation time\n"); return (-1); } // Write obs_time strcpy(var_name, "obs_time"); if ((NCF_put_var(&output_file, var_name, &data->obs_time, dim)) < 0) { logfile->write_time("Error: Unable to write data for variable %s\n", var_name); return (-1); } // Write num_sites strcpy(var_name, "num_sites"); if ((NCF_put_var(&output_file, var_name, &data->num_sites, dim)) < 0) { logfile->write_time("Error: Unable to write data for variable %s\n", var_name); return (-1); } // Write station id's dim[0] = data->num_sites; dim[1] = 0; strcpy(var_name, "site_list"); if ((NCF_put_var(&output_file, var_name, data->dicast_id, dim)) < 0) { logfile->write_time("Error: Unable to write data for variable %s\n", var_name); return (-1); } /****************************************************/ // Store the met data - hourly data first /****************************************************/ // T strcpy(var_name, "T"); dim[1] = num_out_times; if ((NCF_put_var(&output_file, var_name, data->T, dim)) < 0) { logfile->write_time("Error: Unable to write data for variable %s\n", var_name); return (-1); } // dewpt strcpy(var_name, "dewpt"); if ((NCF_put_var(&output_file, var_name, data->dewpt, dim)) < 0) { logfile->write_time("Error: Unable to write data for variable %s\n", var_name); return (-1); } // wind_speed strcpy(var_name, "wind_speed"); if ((NCF_put_var(&output_file, var_name, data->wind_speed, dim)) < 0) { logfile->write_time("Error: Unable to write data for variable %s\n", var_name); return (-1); } // Precip strcpy(var_name, "Precip"); if ((NCF_put_var(&output_file, var_name, data->Precip, dim)) < 0) { logfile->write_time("Error: Unable to write data for variable %s\n", var_name); return (-1); } // road_T strcpy(var_name, "road_T"); if ((NCF_put_var(&output_file, var_name, data->road_T, dim)) < 0) { logfile->write_time("Error: Unable to write data for variable %s\n", var_name); return (-1); } // bridge_T strcpy(var_name, "bridge_T"); if ((NCF_put_var(&output_file, var_name, data->bridge_T, dim)) < 0) { logfile->write_time("Error: Unable to write data for variable %s\n", var_name); return (-1); } // road_condition strcpy(var_name, "road_condition"); if ((NCF_put_var(&output_file, var_name, data->road_condition, dim)) < 0) { logfile->write_time("Error: Unable to write data for variable %s\n", var_name); return (-1); } // subsurface_T strcpy(var_name, "subsurface_T"); if ((NCF_put_var(&output_file, var_name, data->subsurface_T, dim)) < 0) { logfile->write_time("Error: Unable to write data for variable %s\n", var_name); return (-1); } logfile->write_time(1, "Info: Wrote %d sites to %s\n", data->num_sites, output_file_name); return (0); }
28.960265
96
0.604162
[ "vector" ]
6edc32eac03df93f46e23241944c0fbaafe8804e
4,594
hpp
C++
service/src/ServiceIOGroup.hpp
avilcheslopez/geopm
35ad0af3f17f42baa009c97ed45eca24333daf33
[ "MIT", "BSD-3-Clause" ]
null
null
null
service/src/ServiceIOGroup.hpp
avilcheslopez/geopm
35ad0af3f17f42baa009c97ed45eca24333daf33
[ "MIT", "BSD-3-Clause" ]
null
null
null
service/src/ServiceIOGroup.hpp
avilcheslopez/geopm
35ad0af3f17f42baa009c97ed45eca24333daf33
[ "MIT", "BSD-3-Clause" ]
null
null
null
/* * Copyright (c) 2015 - 2022, Intel Corporation * SPDX-License-Identifier: BSD-3-Clause */ #ifndef SERVICEIOGROUP_HPP_INCLUDE #define SERVICEIOGROUP_HPP_INCLUDE #include <map> #include "geopm/IOGroup.hpp" struct geopm_request_s; namespace geopm { class PlatformTopo; class ServiceProxy; class BatchClient; struct signal_info_s; struct control_info_s; /// @brief IOGroup that uses DBus interface to access geopmd /// provided signals and controls. This IOGroup is not /// loaded by a server side PlatformIO object. class ServiceIOGroup : public IOGroup { public: ServiceIOGroup(); ServiceIOGroup(const PlatformTopo &platform_topo, std::shared_ptr<ServiceProxy> service_proxy, std::shared_ptr<BatchClient> batch_client_mock); virtual ~ServiceIOGroup(); std::set<std::string> signal_names(void) const override; std::set<std::string> control_names(void) const override; bool is_valid_signal(const std::string &signal_name) const override; bool is_valid_control(const std::string &control_name) const override; int signal_domain_type(const std::string &signal_name) const override; int control_domain_type(const std::string &control_name) const override; int push_signal(const std::string &signal_name, int domain_type, int domain_idx) override; int push_control(const std::string &control_name, int domain_type, int domain_idx) override; void read_batch(void) override; void write_batch(void) override; double sample(int sample_idx) override; void adjust(int control_idx, double setting) override; double read_signal(const std::string &signal_name, int domain_type, int domain_idx) override; void write_control(const std::string &control_name, int domain_type, int domain_idx, double setting) override; // NOTE: This IOGroup will not directlly implement a // save/restore since it is a proxy. Creating this // IOGroup will start a session with the service, // and save and restore will be managed by the // geopmd service for every session that is opened. void save_control(void) override; void restore_control(void) override; std::function<double(const std::vector<double> &)> agg_function(const std::string &signal_name) const override; std::function<std::string(double)> format_function(const std::string &signal_name) const override; std::string signal_description(const std::string &signal_name) const override; std::string control_description(const std::string &control_name) const override; int signal_behavior(const std::string &signal_name) const override; void save_control(const std::string &save_path) override; void restore_control(const std::string &save_path) override; std::string name(void) const override; static std::string plugin_name(void); static std::unique_ptr<IOGroup> make_plugin(void); private: void init_batch_server(void); static const std::string M_PLUGIN_NAME; static std::map<std::string, signal_info_s> service_signal_info(std::shared_ptr<ServiceProxy> service_proxy); static std::map<std::string, control_info_s> service_control_info(std::shared_ptr<ServiceProxy> service_proxy); static std::string strip_plugin_name(const std::string &name); const PlatformTopo &m_platform_topo; std::shared_ptr<ServiceProxy> m_service_proxy; std::map<std::string, signal_info_s> m_signal_info; std::map<std::string, control_info_s> m_control_info; std::vector<geopm_request_s> m_signal_requests; std::vector<geopm_request_s> m_control_requests; std::shared_ptr<BatchClient> m_batch_client; std::vector<double> m_batch_samples; std::vector<double> m_batch_settings; int m_session_pid; bool m_is_batch_active; }; } #endif
47.854167
123
0.622769
[ "object", "vector" ]
6eefd3c0c869a2b3c6d7b9d037c133765aa8ba56
21,580
cpp
C++
src/crtl/compiler/ast_builder_visitor.cpp
Twinklebear/ChameleonRT-lang
578679e315018546b0e6f303090c3641cac8ea20
[ "MIT" ]
11
2021-12-31T19:32:24.000Z
2022-03-30T09:51:54.000Z
src/crtl/compiler/ast_builder_visitor.cpp
Twinklebear/ChameleonRT-lang
578679e315018546b0e6f303090c3641cac8ea20
[ "MIT" ]
1
2022-03-30T15:08:21.000Z
2022-03-30T16:01:06.000Z
src/crtl/compiler/ast_builder_visitor.cpp
Twinklebear/ChameleonRT-lang
578679e315018546b0e6f303090c3641cac8ea20
[ "MIT" ]
null
null
null
#include "ast_builder_visitor.h" #include "ast/declaration.h" #include "ast/expression.h" #include "ast/statement.h" #include "ast_expr_builder_visitor.h" #include "error_listener.h" namespace crtl { using namespace ast; std::any ASTBuilderVisitor::visitTopLevelDeclaration( crtg::ChameleonRTParser::TopLevelDeclarationContext *ctx) { std::shared_ptr<Node> n; auto child = visitChildren(ctx); if (child.has_value()) { // A bit of a pain, but there's a limited number of types of top-level declarations // we can have so do this cast up to the generic Node type here if (child.type() == typeid(std::shared_ptr<decl::EntryPoint>)) { n = std::any_cast<std::shared_ptr<decl::EntryPoint>>(child); } else if (child.type() == typeid(std::shared_ptr<decl::Function>)) { n = std::any_cast<std::shared_ptr<decl::Function>>(child); } else if (child.type() == typeid(std::shared_ptr<decl::Struct>)) { n = std::any_cast<std::shared_ptr<decl::Struct>>(child); } else if (child.type() == typeid(std::shared_ptr<stmt::VariableDeclaration>)) { n = std::any_cast<std::shared_ptr<stmt::VariableDeclaration>>(child); } else if (child.type() == typeid(std::shared_ptr<decl::GlobalParam>)) { n = std::any_cast<std::shared_ptr<decl::GlobalParam>>(child); } } if (n) { ast->top_level_decls.push_back(n); } else { // report_error(ctx->getStart(), "Unhandled/unrecognized top level declaration!"); report_warning(ctx->getStart(), "Unhandled/unrecognized top level declaration! TODO make error later"); } return std::any(); } std::any ASTBuilderVisitor::visitFunctionDecl( crtg::ChameleonRTParser::FunctionDeclContext *ctx) { antlr4::Token *token = ctx->IDENTIFIER()->getSymbol(); std::string name = ctx->IDENTIFIER()->getText(); std::vector<std::shared_ptr<decl::Variable>> params; if (ctx->parameterList()) { // TODO: Now that ANTLR4 is using std::any this could change to not return the shared // ptr wrapper anymore params = *std::any_cast<std::shared_ptr<std::vector<std::shared_ptr<decl::Variable>>>>( visitParameterList(ctx->parameterList())); } auto block = std::any_cast<std::shared_ptr<stmt::Block>>(visit(ctx->block())); // Shader entry points just have the entry point type and no return value if (ctx->entryPointType()) { auto entry_pt_type_ctx = ctx->entryPointType(); auto entry_pt_type = ty::EntryPointType::INVALID; if (entry_pt_type_ctx->RAY_GEN()) { entry_pt_type = ty::EntryPointType::RAY_GEN; } else if (entry_pt_type_ctx->CLOSEST_HIT()) { entry_pt_type = ty::EntryPointType::CLOSEST_HIT; } else if (entry_pt_type_ctx->ANY_HIT()) { entry_pt_type = ty::EntryPointType::ANY_HIT; } else if (entry_pt_type_ctx->INTERSECTION()) { entry_pt_type = ty::EntryPointType::INTERSECTION; } else if (entry_pt_type_ctx->MISS()) { entry_pt_type = ty::EntryPointType::MISS; } else if (entry_pt_type_ctx->COMPUTE()) { entry_pt_type = ty::EntryPointType::COMPUTE; } else { report_error(entry_pt_type_ctx->getStart(), "Invalid entry point type " + entry_pt_type_ctx->getText()); return std::any(); } return std::make_shared<decl::EntryPoint>(name, token, params, entry_pt_type, block); } // Regular functions have a return type auto return_type = std::any_cast<std::shared_ptr<ty::Type>>(visitTypeName(ctx->typeName())); return std::make_shared<decl::Function>(name, token, params, block, return_type); } std::any ASTBuilderVisitor::visitStructDecl(crtg::ChameleonRTParser::StructDeclContext *ctx) { const std::string name = ctx->IDENTIFIER()->getText(); std::vector<std::shared_ptr<decl::StructMember>> struct_members; auto struct_member_decls = ctx->structMember(); for (auto &m : struct_member_decls) { struct_members.push_back( std::any_cast<std::shared_ptr<decl::StructMember>>(visitStructMember(m))); } return std::make_shared<decl::Struct>( name, ctx->IDENTIFIER()->getSymbol(), struct_members); } std::any ASTBuilderVisitor::visitStructMember( crtg::ChameleonRTParser::StructMemberContext *ctx) { const std::string name = ctx->IDENTIFIER()->getText(); auto type = std::any_cast<std::shared_ptr<ty::Type>>(visitTypeName(ctx->typeName())); return std::make_shared<decl::StructMember>(name, ctx->IDENTIFIER()->getSymbol(), type); } std::any ASTBuilderVisitor::visitParameterList( crtg::ChameleonRTParser::ParameterListContext *ctx) { // Non trivial/POD types need to be wrapped in a shared ptr to work around std::any // limitations auto parameters = std::make_shared<std::vector<std::shared_ptr<decl::Variable>>>(); auto param_list = ctx->parameter(); for (auto *p : param_list) { auto res = std::any_cast<std::shared_ptr<decl::Variable>>(visitParameter(p)); parameters->push_back(res); } return parameters; } std::any ASTBuilderVisitor::visitParameter(crtg::ChameleonRTParser::ParameterContext *ctx) { antlr4::Token *token = ctx->IDENTIFIER()->getSymbol(); const std::string name = ctx->IDENTIFIER()->getText(); auto type = std::any_cast<std::shared_ptr<ty::Type>>(visitTypeName(ctx->typeName())); type->modifiers = parse_modifiers(token, ctx->modifier()); return std::make_shared<decl::Variable>(name, token, type); } std::any ASTBuilderVisitor::visitBlock(crtg::ChameleonRTParser::BlockContext *ctx) { std::vector<std::shared_ptr<stmt::Statement>> statements; auto ctx_stmts = ctx->statement(); for (auto &s : ctx_stmts) { auto res = visit(s); if (!res.has_value()) { report_warning(s->getStart(), "TODO WILL: Unimplemented statement -> AST mapping"); } else { if (res.type() == typeid(std::shared_ptr<stmt::VariableDeclaration>)) { // varDeclStmt can be in top level and blocks, so it returns itself as its // child type, not the parent Statement class auto var_decl_stmt = std::any_cast<std::shared_ptr<stmt::VariableDeclaration>>(res); statements.push_back( std::dynamic_pointer_cast<stmt::Statement>(var_decl_stmt)); } else if (res.type() == typeid(std::shared_ptr<stmt::Block>)) { // Similar case for block, where it returns as a block instead of a statement // to make some other code a bit easier auto block_stmt = std::any_cast<std::shared_ptr<stmt::Block>>(res); statements.push_back(std::dynamic_pointer_cast<stmt::Statement>(block_stmt)); } else { if (res.type() != typeid(std::shared_ptr<stmt::Statement>)) { report_error( s->getStart(), "Expecting statement for block statements but got non-statement!"); } statements.push_back(std::any_cast<std::shared_ptr<stmt::Statement>>(res)); } } } return std::make_shared<stmt::Block>(ctx->getStart(), statements); } std::any ASTBuilderVisitor::visitVarDecl(crtg::ChameleonRTParser::VarDeclContext *ctx) { antlr4::Token *token = ctx->IDENTIFIER()->getSymbol(); const std::string name = ctx->IDENTIFIER()->getText(); auto type = std::any_cast<std::shared_ptr<ty::Type>>(visitTypeName(ctx->typeName())); if (ctx->CONST()) { type->modifiers.insert(ty::Modifier::CONST); } std::shared_ptr<expr::Expression> initializer; if (ctx->expr()) { // Temporarily filter out unimplemented parts of the AST visitor auto init_res_tmp = visit(ctx->expr()); if (!init_res_tmp.has_value()) { report_warning(ctx->expr()->getStart(), "TODO WILL: Parse initializer expression"); } else { initializer = std::any_cast<std::shared_ptr<expr::Expression>>(init_res_tmp); } } return std::make_shared<decl::Variable>(name, token, type, initializer); } std::any ASTBuilderVisitor::visitVarDeclStmt(crtg::ChameleonRTParser::VarDeclStmtContext *ctx) { auto decl = std::any_cast<std::shared_ptr<decl::Variable>>(visitVarDecl(ctx->varDecl())); return std::make_shared<stmt::VariableDeclaration>(ctx->getStart(), decl); } std::any ASTBuilderVisitor::visitGlobalParamDecl( crtg::ChameleonRTParser::GlobalParamDeclContext *ctx) { antlr4::Token *token = ctx->IDENTIFIER()->getSymbol(); const std::string name = ctx->IDENTIFIER()->getText(); auto type = std::any_cast<std::shared_ptr<ty::Type>>(visitTypeName(ctx->typeName())); if (ctx->CONST()) { type->modifiers.insert(ty::Modifier::CONST); } return std::make_shared<decl::GlobalParam>(name, token, type); } std::any ASTBuilderVisitor::visitIfStmt(crtg::ChameleonRTParser::IfStmtContext *ctx) { auto condition = std::any_cast<std::shared_ptr<expr::Expression>>(visit(ctx->expr())); auto branches = ctx->statement(); // There will always at least be an if branch auto if_branch = std::any_cast<std::shared_ptr<stmt::Statement>>(visit(branches[0])); std::shared_ptr<stmt::Statement> else_branch; if (branches.size() == 2) { else_branch = std::any_cast<std::shared_ptr<stmt::Statement>>(visit(branches[1])); } return std::dynamic_pointer_cast<stmt::Statement>( std::make_shared<stmt::IfElse>(ctx->getStart(), condition, if_branch, else_branch)); } std::any ASTBuilderVisitor::visitWhileStmt(crtg::ChameleonRTParser::WhileStmtContext *ctx) { return std::any(); } std::any ASTBuilderVisitor::visitForStmt(crtg::ChameleonRTParser::ForStmtContext *ctx) { return std::any(); } std::any ASTBuilderVisitor::visitReturnStmt(crtg::ChameleonRTParser::ReturnStmtContext *ctx) { return std::any(); } std::any ASTBuilderVisitor::visitExprStmt(crtg::ChameleonRTParser::ExprStmtContext *ctx) { ASTExprBuilderVisitor expr_visitor; // TODO: Is some error handling needed here for malformed or invalid expressions? // Most errors would be checked for and handled in a later pass (types, etc) auto expr = std::any_cast<std::shared_ptr<expr::Expression>>(expr_visitor.visit(ctx->expr())); return std::dynamic_pointer_cast<stmt::Statement>( std::make_shared<stmt::Expression>(ctx->getStart(), expr)); } std::any ASTBuilderVisitor::visitTypeName(crtg::ChameleonRTParser::TypeNameContext *ctx) { std::vector<std::shared_ptr<ty::Type>> template_parameters; if (ctx->templateParameters()) { // Note: must return shared_ptr wrapper to work around antlrcpp::Any limitation // TODO: Now that ANTLR4 C++ uses std::any this workaround is no longer needed template_parameters = *std::any_cast<std::shared_ptr<std::vector<std::shared_ptr<ty::Type>>>>( visitTemplateParameters(ctx->templateParameters())); } if (template_parameters.size() > 1) { // TODO: Haven't implemented template struct parsing/mapping in AST report_error(ctx->templateParameters()->getStart(), "Error: Unsupported number of template parameters"); return std::any(); } if (ctx->IDENTIFIER()) { // TODO: template structs if (!template_parameters.empty()) { report_error(ctx->templateParameters()->getStart(), "Error TODO: template structs"); } // TODO: Here it would be good to re-use type's we've already allocated so that it's // easier to see two structs have the same type. return std::dynamic_pointer_cast<ty::Type>( std::make_shared<ty::Struct>(ctx->IDENTIFIER()->getText())); } if (ctx->TEXTURE()) { const std::string dimensionality_str = ctx->TEXTURE()->getText().substr(7, 1); const size_t dimensionality = std::stoi(dimensionality_str); if (template_parameters[0]->base_type != ty::BaseType::PRIMITIVE && template_parameters[0]->base_type != ty::BaseType::VECTOR) { report_error(ctx->TEXTURE()->getSymbol(), "Invalid type parameter for Texture: '" + template_parameters[0]->to_string() + "', texture types must be primitive or vector types"); } return std::dynamic_pointer_cast<ty::Type>(std::make_shared<ty::Texture>( template_parameters[0], ty::Access::READ_ONLY, dimensionality)); } if (ctx->RWTEXTURE()) { const std::string dimensionality_str = ctx->RWTEXTURE()->getText().substr(9, 1); const size_t dimensionality = std::stoi(dimensionality_str); if (template_parameters[0]->base_type != ty::BaseType::PRIMITIVE && template_parameters[0]->base_type != ty::BaseType::VECTOR) { report_error(ctx->TEXTURE()->getSymbol(), "Invalid type parameter for RWTexture: '" + template_parameters[0]->to_string() + "', texture types must be primitive or vector types"); } return std::dynamic_pointer_cast<ty::Type>(std::make_shared<ty::Texture>( template_parameters[0], ty::Access::READ_WRITE, dimensionality)); } if (ctx->BUFFER()) { return std::dynamic_pointer_cast<ty::Type>( std::make_shared<ty::Buffer>(template_parameters[0], ty::Access::READ_ONLY)); } if (ctx->RWBUFFER()) { return std::dynamic_pointer_cast<ty::Type>( std::make_shared<ty::Buffer>(template_parameters[0], ty::Access::READ_WRITE)); } if (ctx->ACCELERATION_STRUCTURE()) { return std::dynamic_pointer_cast<ty::Type>( std::make_shared<ty::AccelerationStructure>()); } if (ctx->RAY()) { return std::dynamic_pointer_cast<ty::Type>(std::make_shared<ty::Ray>()); } // Now handle all the primitive types if (ctx->VOID()) { return std::dynamic_pointer_cast<ty::Type>( std::make_shared<ty::Primitive>(ty::PrimitiveType::VOID)); } const std::string type_str = ctx->getText(); if (type_str.starts_with("bool")) { auto primitive_type = std::make_shared<ty::Primitive>(ty::PrimitiveType::BOOL); if (ctx->BOOL()) { return std::dynamic_pointer_cast<ty::Type>(primitive_type); } const size_t dimension_0 = std::stoi(type_str.substr(4, 1)); if (ctx->BOOL1() || ctx->BOOL2() || ctx->BOOL3() || ctx->BOOL4()) { return std::dynamic_pointer_cast<ty::Type>( std::make_shared<ty::Vector>(primitive_type, dimension_0)); } const size_t dimension_1 = std::stoi(type_str.substr(6, 1)); return std::dynamic_pointer_cast<ty::Type>( std::make_shared<ty::Matrix>(primitive_type, dimension_0, dimension_1)); } if (type_str.starts_with("int")) { auto primitive_type = std::make_shared<ty::Primitive>(ty::PrimitiveType::INT); if (ctx->INT()) { return std::dynamic_pointer_cast<ty::Type>(primitive_type); } const size_t dimension_0 = std::stoi(type_str.substr(3, 1)); if (ctx->INT1() || ctx->INT2() || ctx->INT3() || ctx->INT4()) { return std::dynamic_pointer_cast<ty::Type>( std::make_shared<ty::Vector>(primitive_type, dimension_0)); } const size_t dimension_1 = std::stoi(type_str.substr(5, 1)); return std::dynamic_pointer_cast<ty::Type>( std::make_shared<ty::Matrix>(primitive_type, dimension_0, dimension_1)); } if (type_str.starts_with("uint")) { auto primitive_type = std::make_shared<ty::Primitive>(ty::PrimitiveType::UINT); if (ctx->UINT()) { return std::dynamic_pointer_cast<ty::Type>(primitive_type); } const size_t dimension_0 = std::stoi(type_str.substr(4, 1)); if (ctx->UINT1() || ctx->UINT2() || ctx->UINT3() || ctx->UINT4()) { return std::dynamic_pointer_cast<ty::Type>( std::make_shared<ty::Vector>(primitive_type, dimension_0)); } const size_t dimension_1 = std::stoi(type_str.substr(6, 1)); return std::dynamic_pointer_cast<ty::Type>( std::make_shared<ty::Matrix>(primitive_type, dimension_0, dimension_1)); } if (type_str.starts_with("float")) { auto primitive_type = std::make_shared<ty::Primitive>(ty::PrimitiveType::FLOAT); if (ctx->FLOAT()) { return std::dynamic_pointer_cast<ty::Type>(primitive_type); } const size_t dimension_0 = std::stoi(type_str.substr(5, 1)); if (ctx->FLOAT1() || ctx->FLOAT2() || ctx->FLOAT3() || ctx->FLOAT4()) { return std::dynamic_pointer_cast<ty::Type>( std::make_shared<ty::Vector>(primitive_type, dimension_0)); } const size_t dimension_1 = std::stoi(type_str.substr(7, 1)); return std::dynamic_pointer_cast<ty::Type>( std::make_shared<ty::Matrix>(primitive_type, dimension_0, dimension_1)); } if (type_str.starts_with("double")) { auto primitive_type = std::make_shared<ty::Primitive>(ty::PrimitiveType::DOUBLE); if (ctx->DOUBLE()) { return std::dynamic_pointer_cast<ty::Type>(primitive_type); } const size_t dimension_0 = std::stoi(type_str.substr(6, 1)); if (ctx->DOUBLE1() || ctx->DOUBLE2() || ctx->DOUBLE3() || ctx->DOUBLE4()) { return std::dynamic_pointer_cast<ty::Type>( std::make_shared<ty::Vector>(primitive_type, dimension_0)); } const size_t dimension_1 = std::stoi(type_str.substr(8, 1)); return std::dynamic_pointer_cast<ty::Type>( std::make_shared<ty::Matrix>(primitive_type, dimension_0, dimension_1)); } report_error(ctx->getStart(), "Unhandled type string " + ctx->getText()); return std::any(); } std::any ASTBuilderVisitor::visitTemplateParameters( crtg::ChameleonRTParser::TemplateParametersContext *ctx) { auto template_params = std::make_shared<std::vector<std::shared_ptr<ty::Type>>>(); auto type_list = ctx->typeName(); for (auto &t : type_list) { template_params->push_back(std::any_cast<std::shared_ptr<ty::Type>>(visitTypeName(t))); } return template_params; } std::set<ty::Modifier> ASTBuilderVisitor::parse_modifiers( antlr4::Token *token, const std::vector<crtg::ChameleonRTParser::ModifierContext *> &modifier_list) { std::set<ty::Modifier> modifiers; for (auto *m : modifier_list) { if (m->CONST()) { modifiers.insert(ty::Modifier::CONST); } else if (m->IN()) { modifiers.insert(ty::Modifier::IN); } else if (m->OUT()) { modifiers.insert(ty::Modifier::OUT); } else if (m->IN_OUT()) { modifiers.insert(ty::Modifier::IN_OUT); } } if (modifiers.size() != modifier_list.size()) { report_error(token, "Redundant modifiers found in modifier list"); } if (modifiers.contains(ty::Modifier::CONST) && (modifiers.contains(ty::Modifier::OUT) || modifiers.contains(ty::Modifier::IN_OUT))) { report_error(token, "Invalid modifier set: const found with out or inout"); } if (modifiers.contains(ty::Modifier::IN_OUT) && (modifiers.contains(ty::Modifier::IN) || modifiers.contains(ty::Modifier::OUT))) { report_error(token, "Invalid modifier set: redundant use of in or out with inout"); } return modifiers; } std::any ASTBuilderVisitor::visitUnary(crtg::ChameleonRTParser::UnaryContext *ctx) { return visit_expr(ctx); } std::any ASTBuilderVisitor::visitCall(crtg::ChameleonRTParser::CallContext *ctx) { return visit_expr(ctx); } std::any ASTBuilderVisitor::visitStructArray(crtg::ChameleonRTParser::StructArrayContext *ctx) { return visit_expr(ctx); } std::any ASTBuilderVisitor::visitMult(crtg::ChameleonRTParser::MultContext *ctx) { return visit_expr(ctx); } std::any ASTBuilderVisitor::visitDiv(crtg::ChameleonRTParser::DivContext *ctx) { return visit_expr(ctx); } std::any ASTBuilderVisitor::visitAddSub(crtg::ChameleonRTParser::AddSubContext *ctx) { return visit_expr(ctx); } std::any ASTBuilderVisitor::visitComparison(crtg::ChameleonRTParser::ComparisonContext *ctx) { return visit_expr(ctx); } std::any ASTBuilderVisitor::visitEquality(crtg::ChameleonRTParser::EqualityContext *ctx) { return visit_expr(ctx); } std::any ASTBuilderVisitor::visitLogicAnd(crtg::ChameleonRTParser::LogicAndContext *ctx) { return visit_expr(ctx); } std::any ASTBuilderVisitor::visitLogicOr(crtg::ChameleonRTParser::LogicOrContext *ctx) { return visit_expr(ctx); } std::any ASTBuilderVisitor::visitAssign(crtg::ChameleonRTParser::AssignContext *ctx) { return visit_expr(ctx); } std::any ASTBuilderVisitor::visitParens(crtg::ChameleonRTParser::ParensContext *ctx) { return visit_expr(ctx); } std::any ASTBuilderVisitor::visitPrimary(crtg::ChameleonRTParser::PrimaryContext *ctx) { return visit_expr(ctx); } std::any ASTBuilderVisitor::visit_expr(crtg::ChameleonRTParser::ExprContext *ctx) { ASTExprBuilderVisitor expr_visitor; return expr_visitor.visit(ctx); } }
41.026616
95
0.644347
[ "vector" ]
6ef1f2329ba0260b51837572ca34d1bc89aa5364
2,106
cpp
C++
icli.cpp
luccanunes/icli
27dd0609603e6582ecf9b7cf076a178f2a2a6c0f
[ "MIT" ]
1
2020-10-17T02:08:02.000Z
2020-10-17T02:08:02.000Z
icli.cpp
luccanunes/icli
27dd0609603e6582ecf9b7cf076a178f2a2a6c0f
[ "MIT" ]
null
null
null
icli.cpp
luccanunes/icli
27dd0609603e6582ecf9b7cf076a178f2a2a6c0f
[ "MIT" ]
null
null
null
#include <iostream> #include <cpr/cpr.h> #include <nlohmann/json.hpp> using namespace std; bool cointains(vector<string> container, string item); int main(int argc, char* argv[]) { if (argc == 1 || strcmp(argv[1], "-h") == 0 || strcmp(argv[1], "--help") == 0) { vector<string> commands = { "icli {user} ---------- gets all info about that user", "icli {user} {info} --- gets that info about that user" }; for (string cmd : commands) cout << cmd << endl; return 0; } if (argc > 3) { cout << "Too many arguments." << endl; cout << "To get a list of commands, type icli --help or icli -h." << endl; return 0; } vector<string> info_fields = { "id", "full_name", "biography", "is_private", "is_verified", "is_business_account", "business_category_name", "business_email", "is_joined_recently", "profile_pic_url_hd" }; string field; if (argc == 3) { field = argv[2]; if (!cointains(info_fields, field) && field != "followed_by" && field != "follows") { cout << "The information you requested is unavailable or doesn't exist." << endl; cout << "To get a list of data fields, go to https://github.com/luccanunes/icli " << endl; return 0; } } string user = argv[1]; string URL = "https://www.instagram.com/" + user + "/?__a=1"; cpr::Response res = cpr::Get(cpr::Url{ URL }); nlohmann::json jdata; jdata = nlohmann::json::parse(res.text); nlohmann::json info = jdata["graphql"]["user"]; if (argc == 2) { for (string info_field : info_fields) cout << info_field << ": " << info[info_field] << endl; cout << "followed by: " << info["edge_followed_by"]["count"] << endl; cout << "follows: " << info["edge_follow"]["count"] << endl; return 0; } if (field == "followed_by") { cout << info["edge_followed_by"]["count"] << endl; } else if (field == "follows") { cout << info["edge_follow"]["count"] << endl; } else { cout << info[field] << endl; } return 0; } bool cointains(vector<string> container, string item) { return find(container.begin(), container.end(), item) != container.end(); }
28.459459
102
0.618708
[ "vector" ]
6ef82b7e0c29d312a27febbff777f03d77d94c50
4,769
cpp
C++
TGEngine/pipeline/buffer/Texturebuffer.cpp
ThePixly/TGEngine
aff5d5f42c3094dcc37253f4a3f5e09db560a4eb
[ "Apache-2.0" ]
null
null
null
TGEngine/pipeline/buffer/Texturebuffer.cpp
ThePixly/TGEngine
aff5d5f42c3094dcc37253f4a3f5e09db560a4eb
[ "Apache-2.0" ]
null
null
null
TGEngine/pipeline/buffer/Texturebuffer.cpp
ThePixly/TGEngine
aff5d5f42c3094dcc37253f4a3f5e09db560a4eb
[ "Apache-2.0" ]
null
null
null
#include "Texturebuffer.hpp" std::vector<Texture*> texture_buffers; Descriptor texture_descriptor; VkSampler tex_image_sampler; uint32_t tex_array_index = 0; using namespace nio; void createTexture(Texture* tex) { TG_VECTOR_APPEND_NORMAL(texture_buffers, tex); tex->index = (uint32_t)last_size; } void initAllTextures() { VkSamplerCreateInfo sampler_create_info = { VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO, nullptr, 0, VK_FILTER_LINEAR, VK_FILTER_LINEAR, VK_SAMPLER_MIPMAP_MODE_LINEAR, VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE, VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE, VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE, 0, VK_TRUE, 16.0f, VK_TRUE, VK_COMPARE_OP_ALWAYS, 0, 1, VK_BORDER_COLOR_FLOAT_TRANSPARENT_BLACK, VK_FALSE }; last_result = vkCreateSampler(device, &sampler_create_info, nullptr, &tex_image_sampler); HANDEL(last_result) texture_descriptor = { VK_SHADER_STAGE_FRAGMENT_BIT, MAX_TEXTURES, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, VK_NULL_HANDLE, tex_image_sampler, NULL }; addDescriptor(&texture_descriptor); uint32_t buffer_index; FIND_INDEX(buffer_index, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT) vlib_image_create_info.usage = VK_IMAGE_USAGE_SAMPLED_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT; vlib_image_create_info.samples = VK_SAMPLE_COUNT_1_BIT; vlib_image_view_create_info.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; for each(Texture* ptr in texture_buffers) { if (ptr->texture_path) { File file = open(ptr->texture_path, "rb"); ptr->image_data = stbi_load_from_file(file, &ptr->width, &ptr->height, &ptr->channel, STBI_rgb_alpha); } vlib_image_create_info.format = ptr->image_format; vlib_image_create_info.extent.width = ptr->width; vlib_image_create_info.extent.height = ptr->height; last_result = vkCreateImage(device, &vlib_image_create_info, nullptr, &ptr->image); HANDEL(last_result) vkGetImageMemoryRequirements(device, ptr->image, &ptr->requierments); vlib_buffer_memory_allocate_info.allocationSize = ptr->requierments.size; vlib_buffer_memory_allocate_info.memoryTypeIndex = vlib_device_local_memory_index; last_result = vkAllocateMemory(device, &vlib_buffer_memory_allocate_info, nullptr, &ptr->d_memory); HANDEL(last_result) last_result = vkBindImageMemory(device, ptr->image, ptr->d_memory, 0); HANDEL(last_result) vlib_buffer_create_info.size = ptr->width * ptr->height * 4; last_result = vkCreateBuffer(device, &vlib_buffer_create_info, nullptr, &ptr->buffer); HANDEL(last_result) vkGetBufferMemoryRequirements(device, ptr->buffer, &ptr->buffer_requierments); vlib_buffer_memory_allocate_info.allocationSize = ptr->buffer_requierments.size; vlib_buffer_memory_allocate_info.memoryTypeIndex = buffer_index; last_result = vkAllocateMemory(device, &vlib_buffer_memory_allocate_info, nullptr, &ptr->buffer_memory); HANDEL(last_result) last_result = vkBindBufferMemory(device, ptr->buffer, ptr->buffer_memory, 0); HANDEL(last_result) last_result = vkMapMemory(device, ptr->buffer_memory, 0, ptr->width * ptr->height * 4, 0, &ptr->memory); HANDEL(last_result); memcpy(ptr->memory, ptr->image_data, ptr->width * ptr->height * 4); vkUnmapMemory(device, ptr->buffer_memory); if (ptr->texture_path) { stbi_image_free(ptr->image_data); } else { delete[] ptr->image_data; } vlib_image_view_create_info.format = ptr->image_format; vlib_image_view_create_info.image = ptr->image; last_result = vkCreateImageView(device, &vlib_image_view_create_info, nullptr, &ptr->image_view); HANDEL(last_result) } } void addTextures() { uint32_t index = 0; texture_descriptor.image_view = new VkImageView[MAX_TEXTURES]; for each (Texture* tex in texture_buffers) { texture_descriptor.image_view[index] = tex->image_view; index++; } for (; index < MAX_TEXTURES; index++) { texture_descriptor.image_view[index] = texture_buffers[0]->image_view; } texture_descriptor.count = MAX_TEXTURES; texture_descriptor.binding = 0; texture_descriptor.descriptor_set = 1; updateDescriptorSet(&texture_descriptor, 0); texture_descriptor.descriptor_set = 0; updateDescriptorSet(&texture_descriptor, 0); } void destroyBufferofTexture(Texture* tex) { vkFreeMemory(device, tex->buffer_memory, nullptr); vkDestroyBuffer(device, tex->buffer, nullptr); } void destroyTexture(Texture* tex) { vkDestroyImageView(device, tex->image_view, nullptr); vkFreeMemory(device, tex->d_memory, nullptr); vkDestroyImage(device, tex->image, nullptr); } void destroyAllTextures() { last_result = vkDeviceWaitIdle(device); HANDEL(last_result) vkDestroySampler(device, tex_image_sampler, nullptr); for each(Texture* tex in texture_buffers) { destroyTexture(tex); } }
31.582781
106
0.784651
[ "vector" ]
3e02d3f1afc4568f5ee8f75c3d973f6176cfa566
2,199
cc
C++
src/ctcbin/ctc-copy-transition-model.cc
roscisz/kaldi-mpi
2176d0810da77defb382fd8da7066ed583b7fe73
[ "Apache-2.0" ]
2
2018-08-09T14:11:48.000Z
2020-04-27T02:46:00.000Z
src/ctcbin/ctc-copy-transition-model.cc
roscisz/kaldi-mpi
2176d0810da77defb382fd8da7066ed583b7fe73
[ "Apache-2.0" ]
null
null
null
src/ctcbin/ctc-copy-transition-model.cc
roscisz/kaldi-mpi
2176d0810da77defb382fd8da7066ed583b7fe73
[ "Apache-2.0" ]
null
null
null
// ctcbin/ctc-copy-transition-model.cc // Copyright 2015 Johns Hopkins University (author: Daniel Povey) // See ../../COPYING for clarification regarding multiple authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED // WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, // MERCHANTABLITY OR NON-INFRINGEMENT. // See the Apache 2 License for the specific language governing permissions and // limitations under the License. #include <typeinfo> #include "base/kaldi-common.h" #include "util/common-utils.h" #include "hmm/transition-model.h" #include "ctc/cctc-transition-model.h" int main(int argc, char *argv[]) { try { using namespace kaldi; using namespace kaldi::ctc; typedef kaldi::int32 int32; const char *usage = "Copy CTC transition model (possibly changing binary mode)\n" "\n" "Usage: ctc-copy-transition-model [options] <ctc-transition-model-in> <ctc-transition-model-out>\n" "e.g.:\n" " ctc-copy-transition-model --binary=false 0.trans_mdl - | less\n"; bool binary_write = true; ParseOptions po(usage); po.Register("binary", &binary_write, "Write output in binary mode"); po.Read(argc, argv); if (po.NumArgs() != 2) { po.PrintUsage(); exit(1); } std::string ctc_trans_model_rxfilename = po.GetArg(1), ctc_trans_model_wxfilename = po.GetArg(2); CctcTransitionModel trans_model; ReadKaldiObject(ctc_trans_model_rxfilename, &trans_model); WriteKaldiObject(trans_model, ctc_trans_model_wxfilename, binary_write); KALDI_LOG << "Copied CTC transition model from " << ctc_trans_model_rxfilename << " to " << ctc_trans_model_wxfilename; return 0; } catch(const std::exception &e) { std::cerr << e.what() << '\n'; return -1; } }
32.820896
108
0.6794
[ "model" ]
3e0365d23c2228c278087d2cad1296f2e2534fd3
5,335
cpp
C++
apps/image_pa5.cpp
cdriehuys/comp475
efcd1d5a3055f0a6676a8771397bd826ee1d7b50
[ "MIT" ]
1
2018-07-26T05:02:28.000Z
2018-07-26T05:02:28.000Z
apps/image_pa5.cpp
cdriehuys/comp475
efcd1d5a3055f0a6676a8771397bd826ee1d7b50
[ "MIT" ]
null
null
null
apps/image_pa5.cpp
cdriehuys/comp475
efcd1d5a3055f0a6676a8771397bd826ee1d7b50
[ "MIT" ]
4
2018-04-25T05:39:47.000Z
2022-02-24T04:21:56.000Z
/** * Copyright 2015 Mike Reed */ #include "image.h" #include "GCanvas.h" #include "GBitmap.h" #include "GColor.h" #include "GMatrix.h" #include "GPath.h" #include "GPoint.h" #include "GRandom.h" #include "GRect.h" #include "GFilter.h" #include <string> static void make_star(GPath* path, int count, float anglePhase) { GASSERT(count & 1); float da = 2 * M_PI * (count >> 1) / count; float angle = anglePhase; for (int i = 0; i < count; ++i) { GPoint p = { cosf(angle), sinf(angle) }; i == 0 ? path->moveTo(p) : path->lineTo(p); angle += da; } } static void add_star(GPath* path, int count) { if (count & 1) { make_star(path, count, 0); } else { count >>= 1; make_star(path, count, 0); make_star(path, count, M_PI); } } static void make_diamonds(GPath* path) { const GPoint pts[] { { 0, 0.1f }, { -1, 5 }, { 0, 6 }, { 1, 5 }, }; float steps = 12; float step = 1 / (steps - 1); GMatrix matrix; for (float angle = 0; angle < 2*M_PI - 0.001f; angle += 2*M_PI/steps) { GPoint dst[4]; GMatrix::MakeRotate(angle).mapPoints(dst, pts, 4); path->addPolygon(dst, 4); } } static void stars(GCanvas* canvas) { canvas->clear({1, 1, 1, 1}); GMatrix scale; scale.setScale(100, 100); GPath path;; add_star(&path, 5); path.transform(scale); canvas->translate(120, 120); canvas->drawPath(path, GPaint({1,1,0,0})); path.reset(); canvas->translate(250, 0); add_star(&path, 6); path.transform(scale); canvas->drawPath(path, GPaint({1,0,0,1})); path.reset(); canvas->translate(-250, 250); path.moveTo(-1, -1).lineTo( 1, -1).lineTo(1, 1).lineTo(-1, 1); path.moveTo( 0, -1).lineTo(-1, 0).lineTo(0, 1).lineTo( 1, 0); path.moveTo(-0.5, -0.5).lineTo(0.5, -0.5).lineTo(0.5, 0.5).lineTo(-0.5, 0.5); path.moveTo(0, -0.5).lineTo(-0.5, 0).lineTo(0, 0.5).lineTo(0.5, 0); path.transform(scale); canvas->drawPath(path, GPaint()); path.reset(); make_diamonds(&path); path.transform(GMatrix::MakeScale(20)); canvas->translate(250, 0); canvas->drawPath(path, GPaint({1, 0, 1, 0})); } static void draw_lion_bare(GCanvas* canvas) { #include "lion.inc" } static void draw_lion(GCanvas* canvas) { canvas->translate(130, 40); canvas->scale(1.2, 1.2); draw_lion_bare(canvas); } static void draw_lion_head(GCanvas* canvas) { canvas->translate(-40, 10); canvas->scale(3, 3); draw_lion_bare(canvas); } static void draw_grad(GCanvas* canvas) { GRect r = GRect::MakeXYWH(20, 30, 200, 150); const GColor colors[] = { {1,1,0,0}, {1,0,1,0}, {1,0,0,1}, }; auto sh = GCreateLinearGradient({r.fLeft, r.fTop}, {r.fRight, r.fBottom}, colors, GARRAY_COUNT(colors)); GPaint paint(sh.get()); canvas->drawPaint(paint); } static void draw_mode_gradients(GCanvas* canvas, const GRect& bounds, GBlendMode mode) { outer_frame(canvas, bounds); auto dstsh = GCreateLinearGradient({bounds.fLeft, bounds.fTop}, {bounds.fLeft, bounds.fBottom}, {0, 0, 0, 0}, {1, 1, 0, 0}); auto srcsh = GCreateLinearGradient({bounds.fLeft, bounds.fTop}, {bounds.fRight, bounds.fTop}, {0, 0, 0, 0}, {1, 0, 0, 1}); GPaint paint; GPath path; path.addRect(bounds); paint.setBlendMode(GBlendMode::kSrc); paint.setShader(dstsh.get()); canvas->drawRect(bounds, paint); paint.setBlendMode(mode); paint.setShader(srcsh.get()); canvas->drawPath(path, paint); } static void draw_gradient_blendmodes(GCanvas* canvas) { draw_all_blendmodes(canvas, draw_mode_gradients); } ////////////////////////////////////////////////////////////////////////////////////////////////// static void graph_path(GPath* path, int steps, float min, float max, float (*func)(float x)) { path->reset(); const float dx = (max - min) / (steps - 1); float x = min; path->moveTo(x, -func(x)); for (int i = 1; i < steps; ++i) { x += dx; path->lineTo(x, -func(x)); } } static void draw_graphs2(GCanvas* canvas) { GPath path; float min = -M_PI; float max = M_PI; canvas->save(); canvas->translate(128, 128); canvas->scale(40, 60); graph_path(&path, 30, min, max, [](float x) { return sinf(x); }); auto sh = GCreateLinearGradient({min, 0}, {max, 0}, {1, 0, 0, 1}, {1, 1, 0, 0}); canvas->drawPath(path, GPaint(sh.get())); canvas->restore(); GColor color = {1, 0, 0.5f, 0}; min = -5*M_PI; max = 5*M_PI; canvas->save(); canvas->translate(128, 40); canvas->scale(10, 40); graph_path(&path, 70, min, max, [](float x) { return sinf(x)/x; }); sh = GCreateLinearGradient({0, -1.f}, {0, 1.f}, &color, 1); canvas->drawPath(path, GPaint(sh.get())); canvas->restore(); min = 0; max = 1; canvas->save(); canvas->translate(128, 250); canvas->scale(100, 100); graph_path(&path, 40, min, max, [](float x) { return sqrtf(x); }); path.lineTo(1, 0); sh = GCreateLinearGradient({min,0}, {max,0}, {1,0.75f,0.75f,0.75f}, {1,0,0,0}); canvas->drawPath(path, GPaint(sh.get())); canvas->restore(); }
28.529412
99
0.563824
[ "transform" ]
3e0be04495fde33ae8d6216763e8cd48fe804b9f
10,027
cpp
C++
src/distancefield.cpp
ZephyrL/DH2323Project
598fc2f817f256a187e37473548abeefee689795
[ "Apache-2.0" ]
1
2020-08-19T07:49:48.000Z
2020-08-19T07:49:48.000Z
src/distancefield.cpp
ZephyrL/DH2323Project
598fc2f817f256a187e37473548abeefee689795
[ "Apache-2.0" ]
null
null
null
src/distancefield.cpp
ZephyrL/DH2323Project
598fc2f817f256a187e37473548abeefee689795
[ "Apache-2.0" ]
null
null
null
#include "debug.h" #include "parameters.h" #include "distancefield.h" #include <vector> #include <fstream> #include <functional> #include <glm/glm.hpp> #include <iostream> #include <glm/gtx/string_cast.hpp> using namespace std; using namespace glm; #include "boundingbox.hpp" #include "mesh.h" #include "mathUtils.h" ofstream &operator<<(ofstream &o, const DistanceFieldData &data) { o << data.hashedName << endl << data.size.x << " " << data.size.y << " " << data.size.z << endl << data.resolution << endl; vec3 v = data.distanceFieldBBox.min; o << v.x << " " << v.y << " " << v.z << endl; v = data.distanceFieldBBox.max; o << v.x << " " << v.y << " " << v.z << endl; vec2 v2 = data.minMaxDistance; o << v2.x << " " << v2.y << endl; for (float f : data.uncompressedVolumeData) { o << f << endl; } for (vec3 v : data.positionData) { o << v.x << " " << v.y << " " << v.z << endl; } return o; } ifstream &operator>>(ifstream &i, DistanceFieldData &data) { int x, y, z; float fx, fy, fz; float gx, gy, gz; i >> data.hashedName; i >> x >> y >> z; data.size = ivec3(x, y, z); i >> data.resolution; i >> fx >> fy >> fz >> gx >> gy >> gz; data.distanceFieldBBox = BBox(vec3(fx, fy, fz), vec3(gx, gy, gz)); i >> fx >> fy; data.minMaxDistance = vec2(fx, fy); int size = data.size.x * data.size.y * data.size.z; data.uncompressedVolumeData = vector<float>(size); data.positionData = vector<vec3>(size); for (int idx = 0; idx < size; idx++) { i >> data.uncompressedVolumeData.at(idx); } for (int idx = 0; idx < size; idx++) { i >> fx >> fy >> fz; data.positionData.at(idx) = vec3(fx, fy, fz); } return i; } void DistanceFieldData::CheckExistDistanceFieldData() { string str = this->mesh.name + std::to_string(this->resolution); hashedName = hash<string>{}(str); #ifdef DEBUG cout << "DistanceField: hashedName " << hashedName << endl; #endif // DEBUG string path = "./data/" + std::to_string(hashedName) + ".sdf"; ifstream ifs(path); if (ifs) { cout << "DistanceField: Existing distance field data, loading. " << endl; ifs >> (*this); cout << "DistanceField: Data loaded." << endl; ifs.close(); #ifdef DEBUG cout << "DistanceField:: Volumn Size: " << glm::to_string(this->size) << endl; #endif // DEBUG } else { ifs.close(); CalculateDistanceField(); } } void DistanceFieldData::CalculateDistanceField() { // at least (?) voxels on each dimension int minVoxelPerDim = (int)trunc(DF_MIN_VOXEL_PER_DIM * resolution); // new bounding box : bit larger BBox originalBox = mesh.boundingBox; vec3 originalDiag = originalBox.GetHalfDiagonal(); // new diagonal length, guarantee that the bounding box of distance field volume is LARGER than the bbox of mesh // how much larger? depends on the method to handle sdf query on bbox borders, // in this case it should be several-voxels-larger. vec3 newDiag = CoordMax(originalDiag * 0.2f, 4.f * originalBox.GetSize() / (float)minVoxelPerDim); distanceFieldBBox = BBox(originalBox.min - newDiag, originalBox.max + newDiag); #ifdef DEBUG cout << "Original Box: \t" << glm::to_string(originalBox.min) << " \t " << glm::to_string(originalBox.max) << endl; cout << glm::to_string(originalBox.GetCenter()) << endl; cout << "New D F Box: \t" << glm::to_string(distanceFieldBBox.min) << " \t " << glm::to_string(distanceFieldBBox.max) << endl; cout << glm::to_string(distanceFieldBBox.GetCenter()) << endl; #endif // DEBUG // voxel should be like a cube, having at least certain amount on shortest axis vec3 dfBoxSize = distanceFieldBBox.GetSize(); float voxelSideLength = fmin(fmin(dfBoxSize.x, dfBoxSize.y), dfBoxSize.z) / minVoxelPerDim; vec3 dfDimensions = dfBoxSize / voxelSideLength; size = ivec3((int)trunc(dfDimensions.x), (int)trunc(dfDimensions.y), (int)trunc(dfDimensions.z)); // sample rays int thetaSteps = (int)std::trunc(sqrt(DF_NUM_SAMPLE_RAYS * 2)); int phiSteps = thetaSteps / 2; vector<vec3> sampleRays; sampleRays.clear(); vec3 sum(0); float phiOffset = PI / phiSteps * 0.5f; for (int phiStep = 0; phiStep < phiSteps; phiStep++) { float phi = -PI / 2.f + (PI * phiStep) / phiSteps + phiOffset; for (int thetaStep = 0; thetaStep < thetaSteps; thetaStep++) { float theta = (PI * 2.f * thetaStep) / thetaSteps; vec3 direction(cosf(theta), sinf(theta), sinf(phi)); sum += normalize(direction); sampleRays.push_back(normalize(direction)); } } int vectorSize = size.x * size.y * size.z; uncompressedVolumeData = vector<float>(vectorSize); positionData = vector<vec3>(vectorSize); cout << "DistanceField: Calculate distance field voxels" << endl; for (int zIndex = 0; zIndex < dfDimensions.z; zIndex++) { CalculateDistanceFieldLayer(sampleRays, zIndex); cout << (int)trunc((zIndex + 1) * 100.f / dfDimensions.z) << "% complete ... " << endl; } cout << "DistanceField: Calculation finished" << endl; PostDistanceFieldCalculation(); } void DistanceFieldData::PostDistanceFieldCalculation() { string path = "./data/" + std::to_string(hashedName) + ".sdf"; ofstream ofs; ofs.open(path); if (!ofs.is_open()) { cout << "DistanceField: Meet error saving SDF texture, won't save." << endl; cout << path << endl; } else { cout << "DistanceField: Texture saving." << endl; ofs << (*this); ofs.close(); cout << "DistanceField: Texture saved." << endl; } } void DistanceFieldData::CalculateDistanceFieldLayer( vector<vec3> &sampleRays, int zIndex) { const ivec3 &dimensions = size; vec3 boxSize = distanceFieldBBox.GetSize(); vec3 voxelSize(boxSize.x / dimensions.x, boxSize.y / dimensions.y, boxSize.z / dimensions.z); float maxLength = glm::length(boxSize); for (int yIndex = 0; yIndex < dimensions.y; yIndex++) { for (int xIndex = 0; xIndex < dimensions.x; xIndex++) { // offset, refer to output buffer int index = zIndex * dimensions.y * dimensions.x + yIndex * dimensions.x + xIndex; vec3 position = distanceFieldBBox.min + voxelSize * vec3(xIndex + 0.5f, yIndex + 0.5f, zIndex + 0.5f); // cout << glm::to_string(position) << " " ; int hit = 0; int hitBack = 0; float minDist = maxLength; // shortest distance to mesh among rays for (vec3 &dir : sampleRays) { ivec3 hitIndex(-1); float shortestDist = maxLength; // shortest distance to mesh of 1 sample ray vec3 hitNormal(0); if (RayMeshIntersection(position, dir, shortestDist, hitIndex, hitNormal)) { hit++; if (dot(dir, hitNormal) > 0) { hitBack++; } if (shortestDist < minDist) minDist = shortestDist; } } if (hitBack > 0.5f * DF_NUM_SAMPLE_RAYS || hitBack > 0.9f * hit) { minDist = -minDist; } uncompressedVolumeData.at(index) = minDist; positionData.at(index) = position; // cout << ((minDist > 0) ? 1 : 0) << " "; } // cout << endl; } } bool DistanceFieldData::RayMeshIntersection(const vec3 &ori, const vec3 &dir, float &minDist, ivec3 &hitIndex, vec3 &hitNormal) { for (int idx = 0; idx < mesh.indices.size(); idx += 3) { unsigned int i0 = mesh.indices[idx]; unsigned int i1 = mesh.indices[idx + 1]; unsigned int i2 = mesh.indices[idx + 2]; vec3 v0 = mesh.vertices[i0].Position; vec3 v1 = mesh.vertices[i1].Position; vec3 v2 = mesh.vertices[i2].Position; vec3 e1 = v1 - v0; // edge 1 vec3 e2 = v2 - v0; // edge 2 vec3 b = ori - v0; // Ax = b; vec3 d = dir; mat3 A(-d, e1, e2); // use Cramer's rule instead of inverse of matrix float f2 = -d.x * e1.y * e2.z - d.y * e1.z * e2.x - d.z * e1.x * e2.y - (-d.z * e1.y * e2.x - d.y * e1.x * e2.z - d.x * e1.z * e2.y); if (f2 != 0) { // float t = glm::determinant(mat3(b, e1, e2)) / f2; float t = b.x * e1.y * e2.z + b.y * e1.z * e2.x + b.z * e1.x * e2.y - (b.z * e1.y * e2.x + b.y * e1.x * e2.z + b.x * e1.z * e2.y); t /= f2; if (t >= ZERO && t < minDist) { // float u = glm::determinant(mat3(-d, b, e2)) / f2; float u = -d.x * b.y * e2.z - d.y * b.z * e2.x - d.z * b.x * e2.y - (-d.z * b.y * e2.x - d.y * b.x * e2.z - d.x * b.z * e2.y); u /= f2; if (u >= 0 && u <= 1.0f) { // float v = glm::determinant(mat3(-d, e1, b)) / f2; float v = -d.x * e1.y * b.z - d.y * e1.z * b.x - d.z * e1.x * b.y - (-d.z * e1.y * b.x - d.y * e1.x * b.z - d.x * e1.z * b.y); v /= f2; if (v >= 0 && u + v <= 1.0f) { minDist = t; hitNormal = (1.f - u - v) * mesh.vertices[i0].Normal + u * mesh.vertices[i1].Normal + v * mesh.vertices[i2].Normal; hitIndex = ivec3(i0, i1, i2); } } } } } if (hitIndex.x != -1) { return true; } return false; }
32.661238
146
0.533659
[ "mesh", "vector" ]
3e144e183885f62c26831a72aa8c858c4218b686
27,280
hpp
C++
VS/Spike-Masquelier-LIB/v3/Topology.hpp
HJLebbink/Spike-Masq
01f458dc5792947c892af296ea82d0a7447dd19c
[ "MIT" ]
1
2021-07-15T09:13:50.000Z
2021-07-15T09:13:50.000Z
VS/Spike-Masquelier-LIB/v3/Topology.hpp
HJLebbink/Spike-Masq
01f458dc5792947c892af296ea82d0a7447dd19c
[ "MIT" ]
null
null
null
VS/Spike-Masquelier-LIB/v3/Topology.hpp
HJLebbink/Spike-Masq
01f458dc5792947c892af296ea82d0a7447dd19c
[ "MIT" ]
1
2019-05-20T03:01:00.000Z
2019-05-20T03:01:00.000Z
// The MIT License (MIT) // // Copyright (c) 2017 Henk-Jan Lebbink // // 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. #pragma once #include <string> #include <vector> #include "../../Spike-Tools-LIB/NeuronIdRange.hpp" #include "Types.hpp" #include "SpikeOptionsStatic.hpp" namespace spike { namespace v3 { using namespace ::spike::tools; template <typename Options_i> class Topology { public: using Options = Options_i; static const size_t Ne = Options::Ne; static const size_t Ni = Options::Ni; static const size_t Ns = Options::Ns; static const size_t Nm = Options::Nm; static const size_t nNeurons = Ne + Ni + Ns + Nm; static const size_t Ne_start = 0; static const size_t Ne_end = Ne; static const size_t Ni_start = Ne_end; static const size_t Ni_end = Ne_end + Ni; static const size_t Nm_start = Ni_end; static const size_t Nm_end = Ni_end + Nm; static const size_t Ns_start = Nm_end; static const size_t Ns_end = Nm_end + Ns; // constructor Topology() { } std::vector<Pathway> getOutgoingPathways(const NeuronId origin) const { std::vector<Pathway> v; for (const Pathway& pathway : this->pathways_) { if (pathway.origin == origin) { v.push_back(pathway); } } //std::cout << "calcOutgoingPathways: neuronId " << origin << "; nOutgoing neurons " << v.size() << std::endl; return v; } std::vector<Pathway> getIncommingPathways(const NeuronId destination) const { std::vector<Pathway> v; for (const Pathway& pathway : this->pathways_) { if (pathway.destination == destination) { v.push_back(pathway); } } return v; } void clearPathways() { this->pathways_.clear(); } void addPathway( const NeuronId origin, const NeuronId destination, const Delay delay, const Efficacy efficacy) { this->pathways_.push_back(Pathway(origin, destination, delay, efficacy)); } void init_Masquelier() { printf("spike::v3::topology::init_Masquelier: similar to Masquelier setup with fully connected network\n"); if (Options::Ne != 0) std::cerr << "spike::v3::Topology:init_Masquelier(): warning: original experiment had 0 excitatory neurons. currently " << Options::Ne << std::endl; if (Options::Ni != 3) std::cerr << "spike::v3::Topology:init_Masquelier(): warning: original experiment had 3 inhibitory neurons. currently " << Options::Ni << std::endl; if (Options::Ns != 2000) std::cerr << "spike::v3::Topology:init_Masquelier(): warning: original experiment had 2000 sensory neurons. currently " << Options::Ns << std::endl; if (Options::Nm != 0) std::cerr << "spike::v3::Topology:init_Masquelier(): warning: original experiment had 0 motor neurons. currently " << Options::Nm << std::endl; if (Options::nSynapses != 2000) std::cerr << "spike::v3::Topology:init_Masquelier(): warning: original experiment had 2000 synapses per (excitiatory) neurons. currently " << Options::nSynapses << std::endl; this->clearPathways(); // clear this topology, make it empty // 2] neurons from exc have a pathways to all inh neurons // 4] neurons from inh have a pathways to neurons from exc1 (and not inh); for (const NeuronId sensorNeuronId : Topology::iterator_SensorNeurons()) { const Delay delay = 1; const Efficacy weight = 1; //TODO find correct initial weight for (const NeuronId inhNeuronId : Topology::iterator_InhNeurons()) { this->addPathway(sensorNeuronId, inhNeuronId, delay, weight); } } for (const NeuronId inhNeuron1Id : Topology::iterator_InhNeurons()) { const Delay delay = 1; // Original delay in Masquelier was 0ms const Efficacy weight = -1; //TODO find correct initial weight for (const NeuronId inhNeuron2Id : Topology::iterator_InhNeurons()) { if (inhNeuron1Id != inhNeuron2Id) { this->addPathway(inhNeuron1Id, inhNeuron2Id, delay, weight); } } } } void init_Izhikevich() { if (Options::Ne != 800) std::cerr << "spike::v3::Topology:init_Izhikevich(): warning: original experiment had 800 excitatory neurons. currently " << Options::Ne << std::endl; if (Options::Ni != 200) std::cerr << "spike::v3::Topology:init_Izhikevich(): warning: original experiment had 200 inhibitory neurons. currently " << Options::Ni << std::endl; if (Options::nSynapses != 100) std::cerr << "spike::v3::Topology:init_Izhikevich(): warning: original experiment had 100 synapses per neurons. currently " << Options::nSynapses << std::endl; if (Options::nSynapses > Options::Ne) { std::cerr << "spike::v3::Topology:init_Izhikevich(): error: not enough neurons (" << Options::Ne << ") for inhibitory pathways (" << Options::nSynapses << ")" << std::endl; throw 1; } if (Options::nSynapses > (Options::Ne + Options::Ni)) { std::cerr << "spike::v3::Topology:init_Izhikevich(): error: not enough neurons (" << (Options::Ne + Options::Ni) << ") for excitatory pathways (" << Options::nSynapses << ")" << std::endl; throw 1; } this->clearPathways(); // clear this topology, make it empty // 2] neurons from exc1 have s pathways to neurons from exc1 or inh; // 4] neurons from inh have s pathways to neurons from exc1 (and not inh); std::vector<NeuronId> exc_neurons; std::vector<NeuronId> inh_neurons; std::vector<NeuronId> all_neurons; for (const NeuronId neuronId : Topology::iterator_ExcNeurons()) { all_neurons.push_back(neuronId); exc_neurons.push_back(neuronId); } for (const NeuronId neuronId : Topology::iterator_InhNeurons()) { all_neurons.push_back(neuronId); inh_neurons.push_back(neuronId); } std::vector<NeuronId> alreadyUseNeuronIds; for (const NeuronId origin : exc_neurons) { unsigned int s = 0; alreadyUseNeuronIds.clear(); alreadyUseNeuronIds.push_back(origin); // 2] neurons from exc1 have M pathways to neurons from exc1 or inh; while (s < Options::nSynapses) { const NeuronId destination = this->getRandomNeuronId(all_neurons, alreadyUseNeuronIds); alreadyUseNeuronIds.push_back(destination); const Delay delay = ((s%Options::maxDelay) < Options::minDelay) ? Options::minDelay : (s%Options::maxDelay); const Efficacy weight = Options::initialWeightExc; this->addPathway(origin, destination, delay, weight); s++; } } for (const NeuronId origin : inh_neurons) { unsigned int s = 0; alreadyUseNeuronIds.clear(); alreadyUseNeuronIds.push_back(origin); // 4] neurons from inh have M pathways to neurons from exc1 (and not inh); while (s < Options::nSynapses) { const NeuronId destination = getRandomNeuronId(exc_neurons, alreadyUseNeuronIds); alreadyUseNeuronIds.push_back(destination); const Delay delay = Options::minDelay; //const Delay delay = ((s%Options::maxDelay) < Options::minDelay) ? Options::minDelay : (s%Options::maxDelay); const Efficacy weight = Options::initialWeightInh; this->addPathway(origin, destination, delay, weight); s++; } } } void init_mnist() { if (Options::nSynapses > Ne) { std::cerr << "spike::v3::Topology:init_mnist: error: not enough neurons (" << Ne << ") for inhibitory pathways (" << Options::nSynapses << ")" << std::endl; throw 1; } if (Options::nSynapses > (Ne + Ni)) { std::cerr << "spike::v3::Topology:init_mnist: error: not enough neurons (" << (Ne + Ni) << ") for excitatory pathways (" << Options::nSynapses << ")" << std::endl; throw 1; } if (Ns != 28 * 28) { std::cerr << "spike::v3::Topology:init_mnist: error: incorrect number of sensory neurons (" << Ns << "), expecting " << 28 * 28 << std::endl; throw 1; } if (Nm != 10) { std::cerr << "spike::v3::Topology:init_mnist: error: incorrect number of motor neurons (" << Nm << "), expecting 10." << std::endl; throw 1; } const Delay minDelay = 1; // original Izhikevich experiment minDelay = 0; this->clearPathways(); // clear this topology, make it empty std::vector<NeuronId> exc_neurons; // excitatory std::vector<NeuronId> inh_neurons; // inhibitory std::vector<NeuronId> sensor_neurons; // input std::vector<NeuronId> motor_neurons; // output std::vector<NeuronId> exc_inh_motor_neurons; // output std::vector<NeuronId> exc_motor_neurons; // output for (const NeuronId& neuronId : Topology::iterator_ExcNeurons()) { exc_inh_motor_neurons.push_back(neuronId); exc_neurons.push_back(neuronId); exc_motor_neurons.push_back(neuronId); } for (const NeuronId& neuronId : Topology::iterator_InhNeurons()) { exc_inh_motor_neurons.push_back(neuronId); inh_neurons.push_back(neuronId); } for (const NeuronId& neuronId : Topology::iterator_MotorNeurons()) { motor_neurons.push_back(neuronId); exc_inh_motor_neurons.push_back(neuronId); exc_motor_neurons.push_back(neuronId); } for (const NeuronId& neuronId : Topology::iterator_SensorNeurons()) { sensor_neurons.push_back(neuronId); } std::vector<NeuronId> alreadyUseNeuronIds; for (const NeuronId& neuronId1 : exc_neurons) { alreadyUseNeuronIds.clear(); alreadyUseNeuronIds.push_back(neuronId1); // 2] neurons from exc_neurons have M pathways to neurons from exc, inh or motor; for (size_t s = 0; s < Options::nSynapses; ++s) { const NeuronId neuronId2 = this->getRandomNeuronId(exc_inh_motor_neurons, alreadyUseNeuronIds); alreadyUseNeuronIds.push_back(neuronId2); const unsigned int maxDelay = static_cast<unsigned int>(Options::maxDelay); const Delay delay = static_cast<Delay>(::tools::random::rand_int32(minDelay, maxDelay+1)); const float weight = Options::initialWeightExc; this->addPathway(neuronId1, neuronId2, delay, weight); } } for (const NeuronId& neuronId1 : inh_neurons) { alreadyUseNeuronIds.clear(); size_t s = 0; // 4] neurons from inh_neurons have M pathways to neurons from exc1 (and not inh); while (s < Options::nSynapses) { const NeuronId neuronId2 = getRandomNeuronId(exc_motor_neurons, alreadyUseNeuronIds); alreadyUseNeuronIds.push_back(neuronId2); const Delay delay = minDelay; const float weight = Options::initialWeightInh; this->addPathway(neuronId1, neuronId2, delay, weight); s++; } } //for (const NeuronId neuronId1 : motor_neurons) { // motor neurons have no outgoing pathways //} for (const NeuronId& neuronId1 : sensor_neurons) { alreadyUseNeuronIds.clear(); size_t s = 0; /* for (const NeuronId neuronId2 : motor_neurons) { alreadyUseNeuronIds.push_back(neuronId2); const unsigned int maxDelay = static_cast<unsigned int>(D); const Delay delay = static_cast<Delay>(tools::getRandomInt_excl(minDelay, maxDelay)); const float weight = 5; this->addPathway(neuronId1, neuronId2, delay, weight); s++; } */ while (s < Options::nSynapses) { const NeuronId neuronId2 = getRandomNeuronId(exc_neurons, alreadyUseNeuronIds); alreadyUseNeuronIds.push_back(neuronId2); const unsigned int maxDelay = static_cast<unsigned int>(Options::maxDelay); const Delay delay = static_cast<Delay>(::tools::random::rand_int32(minDelay, maxDelay)); const float weight = Options::initialWeightExc; this->addPathway(neuronId1, neuronId2, delay, weight); s++; } } } void init_mnist2() { if (Options::nSynapses > Options::Ne) { std::cerr << "Topology::load_mnist(): error: not enough neurons (" << Ne << ") for inhibitory pathways (" << Options::nSynapses << ")" << std::endl; throw 1; } if (Options::nSynapses > (Options::Ne + Options::Ni)) { std::cerr << "Topology::load_mnist(): error: not enough neurons (" << (Ne + Ni) << ") for excitatory pathways (" << Options::nSynapses << ")" << std::endl; throw 1; } if (Options::Ne != 800 + Options::Ns) { std::cerr << "Topology::load_mnist(): error: incorrect number of exitatory neurons (" << Ne << "), expecting " << 800 + Ns << std::endl; throw 1; } if (Options::Ns != (28 * 28)) { std::cerr << "Topology::load_mnist(): error: incorrect number of sensory neurons (" << Ns << "), expecting " << (28 * 28) << std::endl; throw 1; } if (Options::Nm != 10) { std::cerr << "Topology::load_mnist(): error: incorrect number of motor neurons (" << Nm << "), expecting 10." << std::endl; throw 1; } const Delay minDelay = 1; // original Izhikevich experiment minDelay = 0; const Delay maxDelay = Options::nSynapses; this->clearPathways(); // clear this topology, make it empty std::vector<NeuronId> exc_neurons; // excitatory std::vector<NeuronId> inh_neurons; // inhibitory std::vector<NeuronId> sensor_neurons; // input std::vector<NeuronId> motor_neurons; // output std::vector<NeuronId> exc1_neurons; // excitatory layer1 std::vector<NeuronId> exc2_neurons; // excitatory layer2 std::vector<NeuronId> exc_inh_neurons; unsigned int count = 0; for (const NeuronId& neuronId : Topology::iterator_ExcNeurons()) { exc_neurons.push_back(neuronId); exc_inh_neurons.push_back(neuronId); if (count < (28 * 28)) { exc1_neurons.push_back(neuronId); } else { exc2_neurons.push_back(neuronId); } count++; } BOOST_ASSERT_MSG_HJ(exc1_neurons.size() == 28 * 28, "incorrect size"); for (const NeuronId& neuronId : Topology::iterator_InhNeurons()) { inh_neurons.push_back(neuronId); exc_inh_neurons.push_back(neuronId); } for (const NeuronId& neuronId : Topology::iterator_MotorNeurons()) { motor_neurons.push_back(neuronId); } for (const NeuronId& neuronId : Topology::iterator_SensorNeurons()) { sensor_neurons.push_back(neuronId); } std::vector<NeuronId> alreadyUseNeuronIds; for (const NeuronId& destination : exc1_neurons) { const int x1 = (destination - Ne_start) / 28; const int y1 = (destination - Ne_start) % 28; //std::cout << "load_mnist2: destination " << destination << ":" << x1 << "," << y1 << std::endl; if (((x1 * 28) + y1) != (destination - Ne_start)) //DEBUG_BREAK(); for (int x2 = (x1 - 5); x2 < (x1 + 5); ++x2) { for (int y2 = (y1 - 5); y2 < (y1 + 5); ++y2) { if ((x2 < 0) || (x2 >= 28) || (y2 < 0) || (y2 >= 28)) { // do nothing } else { const NeuronId origin = static_cast<NeuronId>(Ns_start + (x2 * 28) + y2); const unsigned int maxDelay = static_cast<unsigned int>(Options::maxDelay); const Delay delay = static_cast<Delay>(tools::getRandomInt_excl(minDelay, maxDelay)); const float weight = Options::initialWeightExc; //std::cout << "load_mnist2: sensor " << x2 << "," << y2 << " (" << origin << ") is maped to " << x1 << "," << y1 << " (" << destination << ")" << std::endl; this->addPathway(origin, destination, delay, weight); } } } } for (const NeuronId& destination : exc2_neurons) { alreadyUseNeuronIds.clear(); alreadyUseNeuronIds.push_back(destination); // connot make pathway to itself // 2] neurons from exc_neurons have M pathways to neurons from exc2, inh or motor; for (size_t s = 0; s < Options::nSynapses; ++s) { const NeuronId origin = this->getRandomNeuronId(exc_inh_neurons, alreadyUseNeuronIds); alreadyUseNeuronIds.push_back(origin); const unsigned int maxDelay = static_cast<unsigned int>(Options::maxDelay); const Delay delay = static_cast<Delay>(tools::getRandomInt_excl(minDelay, maxDelay)); const float weight = Options::initialWeightExc; this->addPathway(origin, destination, delay, weight); } } for (const NeuronId& destination : inh_neurons) { alreadyUseNeuronIds.clear(); // 4] neurons from inh_neurons have M pathways to neurons from exc1 (and not inh); for (size_t s = 0; s < Options::nSynapses; ++s) { const NeuronId origin = this->getRandomNeuronId(exc2_neurons, alreadyUseNeuronIds); alreadyUseNeuronIds.push_back(origin); const Delay delay = minDelay; const float weight = Options::initialWeightInh; this->addPathway(origin, destination, delay, weight); } } for (const NeuronId destination : motor_neurons) { alreadyUseNeuronIds.clear(); for (size_t s = 0; s < Options::nSynapses; ++s) { const NeuronId origin = this->getRandomNeuronId(exc2_neurons, alreadyUseNeuronIds); alreadyUseNeuronIds.push_back(origin); const Delay delay = static_cast<Delay>(tools::getRandomInt_excl(minDelay, maxDelay)); const float weight = Options::initialWeightExc; this->addPathway(origin, destination, delay, weight); } } } static const NeuronIdRange<NeuronId, Ne_start, Ne_end> iterator_ExcNeurons() { return NeuronIdRange<NeuronId, Ne_start, Ne_end>(); } static const NeuronIdRange<NeuronId, Ni_start, Ni_end> iterator_InhNeurons() { return NeuronIdRange<NeuronId, Ni_start, Ni_end>(); } static const NeuronIdRange<NeuronId, Nm_start, Nm_end> iterator_MotorNeurons() { return NeuronIdRange<NeuronId, Nm_start, Nm_end>(); } static const NeuronIdRange<NeuronId, Ns_start, Ns_end> iterator_SensorNeurons() { return NeuronIdRange<NeuronId, Ns_start, Ns_end>(); } // active neurons are excitatory, sensor and motor neurons static const NeuronIdRange<NeuronId, Ne_start, Nm_end> iterator_ActiveNeurons() { return NeuronIdRange<NeuronId, Ne_start, Nm_end>(); } static const NeuronIdRange<NeuronId, Ne_start, Ni_end> iterator_ExcInhNeurons() { return NeuronIdRange<NeuronId, Ne_start, Ni_end>(); } static const NeuronIdRange<NeuronId, Ne_start, Ns_end> iterator_AllNeurons() { return NeuronIdRange<NeuronId, Ne_start, Ns_end>(); } static bool isExcNeuron(const NeuronId neuronId) { BOOST_ASSERT_MSG_HJ(Ne_start == 0, "spike::v3::Topology:isExcNeuron: assumed Ne_start is zero"); return (neuronId < Ne_end); // return (neuronId >= Ne_start) && (neuronId < Ne_end); } static bool isInhNeuron(const NeuronId neuronId) { return (neuronId >= Ni_start) && (neuronId < Ni_end); } static bool isMotorNeuron(const NeuronId neuronId) { return (neuronId >= Nm_start) && (neuronId < Nm_end); } static bool isSensorNeuron(const NeuronId neuronId) { return (neuronId >= Ns_start) && (neuronId < Ns_end); } static NeuronId translateToSensorNeuronId(const NeuronId caseNeuronId) { const NeuronId sensorNeuronId = Ns_start + caseNeuronId; if (isSensorNeuron(sensorNeuronId)) { return sensorNeuronId; } else { std::cout << "Topology::translateToSensorNeuronId: caseNeuronId " << caseNeuronId << " is larger than number of sensor neurons Ns=" << Ns << std::endl; //DEBUG_BREAK(); return sensorNeuronId; } } static NeuronId translateToMotorNeuronId(const CaseLabel caseLabel) { const NeuronId motorNeuronId = Nm_start + static_cast<NeuronId>(caseLabel.val); if (isMotorNeuron(motorNeuronId)) { return motorNeuronId; } else { std::cout << "Topology::translateToMotorNeuronId: caseLabel " << caseLabel.val << " is too large" << std::endl; //DEBUG_BREAK(); return motorNeuronId; } } void loadFromFile(const std::string& filename) { // mutex to protect file access //static std::mutex mutex; // lock mutex before accessing file //std::lock_guard<std::mutex> lock(mutex); std::string line; std::ifstream inputFile(filename); if (!inputFile.is_open()) { std::cerr << "spike::v3::Topology::loadFromFile(): Unable to open file " << filename << std::endl; throw std::runtime_error("Unable to open file"); } else { //std::cout << "Topology::loadFromFile(): Opening file " << filename << std::endl; // the first line contains "# topology <nNeurons> <nPathways>" const std::vector<std::string> content = ::tools::loadNextLineAndSplit(inputFile, ' '); const unsigned int nNeurons = ::tools::file::string2int(content[0]); const unsigned int nPathways = ::tools::file::string2int(content[1]); for (unsigned int i = 0; i < nNeurons; ++i) { const std::vector<std::string> content = ::tools::loadNextLineAndSplit(inputFile, ' '); /* if (content.size() == 7) { const NeuronId neuronId = static_cast<NeuronId>(tools::file::string2int(content[0])); if (neuronId >= nNeurons) { std::cerr << "spike::v3::Topology::load(): line " << line << " has incorrect content: neuronId= " << neuronId << std::endl; throw std::exception(); } // retrieve neuron type this->setParameterA(neuronId, ::tools::file::string2float(content[1])); this->setParameterB(neuronId, ::tools::file::string2float(content[2])); this->setParameterC(neuronId, ::tools::file::string2float(content[3])); this->setParameterD(neuronId, ::tools::file::string2float(content[4])); this->trainRate_[neuronId] = ::tools::file::string2float(content[5]); this->inputScaling_[neuronId] = ::tools::file::string2float(content[6]); } else { std::cerr << "spike::v3::Topology::loadFromFile(): line " << line << " has incorrect content" << std::endl; } */ } this->pathways_.clear(); for (unsigned int i = 0; i < nPathways; ++i) { const std::vector<std::string> content = ::tools::loadNextLineAndSplit(inputFile, ' '); if (content.size() == 4) { const NeuronId neuronId1 = static_cast<NeuronId>(tools::file::string2int(content[0])); const NeuronId neuronId2 = static_cast<NeuronId>(tools::file::string2int(content[1])); const Delay delay = static_cast<Delay>(tools::file::string2int(content[2])); const Efficacy weigth = ::tools::file::string2float(content[3]); if ((neuronId1 < 0) || (neuronId1 >= nNeurons)) std::cerr << "spike::v3::Topology::load(): line " << line << " has incorrect content: neuronId1= " << neuronId1 << std::endl; if ((neuronId2 < 0) || (neuronId2 >= nNeurons)) std::cerr << "spike::v3::Topology::load(): line " << line << " has incorrect content: neuronId2= " << neuronId2 << std::endl; if ((delay < 0) || (delay >= Options::maxDelay)) std::cerr << "spike::v3::Topology::load(): ERROR A. line " << line << " has incorrect content: delay= " << delay << std::endl; this->addPathway(neuronId1, neuronId2, delay, weigth); } else { std::cerr << "spike::v3::Topology::loadFromFile(): ERROR B. line " << line << " has incorrect content" << std::endl; } } } } void saveToFile(const std::string& filename) const { // mutex to protect file access //static std::mutex mutex; // lock mutex before accessing file //std::lock_guard<std::mutex> lock(mutex); // create the directory const std::string tree = ::tools::file::getDirectory(filename); if (!::tools::file::mkdirTree(tree)) { std::cerr << "spike::v3::Topology::saveToFile: Unable to create directory " << tree << std::endl; throw std::runtime_error("unable to create directory"); } // try to open file std::ofstream outputFile(filename); //fstream is a proper RAII object, it does close automatically at the end of the scope if (!outputFile.is_open()) { std::cerr << "spike::v3::Topology::saveToFile: Unable to open file " << filename << std::endl; throw std::runtime_error("Unable to open file"); } else { //std::cout << "Topology::saveToFile(): Opening file " << filename << std::endl; const size_t nPathways = this->pathways_.size(); outputFile << "# topology <nNeurons> <nPathways>" << std::endl; outputFile << Options::nNeurons << " " << nPathways << std::endl; outputFile << "# parameter <neuronId> <a> <b> <c> <d> <trainRate> <inputScaling>" << std::endl; for (NeuronId neuronId = 0; neuronId < Options::nNeurons; ++neuronId) { //const float a = this->getParameterA(neuronId); //const float b = this->getParameterB(neuronId); //const float c = this->getParameterC(neuronId); //const float d = this->getParameterD(neuronId); //const float tr = this->trainRate_[neuronId]; //const float is = this->getInputScaling(neuronId); outputFile << neuronId << " " << std::endl; } outputFile << "# pathway <origin> <destination> <delay> <weight>" << std::endl; for (unsigned int i = 0; i < nPathways; ++i) { outputFile << this->pathways_[i].origin << " " << this->pathways_[i].destination << " " << this->pathways_[i].delay << " " << this->pathways_[i].efficacy << std::endl; } } } private: std::vector<Pathway> pathways_; NeuronId getRandomNeuronId( const std::vector<NeuronId>& allowedValues, const std::vector<NeuronId>& notAllowedValues) { unsigned int retryCounter = 0; NeuronId randomNeuronId = NO_NEURON; bool exists; const unsigned int largestIndex = static_cast<unsigned int>(allowedValues.size()); do { randomNeuronId = allowedValues.at(::tools::random::rand_int32(0U, largestIndex)); exists = false; for (std::vector<NeuronId>::size_type i = 0; i != notAllowedValues.size(); i++) { if (notAllowedValues.at(i) == randomNeuronId) { exists = true; retryCounter++; if (retryCounter == 100000) { std::cout << "Topology::getRandomNeuronId: could not find a random neuronId: I've tried " << retryCounter << " times, giving up." << std::endl; //DEBUG_BREAK(); } } } } while (exists); return randomNeuronId; } }; } }
36.765499
210
0.64989
[ "object", "vector" ]
3e19f32c9d112a4cc4695480735832b1dde2fbef
7,544
cxx
C++
alg/teca_temporal_average.cxx
mhaseeb123/TECA
4233bac9dd2a86da3848ae088b462b4544b3ddc7
[ "BSD-3-Clause-LBNL" ]
null
null
null
alg/teca_temporal_average.cxx
mhaseeb123/TECA
4233bac9dd2a86da3848ae088b462b4544b3ddc7
[ "BSD-3-Clause-LBNL" ]
null
null
null
alg/teca_temporal_average.cxx
mhaseeb123/TECA
4233bac9dd2a86da3848ae088b462b4544b3ddc7
[ "BSD-3-Clause-LBNL" ]
null
null
null
#include "teca_temporal_average.h" #include "teca_mesh.h" #include "teca_array_collection.h" #include "teca_variant_array.h" #include "teca_metadata.h" #include <algorithm> #include <iostream> #include <string> #if defined(TECA_HAS_BOOST) #include <boost/program_options.hpp> #endif using std::string; using std::vector; using std::cerr; using std::endl; //#define TECA_DEBUG // -------------------------------------------------------------------------- teca_temporal_average::teca_temporal_average() : filter_width(3), filter_type(backward) { this->set_number_of_input_connections(1); this->set_number_of_output_ports(1); } // -------------------------------------------------------------------------- teca_temporal_average::~teca_temporal_average() {} #if defined(TECA_HAS_BOOST) // -------------------------------------------------------------------------- void teca_temporal_average::get_properties_description( const string &prefix, options_description &global_opts) { options_description opts("Options for " + (prefix.empty()?"teca_temporal_average":prefix)); opts.add_options() TECA_POPTS_GET(unsigned int, prefix, filter_width, "number of steps to average over") TECA_POPTS_GET(int, prefix, filter_type, "use a backward(0), forward(1) or centered(2) stencil") ; global_opts.add(opts); } // -------------------------------------------------------------------------- void teca_temporal_average::set_properties( const string &prefix, variables_map &opts) { TECA_POPTS_SET(opts, unsigned int, prefix, filter_width) TECA_POPTS_SET(opts, int, prefix, filter_type) } #endif // -------------------------------------------------------------------------- std::vector<teca_metadata> teca_temporal_average::get_upstream_request( unsigned int port, const std::vector<teca_metadata> &input_md, const teca_metadata &request) { #ifdef TECA_DEBUG std::string type = "unknown"; switch(this->filter_type) { case backward: type = "backward"; break; case centered: type = "centered"; break; case forward: type = "forward"; break; } cerr << teca_parallel_id() << "teca_temporal_average::get_upstream_request filter_type=" << type << endl; #endif (void) port; vector<teca_metadata> up_reqs; // get the time values required to compute the average // centered on the requested time long active_step; if (request.get("time_step", active_step)) { TECA_ERROR("request is missing \"time_step\"") return up_reqs; } long num_steps; if (input_md[0].get("number_of_time_steps", num_steps)) { TECA_ERROR("input is missing \"number_of_time_steps\"") return up_reqs; } long first = 0; long last = 0; switch(this->filter_type) { case backward: first = active_step - this->filter_width + 1; last = active_step; break; case centered: { if (this->filter_width % 2 == 0) TECA_ERROR("\"filter_width\" should be odd for centered calculation") long delta = this->filter_width/2; first = active_step - delta; last = active_step + delta; } break; case forward: first = active_step; last = active_step + this->filter_width - 1; break; default: TECA_ERROR("Invalid \"filter_type\" " << this->filter_type) return up_reqs; } for (long i = first; i <= last; ++i) { // make a request for each time that will be used in the // average if ((i >= 0) && (i < num_steps)) { #ifdef TECA_DEBUG cerr << teca_parallel_id() << "request time_step " << i << endl; #endif teca_metadata up_req(request); up_req.set("time_step", i); up_reqs.push_back(up_req); } } return up_reqs; } // -------------------------------------------------------------------------- const_p_teca_dataset teca_temporal_average::execute( unsigned int port, const std::vector<const_p_teca_dataset> &input_data, const teca_metadata &request) { #ifdef TECA_DEBUG cerr << teca_parallel_id() << "teca_temporal_average::execute" << endl; #endif (void)port; // create output and copy metadata, coordinates, etc p_teca_mesh out_mesh = std::dynamic_pointer_cast<teca_mesh>(input_data[0]->new_instance()); if (!out_mesh) { TECA_ERROR("input data[0] is not a teca_mesh") return nullptr; } // initialize the output array collections from the // first input const_p_teca_mesh in_mesh = std::dynamic_pointer_cast<const teca_mesh>(input_data[0]); if (!in_mesh) { TECA_ERROR("Failed to average. dataset is not a teca_mesh") return nullptr; } size_t n_meshes = input_data.size(); // TODO -- handle cell, edge, face arrays p_teca_array_collection out_arrays = out_mesh->get_point_arrays(); // initialize with a copy of the first dataset out_arrays->copy(in_mesh->get_point_arrays()); size_t n_arrays = out_arrays->size(); size_t n_elem = n_arrays ? out_arrays->get(0)->size() : 0; // accumulate each array from remaining datasets for (size_t i = 1; i < n_meshes; ++i) { in_mesh = std::dynamic_pointer_cast<const teca_mesh>(input_data[i]); const_p_teca_array_collection in_arrays = in_mesh->get_point_arrays(); for (size_t j = 0; j < n_arrays; ++j) { const_p_teca_variant_array in_a = in_arrays->get(j); p_teca_variant_array out_a = out_arrays->get(j); TEMPLATE_DISPATCH( teca_variant_array_impl, out_a.get(), const NT *p_in_a = dynamic_cast<const TT*>(in_a.get())->get(); NT *p_out_a = dynamic_cast<TT*>(out_a.get())->get(); for (size_t q = 0; q < n_elem; ++q) p_out_a[q] += p_in_a[q]; ) } } // scale result by the filter width for (size_t j = 0; j < n_arrays; ++j) { p_teca_variant_array out_a = out_arrays->get(j); TEMPLATE_DISPATCH( teca_variant_array_impl, out_a.get(), NT *p_out_a = dynamic_cast<TT*>(out_a.get())->get(); NT fac = static_cast<NT>(n_meshes); for (size_t q = 0; q < n_elem; ++q) p_out_a[q] /= fac; ) } // get active time step unsigned long active_step; if (request.get("time_step", active_step)) { TECA_ERROR("request is missing \"time_step\"") return nullptr; } // copy metadata and information arrays from the // active step for (size_t i = 0; i < n_meshes; ++i) { in_mesh = std::dynamic_pointer_cast<const teca_mesh>(input_data[i]); unsigned long step; if (in_mesh->get_metadata().get("time_step", step)) { TECA_ERROR("input dataset metadata missing \"time_step\"") return nullptr; } if (step == active_step) { out_mesh->copy_metadata(in_mesh); out_mesh->get_information_arrays()->copy(in_mesh->get_information_arrays()); } } return out_mesh; }
28.360902
88
0.565615
[ "vector" ]
3e1d2e3b70536d1db39511e83ec55cb8e8f62df0
6,571
cpp
C++
source/texture.cpp
deyahruhd/terramagna
931887afad11c6cf2c071cac9fc0ed24a15067de
[ "MIT" ]
null
null
null
source/texture.cpp
deyahruhd/terramagna
931887afad11c6cf2c071cac9fc0ed24a15067de
[ "MIT" ]
null
null
null
source/texture.cpp
deyahruhd/terramagna
931887afad11c6cf2c071cac9fc0ed24a15067de
[ "MIT" ]
null
null
null
#include <fstream> #include <iostream> #include <png.h> #include "texture.h" namespace game { texture_params::texture_params (void) { } texture_params::texture_params (int unit, GLint mag_func, GLint wrapping, GLint internalformat, GLenum format, GLenum type, vec2 resolution) : unit (unit), mag_func (mag_func), wrapping (wrapping), internalformat (internalformat), format (format), type (type), resolution (resolution) { } void sread (png_structp pngptr, png_bytep data, png_size_t length) { png_voidp a = png_get_io_ptr (pngptr); ((std::ifstream *) a) -> read ((char*) data, length); } texture::texture (void) : id (NULL), v_ (NULL), is_built (false) { } texture::texture (int unit, GLint mag_func, GLint wrapping, GLint internalformat, GLenum format, GLenum type, vec2 resolution, const GLvoid * data, int unpack, std::vector <int> * v_) : params (texture_params (unit, mag_func, wrapping, internalformat, format, type, resolution)), id (NULL), v_ (v_), is_built (false) { glGenTextures (1, &id); if (params.unit > -1) glActiveTexture (GL_TEXTURE0 + params.unit); glBindTexture (GL_TEXTURE_2D, id); glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, params.mag_func); glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, params.mag_func); glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, params.wrapping); glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, params.wrapping); glPixelStorei (GL_UNPACK_ALIGNMENT, unpack > 0 ? unpack : 4); glTexImage2D (GL_TEXTURE_2D, 0, params.internalformat, params.resolution.x, params.resolution.y, 0, params.format, params.type, data); is_built = true; } texture::texture (int unit, GLint mag_func, GLint wrapping, GLint internalformat, std::string name, int unpack, std::vector <int> * v_) : id (NULL), v_ (v_) { png_byte header [8]; std::ifstream s ("files\\assets\\images\\" + name + ".png", std::ios::in | std::ios::binary); if (! s.is_open ()) { std::cerr << "Error in texture '" << name << "': File 'files\\assets\\images\\" << name << ".png" << "' could not be found" << std::endl; return; } s.read ((char *) header, 8); if (png_sig_cmp (header, 0, 8)) { std::cerr << "Error in texture '" << name << "': File 'files\\assets\\images\\" << name << ".png" << "' is not a PNG file" << std::endl; return; } png_structp png_ptr = png_create_read_struct (PNG_LIBPNG_VER_STRING, NULL, NULL, NULL); if (! png_ptr) { std::cerr << "Error in texture '" << name << "': Function png_create_read_struct returned a NULL pointer" << std::endl; return; } png_infop info_ptr = png_create_info_struct (png_ptr); if (! info_ptr) { std::cerr << "Error in texture '" << name << "': Function png_create_info_struct returned a NULL pointer" << std::endl; png_destroy_read_struct (& png_ptr, (png_infopp) NULL, (png_infopp) NULL); return; } if (setjmp (png_jmpbuf (png_ptr))) { std::cerr << "Error in texture '" << name << "': libpng encountered an error - refer above" << std::endl; png_destroy_read_struct (& png_ptr, & info_ptr, (png_infopp) NULL); return; } png_set_read_fn (png_ptr, (png_voidp) & s, sread); png_set_sig_bytes (png_ptr, 8); png_read_info (png_ptr, info_ptr); int bit_depth, color_type; png_uint_32 width, height; GLint png_format; png_get_IHDR (png_ptr, info_ptr, &width, &height, &bit_depth, &color_type, NULL, NULL, NULL); if (bit_depth != 8) { std::cerr << "Error in texture '" << name << "': PNG 'files\\assets\\images\\" << name << ".png' has an unsupported bit-depth" << std::endl; png_destroy_read_struct (& png_ptr, & info_ptr, (png_infopp) NULL); return; } switch (color_type) { case PNG_COLOR_TYPE_RGB: png_format = GL_RGB; break; case PNG_COLOR_TYPE_RGB_ALPHA: png_format = GL_RGBA; break; default: std::cerr << "Error in texture '" << name << "': PNG 'files\\assets\\images\\" << name << ".png' has an unknown color type" << std::endl; png_destroy_read_struct (& png_ptr, & info_ptr, (png_infopp) NULL); return; } png_read_update_info (png_ptr, info_ptr); int row_bytes = png_get_rowbytes (png_ptr, info_ptr); row_bytes += 3 - ((row_bytes - 1) % 4); png_byte * image_data = new png_byte [row_bytes * height * sizeof (png_byte) + 15]; png_byte ** row_pointers = new png_byte * [height * sizeof (png_byte *)]; for (unsigned int it = 0; it < height; ++ it) { row_pointers [it] = image_data + it * row_bytes; } png_read_image (png_ptr, row_pointers); png_destroy_read_struct (& png_ptr, & info_ptr, (png_infopp) NULL); delete [] row_pointers; params = texture_params (unit, mag_func, wrapping, internalformat, png_format, GL_UNSIGNED_BYTE, vec2 ((int) width, (int) height)); glGenTextures (1, &id); if (params.unit > -1) glActiveTexture (GL_TEXTURE0 + params.unit); glBindTexture (GL_TEXTURE_2D, id); glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, params.mag_func); glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, params.mag_func); glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, params.wrapping); glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, params.wrapping); glPixelStorei (GL_UNPACK_ALIGNMENT, unpack > 0 ? unpack : 4); glTexImage2D (GL_TEXTURE_2D, 0, params.internalformat, params.resolution.x, params.resolution.y, 0, params.format, params.type, image_data); delete [] image_data; is_built = true; } texture::~texture (void) { } void texture::sub (vec2 pos, vec2 dim, GLvoid * data) { if (! is_built) return; glBindTexture (GL_TEXTURE_2D, id); glTexSubImage2D (GL_TEXTURE_2D, 0, pos.x, pos.y, dim.x, dim.y, params.format, params.type, data); } void texture::bind (void) { glBindTexture (GL_TEXTURE_2D, id); } void texture::unbind (void) { glBindTexture (GL_TEXTURE_2D, 0); } void texture::clear (void) { if (! is_built) return; unbind (); glDeleteTextures (1, &id); if (params.unit > -1 && v_ != NULL && v_ -> size () > 0) { for (auto it = v_ -> begin (); it != v_ -> end (); ++ it) { if (* it == params.unit) { v_ -> erase (it); break; } } } v_ = NULL; is_built = false; } const GLuint texture::get_id (void) const { return id; } const bool texture::get_completed (void) const { return is_built; } const texture_params texture::get_params (void) const { return params; } }
36.709497
320
0.65926
[ "vector" ]
3e200b4da38669710157847a8bb0840c34dd4fbd
25,150
hpp
C++
libraries/chain/include/eosio/chain/pbft_database.hpp
boscore/ibc_plugin
9404871000d16ff402b608d3a8f6eb666dba5fda
[ "MIT" ]
68
2018-11-20T02:09:14.000Z
2021-12-22T03:30:59.000Z
libraries/chain/include/eosio/chain/pbft_database.hpp
boscore/ibc_plugin
9404871000d16ff402b608d3a8f6eb666dba5fda
[ "MIT" ]
57
2018-11-21T07:31:54.000Z
2020-07-17T03:08:12.000Z
libraries/chain/include/eosio/chain/pbft_database.hpp
boscore/ibc_plugin
9404871000d16ff402b608d3a8f6eb666dba5fda
[ "MIT" ]
37
2018-11-20T03:59:11.000Z
2021-01-26T03:59:46.000Z
#pragma once #include <eosio/chain/controller.hpp> #include <eosio/chain/fork_database.hpp> #include <boost/signals2/signal.hpp> #include <boost/multi_index_container.hpp> #include <boost/multi_index/member.hpp> #include <boost/multi_index/ordered_index.hpp> #include <boost/multi_index/hashed_index.hpp> #include <boost/multi_index/mem_fun.hpp> #include <boost/multi_index/composite_key.hpp> #include <fc/bitutil.hpp> namespace eosio { namespace chain { using boost::multi_index_container; using namespace boost::multi_index; using namespace std; using pbft_view_type = uint32_t; constexpr uint16_t oldest_stable_checkpoint = 10000; enum class pbft_message_type : uint8_t { prepare, commit, checkpoint, view_change, new_view }; struct block_info_type { block_id_type block_id; block_num_type block_num() const { return fc::endian_reverse_u32(block_id._hash[0]); } bool operator==(const block_info_type& rhs) const { return block_id == rhs.block_id; } bool operator!=(const block_info_type& rhs) const { return !(*this == rhs); } bool empty() const { return block_id == block_id_type(); } }; using fork_info_type = vector<block_info_type>; struct pbft_message_common { explicit pbft_message_common(pbft_message_type t): type{t} {}; pbft_message_type type; time_point timestamp = time_point::now(); ~pbft_message_common() = default; }; template<typename pbft_message_body> struct pbft_message_metadata { explicit pbft_message_metadata(pbft_message_body m, chain_id_type& chain_id): msg{m} { try { sender_key = crypto::public_key(msg.sender_signature, msg.digest(chain_id), true); } catch (fc::exception & /*e*/) { wlog("bad pbft message signature: ${m}", ("m", msg)); } } pbft_message_body msg; public_key_type sender_key; }; template<typename pbft_message_body> using pbft_metadata_ptr = std::shared_ptr<pbft_message_metadata<pbft_message_body>>; struct pbft_prepare { explicit pbft_prepare() = default; pbft_message_common common = pbft_message_common(pbft_message_type::prepare); pbft_view_type view = 0; block_info_type block_info; signature_type sender_signature; bool operator<(const pbft_prepare& rhs) const { if (block_info.block_num() < rhs.block_info.block_num()) { return true; } else if (block_info.block_num() == rhs.block_info.block_num()) { return view < rhs.view; } else { return false; } } bool empty() const { return !view && block_info.empty() && sender_signature == signature_type(); } digest_type digest(chain_id_type chain_id) const { digest_type::encoder enc; fc::raw::pack(enc, chain_id); fc::raw::pack(enc, common); fc::raw::pack(enc, view); fc::raw::pack(enc, block_info); return enc.result(); } }; using pbft_prepare_ptr = std::shared_ptr<pbft_prepare>; struct pbft_commit { explicit pbft_commit() = default; pbft_message_common common = pbft_message_common(pbft_message_type::commit); pbft_view_type view = 0; block_info_type block_info; signature_type sender_signature; bool operator<(const pbft_commit& rhs) const { if (block_info.block_num() < rhs.block_info.block_num()) { return true; } else if (block_info.block_num() == rhs.block_info.block_num()) { return view < rhs.view; } else { return false; } } bool empty() const { return !view && block_info.empty() && sender_signature == signature_type(); } digest_type digest(chain_id_type chain_id) const { digest_type::encoder enc; fc::raw::pack(enc, chain_id); fc::raw::pack(enc, common); fc::raw::pack(enc, view); fc::raw::pack(enc, block_info); return enc.result(); } }; using pbft_commit_ptr = std::shared_ptr<pbft_commit>; struct pbft_checkpoint { explicit pbft_checkpoint() = default; pbft_message_common common = pbft_message_common(pbft_message_type::checkpoint); block_info_type block_info; signature_type sender_signature; bool operator<(const pbft_checkpoint& rhs) const { return block_info.block_num() < rhs.block_info.block_num(); } digest_type digest(chain_id_type chain_id) const { digest_type::encoder enc; fc::raw::pack(enc, chain_id); fc::raw::pack(enc, common); fc::raw::pack(enc, block_info); return enc.result(); } }; using pbft_checkpoint_ptr = std::shared_ptr<pbft_checkpoint>; struct pbft_stable_checkpoint { explicit pbft_stable_checkpoint() = default; block_info_type block_info; vector<pbft_checkpoint> checkpoints; bool operator<(const pbft_stable_checkpoint& rhs) const { return block_info.block_num() < rhs.block_info.block_num(); } bool empty() const { return block_info == block_info_type() && checkpoints.empty(); } }; struct pbft_prepared_certificate { explicit pbft_prepared_certificate() = default; block_info_type block_info; set<block_id_type> pre_prepares; vector<pbft_prepare> prepares; bool operator<(const pbft_prepared_certificate& rhs) const { return block_info.block_num() < rhs.block_info.block_num(); } bool empty() const { return block_info == block_info_type() && prepares.empty(); } }; struct pbft_committed_certificate { explicit pbft_committed_certificate() = default; block_info_type block_info; vector<pbft_commit> commits; bool operator<(const pbft_committed_certificate& rhs) const { return block_info.block_num() < rhs.block_info.block_num(); } bool empty() const { return block_info == block_info_type() && commits.empty(); } }; struct pbft_view_change { explicit pbft_view_change() = default; pbft_message_common common = pbft_message_common(pbft_message_type::view_change); pbft_view_type current_view = 0; pbft_view_type target_view = 1; pbft_prepared_certificate prepared_cert; vector<pbft_committed_certificate> committed_certs; pbft_stable_checkpoint stable_checkpoint; signature_type sender_signature; bool operator<(const pbft_view_change& rhs) const { return target_view < rhs.target_view; } digest_type digest(chain_id_type chain_id) const { digest_type::encoder enc; fc::raw::pack(enc, chain_id); fc::raw::pack(enc, common); fc::raw::pack(enc, current_view); fc::raw::pack(enc, target_view); fc::raw::pack(enc, prepared_cert); fc::raw::pack(enc, committed_certs); fc::raw::pack(enc, stable_checkpoint); return enc.result(); } bool empty() const { return !current_view && target_view == 1 && prepared_cert.empty() && committed_certs.empty() && stable_checkpoint.empty() && sender_signature == signature_type(); } }; using pbft_view_change_ptr = std::shared_ptr<pbft_view_change>; struct pbft_view_changed_certificate { explicit pbft_view_changed_certificate() = default; pbft_view_type target_view = 0; vector<pbft_view_change> view_changes; bool empty() const { return !target_view && view_changes.empty(); } }; struct pbft_new_view { explicit pbft_new_view() = default; pbft_message_common common = pbft_message_common(pbft_message_type::new_view); pbft_view_type new_view = 0; pbft_prepared_certificate prepared_cert; vector<pbft_committed_certificate> committed_certs; pbft_stable_checkpoint stable_checkpoint; pbft_view_changed_certificate view_changed_cert; signature_type sender_signature; bool operator<(const pbft_new_view& rhs) const { return new_view < rhs.new_view; } digest_type digest(chain_id_type chain_id) const { digest_type::encoder enc; fc::raw::pack(enc, chain_id); fc::raw::pack(enc, common); fc::raw::pack(enc, new_view); fc::raw::pack(enc, prepared_cert); fc::raw::pack(enc, committed_certs); fc::raw::pack(enc, stable_checkpoint); fc::raw::pack(enc, view_changed_cert); return enc.result(); } bool empty() const { return !new_view && prepared_cert.empty() && committed_certs.empty() && stable_checkpoint.empty() && view_changed_cert.empty() && sender_signature == signature_type(); } }; using pbft_new_view_ptr = std::shared_ptr<pbft_new_view>; struct pbft_state { block_id_type block_id; block_num_type block_num = 0; flat_map<std::pair<pbft_view_type, public_key_type>, pbft_prepare> prepares; bool is_prepared = false; flat_map<std::pair<pbft_view_type, public_key_type>, pbft_commit> commits; bool is_committed = false; }; struct pbft_view_change_state { pbft_view_type view; flat_map<public_key_type, pbft_view_change> view_changes; bool is_view_changed = false; }; struct pbft_checkpoint_state { block_id_type block_id; block_num_type block_num = 0; flat_map<public_key_type, pbft_checkpoint> checkpoints; bool is_stable = false; }; using producer_and_block_info = std::pair<public_key_type, block_info_type>; struct validation_state { block_id_type block_id; block_num_type block_num = 0; vector<public_key_type> producers; bool enough = false; }; using pbft_state_ptr = std::shared_ptr<pbft_state>; using pbft_view_change_state_ptr = std::shared_ptr<pbft_view_change_state>; using pbft_checkpoint_state_ptr = std::shared_ptr<pbft_checkpoint_state>; using validation_state_ptr = std::shared_ptr<validation_state>; struct by_block_id; struct by_num; struct by_prepare_and_num; struct by_commit_and_num; typedef multi_index_container< pbft_state_ptr, indexed_by< hashed_unique < tag<by_block_id>, member<pbft_state, block_id_type, &pbft_state::block_id>, std::hash<block_id_type> >, ordered_non_unique< tag<by_num>, member<pbft_state, uint32_t, &pbft_state::block_num>, less<> >, ordered_non_unique< tag<by_prepare_and_num>, composite_key< pbft_state, member<pbft_state, bool, &pbft_state::is_prepared>, member<pbft_state, uint32_t, &pbft_state::block_num> >, composite_key_compare< greater<>, greater<> > >, ordered_non_unique< tag<by_commit_and_num>, composite_key< pbft_state, member<pbft_state, bool, &pbft_state::is_committed>, member<pbft_state, uint32_t, &pbft_state::block_num> >, composite_key_compare< greater<>, greater<> > > > > pbft_state_multi_index_type; struct by_view; struct by_count_and_view; typedef multi_index_container< pbft_view_change_state_ptr, indexed_by< ordered_unique< tag<by_view>, member<pbft_view_change_state, pbft_view_type, &pbft_view_change_state::view>, greater<> >, ordered_non_unique< tag<by_count_and_view>, composite_key< pbft_view_change_state, member<pbft_view_change_state, bool, &pbft_view_change_state::is_view_changed>, member<pbft_view_change_state, pbft_view_type, &pbft_view_change_state::view> >, composite_key_compare<greater<>, greater<>> > > > pbft_view_state_multi_index_type; struct by_block_id; struct by_num; typedef multi_index_container< pbft_checkpoint_state_ptr, indexed_by< hashed_unique< tag<by_block_id>, member<pbft_checkpoint_state, block_id_type, &pbft_checkpoint_state::block_id>, std::hash<block_id_type> >, ordered_non_unique< tag<by_num>, member<pbft_checkpoint_state, uint32_t, &pbft_checkpoint_state::block_num>, less<> > > > pbft_checkpoint_state_multi_index_type; struct by_block_id; struct by_status_and_num; typedef multi_index_container< validation_state_ptr, indexed_by< hashed_unique < tag<by_block_id>, member<validation_state, block_id_type, &validation_state::block_id>, std::hash<block_id_type> >, ordered_non_unique< tag<by_status_and_num>, composite_key< validation_state, member<validation_state, bool, &validation_state::enough>, member<validation_state, uint32_t, &validation_state::block_num> >, composite_key_compare< greater<>, greater<> > > > > local_state_multi_index_type; class pbft_database { public: explicit pbft_database(controller& ctrl); ~pbft_database(); void add_pbft_prepare(const pbft_prepare& p, const public_key_type& pk); void add_pbft_commit(const pbft_commit& c, const public_key_type& pk); void add_pbft_view_change(const pbft_view_change& vc, const public_key_type& pk); void add_pbft_checkpoint(const pbft_checkpoint& cp, const public_key_type& pk); vector<pbft_prepare> generate_and_add_pbft_prepare(const pbft_prepare& cached_prepare = pbft_prepare()); vector<pbft_commit> generate_and_add_pbft_commit(const pbft_commit& cached_commit = pbft_commit()); vector<pbft_view_change> generate_and_add_pbft_view_change( const pbft_view_change& cached_view_change = pbft_view_change(), const pbft_prepared_certificate& ppc = pbft_prepared_certificate(), const vector<pbft_committed_certificate>& pcc = vector<pbft_committed_certificate>{}, pbft_view_type target_view = 1); pbft_new_view generate_pbft_new_view( const pbft_view_changed_certificate& vcc = pbft_view_changed_certificate(), pbft_view_type new_view = 1); vector<pbft_checkpoint> generate_and_add_pbft_checkpoint(); bool should_prepared(); bool should_committed(); pbft_view_type should_view_change(); bool should_new_view(pbft_view_type target_view); //new view bool has_new_primary(const public_key_type& pk); pbft_view_type get_proposed_new_view_num(); pbft_view_type get_committed_view(); public_key_type get_new_view_primary_key(pbft_view_type target_view); void mark_as_prepared(const block_id_type& bid); void mark_as_committed(const block_id_type& bid); void commit_local(); void checkpoint_local(); //view change pbft_prepared_certificate generate_prepared_certificate(); vector<pbft_committed_certificate> generate_committed_certificate(); pbft_view_changed_certificate generate_view_changed_certificate(pbft_view_type target_view); bool should_stop_view_change(const pbft_view_change& vc); //validations bool is_valid_prepare(const pbft_prepare& p, const public_key_type& pk); bool is_valid_commit(const pbft_commit& c, const public_key_type& pk); bool is_valid_checkpoint(const pbft_checkpoint& cp, const public_key_type& pk); bool is_valid_view_change(const pbft_view_change& vc, const public_key_type& pk); void validate_new_view(const pbft_new_view& nv, const public_key_type& pk); bool is_valid_stable_checkpoint(const pbft_stable_checkpoint& scp, bool add_to_pbft_db = false); bool should_send_pbft_msg(); bool should_recv_pbft_msg(const public_key_type& pub_key); bool pending_pbft_lib(); chain_id_type& get_chain_id() { return chain_id; } pbft_stable_checkpoint get_stable_checkpoint_by_id(const block_id_type& block_id, bool incl_blk_extn = true); pbft_stable_checkpoint fetch_stable_checkpoint_from_blk_extn(const signed_block_ptr& b); void cleanup_on_new_view(); void update_fork_schedules(); uint16_t get_view_change_timeout() const; uint16_t get_checkpoint_interval() const; const pbft_view_type get_current_view() { return _current_view; } void set_current_view(pbft_view_type view) { _current_view = view; } //api related pbft_state_ptr get_pbft_state_by_id(const block_id_type& id) const; vector<pbft_checkpoint_state> get_checkpoints_by_num(block_num_type num) const; pbft_view_change_state_ptr get_view_changes_by_target_view(pbft_view_type tv) const; vector<block_num_type> get_pbft_watermarks() const; flat_map<public_key_type, uint32_t> get_pbft_fork_schedules() const; producer_schedule_type lscb_active_producers() const; private: controller& ctrl; pbft_state_multi_index_type pbft_state_index; pbft_view_state_multi_index_type view_state_index; pbft_checkpoint_state_multi_index_type checkpoint_index; fc::path pbft_db_dir; fc::path checkpoints_dir; vector<block_num_type> prepare_watermarks; flat_map<public_key_type, block_num_type> fork_schedules; chain_id_type chain_id = ctrl.get_chain_id(); pbft_view_type _current_view = 0; block_info_type cal_pending_stable_checkpoint() const; bool is_less_than_high_watermark(block_num_type bnum); bool is_valid_prepared_certificate(const pbft_prepared_certificate& certificate, bool add_to_pbft_db = false); bool is_valid_committed_certificate(const pbft_committed_certificate& certificate, bool add_to_pbft_db = false, bool at_the_top = false); bool is_valid_longest_fork(const vector<producer_and_block_info>& producers, const block_info_type& cert_info, bool at_the_top = false); vector<block_num_type>& get_updated_watermarks(); flat_map<public_key_type, uint32_t>& get_updated_fork_schedules(); block_num_type get_current_pbft_watermark(); void set(const pbft_state_ptr& s); void set(const pbft_checkpoint_state_ptr& s); void prune(const pbft_state_ptr& h); void prune(const pbft_checkpoint_state_ptr& h); }; } } /// namespace eosio::chain FC_REFLECT(eosio::chain::block_info_type, (block_id)) FC_REFLECT_ENUM(eosio::chain::pbft_message_type, (prepare)(commit)(checkpoint)(view_change)(new_view)) FC_REFLECT(eosio::chain::pbft_message_common, (type)(timestamp)) FC_REFLECT_TEMPLATE((typename pbft_message_body), eosio::chain::pbft_message_metadata<pbft_message_body>, (msg)(sender_key)) FC_REFLECT(eosio::chain::pbft_prepare, (common)(view)(block_info)(sender_signature)) FC_REFLECT(eosio::chain::pbft_commit, (common)(view)(block_info)(sender_signature)) FC_REFLECT(eosio::chain::pbft_checkpoint,(common)(block_info)(sender_signature)) FC_REFLECT(eosio::chain::pbft_view_change, (common)(current_view)(target_view)(prepared_cert)(committed_certs)(stable_checkpoint)(sender_signature)) FC_REFLECT(eosio::chain::pbft_new_view, (common)(new_view)(prepared_cert)(committed_certs)(stable_checkpoint)(view_changed_cert)(sender_signature)) FC_REFLECT(eosio::chain::pbft_prepared_certificate, (block_info)(pre_prepares)(prepares)) FC_REFLECT(eosio::chain::pbft_committed_certificate,(block_info)(commits)) FC_REFLECT(eosio::chain::pbft_view_changed_certificate, (target_view)(view_changes)) FC_REFLECT(eosio::chain::pbft_stable_checkpoint, (block_info)(checkpoints)) FC_REFLECT(eosio::chain::pbft_state, (block_id)(block_num)(prepares)(is_prepared)(commits)(is_committed)) FC_REFLECT(eosio::chain::pbft_view_change_state, (view)(view_changes)(is_view_changed)) FC_REFLECT(eosio::chain::pbft_checkpoint_state, (block_id)(block_num)(checkpoints)(is_stable)) FC_REFLECT(eosio::chain::validation_state, (block_id)(block_num)(producers)(enough))
43.73913
149
0.558449
[ "vector" ]
4a3df08e1530694e8ed018c6f446cf7b917888a8
7,588
cpp
C++
src/demi/gfx/ObjectDataArrayMemoryManager.cpp
wangyanxing/Demi3D
73e684168bd39b894f448779d41fab600ba9b150
[ "MIT" ]
10
2015-03-04T04:27:15.000Z
2020-06-04T14:06:47.000Z
src/demi/gfx/ObjectDataArrayMemoryManager.cpp
wangyanxing/Demi3D
73e684168bd39b894f448779d41fab600ba9b150
[ "MIT" ]
null
null
null
src/demi/gfx/ObjectDataArrayMemoryManager.cpp
wangyanxing/Demi3D
73e684168bd39b894f448779d41fab600ba9b150
[ "MIT" ]
5
2015-10-17T19:09:58.000Z
2021-11-15T23:42:18.000Z
/********************************************************************** This source file is a part of Demi3D __ ___ __ __ __ | \|_ |\/|| _)| \ |__/|__| || __)|__/ Copyright (c) 2013-2014 Demi team https://github.com/wangyanxing/Demi3D Released under the MIT License https://github.com/wangyanxing/Demi3D/blob/master/License.txt ***********************************************************************/ /// This file is adapted from Ogre 2.0 (unstable version) #include "GfxPch.h" #include "ArrayMemoryManager.h" #include "ObjectData.h" #include "TransformUnit.h" namespace Demi { const size_t ObjectDataArrayMemoryManager::ElementsMemSize [ObjectDataArrayMemoryManager::NumMemoryTypes] = { sizeof( DiNode** ), //ArrayMemoryManager::Parent sizeof( DiTransformUnit** ), //ArrayMemoryManager::Owner 6 * sizeof( float ), //ArrayMemoryManager::LocalAabb 6 * sizeof( float ), //ArrayMemoryManager::WorldAabb 1 * sizeof( float ), //ArrayMemoryManager::LocalRadius 1 * sizeof( float ), //ArrayMemoryManager::WorldRadius 1 * sizeof( float ), //ArrayMemoryManager::SquaredUpperDistance 1 * sizeof(uint32), //ArrayMemoryManager::VisibilityFlags 1 * sizeof(uint32), //ArrayMemoryManager::QueryFlags 1 * sizeof(uint32), //ArrayMemoryManager::LightMask }; const CleanupRoutines ObjectDataArrayMemoryManager::ObjCleanupRoutines[NumMemoryTypes] = { cleanerFlat, //ArrayMemoryManager::Parent cleanerFlat, //ArrayMemoryManager::Owner cleanerArrayAabb, //ArrayMemoryManager::LocalAabb cleanerArrayAabb, //ArrayMemoryManager::WorldAabb cleanerFlat, //ArrayMemoryManager::LocalRadius cleanerFlat, //ArrayMemoryManager::WorldRadius cleanerFlat, //ArrayMemoryManager::SquaredUpperDistance cleanerFlat, //ArrayMemoryManager::VisibilityFlags cleanerFlat, //ArrayMemoryManager::QueryFlags cleanerFlat, //ArrayMemoryManager::LightMask }; ObjectDataArrayMemoryManager::ObjectDataArrayMemoryManager( uint16 depthLevel, size_t hintMaxNodes, DiNode *dummyNode, DiTransUnitPtr dummyObject, size_t cleanupThreshold, size_t maxHardLimit, RebaseListener *rebaseListener ) : ArrayMemoryManager( ArrayMemoryManager::ObjectDataType, ElementsMemSize, ObjCleanupRoutines, sizeof( ElementsMemSize ) / sizeof( size_t ), depthLevel, hintMaxNodes, cleanupThreshold, maxHardLimit, rebaseListener ), mDummyNode( dummyNode ), mDummyObject( dummyObject ) { } void ObjectDataArrayMemoryManager::slotsRecreated( size_t prevNumSlots ) { ArrayMemoryManager::slotsRecreated( prevNumSlots ); DiNode **nodesPtr = reinterpret_cast<DiNode**>( mMemoryPools[Parent] ) + prevNumSlots; DiTransUnitPtr *ownersPtr = reinterpret_cast<DiTransUnitPtr*>(mMemoryPools[Owner]) + prevNumSlots; for( size_t i=prevNumSlots; i<mMaxMemory; ++i ) { *nodesPtr++ = mDummyNode; *ownersPtr++ = mDummyObject; } } void ObjectDataArrayMemoryManager::createNewNode( ObjectData &outData ) { const size_t nextSlot = createNewSlot(); const unsigned char nextSlotIdx = nextSlot % ARRAY_PACKED_REALS; const size_t nextSlotBase = nextSlot - nextSlotIdx; //Set memory ptrs outData.mIndex = nextSlotIdx; outData.mParents = reinterpret_cast<DiNode**>( mMemoryPools[Parent] + nextSlotBase * mElementsMemSizes[Parent] ); outData.mOwner = reinterpret_cast<DiTransUnitPtr*>( mMemoryPools[Owner] + nextSlotBase * mElementsMemSizes[Owner] ); outData.mLocalAabb = reinterpret_cast<ArrayAabb*>( mMemoryPools[LocalAabb] + nextSlotBase * mElementsMemSizes[LocalAabb] ); outData.mWorldAabb = reinterpret_cast<ArrayAabb*>( mMemoryPools[WorldAabb] + nextSlotBase * mElementsMemSizes[WorldAabb] ); outData.mLocalRadius = reinterpret_cast<float*>( mMemoryPools[LocalRadius] + nextSlotBase * mElementsMemSizes[LocalRadius] ); outData.mWorldRadius = reinterpret_cast<float*>( mMemoryPools[WorldRadius] + nextSlotBase * mElementsMemSizes[WorldRadius] ); outData.mUpperDistance = reinterpret_cast<float*>( mMemoryPools[UpperDistance] + nextSlotBase * mElementsMemSizes[UpperDistance] ); outData.mVisibilityFlags = reinterpret_cast<uint32*>( mMemoryPools[VisibilityFlags] + nextSlotBase * mElementsMemSizes[VisibilityFlags] ); outData.mQueryFlags = reinterpret_cast<uint32*>( mMemoryPools[QueryFlags] + nextSlotBase * mElementsMemSizes[QueryFlags] ); outData.mLightMask = reinterpret_cast<uint32*>( mMemoryPools[LightMask] + nextSlotBase * mElementsMemSizes[LightMask] ); //Set default values outData.mParents[nextSlotIdx] = mDummyNode; outData.mOwner[nextSlotIdx] = 0; //Caller has to fill it. Otherwise a crash is a good warning outData.mLocalAabb->setFromAabb( Aabb::BOX_INFINITE, nextSlotIdx ); outData.mWorldAabb->setFromAabb( Aabb::BOX_INFINITE, nextSlotIdx ); outData.mWorldRadius[nextSlotIdx] = 0; outData.mUpperDistance[nextSlotIdx] = std::numeric_limits<float>::max(); outData.mVisibilityFlags[nextSlotIdx] = DiTransformUnit::GetDefaultVisibilityFlags(); outData.mQueryFlags[nextSlotIdx] = DiTransformUnit::GetDefaultQueryFlags(); outData.mLightMask[nextSlotIdx] = 0xFFFFFFFF; } void ObjectDataArrayMemoryManager::destroyNode( ObjectData &inOutData ) { //Zero out important data that would lead to bugs (Remember SIMD SoA means even if //there's one object in scene, 4 objects are still parsed simultaneously) inOutData.mParents[inOutData.mIndex] = mDummyNode; inOutData.mOwner[inOutData.mIndex] = mDummyObject; inOutData.mVisibilityFlags[inOutData.mIndex] = 0; inOutData.mQueryFlags[inOutData.mIndex] = 0; inOutData.mLightMask[inOutData.mIndex] = 0; destroySlot( reinterpret_cast<char*>(inOutData.mParents), inOutData.mIndex ); //Zero out all pointers inOutData = ObjectData(); } size_t ObjectDataArrayMemoryManager::getFirstNode( ObjectData &outData ) { // Quick hack to fill all pointer variables (I'm lazy to type!) memcpy( &outData.mParents, &mMemoryPools[0], sizeof(void*) * mMemoryPools.size() ); return mUsedMemory; } }
54.2
106
0.589352
[ "object" ]
4a3fed9aa1ae97808f6433b84dc8ae94318d9604
6,278
cpp
C++
src/matrix3.cpp
workhorsy/test_wasm
13764cda35102d4ec8a0a2ef46df8187c15c5c50
[ "MIT" ]
null
null
null
src/matrix3.cpp
workhorsy/test_wasm
13764cda35102d4ec8a0a2ef46df8187c15c5c50
[ "MIT" ]
null
null
null
src/matrix3.cpp
workhorsy/test_wasm
13764cda35102d4ec8a0a2ef46df8187c15c5c50
[ "MIT" ]
null
null
null
#include "three.h" namespace THREE { Matrix3::Matrix3() { this->elements = { 1, 0, 0, 0, 1, 0, 0, 0, 1 }; //if ( arguments.length > 0 ) { //console.error( 'THREE.Matrix3: the constructor no longer reads arguments. use .set() instead.' ); //} } THREE::Matrix3* Matrix3::set(float n11, float n12, float n13, float n21, float n22, float n23, float n31, float n32, float n33) { auto te = this->elements; te[ 0 ] = n11; te[ 1 ] = n21; te[ 2 ] = n31; te[ 3 ] = n12; te[ 4 ] = n22; te[ 5 ] = n32; te[ 6 ] = n13; te[ 7 ] = n23; te[ 8 ] = n33; return this; } THREE::Matrix3* Matrix3::identity() { this->set( 1, 0, 0, 0, 1, 0, 0, 0, 1 ); return this; } THREE::Matrix3* Matrix3::clone() { return (new Matrix3())->fromArray( this->elements ); } THREE::Matrix3* Matrix3::copy(THREE::Matrix3* m ) { auto te = this->elements; auto me = m->elements; te[ 0 ] = me[ 0 ]; te[ 1 ] = me[ 1 ]; te[ 2 ] = me[ 2 ]; te[ 3 ] = me[ 3 ]; te[ 4 ] = me[ 4 ]; te[ 5 ] = me[ 5 ]; te[ 6 ] = me[ 6 ]; te[ 7 ] = me[ 7 ]; te[ 8 ] = me[ 8 ]; return this; } THREE::Matrix3* Matrix3::setFromMatrix4(THREE::Matrix4* m ) { auto me = m->elements; this->set( me[ 0 ], me[ 4 ], me[ 8 ], me[ 1 ], me[ 5 ], me[ 9 ], me[ 2 ], me[ 6 ], me[ 10 ] ); return this; } /* BufferAttribute* Matrix3::applyToBufferAttribute(BufferAttribute* attribute) { auto v1 = new Vector3(); for ( int i = 0, l = attribute->count; i < l; i ++ ) { v1.x = attribute->getX( i ); v1.y = attribute->getY( i ); v1.z = attribute->getZ( i ); v1.applyMatrix3( this ); attribute->setXYZ( i, v1.x, v1.y, v1.z ); } return attribute; } */ THREE::Matrix3* Matrix3::multiply(THREE::Matrix3* m ) { return this->multiplyMatrices( this, m ); } THREE::Matrix3* Matrix3::premultiply(THREE::Matrix3* m ) { return this->multiplyMatrices( m, this ); } THREE::Matrix3* Matrix3::multiplyMatrices(THREE::Matrix3* a, THREE::Matrix3* b ) { auto ae = a->elements; auto be = b->elements; auto te = this->elements; auto a11 = ae[ 0 ], a12 = ae[ 3 ], a13 = ae[ 6 ]; auto a21 = ae[ 1 ], a22 = ae[ 4 ], a23 = ae[ 7 ]; auto a31 = ae[ 2 ], a32 = ae[ 5 ], a33 = ae[ 8 ]; auto b11 = be[ 0 ], b12 = be[ 3 ], b13 = be[ 6 ]; auto b21 = be[ 1 ], b22 = be[ 4 ], b23 = be[ 7 ]; auto b31 = be[ 2 ], b32 = be[ 5 ], b33 = be[ 8 ]; te[ 0 ] = a11 * b11 + a12 * b21 + a13 * b31; te[ 3 ] = a11 * b12 + a12 * b22 + a13 * b32; te[ 6 ] = a11 * b13 + a12 * b23 + a13 * b33; te[ 1 ] = a21 * b11 + a22 * b21 + a23 * b31; te[ 4 ] = a21 * b12 + a22 * b22 + a23 * b32; te[ 7 ] = a21 * b13 + a22 * b23 + a23 * b33; te[ 2 ] = a31 * b11 + a32 * b21 + a33 * b31; te[ 5 ] = a31 * b12 + a32 * b22 + a33 * b32; te[ 8 ] = a31 * b13 + a32 * b23 + a33 * b33; return this; } THREE::Matrix3* Matrix3::multiplyScalar(float s ) { auto te = this->elements; te[ 0 ] *= s; te[ 3 ] *= s; te[ 6 ] *= s; te[ 1 ] *= s; te[ 4 ] *= s; te[ 7 ] *= s; te[ 2 ] *= s; te[ 5 ] *= s; te[ 8 ] *= s; return this; } float Matrix3::determinant() { auto te = this->elements; auto a = te[ 0 ]; auto b = te[ 1 ]; auto c = te[ 2 ]; auto d = te[ 3 ]; auto e = te[ 4 ]; auto f = te[ 5 ]; auto g = te[ 6 ]; auto h = te[ 7 ]; auto i = te[ 8 ]; return a * e * i - a * f * h - b * d * i + b * f * g + c * d * h - c * e * g; } THREE::Matrix3* Matrix3::getInverse(THREE::Matrix3* matrix) { return this->getInverse(matrix, false); } THREE::Matrix3* Matrix3::getInverse(THREE::Matrix3* matrix, bool throwOnDegenerate ) { auto me = matrix->elements; auto te = this->elements; auto n11 = me[ 0 ]; auto n21 = me[ 1 ]; auto n31 = me[ 2 ]; auto n12 = me[ 3 ]; auto n22 = me[ 4 ]; auto n32 = me[ 5 ]; auto n13 = me[ 6 ]; auto n23 = me[ 7 ]; auto n33 = me[ 8 ]; auto t11 = n33 * n22 - n32 * n23; auto t12 = n32 * n13 - n33 * n12; auto t13 = n23 * n12 - n22 * n13; auto det = n11 * t11 + n21 * t12 + n31 * t13; if ( det == 0 ) { if ( throwOnDegenerate == true ) { throw "THREE.Matrix3.getInverse(): can't invert matrix, determinant is 0"; } else { //console.warn( msg ); } return this->identity(); } auto detInv = 1 / det; te[ 0 ] = t11 * detInv; te[ 1 ] = ( n31 * n23 - n33 * n21 ) * detInv; te[ 2 ] = ( n32 * n21 - n31 * n22 ) * detInv; te[ 3 ] = t12 * detInv; te[ 4 ] = ( n33 * n11 - n31 * n13 ) * detInv; te[ 5 ] = ( n31 * n12 - n32 * n11 ) * detInv; te[ 6 ] = t13 * detInv; te[ 7 ] = ( n21 * n13 - n23 * n11 ) * detInv; te[ 8 ] = ( n22 * n11 - n21 * n12 ) * detInv; return this; } THREE::Matrix3* Matrix3::transpose() { float tmp = 0; auto m = this->elements; tmp = m[ 1 ]; m[ 1 ] = m[ 3 ]; m[ 3 ] = tmp; tmp = m[ 2 ]; m[ 2 ] = m[ 6 ]; m[ 6 ] = tmp; tmp = m[ 5 ]; m[ 5 ] = m[ 7 ]; m[ 7 ] = tmp; return this; } THREE::Matrix3* Matrix3::getNormalMatrix(THREE::Matrix4* matrix4 ) { return this->setFromMatrix4( matrix4 )->getInverse( this )->transpose(); } THREE::Matrix3* Matrix3::transposeIntoArray(std::vector<float> &r) { auto m = this->elements; r[ 0 ] = m[ 0 ]; r[ 1 ] = m[ 3 ]; r[ 2 ] = m[ 6 ]; r[ 3 ] = m[ 1 ]; r[ 4 ] = m[ 4 ]; r[ 5 ] = m[ 7 ]; r[ 6 ] = m[ 2 ]; r[ 7 ] = m[ 5 ]; r[ 8 ] = m[ 8 ]; return this; } bool Matrix3::equals(THREE::Matrix3* matrix ) { auto te = this->elements; auto me = matrix->elements; for ( int i = 0; i < 9; i ++ ) { if ( te[ i ] != me[ i ] ) return false; } return true; } THREE::Matrix3* Matrix3::fromArray(std::vector<float> arr) { return this->fromArray(arr, 0); } THREE::Matrix3* Matrix3::fromArray(std::vector<float> arr, int offset) { for ( int i = 0; i < 9; i ++ ) { this->elements[ i ] = arr[ i + offset ]; } return this; } std::vector<float> Matrix3::toArray(std::vector<float> arr, int offset) { //if ( arr == nullptr ) arr = {}; //if ( offset == nullptr ) offset = 0; auto te = this->elements; arr[ offset ] = te[ 0 ]; arr[ offset + 1 ] = te[ 1 ]; arr[ offset + 2 ] = te[ 2 ]; arr[ offset + 3 ] = te[ 3 ]; arr[ offset + 4 ] = te[ 4 ]; arr[ offset + 5 ] = te[ 5 ]; arr[ offset + 6 ] = te[ 6 ]; arr[ offset + 7 ] = te[ 7 ]; arr[ offset + 8 ] = te[ 8 ]; return arr; } };
23.425373
130
0.514654
[ "vector" ]
4a507ef2ee477ba38299279f494fecb1990b75ea
4,864
hpp
C++
include/seqan3/search/configuration/all.hpp
wiepvandertoorn/seqan3
c84a1ad0548fb722015b59c7001faa73015887aa
[ "CC-BY-4.0", "CC0-1.0" ]
1
2020-09-28T06:49:14.000Z
2020-09-28T06:49:14.000Z
include/seqan3/search/configuration/all.hpp
wiepvandertoorn/seqan3
c84a1ad0548fb722015b59c7001faa73015887aa
[ "CC-BY-4.0", "CC0-1.0" ]
null
null
null
include/seqan3/search/configuration/all.hpp
wiepvandertoorn/seqan3
c84a1ad0548fb722015b59c7001faa73015887aa
[ "CC-BY-4.0", "CC0-1.0" ]
null
null
null
// ----------------------------------------------------------------------------------------------------- // Copyright (c) 2006-2020, Knut Reinert & Freie Universität Berlin // Copyright (c) 2016-2020, Knut Reinert & MPI für molekulare Genetik // This file may be used, modified and/or redistributed under the terms of the 3-clause BSD-License // shipped with this file and also available at: https://github.com/seqan/seqan3/blob/master/LICENSE.md // ----------------------------------------------------------------------------------------------------- /*!\file * \brief Meta-header for the \link search_configuration search configuration module \endlink. * \author Christopher Pockrandt <christopher.pockrandt AT fu-berlin.de> */ #pragma once #include <seqan3/core/algorithm/configuration.hpp> #include <seqan3/search/configuration/default_configuration.hpp> #include <seqan3/search/configuration/detail.hpp> #include <seqan3/search/configuration/max_error.hpp> #include <seqan3/search/configuration/max_error_rate.hpp> #include <seqan3/search/configuration/hit.hpp> #include <seqan3/search/configuration/output.hpp> #include <seqan3/search/configuration/parallel.hpp> /*!\namespace seqan3::search_cfg * \brief A special sub namespace for the search configurations. */ /*!\defgroup search_configuration Configuration * \ingroup search * \brief Data structures and utility functions for configuring search algorithm. * \see search * * \details * * \section search_configuration_section_introduction Introduction * * In SeqAn the search algorithm uses a configuration object to determine the desired * \ref seqan3::search_cfg::max_error "number"/\ref seqan3::search_cfg::max_error_rate "rate" of errors, * what hits are reported based on a \ref search_configuration_subsection_hit_strategy "strategy", and how to * \ref seqan3::search_cfg::output "output" the results. * These configurations exist in their own namespace, namely seqan3::search_cfg, to disambiguate them from the * configuration of other algorithms. * * If no configuration is provided upon invoking the seqan3::search algorithm, a default configuration is provided: * \include test/snippet/search/configuration_default.cpp * * \section search_configuration_section_overview Overview on search configurations * * Configurations can be combined using the `|`-operator. If a combination is invalid, a static assertion is triggered * during compilation and will inform the user that the the last config cannot be combined with any of the configs from * the left-hand side of the configuration specification. Unfortunately, the names of the invalid * types cannot be printed within the static assert, but the following table shows which combinations are possible. * In general, the same configuration element cannot occur more than once inside of a configuration specification. * * | **Configuration group** | **0** | **1** | **2** | **3** | **4** | * | --------------------------------------------------------------------|-------|-------|-------|-------|-------| * | \ref seqan3::search_cfg::max_error "0: Max error" | ❌ | ❌ | ✅ | ✅ | ✅ | * | \ref seqan3::search_cfg::max_error_rate "1: Max error rate" | ❌ | ❌ | ✅ | ✅ | ✅ | * | \ref seqan3::search_cfg::output "2: Output" | ✅ | ✅ | ❌ | ✅ | ✅ | * | \ref search_configuration_subsection_hit_strategy "3. Hit" | ✅ | ✅ | ✅ | ❌ | ✅ | * | \ref seqan3::search_cfg::parallel "4: Parallel" | ✅ | ✅ | ✅ | ✅ | ❌ | * * \subsection search_configuration_search_result Search result type * * \copydetails seqan3::search_result * * \subsection search_configuration_subsection_hit_strategy 3. Hit Configuration * * This configuration can be used to determine which hits are reported. * Currently these strategies are available: * * | Hit Configurations | Behaviour | * |-------------------------------------|---------------------------------------------------------------------| * | seqan3::search_cfg::hit_all | Report all hits within error bounds. | * | seqan3::search_cfg::hit_all_best | Report all hits with the lowest number of errors within the bounds. | * | seqan3::search_cfg::hit_single_best | Report one best hit (hit with lowest error) within bounds. | * | seqan3::search_cfg::hit_strata | Report all hits within best + `stratum` errors. | * * The individual configuration elements to select a search strategy cannot be combined with each other * (mutual exclusivity). * * \include test/snippet/search/hit_configuration_examples.cpp */
57.904762
120
0.626234
[ "object" ]
4a53f992ca10c047df7e5c5b4c776a7c7bed88ca
665
cpp
C++
1221.cpp
zhulk3/leetCode
0a1dbf8d58558ab9b05c5150aafa9e4344cec5bc
[ "Apache-2.0" ]
2
2020-03-13T08:14:01.000Z
2021-09-03T15:27:49.000Z
1221.cpp
zhulk3/LeetCode
0a1dbf8d58558ab9b05c5150aafa9e4344cec5bc
[ "Apache-2.0" ]
null
null
null
1221.cpp
zhulk3/LeetCode
0a1dbf8d58558ab9b05c5150aafa9e4344cec5bc
[ "Apache-2.0" ]
null
null
null
#include <string> #include <vector> #include <stack> #include <iostream> using namespace std; class Solution { public: int balancedStringSplit(string s) { int len = s.length(); stack<char>store; char temp; int cnt = 0; for (int i = 0; i < len; i++) { temp = s[i]; if (!store.empty()) { if (temp == 'L') if (store.top() == 'R') { store.pop(); if (store.empty()) cnt++; } else store.push(temp); if (temp == 'R') if (store.top() == 'L') { store.pop(); if (store.empty()) cnt++; } else store.push(temp); } else store.push(temp); } return cnt; } };
16.625
36
0.500752
[ "vector" ]
4a587342ce72bd9e9773b39fa760c8837b4b6d5f
4,061
hpp
C++
include/snd/audio/delay.hpp
colugomusic/snd
3ecb87581870b14e62893610d027516aea48ff3c
[ "MIT" ]
18
2020-08-26T11:33:50.000Z
2021-04-13T15:57:28.000Z
include/snd/audio/delay.hpp
colugomusic/snd
3ecb87581870b14e62893610d027516aea48ff3c
[ "MIT" ]
1
2021-05-16T17:11:57.000Z
2021-05-16T17:25:17.000Z
include/snd/audio/delay.hpp
colugomusic/snd
3ecb87581870b14e62893610d027516aea48ff3c
[ "MIT" ]
null
null
null
#pragma once #include <array> #include <functional> #include <vector> #pragma warning(push, 0) #include <DSP/MLDSPGens.h> #include <DSP/MLDSPOps.h> #pragma warning(pop) #include <snd/interpolation.hpp> namespace snd { namespace audio { template <size_t ROWS> class Delay { public: Delay(int SR, size_t size) : SR_(SR) , size_(size) { for (int row = 0; row < ROWS; row++) { buffer_[row].resize(size * kFloatsPerDSPVector); } } ml::DSPVectorArray<ROWS> operator()( const ml::DSPVectorArray<ROWS>& dry, const ml::DSPVectorArray<ROWS>& time) { write(dry); const auto out = process(time); advance(); return out; } void clear() { for (int row = 0; row < ROWS; row++) { std::fill(buffer_[row].begin(), buffer_[row].end(), 0.0f); } } private: struct DelayTime { ml::DSPVectorArrayInt<ROWS> i; ml::DSPVectorArray<ROWS> f; }; using InterpFrames = std::array<ml::DSPVectorArrayInt<ROWS>, 4>; using InterpSamples = std::array<ml::DSPVectorArray<ROWS>, 4>; struct InterpSpec { InterpSamples samples; ml::DSPVectorArray<ROWS> f; }; auto get_delay_time(ml::DSPVectorArray<ROWS> time) { static const ml::DSPVectorArray<ROWS> min { 2.0f }; const ml::DSPVectorArray<ROWS> max { float(size_) * kFloatsPerDSPVector }; time = ml::clamp(time, min, max); DelayTime out; out.i = ml::truncateFloatToInt(time); out.f = ml::fractionalPart(time); return out; } auto get_delayed_frame(const DelayTime& time) { const auto index = ml::truncateFloatToInt(ml::repeatRows<ROWS>(ml::columnIndex())); const auto vector_frame = ml::DSPVectorArrayInt<ROWS>(int(write_vector_) * kFloatsPerDSPVector); const auto just_written_frame = index + vector_frame; return just_written_frame - time.i; } auto get_wrapped_frame(const ml::DSPVectorArrayInt<ROWS>& frame) { ml::DSPVectorArrayInt<ROWS> out; for (int row = 0; row < ROWS; row++) { const auto& frame_row = frame.constRow(row); auto& out_row = out.row(row); for (int i = 0; i < kFloatsPerDSPVector; i++) { out_row[i] = frame_row[i]; if (out_row[i] < 0) { out_row[i] += int(size_ * kFloatsPerDSPVector); } } } return out; } auto get_interp_frames(const DelayTime& time) { const auto delayed_frame = get_delayed_frame(time); InterpFrames out; out[0] = get_wrapped_frame(delayed_frame - ml::DSPVectorArrayInt<ROWS>(1)); out[1] = get_wrapped_frame(delayed_frame); out[2] = get_wrapped_frame(delayed_frame + ml::DSPVectorArrayInt<ROWS>(1)); out[3] = get_wrapped_frame(delayed_frame + ml::DSPVectorArrayInt<ROWS>(2)); return out; } auto get_interp_samples(const InterpFrames& frames) { InterpSamples out; for (int part = 0; part < 4; part++) { for (int row = 0; row < ROWS; row++) { const auto& buffer_row = buffer_[row]; const auto& frames_row = frames[part].constRow(row); auto& out_row = out[part].row(row); for (int i = 0; i < kFloatsPerDSPVector; i++) { const auto frame = frames_row[i]; out[part].row(row)[i] = buffer_row[frame]; } } } return out; } auto get_delayed_signal(const DelayTime& time) { ml::DSPVectorArray<ROWS> out; const auto interp_frames = get_interp_frames(time); const auto interp_samples = get_interp_samples(interp_frames); return snd::interpolation::interp_4pt(interp_samples[0], interp_samples[1], interp_samples[2], interp_samples[3], time.f); } void write(const ml::DSPVectorArray<ROWS>& dry) { for (int row = 0; row < ROWS; row++) { ml::store(dry.constRow(row), buffer_[row].data() + (write_vector_ * kFloatsPerDSPVector)); } } ml::DSPVectorArray<ROWS> process(const ml::DSPVectorArray<ROWS>& time) { const auto delay_time = get_delay_time(time); const auto delayed_signal = get_delayed_signal(delay_time); return delayed_signal; } void advance() { if (++write_vector_ >= size_) write_vector_ = 0; } int SR_ { 44100 }; size_t write_vector_ { 0 }; size_t size_; std::array<std::vector<float>, ROWS> buffer_; }; } // audio } // snd
20.93299
124
0.673726
[ "vector" ]
4a65ebaeeee50308676ffc80147e9907757d4d55
12,313
cpp
C++
src/cpp/dynamic-types/DynamicDataHelper.cpp
jason-fox/Fast-RTPS
af466cfe63a8319cc9d37514267de8952627a9a4
[ "Apache-2.0" ]
575
2015-01-22T20:05:04.000Z
2020-06-01T10:06:12.000Z
src/cpp/dynamic-types/DynamicDataHelper.cpp
jason-fox/Fast-RTPS
af466cfe63a8319cc9d37514267de8952627a9a4
[ "Apache-2.0" ]
1,110
2015-04-20T19:30:34.000Z
2020-06-01T08:13:52.000Z
src/cpp/dynamic-types/DynamicDataHelper.cpp
jason-fox/Fast-RTPS
af466cfe63a8319cc9d37514267de8952627a9a4
[ "Apache-2.0" ]
273
2015-08-10T23:34:42.000Z
2020-05-28T13:03:32.000Z
// Copyright 2019 Proyectos y Sistemas de Mantenimiento SL (eProsima). // // 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 <fastrtps/types/DynamicDataHelper.hpp> #include <fastrtps/types/MemberDescriptor.h> using namespace eprosima::fastrtps::types; void DynamicDataHelper::print( const DynamicData_ptr& data) { print(data.get()); } void DynamicDataHelper::print( const DynamicData* data) { if (nullptr != data) { switch (data->type_->get_kind()) { case TK_STRUCTURE: { std::map<MemberId, DynamicTypeMember*> members; data->type_->get_all_members(members); for (auto it : members) { print_member(const_cast<DynamicData*>(data), it.second); } break; } default: { std::cout << "Only structs are supported by DynamicDataHelper::print method." << std::endl; } } } else { std::cout << "<NULL>" << std::endl; } } void DynamicDataHelper::print_basic_element( DynamicData* data, MemberId id, TypeKind kind) { switch(kind) { case TK_NONE: { std::cout << "<type not defined!>"; break; } case TK_BOOLEAN: { std::cout << (data->get_bool_value(id) ? "true" : "false"); break; } case TK_BYTE: { std::cout << static_cast<uint32_t>(data->get_byte_value(id)); break; } case TK_INT16: { std::cout << data->get_int16_value(id); break; } case TK_INT32: { std::cout << data->get_int32_value(id); break; } case TK_INT64: { std::cout << data->get_int64_value(id); break; } case TK_UINT16: { std::cout << data->get_uint16_value(id); break; } case TK_UINT32: { std::cout << data->get_uint32_value(id); break; } case TK_UINT64: { std::cout << data->get_uint64_value(id); break; } case TK_FLOAT32: { std::cout << data->get_float32_value(id); break; } case TK_FLOAT64: { std::cout << data->get_float64_value(id); break; } case TK_FLOAT128: { std::cout << data->get_float128_value(id); break; } case TK_CHAR8: { std::cout << data->get_char8_value(id); break; } case TK_CHAR16: { std::cout << data->get_char16_value(id); break; } case TK_STRING8: { std::cout << data->get_string_value(id); break; } case TK_STRING16: { std::wcout << data->get_wstring_value(id); break; } case TK_BITMASK: { size_t size = data->type_->get_size(); switch (size) { case 1: std::cout << data->get_uint8_value(id); break; case 2: std::cout << data->get_uint16_value(id); break; case 3: std::cout << data->get_uint32_value(id); break; case 4: std::cout << data->get_uint64_value(id); break; } break; } case TK_ENUM: { std::cout << data->get_uint32_value(id); break; } default: break; } } void DynamicDataHelper::print_collection( DynamicData* data, const std::string& tabs) { switch (data->type_->get_element_type()->get_kind()) { case TK_NONE: case TK_BOOLEAN: case TK_BYTE: case TK_INT16: case TK_INT32: case TK_INT64: case TK_UINT16: case TK_UINT32: case TK_UINT64: case TK_FLOAT32: case TK_FLOAT64: case TK_FLOAT128: case TK_CHAR8: case TK_CHAR16: case TK_STRING8: case TK_STRING16: case TK_ENUM: case TK_BITMASK: { print_basic_collection(data); break; } case TK_STRUCTURE: case TK_BITSET: case TK_UNION: case TK_SEQUENCE: case TK_ARRAY: case TK_MAP: { print_complex_collection(data, tabs); break; } default: break; } } void DynamicDataHelper::fill_array_positions( const std::vector<uint32_t>& bounds, std::vector<std::vector<uint32_t>>& positions) { uint32_t total_size = 1; for (size_t i = 0; i < bounds.size(); ++i) { total_size *= bounds[i]; } for (uint32_t idx = 0; idx < total_size; ++idx) { positions.push_back({}); get_index_position(idx, bounds, positions[idx]); } } void DynamicDataHelper::get_index_position( uint32_t index, const std::vector<uint32_t>& bounds, std::vector<uint32_t>& position) { position.resize(bounds.size()); if (bounds.size() > 0) { aux_index_position(index, static_cast<uint32_t>(bounds.size() - 1), bounds, position); } } void DynamicDataHelper::aux_index_position( uint32_t index, uint32_t inner_index, const std::vector<uint32_t>& bounds, std::vector<uint32_t>& position) { uint32_t remainder = index % bounds[inner_index]; position[inner_index] = remainder; if (inner_index > 0) { aux_index_position(index / bounds[inner_index], inner_index - 1, bounds, position); } } void DynamicDataHelper::print_basic_collection( DynamicData* data) { const std::vector<uint32_t>& bounds = data->type_->descriptor_->bound_; std::vector<std::vector<uint32_t>> positions; fill_array_positions(bounds, positions); std::cout << "["; for (size_t i = 0; i < positions.size(); ++i) { print_basic_element(data, data->get_array_index(positions[i]), data->type_->get_element_type()->get_kind()); std::cout << (i == positions.size() - 1 ? "]" : ", "); } } void DynamicDataHelper::print_complex_collection( DynamicData* data, const std::string& tabs) { const std::vector<uint32_t>& bounds = data->type_->descriptor_->bound_; std::vector<std::vector<uint32_t>> positions; fill_array_positions(bounds, positions); for (size_t i = 0; i < positions.size(); ++i) { std::cout << tabs << "[" << i << "] = "; print_complex_element(data, data->get_array_index(positions[i]), tabs); std::cout << std::endl; } } void DynamicDataHelper::print_complex_element( DynamicData* data, MemberId id, const std::string& tabs) { const TypeDescriptor* desc = data->type_->get_type_descriptor(); switch(desc->get_kind()) { case TK_STRUCTURE: case TK_BITSET: { DynamicData* st_data = data->loan_value(id); std::map<types::MemberId, types::DynamicTypeMember*> members; data->type_->get_all_members(members); for (auto it : members) { print_member(st_data, it.second, tabs + "\t"); } data->return_loaned_value(st_data); break; } case TK_UNION: { DynamicData* st_data = data->loan_value(id); DynamicTypeMember member; data->type_->get_member(member, data->union_id_); print_member(st_data, &member, tabs + "\t"); break; } case TK_SEQUENCE: case TK_ARRAY: { DynamicData* st_data = data->loan_value(id); print_collection(st_data, tabs + "\t"); data->return_loaned_value(st_data); break; } case TK_MAP: { DynamicData* st_data = data->loan_value(id); std::map<types::MemberId, types::DynamicTypeMember*> members; data->type_->get_all_members(members); size_t size = data->get_item_count(); for (size_t i = 0; i < size; ++i) { size_t index = i * 2; MemberId member_id = data->get_member_id_at_index(static_cast<uint32_t>(index)); std::cout << "Key: "; print_member(st_data, members[member_id], tabs + "\t"); member_id = data->get_member_id_at_index(static_cast<uint32_t>(index + 1)); std::cout << "Value: "; print_member(st_data, members[member_id], tabs + "\t"); } data->return_loaned_value(st_data); break; } default: break; } std::cout << std::endl; } void DynamicDataHelper::print_member( DynamicData* data, const DynamicTypeMember* type, const std::string& tabs) { std::cout << tabs << type->get_name() << ": "; const MemberDescriptor* desc = type->get_descriptor(); switch(desc->get_kind()) { case TK_NONE: case TK_BOOLEAN: case TK_BYTE: case TK_INT16: case TK_INT32: case TK_INT64: case TK_UINT16: case TK_UINT32: case TK_UINT64: case TK_FLOAT32: case TK_FLOAT64: case TK_FLOAT128: case TK_CHAR8: case TK_CHAR16: case TK_STRING8: case TK_STRING16: case TK_ENUM: case TK_BITMASK: { print_basic_element(data, type->get_id(), desc->get_kind()); break; } case TK_STRUCTURE: case TK_BITSET: { DynamicData* st_data = data->loan_value(type->get_id()); std::map<types::MemberId, types::DynamicTypeMember*> members; desc->get_type()->get_all_members(members); for (auto it : members) { print_member(st_data, it.second, tabs + "\t"); } data->return_loaned_value(st_data); break; } case TK_UNION: { DynamicData* st_data = data->loan_value(type->get_id()); DynamicTypeMember member; desc->get_type()->get_member(member, data->union_id_); print_member(st_data, &member, tabs + "\t"); break; } case TK_SEQUENCE: case TK_ARRAY: { DynamicData* st_data = data->loan_value(type->get_id()); print_collection(st_data, tabs + "\t"); data->return_loaned_value(st_data); break; } case TK_MAP: { DynamicData* st_data = data->loan_value(type->get_id()); std::map<types::MemberId, types::DynamicTypeMember*> members; desc->get_type()->get_all_members(members); size_t size = data->get_item_count(); for (size_t i = 0; i < size; ++i) { size_t index = i * 2; MemberId id = data->get_member_id_at_index(static_cast<uint32_t>(index)); std::cout << "Key: "; print_member(st_data, members[id], tabs + "\t"); id = data->get_member_id_at_index(static_cast<uint32_t>(index + 1)); std::cout << "Value: "; print_member(st_data, members[id], tabs + "\t"); } data->return_loaned_value(st_data); break; } default: break; } std::cout << std::endl; }
28.568445
116
0.529116
[ "vector" ]
4a664b31cbce430dd36cce4f644223a0b285fbe9
4,387
hpp
C++
modules/core/frame/include/opengv2/frame/Bodyframe.hpp
MobilePerceptionLab/EventCameraCalibration
debd774ac989674b500caf27641b7ad4e94681e9
[ "Apache-2.0" ]
22
2021-08-06T03:21:03.000Z
2022-02-25T03:40:54.000Z
modules/core/frame/include/opengv2/frame/Bodyframe.hpp
MobilePerceptionLab/MultiCamCalib
2f0e94228c2c4aea7f20c26e3e8daa6321ce8022
[ "Apache-2.0" ]
1
2022-02-25T02:55:13.000Z
2022-02-25T15:18:45.000Z
modules/core/frame/include/opengv2/frame/Bodyframe.hpp
MobilePerceptionLab/MultiCamCalib
2f0e94228c2c4aea7f20c26e3e8daa6321ce8022
[ "Apache-2.0" ]
7
2021-08-11T12:29:35.000Z
2022-02-25T03:41:01.000Z
// // Created by huangkun on 2019/12/30. // #ifndef OPENGV2_BODYFRAME_HPP #define OPENGV2_BODYFRAME_HPP #include <shared_mutex> #include <mutex> #include <Eigen/Eigen> #include <Eigen/StdVector> //#include <cereal/types/vector.hpp> //#include <cereal/types/memory.hpp> #include <opengv2/frame/FrameBase.hpp> #include <opengv2/utility/utility.hpp> namespace opengv2 { class Bodyframe { public: EIGEN_MAKE_ALIGNED_OPERATOR_NEW typedef std::shared_ptr<Bodyframe> Ptr; inline static std::vector<Eigen::Matrix<double, 7, 1>> optTsb; std::vector<double> optT; // Qbw.coeffs(), twb: tx ty tz bool isKeyFrame; // not thread safe // maintained by MapOptimizer thread bool fixedInBA; Bodyframe(std::vector<FrameBase::Ptr> &frames, double timeStamp, const Eigen::Ref<const Eigen::Vector3d> &twb = Eigen::Vector3d::Zero(), const Eigen::Quaterniond &unitQwb = Eigen::Quaterniond::Identity()) : isKeyFrame(true), fixedInBA(false), timeStamp_(timeStamp), frames_(std::move(frames)), twb_(twb), unitQwb_(unitQwb) { optT.reserve(7); } /** * @note Return const reference of a non-const object not suitable for shared lock. */ inline Eigen::Vector3d twb() const noexcept { std::shared_lock lock(poseMutex_); return twb_; } inline Eigen::Quaterniond unitQwb() const noexcept { std::shared_lock lock(poseMutex_); return unitQwb_; } inline Eigen::Matrix4d Twb() const noexcept { std::shared_lock lock(poseMutex_); Eigen::Matrix4d Twb = Eigen::Matrix4d::Identity(); Twb.block<3, 3>(0, 0) = unitQwb_.toRotationMatrix(); Twb.block<3, 1>(0, 3) = twb_; return Twb; } inline void setPose(const Eigen::Ref<const Eigen::Vector3d> &twb, const Eigen::Quaterniond &Qwb) { std::scoped_lock lock(poseMutex_); twb_ = twb; unitQwb_ = Qwb; unitQwb_.normalize(); } inline void poseMutexLockShared() const { poseMutex_.lock_shared(); } inline void poseMutexUnlockShared() const { poseMutex_.unlock_shared(); } inline static Eigen::Vector3d tsb(size_t index) { std::shared_lock lock(mutexTsb_); return tsb_[index]; } inline static Eigen::Quaterniond unitQsb(size_t index) { std::shared_lock lock(mutexTsb_); return unitQsb_[index]; } inline static void setTsb(size_t index, const Eigen::Ref<const Eigen::Vector3d> &tsb, const Eigen::Quaterniond &Qsb) { std::scoped_lock lock(mutexTsb_); tsb_[index] = tsb; unitQsb_[index] = Qsb; unitQsb_[index].normalize(); } inline static void setTsb(std::vector<Eigen::Quaterniond, Eigen::aligned_allocator<Eigen::Quaterniond>> &unitQsb, std::vector<Eigen::Vector3d> &tsb) { std::scoped_lock lock(mutexTsb_); tsb_ = std::move(tsb); unitQsb_ = std::move(unitQsb); } inline FrameBase::Ptr frame(size_t index) const noexcept { return frames_[index]; } inline static size_t size() noexcept { return unitQsb_.size(); } inline double timeStamp() const noexcept { return timeStamp_; } /*// This method lets cereal know which data members to serialize template<class Archive> void serialize(Archive &archive) { // serialize things by passing them to the archive archive(timeStamp_, frames_, twb_, unitQwb_); }*/ protected: double timeStamp_; std::vector<FrameBase::Ptr> frames_; Eigen::Vector3d twb_; Eigen::Quaterniond unitQwb_; mutable std::shared_mutex poseMutex_; // since c++17, inline static member don't need outside definition inline static std::vector<Eigen::Vector3d> tsb_; inline static std::vector<Eigen::Quaterniond, Eigen::aligned_allocator<Eigen::Quaterniond>> unitQsb_; inline static std::shared_mutex mutexTsb_; }; } #endif //OPENGV2_BODYFRAME_HPP
32.021898
109
0.598587
[ "object", "vector" ]
4a6afb3c2e872ef51bb139568231c29e258c696b
3,327
cpp
C++
src/model/submodel/containerModel.cpp
Galfurian/RadMud
1362cb0ee1b7a17386e57a98e29dd8baeea75af3
[ "MIT" ]
18
2016-05-26T18:11:31.000Z
2022-02-10T20:00:52.000Z
src/model/submodel/containerModel.cpp
Galfurian/RadMud
1362cb0ee1b7a17386e57a98e29dd8baeea75af3
[ "MIT" ]
null
null
null
src/model/submodel/containerModel.cpp
Galfurian/RadMud
1362cb0ee1b7a17386e57a98e29dd8baeea75af3
[ "MIT" ]
2
2016-06-30T15:20:01.000Z
2020-08-27T18:28:33.000Z
/// @file containerModel.cpp /// @brief Iplement the methods for Container. /// @author Enrico Fraccaroli /// @date Jul 6 2016 /// @copyright /// Copyright (c) 2016 Enrico Fraccaroli <enrico.fraccaroli@gmail.com> /// 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 "containerModel.hpp" #include "logger.hpp" ContainerModel::ContainerModel() : maxWeight(), containerFlags(), keyVnum(), difficulty() { // Nothing to do. } ContainerModel::~ContainerModel() { // Nothing to do. } ModelType ContainerModel::getType() const { return ModelType::Container; } std::string ContainerModel::getTypeName() const { return "Container"; } bool ContainerModel::setModel(const std::string & source) { if (source.empty()) { Logger::log(LogLevel::Error, "Function list is empty (%s).", this->name); return false; } std::vector<std::string> functionList = SplitString(source, " "); if (functionList.size() != 4) { Logger::log(LogLevel::Error, "Wrong number of parameters for Container Model (%s).", this->name); return false; } this->maxWeight = ToNumber<unsigned int>(functionList[0]); this->containerFlags = ToNumber<unsigned int>(functionList[1]); this->keyVnum = ToNumber<unsigned int>(functionList[2]); this->difficulty = ToNumber<unsigned int>(functionList[3]); return true; } void ContainerModel::getSheet(Table & sheet) const { // Call the function of the father class. ItemModel::getSheet(sheet); // Add a divider. sheet.addDivider(); // Set the values. sheet.addRow({"Max Weight", ToString(this->maxWeight)}); sheet.addRow({"Flags", GetContainerFlagString(this->containerFlags)}); sheet.addRow({"Key Vnum", ToString(this->keyVnum)}); sheet.addRow({"Picklock Difficulty", ToString(this->difficulty)}); } std::string GetContainerFlagString(unsigned int flags) { std::string flagList; if (HasFlag(flags, ContainerFlag::CanClose)) flagList += "|CanClose"; if (HasFlag(flags, ContainerFlag::CanBurgle)) flagList += "|CanBurgle"; if (HasFlag(flags, ContainerFlag::CanSee)) flagList += "|CanSee"; flagList += "|"; return flagList; }
34.298969
79
0.681094
[ "vector", "model" ]
4a72a4c598acdd89dbf301f8adae2b6a179aa4d3
9,962
cpp
C++
Firmware/V1.0.0/src/main.cpp
cszielke/Servotester
03800ea2fc66462a37e821e63e504701f4d0bab9
[ "MIT" ]
null
null
null
Firmware/V1.0.0/src/main.cpp
cszielke/Servotester
03800ea2fc66462a37e821e63e504701f4d0bab9
[ "MIT" ]
null
null
null
Firmware/V1.0.0/src/main.cpp
cszielke/Servotester
03800ea2fc66462a37e821e63e504701f4d0bab9
[ "MIT" ]
null
null
null
/********************* Example code for the Adafruit RGB Character LCD Shield and Library This code displays text on the shield, and also reads the buttons on the keypad. When a button is pressed, the backlight changes color. **********************/ // include the library code: #include "Arduino.h" #include <EEPROM.h> #include "global.h" #include "Servo.h" #include "LiquidCrystal_I2C.h" #include "RotaryEncoder.h" struct Config { float field1; byte field2; char name[10]; }; #define COLUMS 16 #define ROWS 2 #define LCD_SPACE_SYMBOL 0x20 //space symbol from the LCD ROM, see p.9 of GDM2004D datasheet LiquidCrystal_I2C lcd(PCF8574_ADDR_A21_A11_A01, 4, 5, 6, 16, 11, 12, 13, 14, POSITIVE); // A pointer to the dynamic created rotary encoder instance. // This will be done in setup() RotaryEncoder *encoder = nullptr; #define PIN_IN1 2 #define PIN_IN2 3 #define PIN_Enter A3 static long pos = 0; static long lastpos = 0; Servo servo0; // create servo object to control a servo Servo servo1; // create servo object to control a servo Servo servo2; // create servo object to control a servo Servo servo3; // create servo object to control a servo Servo servo4; // create servo object to control a servo int potpin = A0; // analog pin used to connect the potentiometer volatile int val=1500; // variable to read the value from the analog pin static int oldval=1499; // force write- and printout bool increment = true; int min_us = 800; int max_us = 2200; volatile long incval = 20; volatile char title[17] = "Servotester"; volatile int timer2Counter; //Timer-Variable volatile long timer2Cnt; //Timer-Variable enum efunction: int{ fNeutral = 0, fPosition = 1, fMinPos = 2, fMaxPos = 3, fSweep = 4, fEnd = 4 }; efunction func = fNeutral; efunction oldfunc = fEnd; //force function init void printServoValue(){ char valstr[17]; int pc = int((long)((val - 1500) * 100 / 500));; lcd.clear(); lcd.setCursor(0,0); snprintf(valstr, sizeof(valstr), "%s", title); lcd.print(valstr); lcd.setCursor(0, 1); snprintf(valstr, sizeof(valstr), "%4dms %+4d%% ", val, pc); lcd.print(valstr); Serial.println(valstr); } void WriteServoPosition(){ servo0.writeMicroseconds(val); // set servo to mid-point servo1.writeMicroseconds(val); // set servo to mid-point servo2.writeMicroseconds(val); // set servo to mid-point servo3.writeMicroseconds(val); // set servo to mid-point servo4.writeMicroseconds(val); // set servo to mid-point } // This interrupt routine will be called on any change of one of the input signals void checkPosition() { encoder->tick(); // just call tick() to check the state. } ISR(TIMER2_OVF_vect) { TCNT2 = timer2Counter; timer2Cnt--; if(timer2Cnt <= 0) { timer2Cnt = incval; if(func == fSweep){ if(increment) val++; else val--; if(val <= min_us){ increment=true; val = min_us; } if(val >= max_us){ increment=false; val = max_us; } } WriteServoPosition(); } } void setup() { // Debugging output Serial.begin(9600); // set up the LCD's number of columns and rows: while (lcd.begin(COLUMS, ROWS) != 1) //colums - 20, rows - 4 { Serial.println(F("PCF8574 is not connected or lcd pins declaration is wrong. Only pins numbers: 4,5,6,16,11,12,13,14 are legal.")); delay(2000); } lcd.setCursor(0, 0); lcd.print(F("PCF8574 is OK...")); //(F()) saves string to flash & keeps dynamic memory free Serial.println(F("PCF8574 is OK...")); delay(200); lcd.clear(); // setup the rotary encoder functionality // use FOUR3 mode when PIN_IN1, PIN_IN2 signals are always HIGH in latch position. // encoder = new RotaryEncoder(PIN_IN1, PIN_IN2, RotaryEncoder::LatchMode::FOUR3); // use FOUR0 mode when PIN_IN1, PIN_IN2 signals are always LOW in latch position. // encoder = new RotaryEncoder(PIN_IN1, PIN_IN2, RotaryEncoder::LatchMode::FOUR0); // use TWO03 mode when PIN_IN1, PIN_IN2 signals are both LOW or HIGH in latch position. encoder = new RotaryEncoder(PIN_IN1, PIN_IN2, RotaryEncoder::LatchMode::FOUR3); // register interrupt routine attachInterrupt(digitalPinToInterrupt(PIN_IN1), checkPosition, CHANGE); attachInterrupt(digitalPinToInterrupt(PIN_IN2), checkPosition, CHANGE); pinMode(PIN_Enter, INPUT_PULLUP); servo0.attach(9); // attaches the servo on pin 9 to the servo object servo1.attach(8); // attaches the servo on pin 9 to the servo object servo2.attach(7); // attaches the servo on pin 9 to the servo object servo3.attach(6); // attaches the servo on pin 9 to the servo object servo4.attach(5); // attaches the servo on pin 9 to the servo object printServoValue(); WriteServoPosition(); // Setup Timer cli();//stop all interrupts TCCR2A = 0; //delete all bits TCCR2B = 0; //delete all bits timer2Counter = 200; timer2Cnt = incval; TCNT2 = timer2Counter;//preload timer TCCR2B |= (1 << CS10); TCCR2B |= (1 << CS12);//Sets Prescaler to 1024 TIMSK2 |= (1 << TOIE2);// enables timer overflow interrups sei();//allow interrupts delay(1000); } uint8_t i=0; void loop() { // set the cursor to column 0, line 1 // (note: line 1 is the second row, since counting begins with 0): // lcd.setCursor(0, 1); // print the number of seconds since reset: // lcd.print(millis()/1000); static boolean enter = 0; boolean newenter = digitalRead(PIN_Enter); if(enter != newenter){ Serial.println("enter: "); Serial.println(newenter); if(enter == 1){ func = (efunction)((int)func + 1); if(func > fEnd) func = fNeutral; } printServoValue(); enter = newenter; } //Accelleration // Define some constants. // the maximum acceleration is 10 times. constexpr float m = 50; // at 200ms or slower, there should be no acceleration. (factor 1) constexpr float longCutoff = 200; // at 5 ms, we want to have maximum acceleration (factor m) constexpr float shortCutoff = 5; // To derive the calc. constants, compute as follows: // On an x(ms) - y(factor) plane resolve a linear formular factor(ms) = a * ms + b; // where f(4)=10 and f(200)=1 constexpr float a = (m - 1) / (shortCutoff - longCutoff); constexpr float b = 1 - longCutoff * a; //Read Encoder lastpos = pos; encoder->tick(); // just call tick() to check the state. long newPos = encoder->getPosition(); if (pos != newPos) { unsigned long ms = encoder->getMillisBetweenRotations(); if(ms > longCutoff){ Serial.print("Slow: "); Serial.println(ms); } else{ // accelerate when there was a previous rotation in the same direction. // do some acceleration using factors a and b // limit to maximum acceleration if (ms < shortCutoff) { ms = shortCutoff; } float ticksActual_float = a * ms + b; Serial.print(" f= "); Serial.println(ticksActual_float); long deltaTicks = (long)ticksActual_float * (newPos - lastpos); Serial.print(" d= "); Serial.println(deltaTicks); newPos = newPos + deltaTicks; encoder->setPosition(newPos); Serial.print("Fast: "); Serial.println(ms); } Serial.print("pos:"); Serial.print(newPos); Serial.print(" dir:"); Serial.println((int)(encoder->getDirection())); pos = newPos; printServoValue(); } if(func == fNeutral){ if(func != oldfunc) { //Init function strncpy((char*)title,"Neutral",sizeof(title)); val = 1500; printServoValue(); oldfunc = func; } } //Position if(func == fPosition){ if(func != oldfunc) { //Init function strncpy((char*)title,"Position",sizeof(title)); val = 1500; pos = val; encoder->setPosition(pos); oldfunc = func; } val = pos; if(val > max_us){ val=max_us; pos = val; encoder->setPosition(pos); } if(val < min_us){ val=min_us; pos = val; encoder->setPosition(pos); } } if(func == fMinPos){ if(func != oldfunc) { //Init function strncpy((char*)title,"Min position",sizeof(title)); val = min_us; pos = val; encoder->setPosition(pos); oldfunc = func; } min_us = encoder->getPosition(); val = min_us; } if(func == fMaxPos){ if(func != oldfunc) { //Init function strncpy((char*)title,"Max position",sizeof(title)); val = max_us; pos = val; encoder->setPosition(pos); oldfunc = func; } max_us = encoder->getPosition(); val = max_us; } if(func == fSweep){ if(func != oldfunc) { //Init function incval = 20l; snprintf((char*)title,sizeof(title),"Sweep Speed: %2ld",incval); encoder->setPosition((long)incval*10); oldfunc = func; } //Get Speed long oldincval = incval; long tmp = encoder->getPosition(); if(tmp > 600){ Serial.print(F(">60: ")); Serial.println(tmp); tmp=600l; encoder->setPosition(tmp); pos = tmp; } if(tmp < 0){ Serial.print(F("<0: ")); Serial.println(tmp); tmp=0l; encoder->setPosition(tmp); pos = tmp; } incval = tmp/10; if(incval != oldincval){ snprintf((char*)title,sizeof(title),"Sweep Speed: %2ld",incval); } } if(val != oldval){ printServoValue(); delay(100); oldval = val; } }
25.80829
136
0.605401
[ "object" ]
4a77096d2d8077704fad7012e2b79caf46113057
33,397
cxx
C++
Rendering/vtkShellExtractor.cxx
chrisidefix/devide.vtkdevide
d14a3851a97b3da8db1f9f9351f992af59ecc290
[ "BSD-3-Clause" ]
null
null
null
Rendering/vtkShellExtractor.cxx
chrisidefix/devide.vtkdevide
d14a3851a97b3da8db1f9f9351f992af59ecc290
[ "BSD-3-Clause" ]
null
null
null
Rendering/vtkShellExtractor.cxx
chrisidefix/devide.vtkdevide
d14a3851a97b3da8db1f9f9351f992af59ecc290
[ "BSD-3-Clause" ]
null
null
null
// vtkShellExtractor.h copyright (c) 2003 // by Charl P. Botha cpbotha@ieee.org // and the TU Delft Visualisation Group http://visualisation.tudelft.nl/ // $Id: vtkShellExtractor.cxx,v 1.21 2004/11/30 22:27:13 cpbotha Exp $ // vtk class for extracting Udupa Shells /* * This software is licensed exclusively for research use. Any * modifications made to this software shall be sent to the author for * possible inclusion in future versions. Ownership and copyright of * said modifications shall be ceded to the author. * * 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 AUTHORS OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <math.h> #include "vtkMatrix4x4.h" #include "vtkObject.h" #include "vtkObjectFactory.h" #include "vtkShellExtractor.h" #include "vtkTransform.h" #include "vtkCharArray.h" #include "vtkUnsignedCharArray.h" #include "vtkShortArray.h" #include "vtkUnsignedShortArray.h" #include "vtkIntArray.h" #include "vtkUnsignedIntArray.h" #include "vtkLongArray.h" #include "vtkPointData.h" #include "vtkUnsignedLongArray.h" #include "vtkFloatArray.h" #include "vtkDoubleArray.h" vtkStandardNewMacro(vtkShellExtractor); #include <vector> using namespace std; /** * Template class for doing the actual work behind shell extraction. * * @param data_ptr Pointer to xyz volume that the shell must be extracted from. * @param xlen Number of voxels in x-direction. * @param ylen Number of voxels in y-direction. * @param zlen Number of voxels in z-direction. * @param x_spacing Object space distance between voxels in X. * @param y_spacing Object space distance between voxels in Y. * @param z_spacing Object space distance between voxels in Y. * @param OpacityTF The opacity function that you're rendering with. * @param OmegaL Lower opacity limit. * @param OmegaH Upper opacity limit. * @param vectorD Pointer to vector of ShellVoxels which will be filled with * the result of the extraction. * @param P array of ints of size ylen*zlen */ template <class T> static void ExtractShell(T* data_ptr, vtkImageData* Input, vtkImageData* GradientImageData, int GradientImageIsGradient, vtkPiecewiseFunction* OpacityTF, vtkColorTransferFunction* ColourTF, float OmegaL, float OmegaH, float min_gradmag, vector<ShellVoxel>* vectorDx, int Px[], vector<ShellVoxel>* vectorDy, int Py[], vector<ShellVoxel>* vectorDz, int Pz[]) { T* dptr = data_ptr; T nbrs[6]; // the six neighbours float gnbrs[6]; // the six neighbours in the gradient volume float nbr_os[6]; // opacities of the six neighbours float t_gradmag; // temp gradient magnitude int nbrv_lt_oh; // flag variable: neighbourhood voxel < OmegaH ? double temp_rgb[3]; // important variables int xlen = Input->GetDimensions()[0]; int ylen = Input->GetDimensions()[1]; int zlen = Input->GetDimensions()[2]; double x_spacing = Input->GetSpacing()[0]; double y_spacing = Input->GetSpacing()[1]; double z_spacing = Input->GetSpacing()[2]; double x_orig = Input->GetOrigin()[0]; double y_orig = Input->GetOrigin()[1]; double z_orig = Input->GetOrigin()[2]; //vector<ShellVoxel> vectorD; // initialise the D vector vectorDx->clear(); vectorDy->clear(); vectorDz->clear(); ShellVoxel temp_sv; // initialise P to all "no shell voxels in these rows (X)" //memset(Px, -1, ylen * zlen * sizeof(int) * 2); //memset(Py, -1, xlen * zlen * sizeof(int) * 2); //memset(Pz, -1, xlen * ylen * sizeof(int) * 2); int Pidx; //int prevPidx; // newly commented, check int xstep = 1; int ystep = xlen; int zstep = xlen * ylen; double dxm2 = 2.0 * x_spacing; double dym2 = 2.0 * y_spacing; double dzm2 = 2.0 * z_spacing; double tempValue; cout << "Building x shell." << endl; for (int z = 0; z < zlen; z++) { for (int y = 0; y < ylen; y++) { // start with new z,y: initialise all P to "no shell voxels in // these rows" Pidx = (z*ylen + y) * 2; Px[Pidx] = -1; Px[Pidx + 1] = -1; for (int x = 0; x < xlen; x++) { //temp_sv.Value = (float)(*dptr); tempValue = (double)(*dptr); // look the suxor up //temp_sv.Opacity = OpacityTF->GetValue(tempValue); // this call is IMMENSELY SLOW - actually, calling just about anything from // the OpacityTF is mind-numbingly slow; my guess is that the Update() call // in GetValue() (and who knows where else) is slowing everything down. temp_sv.Opacity = (float)(OpacityTF->GetValue(tempValue)); // first check if it's opaque enough if (temp_sv.Opacity > OmegaL) { // initially, we assume none of the neighbouring voxels // is < OmegaH nbrv_lt_oh = 0; // and zero the neighbour code temp_sv.nbrOCode = 0; // cache the six neighbour values since we'll probably // be needing them again; the cpu cache doesn't like the // read we're doing here... :( // note that we're zero-padding for both the normal // calculation and neighbourhood thingies // X ************************************************ if (x > 0) { nbrs[0] = *(dptr - xstep); nbr_os[0] = OpacityTF->GetValue((double)(nbrs[0])); if (nbr_os[0] >= OmegaH) temp_sv.nbrOCode |= 0x1; // activate bit 0 if (nbr_os[0] <= OmegaH) nbrv_lt_oh = 1; } else { nbrs[0] = 0; nbr_os[0] = 0.0; // also, since 0.0 < OmegaL <= OmegaH < 1.0, we have a // neighbour with opacity <= OmegaH nbrv_lt_oh = 1; // we don't have to adapt the neighbour opacity code, // since it's zeroed by default } if (x < xlen - 1) { nbrs[1] = *(dptr + xstep); nbr_os[1] = OpacityTF->GetValue((double)(nbrs[1])); if (nbr_os[1] >= OmegaH) temp_sv.nbrOCode |= 0x2; // activate bit 1 if (nbr_os[1] <= OmegaH) nbrv_lt_oh = 1; } else { nbrs[1] = 0; nbr_os[1] = 0.0; // also, since 0.0 < OmegaL <= OmegaH < 1.0, we have a // neighbour with opacity <= OmegaH nbrv_lt_oh = 1; // we don't have to adapt the neighbour opacity code, // since it's zeroed by default } // Y ************************************************ if (y > 0) { nbrs[2] = *(dptr - ystep); nbr_os[2] = OpacityTF->GetValue((double)(nbrs[2])); if (nbr_os[2] >= OmegaH) temp_sv.nbrOCode |= 0x4; // activate bit 2 if (nbr_os[2] <= OmegaH) nbrv_lt_oh = 1; } else { nbrs[2] = 0; nbr_os[2] = 0.0; // also, since 0.0 < OmegaL <= OmegaH < 1.0, we have a // neighbour with opacity <= OmegaH nbrv_lt_oh = 1; // we don't have to adapt the neighbour opacity code, // since it's zeroed by default } if (y < ylen - 1) { nbrs[3] = *(dptr + ystep); nbr_os[3] = OpacityTF->GetValue((double)(nbrs[3])); if (nbr_os[3] >= OmegaH) temp_sv.nbrOCode |= 0x8; // activate bit 3 if (nbr_os[3] <= OmegaH) nbrv_lt_oh = 1; } else { nbrs[3] = 0; nbr_os[3] = 0.0; // also, since 0.0 < OmegaL <= OmegaH < 1.0, we have a // neighbour with opacity <= OmegaH nbrv_lt_oh = 1; // we don't have to adapt the neighbour opacity code, // since it's zeroed by default } // Z ************************************************ if (z > 0) { nbrs[4] = *(dptr - zstep); nbr_os[4] = OpacityTF->GetValue((double)(nbrs[4])); if (nbr_os[4] >= OmegaH) temp_sv.nbrOCode |= 0x10; // activate bit 4 if (nbr_os[4] <= OmegaH) nbrv_lt_oh = 1; } else { nbrs[4] = 0; nbr_os[4] = 0.0; // also, since 0.0 < OmegaL <= OmegaH < 1.0, we have a // neighbour with opacity <= OmegaH nbrv_lt_oh = 1; // we don't have to adapt the neighbour opacity code, // since it's zeroed by default } if (z < zlen - 1) { nbrs[5] = *(dptr + zstep); nbr_os[5] = OpacityTF->GetValue((double)(nbrs[5])); if (nbr_os[5] >= OmegaH) temp_sv.nbrOCode |= 0x20; // activate bit 5 if (nbr_os[5] <= OmegaH) nbrv_lt_oh = 1; } else { nbrs[5] = 0; nbr_os[5] = 0.0; // also, since 0.0 < OmegaL <= OmegaH < 1.0, we have a // neighbour with opacity <= OmegaH nbrv_lt_oh = 1; // we don't have to adapt the neighbour opacity code, // since it's zeroed by default } // DONE with neighbour caching, lookups and neighbour code // only if one of the neighbouring voxels was <= OmegaH // is this a valid shell voxel if (nbrv_lt_oh) { if (!GradientImageData) { // calculate normal // NOTE: we are dividing by 2.0 * spacing as opengl wants // these things to be NORMALISED in world space (although // we'll be rendering in voxel space) temp_sv.Normal[0] = ((double)nbrs[0] - (double)nbrs[1]) / dxm2; temp_sv.Normal[1] = ((double)nbrs[2] - (double)nbrs[3]) / dym2; temp_sv.Normal[2] = ((double)nbrs[4] - (double)nbrs[5]) / dzm2; } // if (!GradientImageData) ... else if (!GradientImageIsGradient) { // make use of the GradientImageVolume for calculating gradients if (x > 0) gnbrs[0] = GradientImageData->GetScalarComponentAsDouble(x - 1, y, z, 0); else gnbrs[0] = 0.0; if (x < xlen - 1) gnbrs[1] = GradientImageData->GetScalarComponentAsDouble(x + 1, y, z, 0); else gnbrs[1] = 0.0; if (y > 0) gnbrs[2] = GradientImageData->GetScalarComponentAsDouble(x, y - 1, z, 0); else gnbrs[2] = 0.0; if (y < ylen - 1) gnbrs[3] = GradientImageData->GetScalarComponentAsDouble(x, y + 1, z, 0); else gnbrs[3] = 0.0; if (z > 0) gnbrs[4] = GradientImageData->GetScalarComponentAsDouble(x, y, z - 1, 0); else gnbrs[4] = 0.0; if (z < zlen - 1) gnbrs[5] = GradientImageData->GetScalarComponentAsDouble(x, y, z + 1, 0); else gnbrs[5] = 0.0; temp_sv.Normal[0] = ((double)gnbrs[0] - (double)gnbrs[1]) / dxm2; temp_sv.Normal[1] = ((double)gnbrs[2] - (double)gnbrs[3]) / dym2; temp_sv.Normal[2] = ((double)gnbrs[4] - (double)gnbrs[5]) / dzm2; } // else if (!GradientImageIsGradient) ... else { temp_sv.Normal[0] = GradientImageData->GetScalarComponentAsDouble(x,y,z,0) / dxm2; temp_sv.Normal[1] = GradientImageData->GetScalarComponentAsDouble(x,y,z,1) / dym2; temp_sv.Normal[2] = GradientImageData->GetScalarComponentAsDouble(x,y,z,2) / dzm2; } // else (i.e. GradientImageIsGradient) t_gradmag = sqrt(temp_sv.Normal[0] * temp_sv.Normal[0] + temp_sv.Normal[1] * temp_sv.Normal[1] + temp_sv.Normal[2] * temp_sv.Normal[2]); if (t_gradmag > min_gradmag) { temp_sv.Normal[0] /= t_gradmag; temp_sv.Normal[1] /= t_gradmag; temp_sv.Normal[2] /= t_gradmag; } else { // the normal is too small, shouldn't count temp_sv.Normal[0] = temp_sv.Normal[1] = temp_sv.Normal[2] = 0.0; } // now we can fill up that structure // Value is done // Opacity is done // Normal is done // nbrOCode is done temp_sv.x = x; // set integer x // and update the voxel coords in voxel space //temp_sv.volCoords[0] = x_orig + (float)x * x_spacing; //temp_sv.volCoords[1] = y_orig + (float)y * y_spacing; //temp_sv.volCoords[2] = z_orig + (float)z * z_spacing; if (!ColourTF) temp_sv.Red = temp_sv.Green = temp_sv.Blue = 1.0; else { ColourTF->GetColor(tempValue, temp_rgb); temp_sv.Red = temp_rgb[0]; temp_sv.Green = temp_rgb[1]; temp_sv.Blue = temp_rgb[2]; } vectorDx->push_back(temp_sv); Pidx = (z*ylen + y) * 2; if (Px[Pidx] == -1) { // this is the first voxel in this x-row, set its // index in the P structure Px[Pidx] = vectorDx->size() - 1; // this means (by definition) that the previous row // is done (or had no shell voxels at all, in which // case it has no length, and in which case we // have to search farther back for a row to tally // up) // we have to travel back to find the previous // row with shell voxels in it // prevPidx = Pidx - 2; // while (prevPidx >= 0 && P[prevPidx] == -1) // prevPidx-=2; // // if we found a valid prevPidx, we can tally, // // if not, Pidx is the FIRST row // if (prevPidx >= 0) // { // P[prevPidx+1] = P[Pidx] - P[prevPidx]; // } } // if (P[Pidx] == -1) ... } // if (nbrv_lt_oh) ... } // if (temp_sv.Opacity > OmegaL ... // make sure to increment dptr!!! dptr++; } // for (int x = 0 ... // now make sure that we COMPLETE the current row Pidx = (z*ylen + y) * 2; if (Px[Pidx] != -1 && Px[Pidx+1] == -1) { // this means that the beginning of the row is indicated // but not the run length Px[Pidx + 1] = vectorDx->size() - Px[Pidx]; } } // for (int y = 0 ... // FIXME: add progress event or something... cout << "row " << z << " done." << endl; } // for (int z = 0 ... // we're done, yahooooo! // --------------------------------------------------------------------- // well not quite... let's build up the y and z Ps and Ds. // we need a temporary pointer matrix so we can charge through Px // and Dx to generate the others... int *pWallZY = new int[zlen * ylen * 2]; //int tempDoffset; // newly commented, check. int PxIdx, PyIdx, PzIdx; // P is Z * X // initialize pWallZY by just copying Px memcpy(pWallZY, Px, zlen * ylen * 2 * sizeof(int)); cout << "Building y shell." << endl; // then complete vectorDy and Py for (int z = 0; z < zlen; z++) { for (int x = 0; x < xlen; x++) { PyIdx = (z * xlen + x) * 2; Py[PyIdx] = -1; Py[PyIdx + 1] = -1; for (int y = 0; y < ylen; y++) { PxIdx = (z * ylen + y) * 2; if (pWallZY[PxIdx] >= 0) { // now check that the ->x of the ShellVoxel is the one we // want temp_sv = (*vectorDx)[pWallZY[PxIdx]]; if (temp_sv.x == x) { // replace the coordinate (we're going to space-leap in y) temp_sv.x = y; // store the copy in our vectorDy vectorDy->push_back(temp_sv); // record in Py if necessary PyIdx = (z * xlen + x) * 2; if (Py[PyIdx] == -1) { Py[PyIdx] = vectorDy->size() - 1; } // then decrement the run-length --pWallZY[PxIdx + 1]; if (pWallZY[PxIdx + 1] == 0) { // so we'll skip this next time (it's done!) pWallZY[PxIdx] = -1; } else { // there are still voxels left, so we can increment this ++pWallZY[PxIdx]; } } // if (temp_sv.x == x) } // if (pWallZY[PxIdx] >= 0) ... } // for (int y = 0 ... // this y-line is done, complete the P PyIdx = (z * xlen + x) * 2; if (Py[PyIdx] != -1) { Py[PyIdx + 1] = vectorDy->size() - Py[PyIdx]; } } // for (int x = 0 ... } // for (int z = 0 ... // ---------------------------------------------------------------------- // P is Y * X // initialize pWallZY by just copying Px memcpy(pWallZY, Px, zlen * ylen * 2 * sizeof(int)); cout << "Building z shell." << endl; // then complete vectorDy and Py for (int y = 0; y < ylen; y++) { for (int x = 0; x < xlen; x++) { PzIdx = (y * xlen + x) * 2; Pz[PzIdx] = -1; Pz[PzIdx + 1] = -1; for (int z = 0; z < zlen; z++) { PxIdx = (z * ylen + y) * 2; if (pWallZY[PxIdx] >= 0) { // now check that the ->x of the ShellVoxel is the one we // want temp_sv = (*vectorDx)[pWallZY[PxIdx]]; if (temp_sv.x == x) { // replace the coordinate (we're going to space-leap in y) temp_sv.x = z; // store the copy in our vectorDy vectorDz->push_back(temp_sv); // record in Py if necessary PzIdx = (y * xlen + x) * 2; if (Pz[PzIdx] == -1) { Pz[PzIdx] = vectorDz->size() - 1; } // then decrement the run-length --pWallZY[PxIdx + 1]; if (pWallZY[PxIdx + 1] == 0) { // so we'll skip this next time (it's done!) pWallZY[PxIdx] = -1; } else { // there are still voxels left, so we can increment this ++pWallZY[PxIdx]; } } // if (temp_sv.x == x) } // if (pWallZY[PxIdx] >= 0) ... } // for (int y = 0 ... // this y-line is done, complete the P PzIdx = (y * xlen + x) * 2; if (Pz[PzIdx] != -1) { Pz[PzIdx + 1] = vectorDz->size() - Pz[PzIdx]; } } // for (int x = 0 ... } // for (int z = 0 ... delete[] pWallZY; } vtkShellExtractor::vtkShellExtractor() { this->Input = NULL; this->OmegaL = 0.0; this->OmegaH = 1.0; this->OpacityTF = NULL; this->ColourTF = NULL; this->GradientImageData = NULL; this->GradientImageIsGradient = 0; this->Dx = this->Dy = this->Dz = NULL; this->Px = this->Py = this->Pz = NULL; } vtkShellExtractor::~vtkShellExtractor() { this->SetInput(NULL); this->SetOpacityTF(NULL); this->SetColourTF(NULL); this->SetGradientImageData(NULL); if (this->Dx) delete this->Dx; if (this->Dy) delete this->Dy; if (this->Dz) delete this->Dz; if (this->Px) delete this->Px; if (this->Py) delete this->Py; if (this->Pz) delete this->Pz; } void vtkShellExtractor::Update(void) { if (!this->Input) { vtkErrorMacro(<< "No input set to calculate shell on."); return; } if (!this->OpacityTF) { vtkErrorMacro(<< "No opacity transfer function set."); return; } if (this->GetMTime() > this->ExtractTime || this->OpacityTF->GetMTime() > this->ExtractTime || this->ColourTF && this->ColourTF->GetMTime() > this->ExtractTime || this->Input->GetMTime() > this->ExtractTime || this->GradientImageData && this->GradientImageData->GetMTime() > this->ExtractTime || !this->Dx) { // make sure our input is up to date this->Input->UpdateInformation(); this->Input->SetUpdateExtentToWholeExtent(); this->Input->Update(); // and the transfer function too this->OpacityTF->Update(); // we can only use the GradientImageData if it has exactly the same number // of elements as the Input vtkImageData* TempGradientImageData = NULL; // update the GradientImageData IF we have it if (this->GradientImageData) { this->GradientImageData->UpdateInformation(); this->GradientImageData->SetUpdateExtentToWholeExtent(); this->GradientImageData->Update(); if (this->GradientImageData->GetDimensions()[0] == this->Input->GetDimensions()[0] && this->GradientImageData->GetDimensions()[1] == this->Input->GetDimensions()[1] && this->GradientImageData->GetDimensions()[2] == this->Input->GetDimensions()[2]) { TempGradientImageData = GradientImageData; } else { vtkWarningMacro("<< GradientImageData and Input have different dimensions."); } if (this->GradientImageIsGradient && this->GradientImageData->GetNumberOfScalarComponents() < 3) { vtkWarningMacro("<< GradientImageIsData ON, but < 3 components in GradientImage. Setting to OFF."); this->GradientImageIsGradient = 0; } } // we're going to iterate through each voxel in the volume and: // 1. if the voxel opacity is > OmegaL and it has at least one voxel // in its neighbourhood that is < OmegaH then // a. calculate object space normal and store // b. extract neighbourhood code // c. store everything and append to D and update P int idims[3]; this->Input->GetDimensions(idims); double ispacing[3]; this->Input->GetSpacing(ispacing); // do stuff here vtkDataArray* scalars = this->Input->GetPointData()->GetScalars(); if (scalars == NULL) { vtkErrorMacro(<< "No scalars to extract shell from!"); return; } if (this->Px) delete this->Px; if (this->Py) delete this->Py; if (this->Pz) delete this->Pz; // need array of Z * Y ints this->Px = new int[idims[2] * idims[1] * 2]; // Z * X ints this->Py = new int[idims[2] * idims[0] * 2]; // Y * X ints this->Pz = new int[idims[1] * idims[0] * 2]; vector<ShellVoxel> vectorDx, vectorDy, vectorDz; double min_gradmag = 0.0; switch (scalars->GetDataType()) { case VTK_CHAR: { char* data_ptr = ((vtkCharArray*)scalars)->GetPointer(0); ExtractShell(data_ptr, this->Input, TempGradientImageData, this->GradientImageIsGradient, this->OpacityTF, this->ColourTF, this->OmegaL, this->OmegaH, min_gradmag, &vectorDx, this->Px, &vectorDy, this->Py, &vectorDz, this->Pz); } break; case VTK_UNSIGNED_CHAR: { unsigned char* data_ptr = ((vtkUnsignedCharArray*)scalars)->GetPointer(0); ExtractShell(data_ptr, this->Input, TempGradientImageData, this->GradientImageIsGradient, this->OpacityTF, this->ColourTF, this->OmegaL, this->OmegaH, min_gradmag, &vectorDx, this->Px, &vectorDy, this->Py, &vectorDz, this->Pz); } break; case VTK_SHORT: { short* data_ptr = ((vtkShortArray*)scalars)->GetPointer(0); ExtractShell(data_ptr, this->Input, TempGradientImageData, this->GradientImageIsGradient, this->OpacityTF, this->ColourTF, this->OmegaL, this->OmegaH, min_gradmag, &vectorDx, this->Px, &vectorDy, this->Py, &vectorDz, this->Pz); } break; case VTK_UNSIGNED_SHORT: { unsigned short* data_ptr = ((vtkUnsignedShortArray*)scalars)->GetPointer(0); ExtractShell(data_ptr, this->Input, TempGradientImageData, this->GradientImageIsGradient, this->OpacityTF, this->ColourTF, this->OmegaL, this->OmegaH, min_gradmag, &vectorDx, this->Px, &vectorDy, this->Py, &vectorDz, this->Pz); } break; case VTK_INT: { int* data_ptr = ((vtkIntArray*)scalars)->GetPointer(0); ExtractShell(data_ptr, this->Input, TempGradientImageData, this->GradientImageIsGradient, this->OpacityTF, this->ColourTF, this->OmegaL, this->OmegaH, min_gradmag, &vectorDx, this->Px, &vectorDy, this->Py, &vectorDz, this->Pz); } break; case VTK_UNSIGNED_INT: { unsigned int* data_ptr = ((vtkUnsignedIntArray*)scalars)->GetPointer(0); ExtractShell(data_ptr, this->Input, TempGradientImageData, this->GradientImageIsGradient, this->OpacityTF, this->ColourTF, this->OmegaL, this->OmegaH, min_gradmag, &vectorDx, this->Px, &vectorDy, this->Py, &vectorDz, this->Pz); } break; case VTK_LONG: { long* data_ptr = ((vtkLongArray*)scalars)->GetPointer(0); ExtractShell(data_ptr, this->Input, TempGradientImageData, this->GradientImageIsGradient, this->OpacityTF, this->ColourTF, this->OmegaL, this->OmegaH, min_gradmag, &vectorDx, this->Px, &vectorDy, this->Py, &vectorDz, this->Pz); } break; case VTK_UNSIGNED_LONG: { unsigned long* data_ptr = ((vtkUnsignedLongArray*)scalars)->GetPointer(0); ExtractShell(data_ptr, this->Input, TempGradientImageData, this->GradientImageIsGradient, this->OpacityTF, this->ColourTF, this->OmegaL, this->OmegaH, min_gradmag, &vectorDx, this->Px, &vectorDy, this->Py, &vectorDz, this->Pz); } break; case VTK_FLOAT: { float* data_ptr = ((vtkFloatArray*)scalars)->GetPointer(0); ExtractShell(data_ptr, this->Input, TempGradientImageData, this->GradientImageIsGradient, this->OpacityTF, this->ColourTF, this->OmegaL, this->OmegaH, min_gradmag, &vectorDx, this->Px, &vectorDy, this->Py, &vectorDz, this->Pz); } break; case VTK_DOUBLE: { double* data_ptr = ((vtkDoubleArray*)scalars)->GetPointer(0); ExtractShell(data_ptr, this->Input, TempGradientImageData, this->GradientImageIsGradient, this->OpacityTF, this->ColourTF, this->OmegaL, this->OmegaH, min_gradmag, &vectorDx, this->Px, &vectorDy, this->Py, &vectorDz, this->Pz); } break; default: vtkErrorMacro(<< "Unknown type of scalar data!"); } // now we should copy vectorD over to D if (this->Dx) delete this->Dx; this->Dx = new ShellVoxel[vectorDx.size()]; for (unsigned i = 0; i < vectorDx.size(); i++) memcpy(this->Dx + i, &(vectorDx[i]), sizeof(ShellVoxel)); // now we should copy vectorD over to D if (this->Dy) delete this->Dy; this->Dy = new ShellVoxel[vectorDy.size()]; for (unsigned i = 0; i < vectorDy.size(); i++) memcpy(this->Dy + i, &(vectorDy[i]), sizeof(ShellVoxel)); // now we should copy vectorD over to D if (this->Dz) delete this->Dz; this->Dz = new ShellVoxel[vectorDz.size()]; for (unsigned i = 0; i < vectorDz.size(); i++) memcpy(this->Dz + i, &(vectorDz[i]), sizeof(ShellVoxel)); cout << vectorDx.size() << " x shell voxels found." << endl; cout << vectorDy.size() << " y shell voxels found." << endl; cout << vectorDz.size() << " z shell voxels found." << endl; // stop doing stuff this->ExtractTime.Modified(); } } const int vtkShellExtractor::shell_noc_visibility_lut[8][64] = { // octant 0, bits 0 & 2 & 4 {1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 1, 1, 1, 1, 1, 0, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 1, 1, 1, 1, 1, 0, 1, 0 }, // octant 1, bits 1 & 2 & 4 {1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0 }, // octant 2, bits 0 & 3 & 4 {1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 1, 0, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 1, 0, 1, 0 }, // octant 3, bits 1 & 3 & 4 {1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 0, 0 }, // octant 4, bits 0 & 2 & 5 {1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 1, 1, 1, 1, 1, 0, 1, 0, 1, 1, 1, 1, 1, 0, 1, 0, 1, 1, 1, 1, 1, 0, 1, 0 }, // octant 5, bits 1 & 2 & 5 {1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0 }, // octant 6, bits 0 & 3 & 5 {1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 1, 0, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 1, 0, 1, 0 }, // octant 7, bits 1 & 3 & 5 {1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 0, 0 } };
35.415695
116
0.485044
[ "object", "vector" ]
4a77903419b659aef0f8b7fe033b1e4dfdeac8e6
677
cpp
C++
uploads/test/lightsaber.cpp
l3lackclevil/ARIN-grader
fdfc1ff13402ae5cf327be32733a4cc1fdecf811
[ "Apache-2.0" ]
null
null
null
uploads/test/lightsaber.cpp
l3lackclevil/ARIN-grader
fdfc1ff13402ae5cf327be32733a4cc1fdecf811
[ "Apache-2.0" ]
null
null
null
uploads/test/lightsaber.cpp
l3lackclevil/ARIN-grader
fdfc1ff13402ae5cf327be32733a4cc1fdecf811
[ "Apache-2.0" ]
null
null
null
#include <cstdio> #include <cstdlib> #include <cstring> #include <cmath> #include <iostream> #include <algorithm> #include <set> #include <map> #include <vector> #include <queue> #include <stack> #include <list> #include <string> #include <time.h> #define SQR(_x) ((_x)*(_x)) #define NL printf("\n") #define LL long long #define DB double #define PB push_back #define INF 1<<30 #define LB lower_bound #define UB upper_bound #define F front #define PQ priority_queue using namespace std; long long ff(int a) { if(a==1) return 1; if(a==0) return 0; return (2*ff(a-1))+(3*ff(a-2)); } int main() { int n; long long ans; scanf("%d",&n); printf("%lld",ff(n+1)); return 0; }
16.512195
32
0.67356
[ "vector" ]
4a7903d646aae08d0b36b932f7b11409b05fa14a
32,455
cc
C++
code/atom/src/proto/Scene.pb.cc
KasumiL5x/atom
90262f59e56a829017f95f297c1a6701fc4e200e
[ "MIT" ]
null
null
null
code/atom/src/proto/Scene.pb.cc
KasumiL5x/atom
90262f59e56a829017f95f297c1a6701fc4e200e
[ "MIT" ]
null
null
null
code/atom/src/proto/Scene.pb.cc
KasumiL5x/atom
90262f59e56a829017f95f297c1a6701fc4e200e
[ "MIT" ]
null
null
null
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: Scene.proto #define INTERNAL_SUPPRESS_PROTOBUF_FIELD_DEPRECATION #include "Scene.pb.h" #include <algorithm> #include <google/protobuf/stubs/common.h> #include <google/protobuf/stubs/port.h> #include <google/protobuf/stubs/once.h> #include <google/protobuf/io/coded_stream.h> #include <google/protobuf/wire_format_lite_inl.h> #include <google/protobuf/descriptor.h> #include <google/protobuf/generated_message_reflection.h> #include <google/protobuf/reflection_ops.h> #include <google/protobuf/wire_format.h> // @@protoc_insertion_point(includes) namespace atom { namespace proto { namespace { const ::google::protobuf::Descriptor* Scene_descriptor_ = NULL; const ::google::protobuf::internal::GeneratedMessageReflection* Scene_reflection_ = NULL; const ::google::protobuf::EnumDescriptor* Scene_Reason_descriptor_ = NULL; } // namespace void protobuf_AssignDesc_Scene_2eproto() { protobuf_AddDesc_Scene_2eproto(); const ::google::protobuf::FileDescriptor* file = ::google::protobuf::DescriptorPool::generated_pool()->FindFileByName( "Scene.proto"); GOOGLE_CHECK(file != NULL); Scene_descriptor_ = file->message_type(0); static const int Scene_offsets_[9] = { GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Scene, transferreason_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Scene, meshes_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Scene, lights_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Scene, cameras_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Scene, materials_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Scene, textures_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Scene, transforms_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Scene, annotations_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Scene, curves_), }; Scene_reflection_ = ::google::protobuf::internal::GeneratedMessageReflection::NewGeneratedMessageReflection( Scene_descriptor_, Scene::default_instance_, Scene_offsets_, -1, -1, -1, sizeof(Scene), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Scene, _internal_metadata_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Scene, _is_default_instance_)); Scene_Reason_descriptor_ = Scene_descriptor_->enum_type(0); } namespace { GOOGLE_PROTOBUF_DECLARE_ONCE(protobuf_AssignDescriptors_once_); inline void protobuf_AssignDescriptorsOnce() { ::google::protobuf::GoogleOnceInit(&protobuf_AssignDescriptors_once_, &protobuf_AssignDesc_Scene_2eproto); } void protobuf_RegisterTypes(const ::std::string&) { protobuf_AssignDescriptorsOnce(); ::google::protobuf::MessageFactory::InternalRegisterGeneratedMessage( Scene_descriptor_, &Scene::default_instance()); } } // namespace void protobuf_ShutdownFile_Scene_2eproto() { delete Scene::default_instance_; delete Scene_reflection_; } void protobuf_AddDesc_Scene_2eproto() { static bool already_here = false; if (already_here) return; already_here = true; GOOGLE_PROTOBUF_VERIFY_VERSION; ::atom::proto::protobuf_AddDesc_SceneObject_2eproto(); ::google::protobuf::DescriptorPool::InternalAddGeneratedFile( "\n\013Scene.proto\022\natom.proto\032\021SceneObject.p" "roto\"\364\003\n\005Scene\0220\n\016TransferReason\030\001 \001(\0162\030" ".atom.proto.Scene.Reason\022\'\n\006Meshes\030\002 \003(\013" "2\027.atom.proto.SceneObject\022\'\n\006Lights\030\003 \003(" "\0132\027.atom.proto.SceneObject\022(\n\007Cameras\030\004 " "\003(\0132\027.atom.proto.SceneObject\022*\n\tMaterial" "s\030\005 \003(\0132\027.atom.proto.SceneObject\022)\n\010Text" "ures\030\006 \003(\0132\027.atom.proto.SceneObject\022+\n\nT" "ransforms\030\007 \003(\0132\027.atom.proto.SceneObject" "\022,\n\013Annotations\030\010 \003(\0132\027.atom.proto.Scene" "Object\022\'\n\006Curves\030\t \003(\0132\027.atom.proto.Scen" "eObject\"b\n\006Reason\022\027\n\023kRebuildOnConnected" "\020\000\022\021\n\rkRebuildOnNew\020\001\022\022\n\016kRebuildOnOpen\020" "\002\022\n\n\006kAdded\020\003\022\014\n\010kRemoved\020\004b\006proto3", 555); ::google::protobuf::MessageFactory::InternalRegisterGeneratedFile( "Scene.proto", &protobuf_RegisterTypes); Scene::default_instance_ = new Scene(); Scene::default_instance_->InitAsDefaultInstance(); ::google::protobuf::internal::OnShutdown(&protobuf_ShutdownFile_Scene_2eproto); } // Force AddDescriptors() to be called at static initialization time. struct StaticDescriptorInitializer_Scene_2eproto { StaticDescriptorInitializer_Scene_2eproto() { protobuf_AddDesc_Scene_2eproto(); } } static_descriptor_initializer_Scene_2eproto_; namespace { static void MergeFromFail(int line) GOOGLE_ATTRIBUTE_COLD; static void MergeFromFail(int line) { GOOGLE_CHECK(false) << __FILE__ << ":" << line; } } // namespace // =================================================================== const ::google::protobuf::EnumDescriptor* Scene_Reason_descriptor() { protobuf_AssignDescriptorsOnce(); return Scene_Reason_descriptor_; } bool Scene_Reason_IsValid(int value) { switch(value) { case 0: case 1: case 2: case 3: case 4: return true; default: return false; } } #if !defined(_MSC_VER) || _MSC_VER >= 1900 const Scene_Reason Scene::kRebuildOnConnected; const Scene_Reason Scene::kRebuildOnNew; const Scene_Reason Scene::kRebuildOnOpen; const Scene_Reason Scene::kAdded; const Scene_Reason Scene::kRemoved; const Scene_Reason Scene::Reason_MIN; const Scene_Reason Scene::Reason_MAX; const int Scene::Reason_ARRAYSIZE; #endif // !defined(_MSC_VER) || _MSC_VER >= 1900 #if !defined(_MSC_VER) || _MSC_VER >= 1900 const int Scene::kTransferReasonFieldNumber; const int Scene::kMeshesFieldNumber; const int Scene::kLightsFieldNumber; const int Scene::kCamerasFieldNumber; const int Scene::kMaterialsFieldNumber; const int Scene::kTexturesFieldNumber; const int Scene::kTransformsFieldNumber; const int Scene::kAnnotationsFieldNumber; const int Scene::kCurvesFieldNumber; #endif // !defined(_MSC_VER) || _MSC_VER >= 1900 Scene::Scene() : ::google::protobuf::Message(), _internal_metadata_(NULL) { SharedCtor(); // @@protoc_insertion_point(constructor:atom.proto.Scene) } void Scene::InitAsDefaultInstance() { _is_default_instance_ = true; } Scene::Scene(const Scene& from) : ::google::protobuf::Message(), _internal_metadata_(NULL) { SharedCtor(); MergeFrom(from); // @@protoc_insertion_point(copy_constructor:atom.proto.Scene) } void Scene::SharedCtor() { _is_default_instance_ = false; _cached_size_ = 0; transferreason_ = 0; } Scene::~Scene() { // @@protoc_insertion_point(destructor:atom.proto.Scene) SharedDtor(); } void Scene::SharedDtor() { if (this != default_instance_) { } } void Scene::SetCachedSize(int size) const { GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); _cached_size_ = size; GOOGLE_SAFE_CONCURRENT_WRITES_END(); } const ::google::protobuf::Descriptor* Scene::descriptor() { protobuf_AssignDescriptorsOnce(); return Scene_descriptor_; } const Scene& Scene::default_instance() { if (default_instance_ == NULL) protobuf_AddDesc_Scene_2eproto(); return *default_instance_; } Scene* Scene::default_instance_ = NULL; Scene* Scene::New(::google::protobuf::Arena* arena) const { Scene* n = new Scene; if (arena != NULL) { arena->Own(n); } return n; } void Scene::Clear() { transferreason_ = 0; meshes_.Clear(); lights_.Clear(); cameras_.Clear(); materials_.Clear(); textures_.Clear(); transforms_.Clear(); annotations_.Clear(); curves_.Clear(); } bool Scene::MergePartialFromCodedStream( ::google::protobuf::io::CodedInputStream* input) { #define DO_(EXPRESSION) if (!(EXPRESSION)) goto failure ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:atom.proto.Scene) for (;;) { ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoff(127); tag = p.first; if (!p.second) goto handle_unusual; switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { // optional .atom.proto.Scene.Reason TransferReason = 1; case 1: { if (tag == 8) { int value; DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< int, ::google::protobuf::internal::WireFormatLite::TYPE_ENUM>( input, &value))); set_transferreason(static_cast< ::atom::proto::Scene_Reason >(value)); } else { goto handle_unusual; } if (input->ExpectTag(18)) goto parse_Meshes; break; } // repeated .atom.proto.SceneObject Meshes = 2; case 2: { if (tag == 18) { parse_Meshes: DO_(input->IncrementRecursionDepth()); parse_loop_Meshes: DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtualNoRecursionDepth( input, add_meshes())); } else { goto handle_unusual; } if (input->ExpectTag(18)) goto parse_loop_Meshes; if (input->ExpectTag(26)) goto parse_loop_Lights; input->UnsafeDecrementRecursionDepth(); break; } // repeated .atom.proto.SceneObject Lights = 3; case 3: { if (tag == 26) { DO_(input->IncrementRecursionDepth()); parse_loop_Lights: DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtualNoRecursionDepth( input, add_lights())); } else { goto handle_unusual; } if (input->ExpectTag(26)) goto parse_loop_Lights; if (input->ExpectTag(34)) goto parse_loop_Cameras; input->UnsafeDecrementRecursionDepth(); break; } // repeated .atom.proto.SceneObject Cameras = 4; case 4: { if (tag == 34) { DO_(input->IncrementRecursionDepth()); parse_loop_Cameras: DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtualNoRecursionDepth( input, add_cameras())); } else { goto handle_unusual; } if (input->ExpectTag(34)) goto parse_loop_Cameras; if (input->ExpectTag(42)) goto parse_loop_Materials; input->UnsafeDecrementRecursionDepth(); break; } // repeated .atom.proto.SceneObject Materials = 5; case 5: { if (tag == 42) { DO_(input->IncrementRecursionDepth()); parse_loop_Materials: DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtualNoRecursionDepth( input, add_materials())); } else { goto handle_unusual; } if (input->ExpectTag(42)) goto parse_loop_Materials; if (input->ExpectTag(50)) goto parse_loop_Textures; input->UnsafeDecrementRecursionDepth(); break; } // repeated .atom.proto.SceneObject Textures = 6; case 6: { if (tag == 50) { DO_(input->IncrementRecursionDepth()); parse_loop_Textures: DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtualNoRecursionDepth( input, add_textures())); } else { goto handle_unusual; } if (input->ExpectTag(50)) goto parse_loop_Textures; if (input->ExpectTag(58)) goto parse_loop_Transforms; input->UnsafeDecrementRecursionDepth(); break; } // repeated .atom.proto.SceneObject Transforms = 7; case 7: { if (tag == 58) { DO_(input->IncrementRecursionDepth()); parse_loop_Transforms: DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtualNoRecursionDepth( input, add_transforms())); } else { goto handle_unusual; } if (input->ExpectTag(58)) goto parse_loop_Transforms; if (input->ExpectTag(66)) goto parse_loop_Annotations; input->UnsafeDecrementRecursionDepth(); break; } // repeated .atom.proto.SceneObject Annotations = 8; case 8: { if (tag == 66) { DO_(input->IncrementRecursionDepth()); parse_loop_Annotations: DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtualNoRecursionDepth( input, add_annotations())); } else { goto handle_unusual; } if (input->ExpectTag(66)) goto parse_loop_Annotations; if (input->ExpectTag(74)) goto parse_loop_Curves; input->UnsafeDecrementRecursionDepth(); break; } // repeated .atom.proto.SceneObject Curves = 9; case 9: { if (tag == 74) { DO_(input->IncrementRecursionDepth()); parse_loop_Curves: DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtualNoRecursionDepth( input, add_curves())); } else { goto handle_unusual; } if (input->ExpectTag(74)) goto parse_loop_Curves; input->UnsafeDecrementRecursionDepth(); if (input->ExpectAtEnd()) goto success; break; } default: { handle_unusual: if (tag == 0 || ::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == ::google::protobuf::internal::WireFormatLite::WIRETYPE_END_GROUP) { goto success; } DO_(::google::protobuf::internal::WireFormatLite::SkipField(input, tag)); break; } } } success: // @@protoc_insertion_point(parse_success:atom.proto.Scene) return true; failure: // @@protoc_insertion_point(parse_failure:atom.proto.Scene) return false; #undef DO_ } void Scene::SerializeWithCachedSizes( ::google::protobuf::io::CodedOutputStream* output) const { // @@protoc_insertion_point(serialize_start:atom.proto.Scene) // optional .atom.proto.Scene.Reason TransferReason = 1; if (this->transferreason() != 0) { ::google::protobuf::internal::WireFormatLite::WriteEnum( 1, this->transferreason(), output); } // repeated .atom.proto.SceneObject Meshes = 2; for (unsigned int i = 0, n = this->meshes_size(); i < n; i++) { ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( 2, this->meshes(i), output); } // repeated .atom.proto.SceneObject Lights = 3; for (unsigned int i = 0, n = this->lights_size(); i < n; i++) { ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( 3, this->lights(i), output); } // repeated .atom.proto.SceneObject Cameras = 4; for (unsigned int i = 0, n = this->cameras_size(); i < n; i++) { ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( 4, this->cameras(i), output); } // repeated .atom.proto.SceneObject Materials = 5; for (unsigned int i = 0, n = this->materials_size(); i < n; i++) { ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( 5, this->materials(i), output); } // repeated .atom.proto.SceneObject Textures = 6; for (unsigned int i = 0, n = this->textures_size(); i < n; i++) { ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( 6, this->textures(i), output); } // repeated .atom.proto.SceneObject Transforms = 7; for (unsigned int i = 0, n = this->transforms_size(); i < n; i++) { ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( 7, this->transforms(i), output); } // repeated .atom.proto.SceneObject Annotations = 8; for (unsigned int i = 0, n = this->annotations_size(); i < n; i++) { ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( 8, this->annotations(i), output); } // repeated .atom.proto.SceneObject Curves = 9; for (unsigned int i = 0, n = this->curves_size(); i < n; i++) { ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( 9, this->curves(i), output); } // @@protoc_insertion_point(serialize_end:atom.proto.Scene) } ::google::protobuf::uint8* Scene::SerializeWithCachedSizesToArray( ::google::protobuf::uint8* target) const { // @@protoc_insertion_point(serialize_to_array_start:atom.proto.Scene) // optional .atom.proto.Scene.Reason TransferReason = 1; if (this->transferreason() != 0) { target = ::google::protobuf::internal::WireFormatLite::WriteEnumToArray( 1, this->transferreason(), target); } // repeated .atom.proto.SceneObject Meshes = 2; for (unsigned int i = 0, n = this->meshes_size(); i < n; i++) { target = ::google::protobuf::internal::WireFormatLite:: WriteMessageNoVirtualToArray( 2, this->meshes(i), target); } // repeated .atom.proto.SceneObject Lights = 3; for (unsigned int i = 0, n = this->lights_size(); i < n; i++) { target = ::google::protobuf::internal::WireFormatLite:: WriteMessageNoVirtualToArray( 3, this->lights(i), target); } // repeated .atom.proto.SceneObject Cameras = 4; for (unsigned int i = 0, n = this->cameras_size(); i < n; i++) { target = ::google::protobuf::internal::WireFormatLite:: WriteMessageNoVirtualToArray( 4, this->cameras(i), target); } // repeated .atom.proto.SceneObject Materials = 5; for (unsigned int i = 0, n = this->materials_size(); i < n; i++) { target = ::google::protobuf::internal::WireFormatLite:: WriteMessageNoVirtualToArray( 5, this->materials(i), target); } // repeated .atom.proto.SceneObject Textures = 6; for (unsigned int i = 0, n = this->textures_size(); i < n; i++) { target = ::google::protobuf::internal::WireFormatLite:: WriteMessageNoVirtualToArray( 6, this->textures(i), target); } // repeated .atom.proto.SceneObject Transforms = 7; for (unsigned int i = 0, n = this->transforms_size(); i < n; i++) { target = ::google::protobuf::internal::WireFormatLite:: WriteMessageNoVirtualToArray( 7, this->transforms(i), target); } // repeated .atom.proto.SceneObject Annotations = 8; for (unsigned int i = 0, n = this->annotations_size(); i < n; i++) { target = ::google::protobuf::internal::WireFormatLite:: WriteMessageNoVirtualToArray( 8, this->annotations(i), target); } // repeated .atom.proto.SceneObject Curves = 9; for (unsigned int i = 0, n = this->curves_size(); i < n; i++) { target = ::google::protobuf::internal::WireFormatLite:: WriteMessageNoVirtualToArray( 9, this->curves(i), target); } // @@protoc_insertion_point(serialize_to_array_end:atom.proto.Scene) return target; } int Scene::ByteSize() const { int total_size = 0; // optional .atom.proto.Scene.Reason TransferReason = 1; if (this->transferreason() != 0) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::EnumSize(this->transferreason()); } // repeated .atom.proto.SceneObject Meshes = 2; total_size += 1 * this->meshes_size(); for (int i = 0; i < this->meshes_size(); i++) { total_size += ::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual( this->meshes(i)); } // repeated .atom.proto.SceneObject Lights = 3; total_size += 1 * this->lights_size(); for (int i = 0; i < this->lights_size(); i++) { total_size += ::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual( this->lights(i)); } // repeated .atom.proto.SceneObject Cameras = 4; total_size += 1 * this->cameras_size(); for (int i = 0; i < this->cameras_size(); i++) { total_size += ::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual( this->cameras(i)); } // repeated .atom.proto.SceneObject Materials = 5; total_size += 1 * this->materials_size(); for (int i = 0; i < this->materials_size(); i++) { total_size += ::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual( this->materials(i)); } // repeated .atom.proto.SceneObject Textures = 6; total_size += 1 * this->textures_size(); for (int i = 0; i < this->textures_size(); i++) { total_size += ::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual( this->textures(i)); } // repeated .atom.proto.SceneObject Transforms = 7; total_size += 1 * this->transforms_size(); for (int i = 0; i < this->transforms_size(); i++) { total_size += ::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual( this->transforms(i)); } // repeated .atom.proto.SceneObject Annotations = 8; total_size += 1 * this->annotations_size(); for (int i = 0; i < this->annotations_size(); i++) { total_size += ::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual( this->annotations(i)); } // repeated .atom.proto.SceneObject Curves = 9; total_size += 1 * this->curves_size(); for (int i = 0; i < this->curves_size(); i++) { total_size += ::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual( this->curves(i)); } GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); _cached_size_ = total_size; GOOGLE_SAFE_CONCURRENT_WRITES_END(); return total_size; } void Scene::MergeFrom(const ::google::protobuf::Message& from) { if (GOOGLE_PREDICT_FALSE(&from == this)) MergeFromFail(__LINE__); const Scene* source = ::google::protobuf::internal::DynamicCastToGenerated<const Scene>( &from); if (source == NULL) { ::google::protobuf::internal::ReflectionOps::Merge(from, this); } else { MergeFrom(*source); } } void Scene::MergeFrom(const Scene& from) { if (GOOGLE_PREDICT_FALSE(&from == this)) MergeFromFail(__LINE__); meshes_.MergeFrom(from.meshes_); lights_.MergeFrom(from.lights_); cameras_.MergeFrom(from.cameras_); materials_.MergeFrom(from.materials_); textures_.MergeFrom(from.textures_); transforms_.MergeFrom(from.transforms_); annotations_.MergeFrom(from.annotations_); curves_.MergeFrom(from.curves_); if (from.transferreason() != 0) { set_transferreason(from.transferreason()); } } void Scene::CopyFrom(const ::google::protobuf::Message& from) { if (&from == this) return; Clear(); MergeFrom(from); } void Scene::CopyFrom(const Scene& from) { if (&from == this) return; Clear(); MergeFrom(from); } bool Scene::IsInitialized() const { return true; } void Scene::Swap(Scene* other) { if (other == this) return; InternalSwap(other); } void Scene::InternalSwap(Scene* other) { std::swap(transferreason_, other->transferreason_); meshes_.UnsafeArenaSwap(&other->meshes_); lights_.UnsafeArenaSwap(&other->lights_); cameras_.UnsafeArenaSwap(&other->cameras_); materials_.UnsafeArenaSwap(&other->materials_); textures_.UnsafeArenaSwap(&other->textures_); transforms_.UnsafeArenaSwap(&other->transforms_); annotations_.UnsafeArenaSwap(&other->annotations_); curves_.UnsafeArenaSwap(&other->curves_); _internal_metadata_.Swap(&other->_internal_metadata_); std::swap(_cached_size_, other->_cached_size_); } ::google::protobuf::Metadata Scene::GetMetadata() const { protobuf_AssignDescriptorsOnce(); ::google::protobuf::Metadata metadata; metadata.descriptor = Scene_descriptor_; metadata.reflection = Scene_reflection_; return metadata; } #if PROTOBUF_INLINE_NOT_IN_HEADERS // Scene // optional .atom.proto.Scene.Reason TransferReason = 1; void Scene::clear_transferreason() { transferreason_ = 0; } ::atom::proto::Scene_Reason Scene::transferreason() const { // @@protoc_insertion_point(field_get:atom.proto.Scene.TransferReason) return static_cast< ::atom::proto::Scene_Reason >(transferreason_); } void Scene::set_transferreason(::atom::proto::Scene_Reason value) { transferreason_ = value; // @@protoc_insertion_point(field_set:atom.proto.Scene.TransferReason) } // repeated .atom.proto.SceneObject Meshes = 2; int Scene::meshes_size() const { return meshes_.size(); } void Scene::clear_meshes() { meshes_.Clear(); } const ::atom::proto::SceneObject& Scene::meshes(int index) const { // @@protoc_insertion_point(field_get:atom.proto.Scene.Meshes) return meshes_.Get(index); } ::atom::proto::SceneObject* Scene::mutable_meshes(int index) { // @@protoc_insertion_point(field_mutable:atom.proto.Scene.Meshes) return meshes_.Mutable(index); } ::atom::proto::SceneObject* Scene::add_meshes() { // @@protoc_insertion_point(field_add:atom.proto.Scene.Meshes) return meshes_.Add(); } ::google::protobuf::RepeatedPtrField< ::atom::proto::SceneObject >* Scene::mutable_meshes() { // @@protoc_insertion_point(field_mutable_list:atom.proto.Scene.Meshes) return &meshes_; } const ::google::protobuf::RepeatedPtrField< ::atom::proto::SceneObject >& Scene::meshes() const { // @@protoc_insertion_point(field_list:atom.proto.Scene.Meshes) return meshes_; } // repeated .atom.proto.SceneObject Lights = 3; int Scene::lights_size() const { return lights_.size(); } void Scene::clear_lights() { lights_.Clear(); } const ::atom::proto::SceneObject& Scene::lights(int index) const { // @@protoc_insertion_point(field_get:atom.proto.Scene.Lights) return lights_.Get(index); } ::atom::proto::SceneObject* Scene::mutable_lights(int index) { // @@protoc_insertion_point(field_mutable:atom.proto.Scene.Lights) return lights_.Mutable(index); } ::atom::proto::SceneObject* Scene::add_lights() { // @@protoc_insertion_point(field_add:atom.proto.Scene.Lights) return lights_.Add(); } ::google::protobuf::RepeatedPtrField< ::atom::proto::SceneObject >* Scene::mutable_lights() { // @@protoc_insertion_point(field_mutable_list:atom.proto.Scene.Lights) return &lights_; } const ::google::protobuf::RepeatedPtrField< ::atom::proto::SceneObject >& Scene::lights() const { // @@protoc_insertion_point(field_list:atom.proto.Scene.Lights) return lights_; } // repeated .atom.proto.SceneObject Cameras = 4; int Scene::cameras_size() const { return cameras_.size(); } void Scene::clear_cameras() { cameras_.Clear(); } const ::atom::proto::SceneObject& Scene::cameras(int index) const { // @@protoc_insertion_point(field_get:atom.proto.Scene.Cameras) return cameras_.Get(index); } ::atom::proto::SceneObject* Scene::mutable_cameras(int index) { // @@protoc_insertion_point(field_mutable:atom.proto.Scene.Cameras) return cameras_.Mutable(index); } ::atom::proto::SceneObject* Scene::add_cameras() { // @@protoc_insertion_point(field_add:atom.proto.Scene.Cameras) return cameras_.Add(); } ::google::protobuf::RepeatedPtrField< ::atom::proto::SceneObject >* Scene::mutable_cameras() { // @@protoc_insertion_point(field_mutable_list:atom.proto.Scene.Cameras) return &cameras_; } const ::google::protobuf::RepeatedPtrField< ::atom::proto::SceneObject >& Scene::cameras() const { // @@protoc_insertion_point(field_list:atom.proto.Scene.Cameras) return cameras_; } // repeated .atom.proto.SceneObject Materials = 5; int Scene::materials_size() const { return materials_.size(); } void Scene::clear_materials() { materials_.Clear(); } const ::atom::proto::SceneObject& Scene::materials(int index) const { // @@protoc_insertion_point(field_get:atom.proto.Scene.Materials) return materials_.Get(index); } ::atom::proto::SceneObject* Scene::mutable_materials(int index) { // @@protoc_insertion_point(field_mutable:atom.proto.Scene.Materials) return materials_.Mutable(index); } ::atom::proto::SceneObject* Scene::add_materials() { // @@protoc_insertion_point(field_add:atom.proto.Scene.Materials) return materials_.Add(); } ::google::protobuf::RepeatedPtrField< ::atom::proto::SceneObject >* Scene::mutable_materials() { // @@protoc_insertion_point(field_mutable_list:atom.proto.Scene.Materials) return &materials_; } const ::google::protobuf::RepeatedPtrField< ::atom::proto::SceneObject >& Scene::materials() const { // @@protoc_insertion_point(field_list:atom.proto.Scene.Materials) return materials_; } // repeated .atom.proto.SceneObject Textures = 6; int Scene::textures_size() const { return textures_.size(); } void Scene::clear_textures() { textures_.Clear(); } const ::atom::proto::SceneObject& Scene::textures(int index) const { // @@protoc_insertion_point(field_get:atom.proto.Scene.Textures) return textures_.Get(index); } ::atom::proto::SceneObject* Scene::mutable_textures(int index) { // @@protoc_insertion_point(field_mutable:atom.proto.Scene.Textures) return textures_.Mutable(index); } ::atom::proto::SceneObject* Scene::add_textures() { // @@protoc_insertion_point(field_add:atom.proto.Scene.Textures) return textures_.Add(); } ::google::protobuf::RepeatedPtrField< ::atom::proto::SceneObject >* Scene::mutable_textures() { // @@protoc_insertion_point(field_mutable_list:atom.proto.Scene.Textures) return &textures_; } const ::google::protobuf::RepeatedPtrField< ::atom::proto::SceneObject >& Scene::textures() const { // @@protoc_insertion_point(field_list:atom.proto.Scene.Textures) return textures_; } // repeated .atom.proto.SceneObject Transforms = 7; int Scene::transforms_size() const { return transforms_.size(); } void Scene::clear_transforms() { transforms_.Clear(); } const ::atom::proto::SceneObject& Scene::transforms(int index) const { // @@protoc_insertion_point(field_get:atom.proto.Scene.Transforms) return transforms_.Get(index); } ::atom::proto::SceneObject* Scene::mutable_transforms(int index) { // @@protoc_insertion_point(field_mutable:atom.proto.Scene.Transforms) return transforms_.Mutable(index); } ::atom::proto::SceneObject* Scene::add_transforms() { // @@protoc_insertion_point(field_add:atom.proto.Scene.Transforms) return transforms_.Add(); } ::google::protobuf::RepeatedPtrField< ::atom::proto::SceneObject >* Scene::mutable_transforms() { // @@protoc_insertion_point(field_mutable_list:atom.proto.Scene.Transforms) return &transforms_; } const ::google::protobuf::RepeatedPtrField< ::atom::proto::SceneObject >& Scene::transforms() const { // @@protoc_insertion_point(field_list:atom.proto.Scene.Transforms) return transforms_; } // repeated .atom.proto.SceneObject Annotations = 8; int Scene::annotations_size() const { return annotations_.size(); } void Scene::clear_annotations() { annotations_.Clear(); } const ::atom::proto::SceneObject& Scene::annotations(int index) const { // @@protoc_insertion_point(field_get:atom.proto.Scene.Annotations) return annotations_.Get(index); } ::atom::proto::SceneObject* Scene::mutable_annotations(int index) { // @@protoc_insertion_point(field_mutable:atom.proto.Scene.Annotations) return annotations_.Mutable(index); } ::atom::proto::SceneObject* Scene::add_annotations() { // @@protoc_insertion_point(field_add:atom.proto.Scene.Annotations) return annotations_.Add(); } ::google::protobuf::RepeatedPtrField< ::atom::proto::SceneObject >* Scene::mutable_annotations() { // @@protoc_insertion_point(field_mutable_list:atom.proto.Scene.Annotations) return &annotations_; } const ::google::protobuf::RepeatedPtrField< ::atom::proto::SceneObject >& Scene::annotations() const { // @@protoc_insertion_point(field_list:atom.proto.Scene.Annotations) return annotations_; } // repeated .atom.proto.SceneObject Curves = 9; int Scene::curves_size() const { return curves_.size(); } void Scene::clear_curves() { curves_.Clear(); } const ::atom::proto::SceneObject& Scene::curves(int index) const { // @@protoc_insertion_point(field_get:atom.proto.Scene.Curves) return curves_.Get(index); } ::atom::proto::SceneObject* Scene::mutable_curves(int index) { // @@protoc_insertion_point(field_mutable:atom.proto.Scene.Curves) return curves_.Mutable(index); } ::atom::proto::SceneObject* Scene::add_curves() { // @@protoc_insertion_point(field_add:atom.proto.Scene.Curves) return curves_.Add(); } ::google::protobuf::RepeatedPtrField< ::atom::proto::SceneObject >* Scene::mutable_curves() { // @@protoc_insertion_point(field_mutable_list:atom.proto.Scene.Curves) return &curves_; } const ::google::protobuf::RepeatedPtrField< ::atom::proto::SceneObject >& Scene::curves() const { // @@protoc_insertion_point(field_list:atom.proto.Scene.Curves) return curves_; } #endif // PROTOBUF_INLINE_NOT_IN_HEADERS // @@protoc_insertion_point(namespace_scope) } // namespace proto } // namespace atom // @@protoc_insertion_point(global_scope)
33.737006
97
0.695301
[ "object" ]
4a84cb082d681f1de02f02197e599d513a58c036
921
cpp
C++
leetcode/15-Programme/JD0807M-Permutation/Permutation.cpp
BinRay/Learning
36a2380a9686e6922632e6b85ddb3d1f0903b37a
[ "MIT" ]
null
null
null
leetcode/15-Programme/JD0807M-Permutation/Permutation.cpp
BinRay/Learning
36a2380a9686e6922632e6b85ddb3d1f0903b37a
[ "MIT" ]
null
null
null
leetcode/15-Programme/JD0807M-Permutation/Permutation.cpp
BinRay/Learning
36a2380a9686e6922632e6b85ddb3d1f0903b37a
[ "MIT" ]
null
null
null
/** * 1. 用S构建一个字符集合 * 2. 假设S共有N个元素,取其中的每个元素 * 3. 将剩余的N-1个元素排列,并将2中取出的元素放到所有N-1字符串排列的末尾,构成新的集合。 * 4. 合并2中所有N个元素的情况。 * 5. 注意边界 */ class Solution { public: vector<string> permutation(string S) { vector<string> strs; unordered_set<char> s( S.begin(), S.end() ); strs = dc( s ); return strs; } vector<string> dc ( const unordered_set<char> &s ){ if ( s.empty() ){ return { "" }; } else { vector<string> strs; for ( auto c: s ){ unordered_set<char> sub_set = s; sub_set.erase( c ); vector<string> sub_strings = dc( sub_set ); for ( auto sub_string: sub_strings ){ sub_string += c; strs.push_back( sub_string ); } } return strs; } } };
23.025
59
0.457112
[ "vector" ]
4a873e6f3ff375972ce285436dca94cad07446a8
45,529
cpp
C++
src/KineticDispersion/relativisticspecies.cpp
SamuelIrvine/Kinetic-Dispersion-Solver
6056ece40e9c241d8c2df3ce8a089d3f10fb99b1
[ "MIT" ]
3
2021-02-03T17:07:43.000Z
2021-12-29T14:56:16.000Z
src/KineticDispersion/relativisticspecies.cpp
SamuelIrvine/Kinetic-Dispersion-Solver
6056ece40e9c241d8c2df3ce8a089d3f10fb99b1
[ "MIT" ]
1
2020-01-03T03:44:58.000Z
2020-01-09T09:41:23.000Z
src/KineticDispersion/relativisticspecies.cpp
SamuelIrvine/Kinetic-Dispersion-Solver
6056ece40e9c241d8c2df3ce8a089d3f10fb99b1
[ "MIT" ]
null
null
null
// // Created by h on 20/07/18. // #include "relativisticspecies.h" #include <boost/math/special_functions/bessel.hpp> #include <boost/math/special_functions/bessel_prime.hpp> static array<double, 2> intersect(const array<double, 2> &P1, const array<double, 2> &P2, const double x){ double m = (P1[1] - P2[1])/(P1[0] - P2[0]); double c = P1[1] - m*P1[0]; return array<double, 2>{x, m*x + c}; }; void setupTriangle(Triangle &t, const double R0, const double R1) { t.R0 = R0; t.R1 = R1; t.y0 = t.QA[1]; t.x0 = t.QA[0]; t.x1 = t.QB[0] - t.x0; double mAB = (t.QA[1] - t.QB[1]) / (t.QA[0] - t.QB[0]); double mAC = (t.QA[1] - t.QC[1]) / (t.QA[0] - t.QC[0]); t.m0 = (mAB > mAC) ? mAC : mAB; t.m1 = (mAB > mAC) ? mAB : mAC; t.active = true; } void zeroTriangle(Triangle &t){ t.active = false; } void computeTriangleIntegral(Triangle& t, const size_t ni, const size_t ai, const double da) { if (!t.active){ for (size_t l=0;l<5;l++) { t.p0[l] = 0.0; t.p1[l] = 0.0; t.p2[l] = 0.0; t.p3[l] = 0.0; t.p4[l] = 0.0; t.p5[l] = 0.0; t.p6[l] = 0.0; t.p7[l] = 0.0; t.p8[l] = 0.0; } return; } double x0 = t.x0; double x1 = t.x1; double y0 = t.y0; double R0 = t.R0; double R1 = t.R1; double m0 = t.m0; double m1 = t.m1; double mx = t.mx; double x0_2 = x0 * x0; double x0_3 = x0 * x0_2; double x0_4 = x0 * x0_3; double x1_2 = x1 * x1; double x1_3 = x1 * x1_2; double x1_4 = x1 * x1_3; double x1_5 = x1 * x1_4; double x1_6 = x1 * x1_5; double x1_7 = x1 * x1_6; double x1_8 = x1 * x1_7; double x1_9 = x1 * x1_8; double x1_10 = x1 * x1_9; double y0_2 = y0 * y0; double y0_3 = y0 * y0_2; double y0_4 = y0 * y0_3; double m0_2 = m0*m0; double m0_3 = m0_2*m0; double m0_4 = m0_3*m0; double m0_5 = m0_4*m0; double m1_2 = m1*m1; double m1_3 = m1_2*m1; double m1_4 = m1_3*m1; double m1_5 = m1_4*m1; double mx_2 = mx*mx; double mx_3 = mx*mx_2; double mx_4 = mx*mx_3; double da_2 = da * da; double da_3 = da*da_2; double da_4 = da*da_3; double R0_2 = R0*R0; double R0_3 = R0_2*R0; double R0_4 = R0_3*R0; double R1_2 = R1*R1; double R1_3 = R1_2*R1; double R1_4 = R1_3*R1; double O1[5], O2[5], O3[5], O4[5], O5[5]; O1[0] = -(x1_2*0.5); O1[1] = (3 * da * x1_2 + 3 * mx * x0 * x1_2 - 2 * mx * x1_3)*(1./6.); O1[2] = (-6 * da_2 * x1_2 - 12 * da * mx * x0 * x1_2 - 6 * mx_2 * x0_2 * x1_2 + 8 * da * mx * x1_3 + 8 * mx_2 * x0 * x1_3 - 3 * mx_2 * x1_4)*(1./12.); O1[3] = (1./20.) * (10 * da_3 * x1_2 + 30 * da_2 * mx * x0 * x1_2 + 30 * da * mx_2 * x0_2 * x1_2 + 10 * mx_3 * x0_3 * x1_2 - 20 * da_2 * mx * x1_3 - 40 * da * mx_2 * x0 * x1_3 - 20 * mx_3 * x0_2 * x1_3 + 15 * da * mx_2 * x1_4 + 15 * mx_3 * x0 * x1_4 - 4 * mx_3 * x1_5); O1[4] = -(1./30.) * x1_2 * (15 * da_4 + 20 * da_3 * mx * (3 * x0 - 2 * x1) + 15 * da_2 * mx_2 * (6 * x0_2 - 8 * x0 * x1 + 3 * x1_2) + 6 * da * mx_3 * (10 * x0_3 - 20 * x0_2 * x1 + 15 * x0 * x1_2 - 4 * x1_3) + mx_4 * (15 * x0_4 - 40 * x0_3 * x1 + 45 * x0_2 * x1_2 - 24 * x0 * x1_3 + 5 * x1_4)); O2[0] = -(x1_3*(1./3.)); O2[1] = (4 * da * x1_3 + 4 * mx * x0 * x1_3 - 3 * mx * x1_4)*(1./12.); O2[2] = (-10 * da_2 * x1_3 - 20 * da * mx * x0 * x1_3 - 10 * mx_2 * x0_2 * x1_3 + 15 * da * mx * x1_4 + 15 * mx_2 * x0 * x1_4 - 6 * mx_2 * x1_5)*(1./30.); O2[3] = (1./60.) * (20 * da_3 * x1_3 + 60 * da_2 * mx * x0 * x1_3 + 60 * da * mx_2 * x0_2 * x1_3 + 20 * mx_3 * x0_3 * x1_3 - 45 * da_2 * mx * x1_4 - 90 * da * mx_2 * x0 * x1_4 - 45 * mx_3 * x0_2 * x1_4 + 36 * da * mx_2 * x1_5 + 36 * mx_3 * x0 * x1_5 - 10 * mx_3 * x1_6); O2[4] = (1./105.) * (-35 * da_4 * x1_3 - 140 * da_3 * mx * x0 * x1_3 - 210 * da_2 * mx_2 * x0_2 * x1_3 - 140 * da * mx_3 * x0_3 * x1_3 - 35 * mx_4 * x0_4 * x1_3 + 105 * da_3 * mx * x1_4 + 315 * da_2 * mx_2 * x0 * x1_4 + 315 * da * mx_3 * x0_2 * x1_4 + 105 * mx_4 * x0_3 * x1_4 - 126 * da_2 * mx_2 * x1_5 - 252 * da * mx_3 * x0 * x1_5 - 126 * mx_4 * x0_2 * x1_5 + 70 * da * mx_3 * x1_6 + 70 * mx_4 * x0 * x1_6 - 15 * mx_4 * x1_7); O3[0] = -(x1_4*(1./4.)); O3[1] = (5 * da * x1_4 + 5 * mx * x0 * x1_4 - 4 * mx * x1_5)*(1./20.); O3[2] = (-15 * da_2 * x1_4 - 30 * da * mx * x0 * x1_4 - 15 * mx_2 * x0_2 * x1_4 + 24 * da * mx * x1_5 + 24 * mx_2 * x0 * x1_5 - 10 * mx_2 * x1_6)*(1./60.); O3[3] = (1./140.) * (35 * da_3 * x1_4 + 105 * da_2 * mx * x0 * x1_4 + 105 * da * mx_2 * x0_2 * x1_4 + 35 * mx_3 * x0_3 * x1_4 - 84 * da_2 * mx * x1_5 - 168 * da * mx_2 * x0 * x1_5 - 84 * mx_3 * x0_2 * x1_5 + 70 * da * mx_2 * x1_6 + 70 * mx_3 * x0 * x1_6 - 20 * mx_3 * x1_7); O3[4] = (1./280.) * (-70 * da_4 * x1_4 - 280 * da_3 * mx * x0 * x1_4 - 420 * da_2 * mx_2 * x0_2 * x1_4 - 280 * da * mx_3 * x0_3 * x1_4 - 70 * mx_4 * x0_4 * x1_4 + 224 * da_3 * mx * x1_5 + 672 * da_2 * mx_2 * x0 * x1_5 + 672 * da * mx_3 * x0_2 * x1_5 + 224 * mx_4 * x0_3 * x1_5 - 280 * da_2 * mx_2 * x1_6 - 560 * da * mx_3 * x0 * x1_6 - 280 * mx_4 * x0_2 * x1_6 + 160 * da * mx_3 * x1_7 + 160 * mx_4 * x0 * x1_7 - 35 * mx_4 * x1_8); O4[0] = -(x1_5*(1./5.)); O4[1] = (6 * da * x1_5 + 6 * mx * x0 * x1_5 - 5 * mx * x1_6)*(1./30.); O4[2] = (-21 * da_2 * x1_5 - 42 * da * mx * x0 * x1_5 - 21 * mx_2 * x0_2 * x1_5 + 35 * da * mx * x1_6 + 35 * mx_2 * x0 * x1_6 - 15 * mx_2 * x1_7)*(1./105.); O4[3] = (1./280.) * (56 * da_3 * x1_5 + 168 * da_2 * mx * x0 * x1_5 + 168 * da * mx_2 * x0_2 * x1_5 + 56 * mx_3 * x0_3 * x1_5 - 140 * da_2 * mx * x1_6 - 280 * da * mx_2 * x0 * x1_6 - 140 * mx_3 * x0_2 * x1_6 + 120 * da * mx_2 * x1_7 + 120 * mx_3 * x0 * x1_7 - 35 * mx_3 * x1_8); O4[4] = (1./630.) * (-126 * da_4 * x1_5 - 504 * da_3 * mx * x0 * x1_5 - 756 * da_2 * mx_2 * x0_2 * x1_5 - 504 * da * mx_3 * x0_3 * x1_5 - 126 * mx_4 * x0_4 * x1_5 + 420 * da_3 * mx * x1_6 + 1260 * da_2 * mx_2 * x0 * x1_6 + 1260 * da * mx_3 * x0_2 * x1_6 + 420 * mx_4 * x0_3 * x1_6 - 540 * da_2 * mx_2 * x1_7 - 1080 * da * mx_3 * x0 * x1_7 - 540 * mx_4 * x0_2 * x1_7 + 315 * da * mx_3 * x1_8 + 315 * mx_4 * x0 * x1_8 - 70 * mx_4 * x1_9); O5[0] = -(x1_6*(1./6.)); O5[1] = (7 * da * x1_6 + 7 * mx * x0 * x1_6 - 6 * mx * x1_7)*(1./42.); O5[2] = (-28 * da_2 * x1_6 - 56 * da * mx * x0 * x1_6 - 28 * mx_2 * x0_2 * x1_6 + 48 * da * mx * x1_7 + 48 * mx_2 * x0 * x1_7 - 21 * mx_2 * x1_8)*(1./168.); O5[3] = (1./504.) * (84 * da_3 * x1_6 + 252 * da_2 * mx * x0 * x1_6 + 252 * da * mx_2 * x0_2 * x1_6 + 84 * mx_3 * x0_3 * x1_6 - 216 * da_2 * mx * x1_7 - 432 * da * mx_2 * x0 * x1_7 - 216 * mx_3 * x0_2 * x1_7 + 189 * da * mx_2 * x1_8 + 189 * mx_3 * x0 * x1_8 - 56 * mx_3 * x1_9); O5[4] = (1./1260.) * (-210 * da_4 * x1_6 - 840 * da_3 * mx * x0 * x1_6 - 1260 * da_2 * mx_2 * x0_2 * x1_6 - 840 * da * mx_3 * x0_3 * x1_6 - 210 * mx_4 * x0_4 * x1_6 + 720 * da_3 * mx * x1_7 + 2160 * da_2 * mx_2 * x0 * x1_7 + 2160 * da * mx_3 * x0_2 * x1_7 + 720 * mx_4 * x0_3 * x1_7 - 945 * da_2 * mx_2 * x1_8 - 1890 * da * mx_3 * x0 * x1_8 - 945 * mx_4 * x0_2 * x1_8 + 560 * da * mx_3 * x1_9 + 560 * mx_4 * x0 * x1_9 - 126 * mx_4 * x1_10); for (size_t l=0;l<5;l++) { double Ix4y0 = (m0 - m1) * O5[l]; double Ix3y1 = 0.5 * (m0_2 - m1_2) * O5[l]; double Ix2y2 = (1. / 3.) * (m0_3 - m1_3) * O5[l]; double Ix1y3 = 0.25 * (m0_4 - m1_4) * O5[l]; double Ix0y4 = 0.2 * (m0_5 - m1_5) * O5[l]; double Ix3y0 = (-m0 + m1) * O4[l]; double Ix2y1 = -0.5 * (m0_2 - m1_2) * O4[l]; double Ix1y2 = (1.0 / 3.0) * (-m0_3 + m1_3) * O4[l]; double Ix0y3 = 0.25 * (-m0_4 + m1_4) * O4[l]; double Ix2y0 = (m0 - m1) * O3[l]; double Ix1y1 = 0.5 * (m0_2 - m1_2) * O3[l]; double Ix0y2 = (1.0 / 3.0) * (m0_3 - m1_3) * O3[l]; double Ix1y0 = (-m0 + m1) * O2[l]; double Ix0y1 = 0.5 * (-m0_2 + m1_2) * O2[l]; double Ix0y0 = (m0 - m1) * O1[l]; t.p0[l] = Ix0y0; t.p1[l] = (R0*Ix1y0 - R1*Ix0y1 + (R0*x0 - R1*y0)*Ix0y0); t.p2[l] = (R0_2*Ix2y0 - 2*R0*R1*Ix1y1 + (2.*R0_2*x0 - 2.*R0*R1*y0)*Ix1y0 + R1_2*Ix0y2 + (-2 * R0 * R1 * x0 + 2.*R1_2 * y0)*Ix0y1 + (R0_2*x0_2 - 2.*R0*R1*x0*y0 + R1_2*y0_2)*Ix0y0); t.p3[l] = (R1*Ix1y0 + R0*Ix0y1 + (R1*x0 + R0*y0)*Ix0y0); t.p4[l] = (R0*R1*Ix2y0 + (R0_2 - R1_2)*Ix1y1 + (2.*R0*R1*x0 + R0_2*y0 - R1_2*y0)*Ix1y0 - R0*R1*Ix0y2 + (R0_2*x0 - R1_2*x0 - 2.*R0*R1*y0)*Ix0y1 + (R0*R1*x0_2 + R0_2*x0*y0 - R1_2*x0*y0 - R0*R1*y0_2)*Ix0y0); t.p5[l] = (R0_2*R1*Ix3y0 + (R0_3 - 2*R0*R1_2)*Ix2y1 + (3 * R0_2 * R1 * x0 + R0_3 * y0 - 2 * R0 * R1_2 * y0)*Ix2y0 + (-2 * R0_2 * R1 + R1_3)*Ix1y2 + (2 * R0_3 * x0 - 4 * R0 * R1_2 * x0 - 4 * R0_2 * R1 * y0 + 2 * R1_3 * y0)*Ix1y1 + (3 * R0_2 * R1 * x0_2 + 2 * R0_3 * x0 * y0 - 4 * R0 * R1_2 * x0 * y0 - 2 * R0_2 * R1 * y0_2 + R1_3 * y0_2) * Ix1y0 + (R0 * R1_2) * Ix0y3 + (-2 * R0_2 * R1 * x0 + R1_3 * x0 + 3 * R0 * R1_2 * y0)*Ix0y2 + (R0_3 * x0_2 - 2 * R0 * R1_2 * x0_2 - 4 * R0_2 * R1 * x0 * y0 + 2 * R1_3 * x0 * y0 + 3 * R0 * R1_2 * y0_2) * Ix0y1 + (R0_2 * R1 * x0_3 + R0_3 * x0_2 * y0 - 2 * R0 * R1_2 * x0_2 * y0 - 2 * R0_2 * R1 * x0 * y0_2 + R1_3 * x0 * y0_2 + R0 * R1_2 * y0_3)*Ix0y0); t.p6[l] = (R1_2 * Ix2y0 + (2 * R0 * R1)*Ix1y1 + (2 * R1_2 * x0 + 2 * R0 * R1 * y0) * Ix1y0 + R0_2*Ix0y2 + (2 * R0 * R1 * x0 + 2 * R0_2 * y0)*Ix0y1 + (R1_2 * x0_2 + 2 * R0 * R1 * x0 * y0 + R0_2 * y0_2)*Ix0y0); t.p7[l] = ((R0 * R1_2) * Ix3y0 + (2 * R0_2 * R1 - R1_3)*Ix2y1 + (3 * R0 * R1_2 * x0 + 2 * R0_2 * R1 * y0 - R1_3 * y0)*Ix2y0 + (R0_3 - 2 * R0 * R1_2)*Ix1y2 + (4 * R0_2 * R1 * x0 - 2 * R1_3 * x0 + 2 * R0_3 * y0 - 4 * R0 * R1_2 * y0) * Ix1y1 + (3 * R0 * R1_2 * x0_2 + 4 * R0_2 * R1 * x0 * y0 - 2 * R1_3 * x0 * y0 + R0_3 * y0_2 - 2 * R0 * R1_2 * y0_2) * Ix1y0 + (-R0_2 * R1)*Ix0y3 + (R0_3 * x0 - 2 * R0 * R1_2 * x0 - 3 * R0_2 * R1 * y0)*Ix0y2 + (2 * R0_2 * R1 * x0_2 - R1_3 * x0_2 + 2 * R0_3 * x0 * y0 - 4 * R0 * R1_2 * x0 * y0 - 3 * R0_2 * R1 * y0_2)*Ix0y1 + (R0 * R1_2 * x0_3 + 2 * R0_2 * R1 * x0_2 * y0 - R1_3 * x0_2 * y0 + R0_3 * x0 * y0_2 - 2 * R0 * R1_2 * x0 * y0_2 - R0_2 * R1 * y0_3)*Ix0y0); t.p8[l] = ((R0_2 * R1_2)*Ix4y0 + (2 * R0_3 * R1 - 2 * R0 * R1_3)*Ix3y1 + (4 * R0_2 * R1_2 * x0 + 2 * R0_3 * R1 * y0 - 2 * R0 * R1_3 * y0)*Ix3y0 + (R0_4 - 4 * R0_2 * R1_2 + R1_4)*Ix2y2 + (6 * R0_3 * R1 * x0 - 6 * R0 * R1_3 * x0 + 2 * R0_4 * y0 - 8 * R0_2 * R1_2 * y0 + 2 * R1_4 * y0)*Ix2y1 + (6 * R0_2 * R1_2 * x0_2 + 6 * R0_3 * R1 * x0 * y0 - 6 * R0 * R1_3 * x0 * y0 + R0_4 * y0_2 - 4 * R0_2 * R1_2 * y0_2 + R1_4 * y0_2)*Ix2y0 + (-2 * R0_3 * R1 + 2 * R0 * R1_3)*Ix1y3 + (2 * R0_4 * x0 - 8 * R0_2 * R1_2 * x0 + 2 * R1_4 * x0 - 6 * R0_3 * R1 * y0 + 6 * R0 * R1_3 * y0)*Ix1y2 + (6 * R0_3 * R1 * x0_2 - 6 * R0 * R1_3 * x0_2 + 4 * R0_4 * x0 * y0 - 16 * R0_2 * R1_2 * x0 * y0 + 4 * R1_4 * x0 * y0 - 6 * R0_3 * R1 * y0_2 + 6 * R0 * R1_3 * y0_2)*Ix1y1 + (4 * R0_2 * R1_2 * x0_3 + 6 * R0_3 * R1 * x0_2 * y0 - 6 * R0 * R1_3 * x0_2 * y0 + 2 * R0_4 * x0 * y0_2 - 8 * R0_2 * R1_2 * x0 * y0_2 + 2 * R1_4 * x0 * y0_2 - 2 * R0_3 * R1 * y0_3 + 2 * R0 * R1_3 * y0_3)*Ix1y0 + (R0_2 * R1_2)*Ix0y4 + (-2 * R0_3 * R1 * x0 + 2 * R0 * R1_3 * x0 + 4 * R0_2 * R1_2 * y0)*Ix0y3 + (R0_4 * x0_2 - 4 * R0_2 * R1_2 * x0_2 + R1_4 * x0_2 - 6 * R0_3 * R1 * x0 * y0 + 6 * R0 * R1_3 * x0 * y0 + 6 * R0_2 * R1_2 * y0_2)*Ix0y2 + (2 * R0_3 * R1 * x0_3 - 2 * R0 * R1_3 * x0_3 + 2 * R0_4 * x0_2 * y0 - 8 * R0_2 * R1_2 * x0_2 * y0 + 2 * R1_4 * x0_2 * y0 - 6 * R0_3 * R1 * x0 * y0_2 + 6 * R0 * R1_3 * x0 * y0_2 + 4 * R0_2 * R1_2 * y0_3)*Ix0y1 + (R0_2 * R1_2 * x0_4 + 2 * R0_3 * R1 * x0_3 * y0 - 2 * R0 * R1_3 * x0_3 * y0 + R0_4 * x0_2 * y0_2 - 4 * R0_2 * R1_2 * x0_2 * y0_2 + R1_4 * x0_2 * y0_2 - 2 * R0_3 * R1 * x0 * y0_3 + 2 * R0 * R1_3 * x0 * y0_3 + R0_2 * R1_2 * y0_4)*Ix0y0); } } Element::Element(){}; Element::Element(size_t n_s, size_t n_a){ sum1 = arr2d(n_s, arr1d(n_a, 0.0)); sum2 = arr2d(n_s, arr1d(n_a, 0.0)); sum3 = arr2d(n_s, arr1d(n_a, 0.0)); sum4 = arr2d(n_s, arr1d(n_a, 0.0)); sum5 = arr2d(n_s, arr1d(n_a, 0.0)); } TaylorSum::TaylorSum() { } TaylorSum::TaylorSum(size_t n_a, vector<int> &ns) { size_t n_s = ns.size(); a0 = arr2d(n_s, arr1d(n_a, 0.0)); sX00a = Element(n_s, n_a); sX01a = Element(n_s, n_a); sX02a = Element(n_s, n_a); sX11a = Element(n_s, n_a); sX12a = Element(n_s, n_a); sX22a = Element(n_s, n_a); sX00b = Element(n_s, n_a); sX01b = Element(n_s, n_a); sX02b = Element(n_s, n_a); sX11b = Element(n_s, n_a); sX12b = Element(n_s, n_a); sX22b = Element(n_s, n_a); mapping = vector<vector<vector<pair<size_t, size_t>>>>(n_s); for (size_t k=0;k<ns.size();k++){ mapping[k] = vector<vector<pair<size_t, size_t>>>(n_a); } } inline void TaylorSum::setA(const size_t ni, const double a_min, const double da){ for (size_t ai=0;ai<a0[ni].size();ai++){ a0[ni][ai] = a_min + ai*da; } } inline void TaylorSum::pushDenominator(const size_t ni, const size_t i, const size_t j, const size_t ai, const double z0, const double z1, const double z2, const double z3){ this->ni = ni; this->i = i; this->j = j; this->ai = ai; setupHalfTriangles(z1-z0, z2-z0, false); setupHalfTriangles(z3-z2, z3-z1, true); double a1 = z0; double a2 = z1 + z2 - z3; double da1 = a1 - a0[ni][ai]; double da2 = a2 - a0[ni][ai]; computeTriangleIntegral(triA, ni, ai, da1); computeTriangleIntegral(triB, ni, ai, da1); computeTriangleIntegral(triC, ni, ai, da2); computeTriangleIntegral(triD, ni, ai, da2); mapping[ni][ai].push_back(pair<size_t, size_t>(i, j)); } void TaylorSum::setupHalfTriangles(const double mx, const double my, const bool upper){ array<double, 2> Q0, Q1, Q2, Q4, Q5, Q6, Q7; double theta = atan2(my, mx); double R0 = cos(theta); double R1 = sin(theta); //a = (R0 * mx + R1 * my) / a0; double mq = (R0 * mx + R1 * my); Triangle &tri1 = upper?triD:triB; Triangle &tri2 = upper?triC:triA; tri1.mx = mq; tri2.mx = mq; if (upper){ //Triangles always clockwise. Q0[0] = 1.0*R0 + 1.0*R1; Q0[1] = 1.0*-R1 + 1.0*R0; Q1[0] = 1.0*R0 + 0.0*R1; Q1[1] = 1.0*-R1 + 0.0*R0; Q2[0] = 0.0*R0 + 1.0*R1; Q2[1] = 0.0*-R1 + 1.0*R0; }else{ Q0[0] = 0.0*R0 + 0.0*R1; Q0[1] = 0.0*-R1 + 0.0*R0; Q1[0] = 1.0*R0 + 0.0*R1; Q1[1] = 1.0*-R1 + 0.0*R0; Q2[0] = 0.0*R0 + 1.0*R1; Q2[1] = 0.0*-R1 + 1.0*R0; } if (fabs(Q0[0] - Q1[0])<0.0000001){ tri1.QA = Q2; tri1.QB = Q0; tri1.QC = Q1; setupTriangle(tri1, R0, R1); zeroTriangle(tri2); return; } if (fabs(Q0[0] - Q2[0])<0.0000001){ tri1.QA = Q1; tri1.QB = Q0; tri1.QC = Q2; setupTriangle(tri1, R0, R1); zeroTriangle(tri2); return; } if (fabs(Q1[0] - Q2[0])<0.0000001){ tri1.QA = Q0; tri1.QB = Q1; tri1.QC = Q2; setupTriangle(tri1, R0, R1); zeroTriangle(tri2); return; } if ((Q1[0] < Q0[0] && Q0[0] < Q2[0]) || (Q2[0] < Q0[0] && Q0[0] < Q1[0])){ Q4 = Q2; Q5 = Q0; Q6 = intersect(Q1, Q2, Q0[0]); Q7 = Q1; } else if ((Q0[0] < Q1[0] && Q1[0] < Q2[0]) || (Q2[0] < Q1[0] && Q1[0] < Q0[0])) { Q4 = Q2; Q5 = Q1; Q6 = intersect(Q0, Q2, Q1[0]); Q7 = Q0; } else{ Q4 = Q0; Q5 = Q2; Q6 = intersect(Q0, Q1, Q2[0]); Q7 = Q1; } tri1.QA = Q4; tri1.QB = Q5; tri1.QC = Q6; tri2.QA = Q7; tri2.QB = Q5; tri2.QC = Q6; setupTriangle(tri1, R0, R1); setupTriangle(tri2, R0, R1); } void TaylorSum::accumulate(Element &X, const arr2d &p, const arr1d &q, const double r){ double z0 = p[i*2][j*2]*q[i*2]*r; double z1 = p[i*2][j*2+1]*q[i*2]*r; double z2 = p[i*2][j*2+2]*q[i*2]*r; double z3 = p[i*2+1][j*2]*q[i*2+1]*r; double z4 = p[i*2+1][j*2+1]*q[i*2+1]*r; double z5 = p[i*2+1][j*2+2]*q[i*2+1]*r; double z6 = p[i*2+2][j*2]*q[i*2+2]*r; double z7 = p[i*2+2][j*2+1]*q[i*2+2]*r; double z8 = p[i*2+2][j*2+2]*q[i*2+2]*r; double c0 = z0; double c1 = -3*z0 + 4*z1 - z2; double c2 = 2*(z0 - 2*z1 + z2); double c3 = -3*z0 + 4*z3 - z6; double c4 = 9*z0 - 12*z1 + 3*z2 - 12*z3 + 16*z4 - 4*z5 + 3*z6 -4*z7 + z8; double c5 = -2*(3*z0 - 6*z1 + 3*z2 - 4*z3 + 8*z4 - 4*z5 + z6 - 2*z7 + z8); double c6 = 2*(z0 - 2*z3 + z6); double c7 = -2*(3*z0 - 4*z1 +z2 - 6*z3 + 8*z4 -2*z5 +3*z6 -4*z7 + z8); double c8 = 4*(z0 -2*z1 + z2 - 2*z3 + 4*z4 -2*z5 + z6 - 2*z7 + z8); for (size_t l=0;l<5;l++){//TODO: Fix this sloppy code double *psum; switch(l){ case 0: psum = &X.sum1[ni][ai]; break; case 1: psum = &X.sum2[ni][ai]; break; case 2: psum = &X.sum3[ni][ai]; break; case 3: psum = &X.sum4[ni][ai]; break; case 4: psum = &X.sum5[ni][ai]; break; default: psum = nullptr; } double &sum = *psum; sum+=c0*(triA.p0[l] + triB.p0[l] + triC.p0[l] + triD.p0[l]); sum+=c1*(triA.p1[l] + triB.p1[l] + triC.p1[l] + triD.p1[l]); sum+=c2*(triA.p2[l] + triB.p2[l] + triC.p2[l] + triD.p2[l]); sum+=c3*(triA.p3[l] + triB.p3[l] + triC.p3[l] + triD.p3[l]); sum+=c4*(triA.p4[l] + triB.p4[l] + triC.p4[l] + triD.p4[l]); sum+=c5*(triA.p5[l] + triB.p5[l] + triC.p5[l] + triD.p5[l]); sum+=c6*(triA.p6[l] + triB.p6[l] + triC.p6[l] + triD.p6[l]); sum+=c7*(triA.p7[l] + triB.p7[l] + triC.p7[l] + triD.p7[l]); sum+=c8*(triA.p8[l] + triB.p8[l] + triC.p8[l] + triD.p8[l]); } } inline void TaylorSum::pushW(cdouble w, const size_t ni, const size_t ai){ this->ni = ni; this->ai = ai; c1 = 1.0/(w + a0[ni][ai]); c2 = c1*c1; c3 = c2*c1; c4 = c3*c1; c5 = c4*c1; } inline cdouble TaylorSum::evaluate(Element &X){ return c1*X.sum1[ni][ai] + c2*X.sum2[ni][ai] + c3*X.sum3[ni][ai] + c4*X.sum4[ni][ai] + c5*X.sum5[ni][ai]; } class TriangleIntegrator{ public: cdouble evaluate(const size_t i, const size_t j, const arr2d &P, const arr1d &Q, const double R){ double z0, z1, z2, z3, z4, z5, z6, z7, z8; double c0, c1, c2, c3, c4, c5, c6, c7, c8; z0 = P[i*2][j*2]*Q[i*2]*R; z1 = P[i*2][j*2+1]*Q[i*2]*R; z2 = P[i*2][j*2+2]*Q[i*2]*R; z3 = P[i*2+1][j*2]*Q[i*2+1]*R; z4 = P[i*2+1][j*2+1]*Q[i*2+1]*R; z5 = P[i*2+1][j*2+2]*Q[i*2+1]*R; z6 = P[i*2+2][j*2]*Q[i*2+2]*R; z7 = P[i*2+2][j*2+1]*Q[i*2+2]*R; z8 = P[i*2+2][j*2+2]*Q[i*2+2]*R; c0 = z0; c1 = -3*z0 + 4*z1 - z2; c2 = 2*(z0 - 2*z1 + z2); c3 = -3*z0 + 4*z3 - z6; c4 = 9*z0 - 12*z1 + 3*z2 - 12*z3 + 16*z4 - 4*z5 + 3*z6 -4*z7 + z8; c5 = -2*(3*z0 - 6*z1 + 3*z2 - 4*z3 + 8*z4 - 4*z5 + z6 - 2*z7 + z8); c6 = 2*(z0 - 2*z3 + z6); c7 = -2*(3*z0 - 4*z1 +z2 - 6*z3 + 8*z4 -2*z5 +3*z6 -4*z7 + z8); c8 = 4*(z0 -2*z1 + z2 - 2*z3 + 4*z4 -2*z5 + z6 - 2*z7 + z8); return evaluate(c0, c1, c2, c3, c4, c5, c6, c7, c8, triA) + evaluate(c0, c1, c2, c3, c4, c5, c6, c7, c8, triB) + evaluate(c0, c1, c2, c3, c4, c5, c6, c7, c8, triC) + evaluate(c0, c1, c2, c3, c4, c5, c6, c7, c8, triD); } void pushTriangles(const double wi, const double z0, const double z1, const double z2, const double z3){ cdouble a0, a3; double a1, a2, a4, a5; a0 = z0 + I*wi; a1 = z1 - z0; a2 = z2 - z0; a4 = z3 - z2; a5 = z3 - z1; a3 = z3 - a4 - a5 + I*wi; setupHalfTriangles(a0, a1, a2, false); setupHalfTriangles(a3, a4, a5, true); } private: struct Triangle{ cdouble p0, p1, p2, p3, p4, p5, p6, p7, p8; array<double, 2> QA, QB, QC; }; Triangle triA, triB, triC, triD; cdouble evaluate(const double c0, const double c1, const double c2, const double c3, const double c4, const double c5, const double c6, const double c7, const double c8, const Triangle &t){ return c0*t.p0 + c1*t.p1 + c2*t.p2 + c3*t.p3 + c4*t.p4 + c5*t.p5 + c6*t.p6 + c7*t.p7 + c8*t.p8; } static array<double, 2> intersect(const array<double, 2> &P1, const array<double, 2> &P2, const double x){ double m = (P1[1] - P2[1])/(P1[0] - P2[0]); double c = P1[1] - m*P1[0]; return array<double, 2>{x, m*x + c}; }; void setupHalfTriangles(const cdouble a0, const double b1, const double c1, const bool upper, bool debug = false){ array<double, 2> Q0, Q1, Q2, Q4, Q5, Q6, Q7; cdouble a; double theta = atan2(c1, b1); double R0 = cos(theta); double R1 = sin(theta); a = (R0 * b1 + R1 * c1) / a0; Triangle &tri1 = upper?triD:triB; Triangle &tri2 = upper?triC:triA; if (upper){ //Triangles always clockwise. Q0[0] = 1.0*R0 + 1.0*R1; Q0[1] = 1.0*-R1 + 1.0*R0; Q1[0] = 1.0*R0 + 0.0*R1; Q1[1] = 1.0*-R1 + 0.0*R0; Q2[0] = 0.0*R0 + 1.0*R1; Q2[1] = 0.0*-R1 + 1.0*R0; }else{ Q0[0] = 0.0*R0 + 0.0*R1; Q0[1] = 0.0*-R1 + 0.0*R0; Q1[0] = 1.0*R0 + 0.0*R1; Q1[1] = 1.0*-R1 + 0.0*R0; Q2[0] = 0.0*R0 + 1.0*R1; Q2[1] = 0.0*-R1 + 1.0*R0; } if (fabs(Q0[0] - Q1[0])<0.00001){ tri1.QA = Q2; tri1.QB = Q0; tri1.QC = Q1; setupTriangle(tri1, R0, R1, a, a0); zeroTriangle(tri2); return; } if (fabs(Q0[0] - Q2[0])<0.00001){ tri1.QA = Q1; tri1.QB = Q0; tri1.QC = Q2; setupTriangle(tri1, R0, R1, a, a0); zeroTriangle(tri2); return; } if (fabs(Q1[0] - Q2[0])<0.00001){ tri1.QA = Q0; tri1.QB = Q1; tri1.QC = Q2; setupTriangle(tri1, R0, R1, a, a0); zeroTriangle(tri2); return; } if ((Q1[0] < Q0[0] && Q0[0] < Q2[0]) || (Q2[0] < Q0[0] && Q0[0] < Q1[0])){ Q4 = Q2; Q5 = Q0; Q6 = intersect(Q1, Q2, Q0[0]); Q7 = Q1; } else if ((Q0[0] < Q1[0] && Q1[0] < Q2[0]) || (Q2[0] < Q1[0] && Q1[0] < Q0[0])) { Q4 = Q2; Q5 = Q1; Q6 = intersect(Q0, Q2, Q1[0]); Q7 = Q0; } else{ Q4 = Q0; Q5 = Q2; Q6 = intersect(Q0, Q1, Q2[0]); Q7 = Q1; } tri1.QA = Q4; tri1.QB = Q5; tri1.QC = Q6; tri2.QA = Q7; tri2.QB = Q5; tri2.QC = Q6; setupTriangle(tri1, R0, R1, a, a0); setupTriangle(tri2, R0, R1, a, a0); } void zeroTriangle(Triangle &t){ t.p0 = t.p1 = t.p2 = t.p3 = t.p4 = t.p5 = t.p6 = t.p7 = t.p8 = 0.0; } void setupTriangle(Triangle &t, const double R0, const double R1, const cdouble a1, const cdouble a0){ double y0 = t.QA[1]; double x0 = t.QA[0]; double x1 = t.QB[0] - x0; double mAB = (t.QA[1] - t.QB[1]) / (t.QA[0] - t.QB[0]); double mAC = (t.QA[1] - t.QC[1]) / (t.QA[0] - t.QC[0]); double m0 = (mAB>mAC)?mAC:mAB; double m1 = (mAB>mAC)?mAB:mAC; computeTriangleIntegral(m0, m1, x0, y0, x1, R0, R1, a1, t); cdouble a0i = (1.0)/a0; t.p0*=a0i; t.p1*=a0i; t.p2*=a0i; t.p3*=a0i; t.p4*=a0i; t.p5*=a0i; t.p6*=a0i; t.p7*=a0i; t.p8*=a0i; } void computeTriangleIntegral(const double m0, const double m1, const double x0, const double y0, const double x1, const double R0, const double R1, const cdouble a1, Triangle& t) { //cdouble logfac = log(1. + (a1 * x1)/(1. + a1 * x0)); //Integral is of form 1/(1 + a1*x0 + a1*x1) //Divide through by (1 + a1*x0) //Integral now of form 1/(1 + a2*x1) //Each triangle would need to contain R0, R1, m0, m1 cdouble Inorm = 1.0/(1.0 + a1*x0); cdouble a2 = a1*Inorm; cdouble O0, O1, O2, O3, O4, O5; double narr[]{1./1., 1./2., 1./3., 1./4., 1./5., 1./5., 1./7., 1./8., 1./9., 1./10., 1./11., 1./12., 1./13., 1./14., 1./15., 1./16.}; if ((x1*x1*(a2.real()*a2.real() + a2.imag()*a2.imag())) < 0.1){ //Logs are expanded for numerical precision purposes cdouble logfacsum{0.0, 0.0}; cdouble powarr[16]; powarr[0] = -x1*a2; for (size_t i=1;i<16;i++){ powarr[i] = powarr[i-1]*(-x1*a2); } for (size_t i = 16; i > 5; i--) { logfacsum -= powarr[i-1]*narr[i-1]; } O5 = logfacsum; O4 = O5 - powarr[4]*narr[4]; O3 = O4 - powarr[3]*narr[3]; O2 = O3 - powarr[2]*narr[2]; O1 = O2 - powarr[1]*narr[1]; O0 = O1 - powarr[0]*narr[0]; }else{ //(1 + ax) * (1 + ax) + b*b*x*x //1 + 2*a*x + a*a*x*x O0 = 0.5*log1p(x1*(2.*a2.real() + x1*(a2.real()*a2.real() + a2.imag()*a2.imag()))) + I*atan2(x1*a2.imag(), 1.0+x1*a2.real()); cdouble powarr[5]; powarr[0] = -x1*a2; for (size_t i=1;i<5;i++){ powarr[i] = powarr[i-1]*(-x1*a2); } O1 = O0 + powarr[0]*narr[0]; O2 = O1 + powarr[1]*narr[1]; O3 = O2 + powarr[2]*narr[2]; O4 = O3 + powarr[3]*narr[3]; O5 = O4 + powarr[4]*narr[4]; } cdouble oa2 = 1.0/a2; cdouble oa2_2 = Inorm*oa2*oa2; cdouble oa2_3 = oa2_2*oa2; cdouble oa2_4 = oa2_3*oa2; cdouble oa2_5 = oa2_4*oa2; cdouble oa2_6 = oa2_5*oa2; O5 *= oa2_6; O4 *= oa2_5; O3 *= oa2_4; O2 *= oa2_3; O1 *= oa2_2; double x0_2 = x0 * x0; double x0_3 = x0 * x0_2; double x0_4 = x0 * x0_3; double y0_2 = y0 * y0; double y0_3 = y0 * y0_2; double y0_4 = y0 * y0_3; double m0_2 = m0*m0; double m0_3 = m0_2*m0; double m0_4 = m0_3*m0; double m0_5 = m0_4*m0; double m1_2 = m1*m1; double m1_3 = m1_2*m1; double m1_4 = m1_3*m1; double m1_5 = m1_4*m1; double R0_2 = R0*R0; double R0_3 = R0_2*R0; double R0_4 = R0_3*R0; double R1_2 = R1*R1; double R1_3 = R1_2*R1; double R1_4 = R1_3*R1; cdouble Ix4y0 = ((m0 - m1) * O5); cdouble Ix3y1 = (0.5*(m0_2 - m1_2) * O5); cdouble Ix3y0 = ((-m0 + m1) * O4); cdouble Ix2y2 = ((m0_3 - m1_3) * O5)*(1./3.); cdouble Ix2y1 = (-0.5*(m0_2 - m1_2) * O4); cdouble Ix2y0 = ((m0 - m1) * O3); cdouble Ix1y3 = (0.25*(m0_4 - m1_4) * O5); cdouble Ix1y2 = ((1.0/3.0) * (-m0_3 + m1_3) * O4); cdouble Ix1y1 = (0.5*(m0_2 - m1_2) * O3); cdouble Ix1y0 = ((-m0 + m1) * O2); cdouble Ix0y4 = (0.2*(m0_5 - m1_5) * O5); cdouble Ix0y3 = (0.25*(-m0_4 + m1_4) * O4); cdouble Ix0y2 = ((1.0/3.0)*(m0_3 - m1_3) * O3); cdouble Ix0y1 = (0.5*(-m0_2 + m1_2) * O2); cdouble Ix0y0 = ((m0 - m1) * O1); //Work out taylor expansions for Ix0y0, ... for omega //60 variables --> precomputation possible but using too much memory t.p0 = Ix0y0; t.p1 = R0*Ix1y0 - R1*Ix0y1 + (R0*x0 - R1*y0)*Ix0y0; t.p2 = R0*R0*Ix2y0 - 2*R0*R1*Ix1y1 + (2.*R0_2*x0 - 2.*R0*R1*y0)*Ix1y0 + R1_2*Ix0y2 + (-2 * R0 * R1 * x0 + 2.*R1*R1 * y0)*Ix0y1 + (R0_2*x0*x0 - 2.*R0*R1*x0*y0 + R1_2*y0*y0)*Ix0y0; t.p3 = R1*Ix1y0 + R0*Ix0y1 + (R1*x0 + R0*y0)*Ix0y0; t.p4 = R0*R1*Ix2y0 + (R0_2 - R1_2)*Ix1y1 + (2.*R0*R1*x0 + R0_2*y0 - R1_2*y0)*Ix1y0 - R0*R1*Ix0y2 + (R0_2*x0 - R1_2*x0 - 2.*R0*R1*y0)*Ix0y1 + (R0*R1*x0_2 + R0_2*x0*y0 - R1_2*x0*y0 - R0*R1*y0_2)*Ix0y0; t.p5 = R0_2*R1*Ix3y0 + (R0_3 - 2*R0*R1_2)*Ix2y1 + (3 * R0_2 * R1 * x0 + R0_3 * y0 - 2 * R0 * R1_2 * y0)*Ix2y0 + (-2 * R0_2 * R1 + R1_3)*Ix1y2 + (2 * R0_3 * x0 - 4 * R0 * R1_2 * x0 - 4 * R0_2 * R1 * y0 + 2 * R1_3 * y0)*Ix1y1 + (3 * R0_2 * R1 * x0_2 + 2 * R0_3 * x0 * y0 - 4 * R0 * R1_2 * x0 * y0 - 2 * R0_2 * R1 * y0_2 + R1_3 * y0_2) * Ix1y0 + (R0 * R1_2) * Ix0y3 + (-2 * R0_2 * R1 * x0 + R1_3 * x0 + 3 * R0 * R1_2 * y0)*Ix0y2 + (R0_3 * x0_2 - 2 * R0 * R1_2 * x0_2 - 4 * R0_2 * R1 * x0 * y0 + 2 * R1_3 * x0 * y0 + 3 * R0 * R1_2 * y0_2) * Ix0y1 + (R0_2 * R1 * x0_3 + R0_3 * x0_2 * y0 - 2 * R0 * R1_2 * x0_2 * y0 - 2 * R0_2 * R1 * x0 * y0_2 + R1_3 * x0 * y0_2 + R0 * R1_2 * y0_3)*Ix0y0; t.p6 = R1_2 * Ix2y0 + (2 * R0 * R1)*Ix1y1 + (2 * R1_2 * x0 + 2 * R0 * R1 * y0) * Ix1y0 + R0_2*Ix0y2 + (2 * R0 * R1 * x0 + 2 * R0_2 * y0)*Ix0y1 + (R1_2 * x0_2 + 2 * R0 * R1 * x0 * y0 + R0_2 * y0_2)*Ix0y0; t.p7 = (R0 * R1_2) * Ix3y0 + (2 * R0_2 * R1 - R1_3)*Ix2y1 + (3 * R0 * R1_2 * x0 + 2 * R0_2 * R1 * y0 - R1_3 * y0)*Ix2y0 + (R0_3 - 2 * R0 * R1_2)*Ix1y2 + (4 * R0_2 * R1 * x0 - 2 * R1_3 * x0 + 2 * R0_3 * y0 - 4 * R0 * R1_2 * y0) * Ix1y1 + (3 * R0 * R1_2 * x0_2 + 4 * R0_2 * R1 * x0 * y0 - 2 * R1_3 * x0 * y0 + R0_3 * y0_2 - 2 * R0 * R1_2 * y0_2) * Ix1y0 + (-R0_2 * R1)*Ix0y3 + (R0_3 * x0 - 2 * R0 * R1_2 * x0 - 3 * R0_2 * R1 * y0)*Ix0y2 + (2 * R0_2 * R1 * x0_2 - R1_3 * x0_2 + 2 * R0_3 * x0 * y0 - 4 * R0 * R1_2 * x0 * y0 - 3 * R0_2 * R1 * y0_2)*Ix0y1 + (R0 * R1_2 * x0_3 + 2 * R0_2 * R1 * x0_2 * y0 - R1_3 * x0_2 * y0 + R0_3 * x0 * y0_2 - 2 * R0 * R1_2 * x0 * y0_2 - R0_2 * R1 * y0_3)*Ix0y0; t.p8 = (R0_2 * R1_2)*Ix4y0 + (2 * R0_3 * R1 - 2 * R0 * R1_3)*Ix3y1 + (4 * R0_2 * R1_2 * x0 + 2 * R0_3 * R1 * y0 - 2 * R0 * R1_3 * y0)*Ix3y0 + (R0_4 - 4 * R0_2 * R1_2 + R1_4)*Ix2y2 + (6 * R0_3 * R1 * x0 - 6 * R0 * R1_3 * x0 + 2 * R0_4 * y0 - 8 * R0_2 * R1_2 * y0 + 2 * R1_4 * y0)*Ix2y1 + (6 * R0_2 * R1_2 * x0_2 + 6 * R0_3 * R1 * x0 * y0 - 6 * R0 * R1_3 * x0 * y0 + R0_4 * y0_2 - 4 * R0_2 * R1_2 * y0_2 + R1_4 * y0_2)*Ix2y0 + (-2 * R0_3 * R1 + 2 * R0 * R1_3)*Ix1y3 + (2 * R0_4 * x0 - 8 * R0_2 * R1_2 * x0 + 2 * R1_4 * x0 - 6 * R0_3 * R1 * y0 + 6 * R0 * R1_3 * y0)*Ix1y2 + (6 * R0_3 * R1 * x0_2 - 6 * R0 * R1_3 * x0_2 + 4 * R0_4 * x0 * y0 - 16 * R0_2 * R1_2 * x0 * y0 + 4 * R1_4 * x0 * y0 - 6 * R0_3 * R1 * y0_2 + 6 * R0 * R1_3 * y0_2)*Ix1y1 + (4 * R0_2 * R1_2 * x0_3 + 6 * R0_3 * R1 * x0_2 * y0 - 6 * R0 * R1_3 * x0_2 * y0 + 2 * R0_4 * x0 * y0_2 - 8 * R0_2 * R1_2 * x0 * y0_2 + 2 * R1_4 * x0 * y0_2 - 2 * R0_3 * R1 * y0_3 + 2 * R0 * R1_3 * y0_3)*Ix1y0 + (R0_2 * R1_2)*Ix0y4 + (-2 * R0_3 * R1 * x0 + 2 * R0 * R1_3 * x0 + 4 * R0_2 * R1_2 * y0)*Ix0y3 + (R0_4 * x0_2 - 4 * R0_2 * R1_2 * x0_2 + R1_4 * x0_2 - 6 * R0_3 * R1 * x0 * y0 + 6 * R0 * R1_3 * x0 * y0 + 6 * R0_2 * R1_2 * y0_2)*Ix0y2 + (2 * R0_3 * R1 * x0_3 - 2 * R0 * R1_3 * x0_3 + 2 * R0_4 * x0_2 * y0 - 8 * R0_2 * R1_2 * x0_2 * y0 + 2 * R1_4 * x0_2 * y0 - 6 * R0_3 * R1 * x0 * y0_2 + 6 * R0 * R1_3 * x0 * y0_2 + 4 * R0_2 * R1_2 * y0_3)*Ix0y1 + (R0_2 * R1_2 * x0_4 + 2 * R0_3 * R1 * x0_3 * y0 - 2 * R0 * R1_3 * x0_3 * y0 + R0_4 * x0_2 * y0_2 - 4 * R0_2 * R1_2 * x0_2 * y0_2 + R1_4 * x0_2 * y0_2 - 2 * R0_3 * R1 * x0 * y0_3 + 2 * R0 * R1_3 * x0 * y0_3 + R0_2 * R1_2 * y0_4)*Ix0y0; } }; RelativisticSpecies::RelativisticSpecies(const boost::python::object &species, double B) { charge = p::extract<double>(species.attr("charge")); mass = p::extract<double>(species.attr("mass")); density = p::extract<double>(species.attr("density")); wc0 = B * abs(charge) / mass; wp0 = pow(density * charge * charge / (e0 * mass), 0.5); ppara = arrayutils::extract1d(species.attr("ppara")); //TODO: Extract just a scaler value pperp = arrayutils::extract1d(species.attr("pperp")); //TODO: Extract just a scaler value npara = ppara.size(); nperp = pperp.size(); f_p = arrayutils::extract2d(species.attr("f_p"), nperp, npara); dppara = ppara[1] - ppara[0]; dpperp = pperp[1] - pperp[0]; nperp_g = nperp/2 + 1; npara_g = npara/2 + 1; nperp_h = nperp_g*2 + 1; npara_h = npara_g*2 + 1; n_taylor = 1000; ppara_h = arr1d(npara_h, 0.0); pperp_h = arr1d(nperp_h, 0.0); arr2d f_p_h = arr2d(nperp_h, arr1d(npara_h, 0.0)); df_dppara_h = arr2d(nperp_h, arr1d(npara_h, 0.0)); df_dpperp_h = arr2d(nperp_h, arr1d(npara_h, 0.0)); vpara_h = arr2d(nperp_h, arr1d(npara_h, 0.0)); igamma = arr2d(nperp_h, arr1d(npara_h, 0.0)); U0 = arr2d(nperp_h, arr1d(npara_h, 0.0)); U1 = arr2d(nperp_h, arr1d(npara_h, 0.0)); U2 = arr2d(nperp_h, arr1d(npara_h, 0.0)); U3 = arr2d(nperp_h, arr1d(npara_h, 0.0)); W0 = arr2d(nperp_h, arr1d(npara_h, 0.0)); W1 = arr2d(nperp_h, arr1d(npara_h, 0.0)); z = arr1d(nperp_h, 0.0); for (size_t i=0;i<nperp_h;i++){ pperp_h[i] = (i + 0.5)*dpperp + pperp[0]; } for (size_t j=0;j<npara_h;j++){ ppara_h[j] = (j - 0.5)*dppara + ppara[0]; } for (size_t i=0;i < nperp - 1; i++){ for (size_t j=0;j < npara - 1; j++){ double dppara_h = ppara[j+1] - ppara[j]; double dpperp_h = pperp[i+1] - pperp[i]; df_dpperp_h[i][j+1] = (f_p[i+1][j] - f_p[i][j] + f_p[i+1][j+1] - f_p[i][j+1])*0.5/dpperp_h; df_dppara_h[i][j+1] = (f_p[i][j+1] - f_p[i][j] + f_p[i+1][j+1] - f_p[i+1][j])*0.5/dppara_h; f_p_h[i][j+1] = 0.25*(f_p[i+1][j] + f_p[i][j] + f_p[i+1][j+1] + f_p[i][j+1]); //TODO: Make sure simpson is setup correctly ---> convergence order should be > O(1) } } double sum = 0.0; for (size_t i=1;i < nperp_h -1 ; i++) { size_t cs1 = (1+i%2); for (size_t j = 1; j < npara_h -1; j++) { size_t cs = 4*cs1*(1+j%2); sum += cs*(f_p_h[i][j]*pperp_h[i]); } } sum = 2.0*M_PI*dppara*dpperp*sum/9.0; for (size_t i=0;i < nperp_h ; i++){ for (size_t j=0;j<npara_h;j++){ igamma[i][j] = 1.0/sqrt(1.0 + pow(pperp_h[i]/(cl*mass), 2) + pow(ppara_h[j]/(cl*mass), 2)); vpara_h[i][j] = ppara_h[j] * igamma[i][j] * (1.0/mass); df_dpperp_h[i][j]/=sum; df_dppara_h[i][j]/=sum; U0[i][j] = df_dpperp_h[i][j] * igamma[i][j]; U1[i][j] = ppara_h[j]*df_dpperp_h[i][j] * igamma[i][j]; U2[i][j] = (pperp_h[i]*df_dppara_h[i][j] - ppara_h[j]*df_dpperp_h[i][j])*igamma[i][j]*igamma[i][j]*(1.0/mass); U3[i][j] = ppara_h[j]*(pperp_h[i]*df_dppara_h[i][j] - ppara_h[j]*df_dpperp_h[i][j])*igamma[i][j]*igamma[i][j]*(1.0/mass); W0[i][j] = ppara_h[j]*pperp_h[i]*df_dppara_h[i][j]*igamma[i][j]; W1[i][j] = ppara_h[j]*(ppara_h[j]*df_dpperp_h[i][j] - pperp_h[i]*df_dppara_h[i][j])*(igamma[i][j]*igamma[i][j]); } } p::list pyns = p::extract<p::list>(species.attr("ns")); for (int i = 0; i < len(pyns); ++i) { int n{p::extract<int>(pyns[i])}; ns.push_back(n); } jns = arr2d(ns.size(), arr1d(nperp_h, 0.0)); jnds = arr2d(ns.size(), arr1d(nperp_h, 0.0)); kp0 = arr2d(ns.size(), arr1d(nperp_h, 0.0)); kp1 = arr2d(ns.size(), arr1d(nperp_h, 0.0)); kp2 = arr2d(ns.size(), arr1d(nperp_h, 0.0)); kp3 = arr2d(ns.size(), arr1d(nperp_h, 0.0)); kp4 = arr2d(ns.size(), arr1d(nperp_h, 0.0)); kp5 = arr2d(ns.size(), arr1d(nperp_h, 0.0)); } void RelativisticSpecies::push_kperp(const double kperp) { for (size_t i=0;i<nperp_h;i++){ z[i] = kperp*pperp_h[i]/(wc0*mass); } for (size_t k=0;k<ns.size();k++){ int n = ns[k]; for (size_t i=0;i<nperp_h;i++) { jns[k][i] = bm::cyl_bessel_j(n, z[i]); jnds[k][i] = bm::cyl_bessel_j_prime(n, z[i]); kp0[k][i] = n*n*jns[k][i]*jns[k][i]*(wc0*mass*wc0*mass/(kperp*kperp)); kp1[k][i] = n*jns[k][i]*jnds[k][i]*pperp_h[i]*(wc0*mass/(kperp)); kp2[k][i] = n*jns[k][i]*jns[k][i]*(wc0*mass/(kperp)); kp3[k][i] = jnds[k][i]*jnds[k][i]*pperp_h[i]*pperp_h[i]; kp4[k][i] = jns[k][i]*jnds[k][i]*pperp_h[i]; kp5[k][i] = jns[k][i]*jns[k][i]; } } } void RelativisticSpecies::push_kpara(const double kpara){ series = TaylorSum(n_taylor+1, ns); das = arr1d(ns.size(), 0.0); a_mins = arr1d(ns.size(), 0.0); damaxs = arr2d(ns.size(), arr1d(n_taylor+1, 0.0)); for (size_t k=0;k<ns.size();k++) { const int n = ns[k]; double a_min{DBL_MAX}, a_max{DBL_MIN}, da; for (size_t i = 0; i < nperp_g + 1; i++) { for (size_t j = 0; j < npara_g + 1; j++) { double a = -kpara*vpara_h[i*2][j*2] - n*wc0*igamma[i*2][j*2]; if (a>a_max){ a_max = a; } if (a<a_min){ a_min = a; } } } da = (a_max - a_min)/n_taylor; das[k] = da; a_mins[k] = a_min; series.setA(k, a_min, da); for (size_t i = 0; i < nperp_g; i++) { for (size_t j = 0; j < npara_g; j++) { double a, a0, z0, z1, z2, z3, damax; size_t ai; z0 = -kpara*vpara_h[i*2][j*2] - n*wc0*igamma[i*2][j*2]; z1 = -kpara*vpara_h[i*2][j*2+2] - n*wc0*igamma[i*2][j*2+2]; z2 = -kpara*vpara_h[i*2+2][j*2] - n*wc0*igamma[i*2+2][j*2]; z3 = -kpara*vpara_h[i*2+2][j*2+2] - n*wc0*igamma[i*2+2][j*2+2]; a = 0.25*(z0+z1+z2+z3); ai = (size_t)((a - a_min)/da + 0.5); a0 = ai*da + a_min; damax = max(max(fabs(z0 - a0), fabs(z1 - a0)), max(fabs(z2 - a0), fabs(z3 - a0))); damaxs[k][ai] = max(damaxs[k][ai], damax); //a1 = a0 - z0; //b = z1 - z0; //c = z2 - z0; //d = z3 - z0 - b - c; //series.pushDenominator(k, i, j, ai, a1, b, c, d); series.pushDenominator(k, i, j, ai, z0, z1, z2, z3); series.accumulate(series.sX00a, U0, kp0[k], 1.0); series.accumulate(series.sX00b, U2, kp0[k], kpara); series.accumulate(series.sX01a, U0, kp1[k], 1.0); series.accumulate(series.sX01b, U2, kp1[k], kpara); series.accumulate(series.sX02a, U1, kp2[k], 1.0); series.accumulate(series.sX02b, U3, kp2[k], kpara); series.accumulate(series.sX11a, U0, kp3[k], 1.0); series.accumulate(series.sX11b, U2, kp3[k], kpara); series.accumulate(series.sX12a, U1, kp4[k], 1.0); series.accumulate(series.sX12b, U3, kp4[k], kpara); series.accumulate(series.sX22a, W0, kp5[k], 1.0); series.accumulate(series.sX22b, W1, kp5[k], n*wc0); } } } } array<array<cdouble, 3>, 3> RelativisticSpecies::push_omega(const double kpara, const double wr, const double wi) { array<array<cdouble, 3>, 3> X; cdouble X00{0.0, 0.0}, X01{0.0, 0.0}, X02{0.0, 0.0}, X11{0.0, 0.0}, X12{0.0, 0.0}, X22{0.0, 0.0}; const cdouble w = wr + I*wi; const cdouble iw = 1.0/w; for (size_t k=0;k<ns.size();k++){ for (size_t ai=0;ai<n_taylor;ai++){ if (fabs(a_mins[k] + ai*das[k] + wr)<10*damaxs[k][ai]){ const int n = ns[k]; //cout<<series.mapping[k].size()<<endl; for (pair<size_t, size_t> p:series.mapping[k][ai]){ double z0, z1, z2, z3; size_t i{p.first}, j{p.second}; z0 = wr -kpara*vpara_h[i*2][j*2] - n*wc0*igamma[i*2][j*2]; z1 = wr -kpara*vpara_h[i*2][j*2+2] - n*wc0*igamma[i*2][j*2+2]; z2 = wr -kpara*vpara_h[i*2+2][j*2] - n*wc0*igamma[i*2+2][j*2]; z3 = wr -kpara*vpara_h[i*2+2][j*2+2] - n*wc0*igamma[i*2+2][j*2+2]; TriangleIntegrator integrator; integrator.pushTriangles(wi, z0, z1, z2, z3); X00 += integrator.evaluate(i, j, U0, kp0[k], 1.0); X00 += integrator.evaluate(i, j, U2, kp0[k], kpara)*iw; X01 += integrator.evaluate(i, j, U0, kp1[k], 1.0); X01 += integrator.evaluate(i, j, U2, kp1[k], kpara)*iw; X02 += integrator.evaluate(i, j, U1, kp2[k], 1.0); X02 += integrator.evaluate(i, j, U3, kp2[k], kpara)*iw; X11 += integrator.evaluate(i, j, U0, kp3[k], 1.0); X11 += integrator.evaluate(i, j, U2, kp3[k], kpara)*iw; X12 += integrator.evaluate(i, j, U1, kp4[k], 1.0); X12 += integrator.evaluate(i, j, U3, kp4[k], kpara)*iw; X22 += integrator.evaluate(i, j, W0, kp5[k], 1.0); X22 += integrator.evaluate(i, j, W1, kp5[k], n*wc0)*iw; } continue; } series.pushW(w, k, ai); X00+=series.evaluate(series.sX00a); X00+=series.evaluate(series.sX00b)*iw; X01+=series.evaluate(series.sX01a); X01+=series.evaluate(series.sX01b)*iw; X02+=series.evaluate(series.sX02a); X02+=series.evaluate(series.sX02b)*iw; X11+=series.evaluate(series.sX11a); X11+=series.evaluate(series.sX11b)*iw; X12+=series.evaluate(series.sX12a); X12+=series.evaluate(series.sX12b)*iw; X22+=series.evaluate(series.sX22a); X22+=series.evaluate(series.sX22b)*iw; } } X[0][0] = X00*2.0*M_PI*wp0*wp0*iw*dppara*dpperp*4.0; X[0][1] = -I*X01*2.0*M_PI*wp0*wp0*iw*dppara*dpperp*4.0; X[0][2] = X02*2.0*M_PI*wp0*wp0*iw*dppara*dpperp*4.0; X[1][0] = I*X01*2.0*M_PI*wp0*wp0*iw*dppara*dpperp*4.0; X[1][1] = X11*2.0*M_PI*wp0*wp0*iw*dppara*dpperp*4.0; X[1][2] = I*X12*2.0*M_PI*wp0*wp0*iw*dppara*dpperp*4.0; X[2][0] = X02*2.0*M_PI*wp0*wp0*iw*dppara*dpperp*4.0; X[2][1] = -I*X12*2.0*M_PI*wp0*wp0*iw*dppara*dpperp*4.0; X[2][2] = X22*2.0*M_PI*wp0*wp0*iw*dppara*dpperp*4.0; //cout<<1.0 + X[0][0]<<", "<<X[0][1]<<", "<<1.0 + X[1][1]<<", "<<1.0 + X[2][2]<<endl; //cout<<X[0][0]<<", "<<X[0][1]<<", "<<X[1][1]<<", "<<X[2][2]<<endl; return X; }
43.237417
256
0.45202
[ "object", "vector" ]
4a87a5e9dc8cf262bc24dbb6ae814aa4e078b8ea
5,375
cpp
C++
main_old.cpp
mihneasaracin/Distributed-CSP
8e4b0cc9e70cbc2451463458aa07c60d66a78c7c
[ "MIT" ]
null
null
null
main_old.cpp
mihneasaracin/Distributed-CSP
8e4b0cc9e70cbc2451463458aa07c60d66a78c7c
[ "MIT" ]
null
null
null
main_old.cpp
mihneasaracin/Distributed-CSP
8e4b0cc9e70cbc2451463458aa07c60d66a78c7c
[ "MIT" ]
null
null
null
#include <iostream> #include <mpi.h> #include "include/hps-1.0.0/src/hps.h" #include <typeinfo> #include <map> #include <type_traits> #include <utility> #include "include/DistributedRuntime.h" #include <functional> // OMPI_CXX=g++-8 ~/Downloads/clion-2018.2.4/bin/cmake/linux/bin/cmake --build ~/Documents/Dissertation/Distributed-CSP/cmake-build-debug --target main -- -j 4 using namespace std; //typedef function<void()> func; // // //void da(int dd){ // cout << dd << "\n"; // //} // //int da1(int e, char d, int * c){ // return 1; //} // // //int nu(double d){ // return 3; //} // //void v(){ // //} int main(int argc, char* argv[]) { // map<string, func> anym; // auto f = bind(da, placeholders::_1); // f(1); //// anym["da"] = f; // anym.emplace(make_pair("da", v)); // anym["da"](3); // HashRing r; // // // r.addNode(0); // r.addNode(1); // r.addNode(2); // r.addNode(3); // r.addNode(4); // for (int i=0; i<100; ++i){ // r.assignKeyToNode(to_string(i % 6)); // } // r.assignKeyToNode(to_string(1)); // r.assignKeyToNode(to_string(2)); // r.assignKeyToNode(to_string(3)); // r.assignKeyToNode(to_string(4));; DistributedRuntime::DistributedChannelUnbounded<int> channel1(4), channel2(2);// channel3, channel4, channel5, channel6; DistributedRuntime::DistributedChannelBounded<int> ch3; DistributedRuntime::run(); // vector v1({1,1,2,3,3,4,32,65423,342}); // vector v2({1}); // vector v3({1}); //if (MPIUtils::getCurrentProc() == 0) { // ch3.write(1); // //} int val; // channel1.read(&val, false); channel1.close(); // channel1.read(&val); // std::string serialized = hps::to_string(&channel1); // hps::from_string<DistributedRuntime::DistributedChannelUnbounded<int> >(serialized); cout << "CLOSEEE" << channel1.isClosed() << endl; //// //if (MPIUtils::getCurrentProc() == 0) { // // // bool res1 = channel2.write(8989); // cout << MPIUtils::getCurrentProc() << "RESULTWRITE1= " << res1 << endl; // //} //else{ // int val; // std::this_thread::sleep_for(chrono::seconds(1)); // cout << MPIUtils::getCurrentProc() << "BeforeRESULTREAD " << endl; // // bool res2 = channel2.read(&val); // cout << MPIUtils::getCurrentProc() << "RESULTREAD1= " << val << endl; //// channel2.read(&val); // //} // bool res2 = channel2.write(2); // cout << MPIUtils::getCurrentProc()<< "RESULT2= " << res2 << endl; // bool res3 = channel2.write(3, false); // cout << "RESULT3= " << res3 << endl; // } //// // vector<DistributedRuntime::DistributedChannelUnbounded<int>*> chs; // for(int i = 0; i <100 ; ++i){ // chs.push_back(new DistributedRuntime::DistributedChannelUnbounded<int>()); // } //// DistributedRuntime::run(); ////// std::this_thread::sleep_for(chrono::seconds(10)); //// //// DistributedRuntime::DistributedChannelUnbounded<int> channel11(4, 1); //// int val = 1, res; //// ////// if (MPIUtils::getCurrentProc() >= 2){ ////// std::this_thread::sleep_for(chrono::seconds(2)); ////// } ////// channel1.write(1); ////// channel1.read(&res); ////// cout << "Result = " << res << endl; //// //// //////// MPI_Finalize(); // for(int i = 0; i <100 ; ++i){ // delete chs[i]; // } // auto t_start = std::chrono::high_resolution_clock::now(); // this_thread::sleep_for(chrono::seconds(2)); // auto t_end = std::chrono::high_resolution_clock::now(); // // double elapsed_time_ms = std::chrono::duration<double, std::milli>(t_end-t_start).count(); // // cout << "ELAPSED MILI " << elapsed_time_ms << endl; // cout << "ELAPSED SEC " << std::chrono::duration_cast<std::chrono::duration<float>>(t_end-t_start).count() << endl; // DistributedChannelUnBounded<int> channel2; // DistributedChannelUnBounded<int> channel1; // vector<DistributedChannelUnBounded<int> > dd; // HashRing h(1); // for(int i= 0 ; i <= 6 ; ++i){ // h.addNode(i); // } // // // // string d = "2"; // cout << endl; // cout << "DATA "<< h.fnv1(d.data()) << endl; // cout << h.assignKeyToNode(d) << endl; // h.deleteNode(3); // //// cout << "TEST "<< typeid(channel2).name() << endl; // MPI_Finalize(); // cout << GET_VARIABLE_NAME(channel2); // serialization // std::vector<int> data({22, 333, -4444}); //// // std::string serialized = hps::to_string(data); // //// cout << serialized; // // auto parsed = hps::from_char_array<vector<int>>(serialized.data()); // auto parsed1 = hps::from_string<vector<int> >(serialized); // for (int i=0; i < parsed.size(); i++) { // cout << parsed[i] << "\n"; // } } //void example4(){ // std::cout << "Run example4()" << std::endl; // DistributedRuntime::DistributedChannelUnbounded<int> channel1, channel2; // DistributedRuntime::run(); // if (MPIUtils::getCurrentProc() == 0) { // int message1, message2; // select { // case message1 <- channel1: // { // std::cout << "1" << std::endl; // } // case message2 <- channel2: // { // std::cout << "2" << std::endl; // } // } // } else { // channel1.write(11); // channel2.write(22); // // } // //}
25.595238
160
0.556837
[ "vector" ]
4a883690a1cd7c975c5bb8ed653300f413047e82
7,207
hpp
C++
include/HoudiniEngineUnity/HEU_WorkItemTally.hpp
sc2ad/BeatSaber-Quest-Codegen
ba8acaae541cfe1161e05fbc3bf87f4bc46bc4ab
[ "Unlicense" ]
23
2020-08-07T04:09:00.000Z
2022-03-31T22:10:29.000Z
include/HoudiniEngineUnity/HEU_WorkItemTally.hpp
sc2ad/BeatSaber-Quest-Codegen
ba8acaae541cfe1161e05fbc3bf87f4bc46bc4ab
[ "Unlicense" ]
6
2021-09-29T23:47:31.000Z
2022-03-30T20:49:23.000Z
include/HoudiniEngineUnity/HEU_WorkItemTally.hpp
sc2ad/BeatSaber-Quest-Codegen
ba8acaae541cfe1161e05fbc3bf87f4bc46bc4ab
[ "Unlicense" ]
17
2020-08-20T19:36:52.000Z
2022-03-30T18:28:24.000Z
// 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" #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 // Type namespace: HoudiniEngineUnity namespace HoudiniEngineUnity { // Forward declaring type: HEU_WorkItemTally class HEU_WorkItemTally; } #include "extern/beatsaber-hook/shared/utils/il2cpp-type-check.hpp" NEED_NO_BOX(HoudiniEngineUnity::HEU_WorkItemTally); DEFINE_IL2CPP_ARG_TYPE(HoudiniEngineUnity::HEU_WorkItemTally*, "HoudiniEngineUnity", "HEU_WorkItemTally"); // Type namespace: HoudiniEngineUnity namespace HoudiniEngineUnity { // Size: 0x28 #pragma pack(push, 1) // Autogenerated type: HoudiniEngineUnity.HEU_WorkItemTally // [TokenAttribute] Offset: FFFFFFFF class HEU_WorkItemTally : public ::Il2CppObject { public: #ifdef USE_CODEGEN_FIELDS public: #else protected: #endif // public System.Int32 _totalWorkItems // Size: 0x4 // Offset: 0x10 int totalWorkItems; // Field size check static_assert(sizeof(int) == 0x4); // public System.Int32 _waitingWorkItems // Size: 0x4 // Offset: 0x14 int waitingWorkItems; // Field size check static_assert(sizeof(int) == 0x4); // public System.Int32 _scheduledWorkItems // Size: 0x4 // Offset: 0x18 int scheduledWorkItems; // Field size check static_assert(sizeof(int) == 0x4); // public System.Int32 _cookingWorkItems // Size: 0x4 // Offset: 0x1C int cookingWorkItems; // Field size check static_assert(sizeof(int) == 0x4); // public System.Int32 _cookedWorkItems // Size: 0x4 // Offset: 0x20 int cookedWorkItems; // Field size check static_assert(sizeof(int) == 0x4); // public System.Int32 _erroredWorkItems // Size: 0x4 // Offset: 0x24 int erroredWorkItems; // Field size check static_assert(sizeof(int) == 0x4); public: // Get instance field reference: public System.Int32 _totalWorkItems int& dyn__totalWorkItems(); // Get instance field reference: public System.Int32 _waitingWorkItems int& dyn__waitingWorkItems(); // Get instance field reference: public System.Int32 _scheduledWorkItems int& dyn__scheduledWorkItems(); // Get instance field reference: public System.Int32 _cookingWorkItems int& dyn__cookingWorkItems(); // Get instance field reference: public System.Int32 _cookedWorkItems int& dyn__cookedWorkItems(); // Get instance field reference: public System.Int32 _erroredWorkItems int& dyn__erroredWorkItems(); // public System.Void ZeroAll() // Offset: 0x16E4614 void ZeroAll(); // public System.Boolean AreAllWorkItemsComplete() // Offset: 0x16E4620 bool AreAllWorkItemsComplete(); // public System.Boolean AnyWorkItemsFailed() // Offset: 0x16E4658 bool AnyWorkItemsFailed(); // public System.Boolean AnyWorkItemsPending() // Offset: 0x16E4668 bool AnyWorkItemsPending(); // public System.String ProgressRatio() // Offset: 0x16E46AC ::Il2CppString* ProgressRatio(); // public System.Void .ctor() // Offset: 0x16E4788 // Implemented from: System.Object // Base method: System.Void Object::.ctor() template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary> static HEU_WorkItemTally* New_ctor() { static auto ___internal__logger = ::Logger::get().WithContext("HoudiniEngineUnity::HEU_WorkItemTally::.ctor"); return THROW_UNLESS((::il2cpp_utils::New<HEU_WorkItemTally*, creationType>())); } }; // HoudiniEngineUnity.HEU_WorkItemTally #pragma pack(pop) static check_size<sizeof(HEU_WorkItemTally), 36 + sizeof(int)> __HoudiniEngineUnity_HEU_WorkItemTallySizeCheck; static_assert(sizeof(HEU_WorkItemTally) == 0x28); } #include "extern/beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp" // Writing MetadataGetter for method: HoudiniEngineUnity::HEU_WorkItemTally::ZeroAll // Il2CppName: ZeroAll template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (HoudiniEngineUnity::HEU_WorkItemTally::*)()>(&HoudiniEngineUnity::HEU_WorkItemTally::ZeroAll)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(HoudiniEngineUnity::HEU_WorkItemTally*), "ZeroAll", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: HoudiniEngineUnity::HEU_WorkItemTally::AreAllWorkItemsComplete // Il2CppName: AreAllWorkItemsComplete template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (HoudiniEngineUnity::HEU_WorkItemTally::*)()>(&HoudiniEngineUnity::HEU_WorkItemTally::AreAllWorkItemsComplete)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(HoudiniEngineUnity::HEU_WorkItemTally*), "AreAllWorkItemsComplete", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: HoudiniEngineUnity::HEU_WorkItemTally::AnyWorkItemsFailed // Il2CppName: AnyWorkItemsFailed template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (HoudiniEngineUnity::HEU_WorkItemTally::*)()>(&HoudiniEngineUnity::HEU_WorkItemTally::AnyWorkItemsFailed)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(HoudiniEngineUnity::HEU_WorkItemTally*), "AnyWorkItemsFailed", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: HoudiniEngineUnity::HEU_WorkItemTally::AnyWorkItemsPending // Il2CppName: AnyWorkItemsPending template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (HoudiniEngineUnity::HEU_WorkItemTally::*)()>(&HoudiniEngineUnity::HEU_WorkItemTally::AnyWorkItemsPending)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(HoudiniEngineUnity::HEU_WorkItemTally*), "AnyWorkItemsPending", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: HoudiniEngineUnity::HEU_WorkItemTally::ProgressRatio // Il2CppName: ProgressRatio template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::Il2CppString* (HoudiniEngineUnity::HEU_WorkItemTally::*)()>(&HoudiniEngineUnity::HEU_WorkItemTally::ProgressRatio)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(HoudiniEngineUnity::HEU_WorkItemTally*), "ProgressRatio", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: HoudiniEngineUnity::HEU_WorkItemTally::New_ctor // Il2CppName: .ctor // Cannot get method pointer of value based method overload from template for constructor! // Try using FindMethod instead!
45.904459
188
0.742473
[ "object", "vector" ]
4a98707fccae279f8c4e269db2ffb262edbe2d77
1,601
cpp
C++
code/924.cpp
Nightwish-cn/my_leetcode
40f206e346f3f734fb28f52b9cde0e0041436973
[ "MIT" ]
23
2020-03-30T05:44:56.000Z
2021-09-04T16:00:57.000Z
code/924.cpp
Nightwish-cn/my_leetcode
40f206e346f3f734fb28f52b9cde0e0041436973
[ "MIT" ]
1
2020-05-10T15:04:05.000Z
2020-06-14T01:21:44.000Z
code/924.cpp
Nightwish-cn/my_leetcode
40f206e346f3f734fb28f52b9cde0e0041436973
[ "MIT" ]
6
2020-03-30T05:45:04.000Z
2020-08-13T10:01:39.000Z
#include <bits/stdc++.h> #define INF 2000000000 using namespace std; typedef long long ll; int read(){ int f = 1, x = 0; char c = getchar(); while(c < '0' || c > '9'){if(c == '-') f = -f; c = getchar();} while(c >= '0' && c <= '9')x = x * 10 + c - '0', c = getchar(); return f * x; } struct TreeNode { int val; TreeNode *left; TreeNode *right; TreeNode(int x) : val(x), left(NULL), right(NULL) {} }; bool isLeaf(TreeNode* root) { return root->left == NULL && root->right == NULL; } struct ListNode { int val; ListNode *next; ListNode(int x) : val(x), next(NULL) {} }; bool vis[305]; class Solution { public: int minMalwareSpread(vector<vector<int>>& graph, vector<int>& initial) { queue<int> q; int n = graph.size(), ans = n + 1, p = -1; for (int removed: initial){ memset(vis, 0, sizeof(vis)); int injected = 0; for (int x: initial) if (x != removed) q.push(x), vis[x] = true, ++injected; while (!q.empty()){ int h = q.front(); q.pop(); for (int i = 0; i < n; ++i) if (graph[h][i] && !vis[i]) vis[i] = true, q.push(i), ++injected; } if (injected < ans) p = removed, ans = injected; else if (injected == ans) p = min(p, removed); } return p; } }; Solution sol; void init(){ } void solve(){ // sol.convert(); } int main(){ init(); solve(); return 0; }
23.544118
76
0.465334
[ "vector" ]
4a9a6ef80c3291b9c202048102066a1b7e64977d
1,472
cpp
C++
shared++/filter_hsv.cpp
uroboro/DIP
1b2aca87438a629ad2e5fcc22508bda66402d26c
[ "MIT" ]
1
2017-07-04T02:50:26.000Z
2017-07-04T02:50:26.000Z
shared++/filter_hsv.cpp
uroboro/DIP
1b2aca87438a629ad2e5fcc22508bda66402d26c
[ "MIT" ]
null
null
null
shared++/filter_hsv.cpp
uroboro/DIP
1b2aca87438a629ad2e5fcc22508bda66402d26c
[ "MIT" ]
2
2016-05-12T02:47:26.000Z
2020-03-02T10:54:14.000Z
#include "filter_hsv.hpp" void maskByHSVMat(cv::Mat& src, cv::Mat& dst, cv::Scalar minHSV, cv::Scalar maxHSV) { std::vector<cv::Mat> rgbChannels(3); { // Get HSV values src.copyTo(dst); cv::GaussianBlur(dst, dst, cv::Size(9, 9), 0, 0, 0); cv::cvtColor(dst, dst, cv::COLOR_RGB2HSV); cv::split(dst, rgbChannels); } //return; // Filter each range separately since cvInRange doesn't handle low limit > high limit (special case for hue range) if (minHSV[0] < maxHSV[0]) { cv::inRange(rgbChannels[0], cv::Scalar(minHSV[0]), cv::Scalar(maxHSV[0]), rgbChannels[0]); } else { cv::Mat tmp1d; cv::inRange(rgbChannels[0], cv::Scalar(0), cv::Scalar(maxHSV[0]), tmp1d); cv::inRange(rgbChannels[0], cv::Scalar(minHSV[0]), cv::Scalar(255), rgbChannels[0]); //cvOr(&tmp1d, &rgbChannels[0], &rgbChannels[0]); // cv::bitwise_or(tmp1d, rgbChannels[0], rgbChannels[0]); // cv::threshold(rgbChannels[0], rgbChannels[0], 0, 255, cv::THRESH_BINARY); } cv::inRange(rgbChannels[1], cv::Scalar(minHSV[1]), cv::Scalar(maxHSV[1]), rgbChannels[1]); cv::inRange(rgbChannels[2], cv::Scalar(minHSV[2]), cv::Scalar(maxHSV[2]), rgbChannels[2]); // Generate mask cv::merge(rgbChannels, dst); cv::cvtColor(dst, dst, cv::COLOR_HSV2RGB); //CVSHOW("skin2", dst->width*6/5, dst->height*2/3, dst->width/2, dst->height/2, dst); cv::threshold(dst, dst, 240, 255, cv::THRESH_BINARY); } void filterByHSVMat(cv::Mat& src, cv::Mat& dst, cv::Scalar minHSV, cv::Scalar maxHSV) { }
39.783784
115
0.667799
[ "vector" ]
4a9b7eea5f971e31b502cb8d95f6d3592ee0286f
3,112
cpp
C++
src/meta/processors/parts/GetPartsAllocProcessor.cpp
jyz0309/nebula
43f213113661a3fedd9ee4cbf8e8059fbddb4dbc
[ "Apache-2.0" ]
null
null
null
src/meta/processors/parts/GetPartsAllocProcessor.cpp
jyz0309/nebula
43f213113661a3fedd9ee4cbf8e8059fbddb4dbc
[ "Apache-2.0" ]
null
null
null
src/meta/processors/parts/GetPartsAllocProcessor.cpp
jyz0309/nebula
43f213113661a3fedd9ee4cbf8e8059fbddb4dbc
[ "Apache-2.0" ]
null
null
null
/* Copyright (c) 2018 vesoft inc. All rights reserved. * * This source code is licensed under Apache 2.0 License. */ #include "meta/processors/parts/GetPartsAllocProcessor.h" namespace nebula { namespace meta { void GetPartsAllocProcessor::process(const cpp2::GetPartsAllocReq& req) { folly::SharedMutex::ReadHolder holder(LockUtils::lock()); auto spaceId = req.get_space_id(); auto prefix = MetaKeyUtils::partPrefix(spaceId); auto iterRet = doPrefix(prefix); if (!nebula::ok(iterRet)) { auto retCode = nebula::error(iterRet); LOG(ERROR) << "Get parts failed, error " << apache::thrift::util::enumNameSafe(retCode); handleErrorCode(retCode); onFinished(); return; } auto iter = nebula::value(iterRet).get(); std::unordered_map<PartitionID, std::vector<nebula::HostAddr>> parts; while (iter->valid()) { auto key = iter->key(); PartitionID partId; memcpy(&partId, key.data() + prefix.size(), sizeof(PartitionID)); std::vector<HostAddr> partHosts = MetaKeyUtils::parsePartVal(iter->val()); parts.emplace(partId, std::move(partHosts)); iter->next(); } handleErrorCode(nebula::cpp2::ErrorCode::SUCCEEDED); resp_.parts_ref() = std::move(parts); auto terms = getTerm(spaceId); if (!terms.empty()) { resp_.terms_ref() = std::move(terms); } onFinished(); } std::unordered_map<PartitionID, TermID> GetPartsAllocProcessor::getTerm(GraphSpaceID spaceId) { std::unordered_map<PartitionID, TermID> ret; auto spaceKey = MetaKeyUtils::spaceKey(spaceId); auto spaceVal = doGet(spaceKey); if (!nebula::ok(spaceVal)) { auto rc = nebula::error(spaceVal); LOG(ERROR) << "Get Space SpaceId: " << spaceId << " error: " << apache::thrift::util::enumNameSafe(rc); handleErrorCode(rc); return ret; } auto properties = MetaKeyUtils::parseSpace(nebula::value(spaceVal)); auto partNum = properties.get_partition_num(); std::vector<PartitionID> partIdVec; std::vector<std::string> leaderKeys; for (auto partId = 1; partId <= partNum; ++partId) { partIdVec.emplace_back(partId); leaderKeys.emplace_back(MetaKeyUtils::leaderKey(spaceId, partId)); } std::vector<std::string> vals; auto [code, statusVec] = kvstore_->multiGet(kDefaultSpaceId, kDefaultPartId, std::move(leaderKeys), &vals); if (code != nebula::cpp2::ErrorCode::SUCCEEDED && code != nebula::cpp2::ErrorCode::E_PARTIAL_RESULT) { LOG(INFO) << "error rc = " << apache::thrift::util::enumNameSafe(code); return ret; } TermID term; for (auto i = 0U; i != vals.size(); ++i) { if (statusVec[i].ok()) { std::tie(std::ignore, term, code) = MetaKeyUtils::parseLeaderValV3(vals[i]); if (code != nebula::cpp2::ErrorCode::SUCCEEDED) { LOG(WARNING) << apache::thrift::util::enumNameSafe(code); LOG(INFO) << folly::sformat("term of part {} is invalid", partIdVec[i]); continue; } LOG(INFO) << folly::sformat("term of part {} is {}", partIdVec[i], term); ret[partIdVec[i]] = term; } } return ret; } } // namespace meta } // namespace nebula
33.106383
95
0.662596
[ "vector" ]
4aa2aea569d6d81495ec5ba1b5e3d01bedbec0ab
7,830
cpp
C++
codeforces/1178g.cpp
sogapalag/problems
0ea7d65448e1177f8b3f81124a82d187980d659c
[ "MIT" ]
1
2020-04-04T14:56:12.000Z
2020-04-04T14:56:12.000Z
codeforces/1178g.cpp
sogapalag/problems
0ea7d65448e1177f8b3f81124a82d187980d659c
[ "MIT" ]
null
null
null
codeforces/1178g.cpp
sogapalag/problems
0ea7d65448e1177f8b3f81124a82d187980d659c
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; template <typename T> struct Line { T k, b; Line() {} Line(const Line<T>& _r) : k(_r.k), b(_r.b) {} Line(T _k, T _b) : k(_k), b(_b) {} inline T eval(T x) const{ return k*x + b; } // act like point Line<T>& operator-=(const Line<T>& _r) { k -= _r.k; b -= _r.b; return *this; } friend Line<T> operator-(const Line<T>& _lhs, const Line<T>& _rhs) { return Line<T>(_lhs) -= _rhs; } // T cross(const Line<T>& _r) { // return k*_r.b - b*_r.k; // } // watch out whether overflow inline long double cross(const Line<T>& _r) const{ return (long double) k*_r.b - (long double) b*_r.k; } }; // when range [l, r), has property P~notP, want last P. // when return l-1, means not found. template <typename T> T bs_last(T l, T r, function<bool (T)> f) { assert(l < r); T mid; while (l != r) { mid = l + (r-l)/2; if (f(mid)) { l = mid + 1; }else { r = mid; } } return r-1; } template <typename T> struct Convex {// max vector<Line<T>> hull; inline void add_line(T k, T b) { // k must be monotonic Line<T> ln(k, b); // if k inc. <= 0 while ((int) hull.size() > 1 && (ln - hull.back()).cross(ln - *(hull.rbegin()+1)) >= 0) { hull.pop_back(); } hull.push_back(ln); } inline T query(T x) { int id = bs_last<int>(0, (int)hull.size(), [&](int i){ if (i == 0) return true; return hull[i].eval(x) >= hull[i-1].eval(x); }); return hull[id].eval(x); } int best_id; T best_x, best_res; inline T brute_query(T x) { assert(x>=best_x); if (x==best_x) return best_res; // hull dec. x->inc, id should dec. while (best_id > 0 && hull[best_id-1].eval(x) >= hull[best_id].eval(x)) { best_id--; } best_x = x; best_res = hull[best_id].eval(best_x); return best_res; } void clear() { hull.clear(); } }; using Ch=Convex<long long>; using ll=long long; const int BLOCK_SIZE = 256; struct Block { int L, R; int x; ll k[BLOCK_SIZE], b[BLOCK_SIZE]; bool sorted; vector<int> ord; Ch ch; Block() {} Block(int _L, int _R) : L(_L), R(_R), x(0), sorted(false), ord(R-L){ iota(ord.begin(), ord.end(), 0); } void build() { ch.clear(); if (!sorted) { sort(ord.begin(), ord.end(), [&](auto& u, auto& v){ return k[u] > k[v]; }); sorted = true; } for(int i: ord){ ch.add_line(k[i], b[i]); } ch.best_id = ch.hull.size()-1; ch.best_x = -1ll; } void update(int l, int r, int dx) { assert(L <= l && r <= R); if (L==l && r==R) { x += dx; return; } for (int i = L; i < R; i++) { b[i-L] += k[i-L]*x; } x = 0; for (int i = l; i < r; i++) { b[i-L] += k[i-L]*dx; } build(); } ll query(int l, int r) { assert(L <= l && r <= R); if (L==l && r==R) { ll res = ch.brute_query(x); //assert(ch.query(x) == res); return res; } ll mx = -(1ll<<62); for (int i = l; i < r; i++) { mx = max(mx, k[i-L]*x + b[i-L]); } return mx; } }; struct HLD { int n; vector<vector<int>> g; vector<int> sz, pa, depth, sta, fin, heavy, top, tour; int tim; vector<int> a,b; vector<Block> bs[2]; HLD(int _n) : n(_n) , g(n) , sz(n, 1) , pa(n, -1) , depth(n) , sta(n) , fin(n) , heavy(n, -1) , top(n) , a(n) , b(n) { tour.reserve(n); input(); } inline void add(int u, int v) { g[u].emplace_back(v); g[v].emplace_back(u); } void input() { //for (int _ = 1; _ < n; _++) { // int x,y; // cin >> x >> y; // --x; --y; // to 0-based // add(x,y); //} for (int i = 1; i < n; i++) { int u; cin >> u; u--; g[u].push_back(i); } for (int i = 0; i < n; i++) { cin >> a[i]; } for (int i = 0; i < n; i++) { cin >> b[i]; } } void dfs(int u) { //if (pa[u] != -1) g[u].erase(find(g[u].begin(), g[u].end(), pa[u])); for (int& v: g[u]) { pa[v] = u; depth[v] = depth[u] + 1; // ! a[v] += a[u]; b[v] += b[u]; dfs(v); sz[u] += sz[v]; // heavy skew left, thus chain consective on sta if (sz[v] > sz[g[u][0]]) swap(v, g[u][0]); } } // sta*tour = I void hld(int u) { sta[u] = tim++; tour.emplace_back(u); for (int v: g[u]) { top[v] = (v == g[u][0] ? heavy[u] = v, top[u] : v); // #h=1 //top[v] = (sz[v] >= (sz[u]+1)/2 ? heavy[u] = v, top[u] : v); // #h<=1 hld(v); } fin[u] = tim; } #define rep(i) for(int i=0;i<2;i++) void build(int root = 0) { dfs(root); tim = 0; top[root] = root; hld(root); for (int l = 0; l < n; l+=BLOCK_SIZE) { int r; rep(_) bs[_].emplace_back(l, r = min(n, l+BLOCK_SIZE)); auto L = bs[0].back().L; assert(L==l); for (int i = l; i < r; i++) { bs[0].back().k[i-L] = b[tour[i]]; bs[0].back().b[i-L] = b[tour[i]] * 1ll * a[tour[i]]; bs[1].back().k[i-L] = -b[tour[i]]; bs[1].back().b[i-L] = -b[tour[i]] * 1ll * a[tour[i]]; } rep(_) bs[_].back().build(); } } inline void across_light(int& v) { v = pa[top[v]]; } int lca(int u, int v) { while (top[u] != top[v]) { sta[u] < sta[v] ? across_light(v) : across_light(u); } return sta[u] < sta[v] ? u : v; } using F = function<void(int,int)>; // range operation tim(0)-based [l..r) // [u..v] void for_v_path(int u, int v, F f) { while (true) { if (sta[u] > sta[v]) swap(u, v); f(max(sta[top[v]], sta[u]), sta[v]+1); if (top[u] == top[v]) return; across_light(v); } } void for_v_sub(int u, F f, bool exclude = 0) { f(sta[u] + exclude, fin[u]); } void update(int l, int r, int x) { for (int i = l/BLOCK_SIZE; l < r; i++) { int _r = min(r, bs[0][i].R); rep(_) bs[_][i].update(l, _r, x); l = _r; } } ll query(int l, int r) { ll mx = -(1ll<<62); for (int i = l/BLOCK_SIZE; l < r; i++) { int _r = min(r, bs[0][i].R); rep(_) mx = max(mx, bs[_][i].query(l, _r)); l = _r; } return mx; } void process(int q) { while (q--) { int op, v; cin >> op >> v; v--; if (op == 1) { int x; cin >> x; for_v_sub(v, [&](int l, int r){update(l,r,x);}); } else { ll x = -(1ll<<62); for_v_sub(v, [&](int l, int r){x=max(x, query(l,r));}); cout << x << "\n"; } } } }; void solve() { int n,q; cin >> n >> q; HLD hld(n); hld.build(); hld.process(q); } int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); solve(); cout << endl; }
25.422078
97
0.396296
[ "vector" ]
4aa31634a910f33e69e8f2f589f3ac2e7223c70b
24,072
cpp
C++
src/internal/rapidxml_parser/HMAuxParserRapidXML.cpp
varsameer/NetCHASM
3071241ce0d2cddc077e5e7e1b957677d733ae76
[ "Apache-2.0" ]
13
2019-06-06T01:14:30.000Z
2022-03-03T05:57:51.000Z
src/internal/rapidxml_parser/HMAuxParserRapidXML.cpp
varsameer/NetCHASM
3071241ce0d2cddc077e5e7e1b957677d733ae76
[ "Apache-2.0" ]
7
2019-07-23T18:31:20.000Z
2021-05-26T12:57:34.000Z
src/internal/rapidxml_parser/HMAuxParserRapidXML.cpp
varsameer/NetCHASM
3071241ce0d2cddc077e5e7e1b957677d733ae76
[ "Apache-2.0" ]
12
2019-06-27T13:58:03.000Z
2021-12-23T07:43:06.000Z
// Copyright 2019, Oath Inc. // Licensed under the terms of the Apache 2.0 license. See LICENSE file in the root of the distribution for licensing details. #include <limits.h> #include <errno.h> #include <iostream> #include <string> #include "HMLogBase.h" #include "HMAuxParserRapidXML.h" #include "rapidxml.h" #include "rapidxml_print.h" using namespace rapidxml; using namespace std; bool HMAuxParserRapidXML::genAuxData(HMAuxInfo& auxInfo, const HM_AUX_TYPE type, const string& rotation, string& xmlOutput) { stringstream ss; xml_document<> doc; xml_node<>* rootNode = nullptr; xml_node<>* dcNode = nullptr; xml_node<>* resourceNode = nullptr; xml_node<>* hostNode = nullptr; xml_node<>* childNode = nullptr; xml_attribute<>* attr = nullptr; char* value = nullptr; string svalue; HMTimeStamp parseTime; map<string, xml_node<>*> datacenters; map<string, xml_node<>*> resources; switch(type) { case HM_LOAD_FILE: rootNode = doc.allocate_node(node_element, "load-file"); ss.str(string()); ss << auxInfo.m_ts.getTimeSinceEpoch(); value = doc.allocate_string(ss.str().c_str()); attr = doc.allocate_attribute("updated", value); rootNode->append_attribute(attr); doc.append_node(rootNode); for(auto entry = auxInfo.m_auxData.begin(); entry != auxInfo.m_auxData.end(); ++entry) { HMAuxBase* base = entry->get(); if(base->m_type != HM_LOAD_FILE) { continue; } HMAuxLoadFB* lfb = dynamic_cast<HMAuxLoadFB*>(base); if(lfb == nullptr) { HMLog(HM_LOG_WARNING, "Failed to parse XML for %s host %s LFB type specified", base->m_host); continue; } auto it = resources.find(lfb->m_resource); if(it == resources.end()) { resourceNode = doc.allocate_node(node_element, "resource"); value = doc.allocate_string(lfb->m_resource.c_str()); attr = doc.allocate_attribute("name", value); resourceNode->append_attribute(attr); rootNode->append_node(resourceNode); resources.insert(make_pair(lfb->m_resource, resourceNode)); } else { resourceNode = it->second; } // now check for an existing node bool skip = false; hostNode = resourceNode->first_node("host"); while(hostNode != nullptr) { attr = hostNode->first_attribute("name"); svalue = attr->value(); if(svalue == lfb->m_host) { childNode = hostNode->first_node("time"); svalue = childNode->value(); parseTime.setTime(atol(svalue.c_str())); if(parseTime.getTimeSinceEpoch() < lfb->m_ts.getTimeSinceEpoch()) { // we need to update this value resourceNode->remove_node(hostNode); } else { // no need to add the attribute skip = true; } break; } hostNode = hostNode->next_sibling("host"); } if(skip) { continue; } hostNode = doc.allocate_node(node_element, "host"); value = doc.allocate_string(lfb->m_host.c_str()); attr = doc.allocate_attribute("name", value); hostNode->append_attribute(attr); ss.str(string()); ss << lfb->m_ts.getTimeSinceEpoch(); value = doc.allocate_string(ss.str().c_str()); childNode = doc.allocate_node(node_element, "time", value); hostNode->append_node(childNode); ss.str(string()); ss << lfb->m_load; value = doc.allocate_string(ss.str().c_str()); childNode = doc.allocate_node(node_element, "load", value); hostNode->append_node(childNode); ss.str(string()); ss << lfb->m_target; value = doc.allocate_string(ss.str().c_str()); childNode = doc.allocate_node(node_element, "target", value); hostNode->append_node(childNode); ss.str(string()); ss << lfb->m_max; value = doc.allocate_string(ss.str().c_str()); childNode = doc.allocate_node(node_element, "max", value); hostNode->append_node(childNode); resourceNode->append_node(hostNode); } break; case HM_OOB_FILE: rootNode = doc.allocate_node(node_element, "oob-file"); ss.str(string()); ss << auxInfo.m_ts.getTimeSinceEpoch(); value = doc.allocate_string(ss.str().c_str()); attr = doc.allocate_attribute("updated", value); rootNode->append_attribute(attr); doc.append_node(rootNode); for(auto entry = auxInfo.m_auxData.begin(); entry != auxInfo.m_auxData.end(); ++entry) { HMAuxBase* base = entry->get(); if(base->m_type != HM_OOB_FILE) { continue; } HMAuxOOB* oob = dynamic_cast<HMAuxOOB*>(base); if(oob == nullptr) { HMLog(HM_LOG_WARNING, "Failed to parse XML for %s host %s LFB type specified", base->m_host); continue; } auto it = resources.find(oob->m_resource); if(it == resources.end()) { resourceNode = doc.allocate_node(node_element, "resource-oob"); value = doc.allocate_string(oob->m_resource.c_str()); attr = doc.allocate_attribute("name", value); resourceNode->append_attribute(attr); rootNode->append_node(resourceNode); resources.insert(make_pair(oob->m_resource, resourceNode)); } else { resourceNode = it->second; } // now check for an existing node bool skip = false; hostNode = resourceNode->first_node("host"); while(hostNode != nullptr) { attr = hostNode->first_attribute("name"); svalue = attr->value(); if(svalue == oob->m_host) { childNode = hostNode->first_node("time"); svalue = childNode->value(); parseTime.setTime(atol(svalue.c_str())); if(parseTime.getTimeSinceEpoch() < oob->m_ts.getTimeSinceEpoch()) { // we need to update this value resourceNode->remove_node(hostNode); } else { // no need to add the attribute skip = true; } break; } hostNode = hostNode->next_sibling("host"); } if(skip) { continue; } hostNode = doc.allocate_node(node_element, "host"); value = doc.allocate_string(oob->m_host.c_str()); attr = doc.allocate_attribute("name", value); hostNode->append_attribute(attr); ss.str(string()); ss << oob->m_ts.getTimeSinceEpoch(); value = doc.allocate_string(ss.str().c_str()); childNode = doc.allocate_node(node_element, "time", value); hostNode->append_node(childNode); ss.str(string()); ss << ((oob->m_forceDown) ? "true" : "false"); value = doc.allocate_string(ss.str().c_str()); childNode = doc.allocate_node(node_element, "force-down", value); hostNode->append_node(childNode); if(oob->m_shed!=0) { ss.str(string()); ss << oob->m_shed; value = doc.allocate_string(ss.str().c_str()); childNode = doc.allocate_node(node_element, "shed", value); hostNode->append_node(childNode); } resourceNode->append_node(hostNode); } break; } // print to the string ss.str(string()); ss << doc; xmlOutput = ss.str(); doc.clear(); return true; } bool HMAuxParserRapidXML::parseAuxData(const string& hostname, const string& sourceURL, const HMIPAddress& address, string& auxStr, HMAuxInfo& auxInfo) { HMLog(HM_LOG_DEBUG3, "[CURLCHECK] HMAuxCache::parseXML: url %s from host %s@%s", hostname.c_str(), sourceURL.c_str(), address.toString().c_str()); // I hate this copy so much. But for now I will leave it to fix in profiling vector<char> buffer(auxStr.begin(), auxStr.end()); buffer.push_back('\0'); xml_node<>* rootNode; xml_document<char> doc; try { doc.parse<0>(&buffer[0]); } catch (parse_error &e) { HMLog(HM_LOG_INFO, "[CURLCHECK] HMAuxCache::parseXML: parse_error exception " "parsing url %s/%s, reason = %s", hostname.c_str(), sourceURL.c_str(), e.what()); doc.clear(); return false; } catch (...) { HMLog(HM_LOG_INFO, "[CURLCHECK] HMAuxCache::parseXML: unknown exception " "parsing url %s@%s", hostname.c_str(), sourceURL.c_str()); doc.clear(); return false; } rootNode = doc.first_node(); if(rootNode == nullptr) { doc.clear(); return false; } string rootName(rootNode->name()); if(rootName == "load-file") { return parseNewLFB(hostname, sourceURL, address, doc, auxInfo); } else if(rootName == "oob-file") { return parseOOB(hostname, sourceURL, address, doc, auxInfo); } else { HMLog(HM_LOG_INFO, "XML Type Not Supported when querying %s %s %s", hostname.c_str(), sourceURL.c_str(), address.toString().c_str()); doc.clear(); return false; } } bool HMAuxParserRapidXML::parseNewLFB(const string& hostname, const string& sourceURL, const HMIPAddress& address, xml_document<char>& doc, HMAuxInfo& auxInfo) { HMTimeStamp filets; HMTimeStamp ts; xml_attribute<>* attr; xml_node<>* rootNode = doc.first_node(); xml_node<>* resourceNode = nullptr; xml_node<>* hostNode = nullptr; xml_node<>* currentNode = nullptr; char* endptr = nullptr; attr = rootNode->first_attribute("updated"); if(attr == nullptr) { HMLog(HM_LOG_INFO, "XML Load File does not contain a timestamp attribute for %s with checkinfo %s", hostname.c_str(), sourceURL.c_str()); doc.clear(); return false; } errno = 0; int64_t tempTime = strtol((const char*) attr->value(), &endptr, 10); tempTime = tempTime * 1000; if ((errno == ERANGE && (tempTime == LONG_MAX || tempTime == LONG_MIN)) || (errno != 0 && tempTime == 0)) { HMLog(HM_LOG_INFO, "XML Load file time tag has invalid value for %s with checkinfo %s", hostname.c_str(), sourceURL.c_str()); doc.clear(); return false; } filets.setTime(tempTime); auxInfo.m_ts.setTime(tempTime); resourceNode = rootNode->first_node("resource"); if(resourceNode == nullptr) { HMLog(HM_LOG_DEBUG, "XML Load file does not contain a resource tag for %s with checkinfo %s", hostname.c_str(), sourceURL.c_str()); doc.clear(); return false; } while(resourceNode != nullptr) { attr = resourceNode->first_attribute("name"); if(attr == nullptr) { HMLog(HM_LOG_INFO, "XML Load file resource node does not contain a name attribute for %s with checkinfo %s", hostname.c_str(), sourceURL.c_str()); doc.clear(); return false; } HMAuxLoadFB lfb; lfb.m_type = HM_LOAD_FILE; lfb.m_ip = address; lfb.m_datacenter = ""; lfb.m_resource = attr->value(); lfb.m_load = 0; lfb.m_target = 0; lfb.m_max = 0; hostNode = resourceNode->first_node("host"); if(hostNode == nullptr) { HMLog(HM_LOG_DEBUG, "XML Load file resource node does not contain a host tag for %s with checkinfo %s", hostname.c_str(), sourceURL.c_str()); doc.clear(); return false; } while(hostNode != nullptr) { attr = hostNode->first_attribute("name"); if (attr == nullptr) { HMLog(HM_LOG_INFO, "XML Load file host node does not contain a name attribute for %s with checkinfo %s", hostname.c_str(), sourceURL.c_str()); doc.clear(); return false; } lfb.m_host = attr->value(); currentNode = hostNode->first_node("load"); if(currentNode == nullptr) { HMLog(HM_LOG_DEBUG3, "XML Load file resource node does not contain a load tag for %s with checkinfo %s", hostname.c_str(), sourceURL.c_str()); } else { errno = 0; lfb.m_load = strtol((const char*)currentNode->value(), &endptr, 10); if((errno == ERANGE && (lfb.m_load == LONG_MAX || lfb.m_load == LONG_MIN)) || (errno != 0 && lfb.m_load == 0)) { HMLog(HM_LOG_DEBUG3, "XML Load file resource node load tag has invalid value for %s with checkinfo %s", hostname.c_str(), sourceURL.c_str()); lfb.m_load = 0; } } currentNode = hostNode->first_node("target"); if(currentNode == nullptr) { HMLog(HM_LOG_DEBUG3, "XML Load file resource node does not contain a target tag for %s with checkinfo %s", hostname.c_str(), sourceURL.c_str()); } else { errno = 0; lfb.m_target = strtol((const char*)currentNode->value(), &endptr, 10); if((errno == ERANGE && (lfb.m_target == LONG_MAX || lfb.m_target == LONG_MIN)) || (errno != 0 && lfb.m_target == 0)) { HMLog(HM_LOG_DEBUG3, "XML Load file resource node target tag has invalid value for %s with checkinfo %s", hostname.c_str(), sourceURL.c_str()); lfb.m_target = 0; } } currentNode = hostNode->first_node("max"); if(currentNode == nullptr) { HMLog(HM_LOG_DEBUG3, "XML Load object resource node does not contain a max tag for %s with checkinfo %s", hostname.c_str(), sourceURL.c_str()); } else { errno = 0; lfb.m_max = strtol((const char*)currentNode->value(), &endptr, 10); if((errno == ERANGE && (lfb.m_max == LONG_MAX || lfb.m_max == LONG_MIN)) || (errno != 0 && lfb.m_max == 0)) { HMLog(HM_LOG_DEBUG3, "XML Load object resource node target tag has an invalid max value for %s with checkinfo %s", hostname.c_str(), sourceURL.c_str()); lfb.m_max = 0; } } currentNode = hostNode->first_node("time"); if (currentNode == nullptr) { HMLog(HM_LOG_DEBUG3, "XML Load file resource node does not contain a time tag for %s with checkinfo %s using file time", hostname.c_str(), sourceURL.c_str()); ts = filets; } else { errno = 0; tempTime = strtol((const char*) currentNode->value(), &endptr, 10); tempTime = tempTime * 1000; if ((errno == ERANGE && (tempTime == LONG_MAX || tempTime == LONG_MIN)) || (errno != 0 && tempTime == 0)) { HMLog(HM_LOG_DEBUG3, "XML Load file resource node time tag has invalid value for %s with checkinfo %s using file time", hostname.c_str(), sourceURL.c_str()); ts = filets; } else { ts.setTime(tempTime); } } // According to Dan, if the filets is older than the resource, record the filets for the entry lfb.m_ts = ts; auxInfo.m_auxData.push_back(make_unique<HMAuxLoadFB>(lfb)); hostNode = hostNode->next_sibling("host"); } resourceNode = resourceNode->next_sibling("resource"); } doc.clear(); return true; } bool HMAuxParserRapidXML::parseOOB(const string& hostname, const string& sourceURL, const HMIPAddress& address, xml_document<char>& doc, HMAuxInfo& auxInfo) { HMTimeStamp ts; HMTimeStamp filets; string resource; xml_attribute<>* attr; xml_node<>* rootNode = doc.first_node(); xml_node<>* resourceNode = nullptr; xml_node<>* hostNode = nullptr; xml_node<>* currentNode = nullptr; char* endptr = nullptr; attr = rootNode->first_attribute("updated"); if(attr == nullptr) { HMLog(HM_LOG_INFO, "XML OOB File does not contain a timestamp attribute for %s with checkinfo %s", hostname.c_str(), sourceURL.c_str()); doc.clear(); return false; } errno = 0; int64_t tempTime = strtol((const char*) attr->value(), &endptr, 10); tempTime = tempTime * 1000; if ((errno == ERANGE && (tempTime == LONG_MAX || tempTime == LONG_MIN)) || (errno != 0 && tempTime == 0)) { HMLog(HM_LOG_INFO, "XML OOB file time tag has invalid value for %s with checkinfo %s", hostname.c_str(), sourceURL.c_str()); doc.clear(); return false; } filets.setTime(tempTime); auxInfo.m_ts = filets; HMLog(HM_LOG_DEBUG3, "oob xml for %s timestamp %s", hostname.c_str(), auxInfo.m_ts.print("%Y-%m-%dT%H:%M:%SZ").c_str()); resourceNode = rootNode->first_node("resource-oob"); if(resourceNode == nullptr) { HMLog(HM_LOG_DEBUG, "XML OOB object does not contain a the resource tag for %s with checkinfo %s", hostname.c_str(), sourceURL.c_str()); doc.clear(); return false; } while(resourceNode != nullptr) { attr = resourceNode->first_attribute("name"); if(attr == nullptr) { HMLog(HM_LOG_INFO, "XML OOB object resource tag does not contain a name attribute for %s with checkinfo %s", hostname.c_str(), sourceURL.c_str()); doc.clear(); return false; } resource = attr->value(); hostNode = resourceNode->first_node("host"); if(hostNode == nullptr) { HMLog(HM_LOG_DEBUG, "XML OOB object resource node does not contain a host tag for %s with checkinfo %s", hostname.c_str(), sourceURL.c_str()); doc.clear(); return false; } while(hostNode != nullptr) { attr = hostNode->first_attribute("name"); if(attr == nullptr) { HMLog(HM_LOG_INFO, "XML OOB object host node does not contain a name attribute for %s with checkinfo %s", hostname.c_str(), sourceURL.c_str()); doc.clear(); return false; } HMAuxOOB oob; oob.m_type = HM_OOB_FILE; oob.m_ip = address; oob.m_resource = resource; attr = hostNode->first_attribute("name"); if (attr == nullptr) { HMLog(HM_LOG_INFO, "XML Load file host node does not contain a name attribute for %s with checkinfo %s", hostname.c_str(), sourceURL.c_str()); doc.clear(); return false; } oob.m_host = attr->value(); currentNode = hostNode->first_node("time"); if(currentNode == nullptr) { HMLog(HM_LOG_DEBUG3, "XML OOB object host node does not contain a time tag for %s with checkinfo %s using file time", hostname.c_str(), sourceURL.c_str()); ts = filets; } else { errno = 0; tempTime = strtol((const char*)currentNode->value(), &endptr, 10); tempTime = tempTime * 1000; if((errno == ERANGE && (tempTime == LONG_MAX || tempTime == LONG_MIN)) || (errno != 0 && tempTime == 0)) { HMLog(HM_LOG_DEBUG3, "XML OOB object resource node load tag has invalid value for %s with checkinfo %s using file time", hostname.c_str(), sourceURL.c_str()); ts = filets; } else { ts.setTime(tempTime); } } oob.m_ts = ts; currentNode = hostNode->first_node("shed"); if(currentNode != nullptr) { errno = 0; oob.m_shed = strtol((const char*)currentNode->value(), &endptr, 10); if((errno == ERANGE && (oob.m_shed == UINT_MAX || oob.m_shed == 0)) || (errno != 0 && oob.m_shed == 0) || oob.m_shed > 100) { HMLog(HM_LOG_DEBUG3, "XML OOB object resource node target tag has invalid value for %s with checkinfo %s setting to 0", hostname.c_str(), sourceURL.c_str()); oob.m_shed = 0; } } else { oob.m_shed = 0; } oob.m_forceDown = HM_OOB_FORCEDOWN_NONE; currentNode = hostNode->first_node("force-down"); if(currentNode != nullptr) { oob.m_forceDown = string(currentNode->value()) == "true"? HM_OOB_FORCEDOWN_TRUE : HM_OOB_FORCEDOWN_FALSE; } auxInfo.m_auxData.push_back(make_unique<HMAuxOOB>(oob)); hostNode = hostNode->next_sibling("host"); } resourceNode = resourceNode->next_sibling("resource-oob"); } doc.clear(); return true; }
34.437768
137
0.499294
[ "object", "vector" ]
4aa77f1c7b7abdae87355474ca297b236e6eb00d
218,372
cc
C++
third_party/blink/renderer/core/exported/web_view_test.cc
zipated/src
2b8388091c71e442910a21ada3d97ae8bc1845d3
[ "BSD-3-Clause" ]
2,151
2020-04-18T07:31:17.000Z
2022-03-31T08:39:18.000Z
third_party/blink/renderer/core/exported/web_view_test.cc
cangulcan/src
2b8388091c71e442910a21ada3d97ae8bc1845d3
[ "BSD-3-Clause" ]
395
2020-04-18T08:22:18.000Z
2021-12-08T13:04:49.000Z
third_party/blink/renderer/core/exported/web_view_test.cc
cangulcan/src
2b8388091c71e442910a21ada3d97ae8bc1845d3
[ "BSD-3-Clause" ]
338
2020-04-18T08:03:10.000Z
2022-03-29T12:33:22.000Z
/* * Copyright (C) 2011, 2012 Google Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * Neither the name of Google Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "third_party/blink/public/web/web_view.h" #include <limits> #include <memory> #include <string> #include "build/build_config.h" #include "gin/handle.h" #include "gin/object_template_builder.h" #include "gin/wrappable.h" #include "testing/gtest/include/gtest/gtest.h" #include "third_party/blink/public/common/manifest/web_display_mode.h" #include "third_party/blink/public/mojom/page/page_visibility_state.mojom-blink.h" #include "third_party/blink/public/platform/platform.h" #include "third_party/blink/public/platform/web_coalesced_input_event.h" #include "third_party/blink/public/platform/web_cursor_info.h" #include "third_party/blink/public/platform/web_drag_data.h" #include "third_party/blink/public/platform/web_drag_operation.h" #include "third_party/blink/public/platform/web_float_point.h" #include "third_party/blink/public/platform/web_input_event.h" #include "third_party/blink/public/platform/web_keyboard_event.h" #include "third_party/blink/public/platform/web_layer_tree_view.h" #include "third_party/blink/public/platform/web_size.h" #include "third_party/blink/public/platform/web_thread.h" #include "third_party/blink/public/platform/web_url_loader_mock_factory.h" #include "third_party/blink/public/public_buildflags.h" #include "third_party/blink/public/web/web_autofill_client.h" #include "third_party/blink/public/web/web_console_message.h" #include "third_party/blink/public/web/web_date_time_chooser_completion.h" #include "third_party/blink/public/web/web_device_emulation_params.h" #include "third_party/blink/public/web/web_document.h" #include "third_party/blink/public/web/web_element.h" #include "third_party/blink/public/web/web_frame.h" #include "third_party/blink/public/web/web_frame_client.h" #include "third_party/blink/public/web/web_frame_content_dumper.h" #include "third_party/blink/public/web/web_frame_widget.h" #include "third_party/blink/public/web/web_hit_test_result.h" #include "third_party/blink/public/web/web_input_method_controller.h" #include "third_party/blink/public/web/web_print_params.h" #include "third_party/blink/public/web/web_script_source.h" #include "third_party/blink/public/web/web_settings.h" #include "third_party/blink/public/web/web_tree_scope_type.h" #include "third_party/blink/public/web/web_view_client.h" #include "third_party/blink/public/web/web_widget.h" #include "third_party/blink/public/web/web_widget_client.h" #include "third_party/blink/renderer/bindings/core/v8/v8_document.h" #include "third_party/blink/renderer/core/dom/document.h" #include "third_party/blink/renderer/core/dom/element.h" #include "third_party/blink/renderer/core/dom/node_computed_style.h" #include "third_party/blink/renderer/core/dom/user_gesture_indicator.h" #include "third_party/blink/renderer/core/editing/frame_selection.h" #include "third_party/blink/renderer/core/editing/ime/input_method_controller.h" #include "third_party/blink/renderer/core/editing/markers/document_marker_controller.h" #include "third_party/blink/renderer/core/exported/fake_web_plugin.h" #include "third_party/blink/renderer/core/exported/web_settings_impl.h" #include "third_party/blink/renderer/core/exported/web_view_impl.h" #include "third_party/blink/renderer/core/frame/event_handler_registry.h" #include "third_party/blink/renderer/core/frame/frame_test_helpers.h" #include "third_party/blink/renderer/core/frame/local_frame.h" #include "third_party/blink/renderer/core/frame/local_frame_view.h" #include "third_party/blink/renderer/core/frame/settings.h" #include "third_party/blink/renderer/core/frame/visual_viewport.h" #include "third_party/blink/renderer/core/frame/web_local_frame_impl.h" #include "third_party/blink/renderer/core/fullscreen/fullscreen.h" #include "third_party/blink/renderer/core/html/forms/html_input_element.h" #include "third_party/blink/renderer/core/html/forms/html_text_area_element.h" #include "third_party/blink/renderer/core/html/html_iframe_element.h" #include "third_party/blink/renderer/core/html/html_object_element.h" #include "third_party/blink/renderer/core/inspector/dev_tools_emulator.h" #include "third_party/blink/renderer/core/layout/layout_view.h" #include "third_party/blink/renderer/core/loader/document_loader.h" #include "third_party/blink/renderer/core/loader/frame_load_request.h" #include "third_party/blink/renderer/core/loader/interactive_detector.h" #include "third_party/blink/renderer/core/page/chrome_client.h" #include "third_party/blink/renderer/core/page/focus_controller.h" #include "third_party/blink/renderer/core/page/page.h" #include "third_party/blink/renderer/core/page/print_context.h" #include "third_party/blink/renderer/core/page/scoped_page_pauser.h" #include "third_party/blink/renderer/core/paint/paint_layer.h" #include "third_party/blink/renderer/core/paint/paint_layer_painter.h" #include "third_party/blink/renderer/core/timing/dom_window_performance.h" #include "third_party/blink/renderer/core/timing/window_performance.h" #include "third_party/blink/renderer/platform/geometry/int_rect.h" #include "third_party/blink/renderer/platform/geometry/int_size.h" #include "third_party/blink/renderer/platform/graphics/color.h" #include "third_party/blink/renderer/platform/graphics/graphics_context.h" #include "third_party/blink/renderer/platform/graphics/graphics_layer.h" #include "third_party/blink/renderer/platform/graphics/paint/paint_record_builder.h" #include "third_party/blink/renderer/platform/keyboard_codes.h" #include "third_party/blink/renderer/platform/scroll/scroll_types.h" #include "third_party/blink/renderer/platform/testing/unit_test_helpers.h" #include "third_party/blink/renderer/platform/testing/url_test_helpers.h" #include "third_party/blink/renderer/platform/testing/wtf/scoped_mock_clock.h" #include "third_party/skia/include/core/SkBitmap.h" #include "third_party/skia/include/core/SkCanvas.h" #include "v8/include/v8.h" #if defined(OS_MACOSX) #include "third_party/blink/public/web/mac/web_substring_util.h" #endif #if BUILDFLAG(ENABLE_UNHANDLED_TAP) #include "mojo/public/cpp/bindings/strong_binding.h" #include "third_party/blink/public/platform/unhandled_tap_notifier.mojom-blink.h" #include "third_party/blink/renderer/platform/testing/testing_platform_support.h" #endif // BUILDFLAG(ENABLE_UNHANDLED_TAP) using blink::FrameTestHelpers::LoadFrame; using blink::URLTestHelpers::ToKURL; using blink::URLTestHelpers::RegisterMockedURLLoad; using blink::test::RunPendingTasks; namespace blink { enum HorizontalScrollbarState { kNoHorizontalScrollbar, kVisibleHorizontalScrollbar, }; enum VerticalScrollbarState { kNoVerticalScrollbar, kVisibleVerticalScrollbar, }; class TestData { public: void SetWebView(WebView* web_view) { web_view_ = static_cast<WebViewImpl*>(web_view); } void SetSize(const WebSize& new_size) { size_ = new_size; } HorizontalScrollbarState GetHorizontalScrollbarState() const { return web_view_->HasHorizontalScrollbar() ? kVisibleHorizontalScrollbar : kNoHorizontalScrollbar; } VerticalScrollbarState GetVerticalScrollbarState() const { return web_view_->HasVerticalScrollbar() ? kVisibleVerticalScrollbar : kNoVerticalScrollbar; } int Width() const { return size_.width; } int Height() const { return size_.height; } private: WebSize size_; WebViewImpl* web_view_; }; class AutoResizeWebViewClient : public FrameTestHelpers::TestWebViewClient { public: // WebViewClient methods void DidAutoResize(const WebSize& new_size) override { test_data_.SetSize(new_size); } // Local methods TestData& GetTestData() { return test_data_; } private: TestData test_data_; }; class TapHandlingWebViewClient : public FrameTestHelpers::TestWebViewClient { public: // WebViewClient methods void DidHandleGestureEvent(const WebGestureEvent& event, bool event_cancelled) override { if (event.GetType() == WebInputEvent::kGestureTap) { tap_x_ = event.PositionInWidget().x; tap_y_ = event.PositionInWidget().y; } else if (event.GetType() == WebInputEvent::kGestureLongPress) { longpress_x_ = event.PositionInWidget().x; longpress_y_ = event.PositionInWidget().y; } } // Local methods void Reset() { tap_x_ = -1; tap_y_ = -1; longpress_x_ = -1; longpress_y_ = -1; } int TapX() { return tap_x_; } int TapY() { return tap_y_; } int LongpressX() { return longpress_x_; } int LongpressY() { return longpress_y_; } private: int tap_x_; int tap_y_; int longpress_x_; int longpress_y_; }; class DateTimeChooserWebViewClient : public FrameTestHelpers::TestWebViewClient { public: WebDateTimeChooserCompletion* ChooserCompletion() { return chooser_completion_; } void ClearChooserCompletion() { chooser_completion_ = nullptr; } // WebViewClient methods bool OpenDateTimeChooser( const WebDateTimeChooserParams&, WebDateTimeChooserCompletion* chooser_completion) override { chooser_completion_ = chooser_completion; return true; } private: WebDateTimeChooserCompletion* chooser_completion_; }; class WebViewTest : public testing::Test { public: WebViewTest() : base_url_("http://www.test.com/") {} void TearDown() override { Platform::Current() ->GetURLLoaderMockFactory() ->UnregisterAllURLsAndClearMemoryCache(); } protected: void SetViewportSize(const WebSize& size) { web_view_helper_.SetViewportSize(size); } std::string RegisterMockedHttpURLLoad(const std::string& file_name) { return URLTestHelpers::RegisterMockedURLLoadFromBase( WebString::FromUTF8(base_url_), test::CoreTestDataPath(), WebString::FromUTF8(file_name)) .GetString() .Utf8(); } void TestAutoResize(const WebSize& min_auto_resize, const WebSize& max_auto_resize, const std::string& page_width, const std::string& page_height, int expected_width, int expected_height, HorizontalScrollbarState expected_horizontal_state, VerticalScrollbarState expected_vertical_state); void TestTextInputType(WebTextInputType expected_type, const std::string& html_file); void TestInputMode(WebTextInputMode expected_input_mode, const std::string& html_file); bool TapElement(WebInputEvent::Type, Element*); bool TapElementById(WebInputEvent::Type, const WebString& id); IntSize PrintICBSizeFromPageSize(const FloatSize& page_size); std::string base_url_; FrameTestHelpers::WebViewHelper web_view_helper_; }; static bool HitTestIsContentEditable(WebView* view, int x, int y) { WebPoint hit_point(x, y); WebHitTestResult hit_test_result = view->HitTestResultAt(hit_point); return hit_test_result.IsContentEditable(); } static std::string HitTestElementId(WebView* view, int x, int y) { WebPoint hit_point(x, y); WebHitTestResult hit_test_result = view->HitTestResultAt(hit_point); return hit_test_result.GetNode().To<WebElement>().GetAttribute("id").Utf8(); } TEST_F(WebViewTest, HitTestVideo) { // Test that hit tests on parts of a video element result in hits on the video // element itself as opposed to its child elements. std::string url = RegisterMockedHttpURLLoad("video_200x200.html"); WebView* web_view = web_view_helper_.InitializeAndLoad(url); web_view->Resize(WebSize(200, 200)); // Center of video. EXPECT_EQ("video", HitTestElementId(web_view, 100, 100)); // Play button. EXPECT_EQ("video", HitTestElementId(web_view, 10, 195)); // Timeline bar. EXPECT_EQ("video", HitTestElementId(web_view, 100, 195)); } TEST_F(WebViewTest, HitTestContentEditableImageMaps) { std::string url = RegisterMockedHttpURLLoad("content-editable-image-maps.html"); WebView* web_view = web_view_helper_.InitializeAndLoad(url); web_view->Resize(WebSize(500, 500)); EXPECT_EQ("areaANotEditable", HitTestElementId(web_view, 25, 25)); EXPECT_FALSE(HitTestIsContentEditable(web_view, 25, 25)); EXPECT_EQ("imageANotEditable", HitTestElementId(web_view, 75, 25)); EXPECT_FALSE(HitTestIsContentEditable(web_view, 75, 25)); EXPECT_EQ("areaBNotEditable", HitTestElementId(web_view, 25, 125)); EXPECT_FALSE(HitTestIsContentEditable(web_view, 25, 125)); EXPECT_EQ("imageBEditable", HitTestElementId(web_view, 75, 125)); EXPECT_TRUE(HitTestIsContentEditable(web_view, 75, 125)); EXPECT_EQ("areaCNotEditable", HitTestElementId(web_view, 25, 225)); EXPECT_FALSE(HitTestIsContentEditable(web_view, 25, 225)); EXPECT_EQ("imageCNotEditable", HitTestElementId(web_view, 75, 225)); EXPECT_FALSE(HitTestIsContentEditable(web_view, 75, 225)); EXPECT_EQ("areaDEditable", HitTestElementId(web_view, 25, 325)); EXPECT_TRUE(HitTestIsContentEditable(web_view, 25, 325)); EXPECT_EQ("imageDNotEditable", HitTestElementId(web_view, 75, 325)); EXPECT_FALSE(HitTestIsContentEditable(web_view, 75, 325)); } static std::string HitTestAbsoluteUrl(WebView* view, int x, int y) { WebPoint hit_point(x, y); WebHitTestResult hit_test_result = view->HitTestResultAt(hit_point); return hit_test_result.AbsoluteImageURL().GetString().Utf8(); } static WebElement HitTestUrlElement(WebView* view, int x, int y) { WebPoint hit_point(x, y); WebHitTestResult hit_test_result = view->HitTestResultAt(hit_point); return hit_test_result.UrlElement(); } TEST_F(WebViewTest, ImageMapUrls) { std::string url = RegisterMockedHttpURLLoad("image-map.html"); WebView* web_view = web_view_helper_.InitializeAndLoad(url); web_view->Resize(WebSize(400, 400)); std::string image_url = "data:image/gif;base64,R0lGODlhAQABAIAAAAUEBAAAACwAAAAAAQABAAACAkQBADs="; EXPECT_EQ("area", HitTestElementId(web_view, 25, 25)); EXPECT_EQ("area", HitTestUrlElement(web_view, 25, 25).GetAttribute("id").Utf8()); EXPECT_EQ(image_url, HitTestAbsoluteUrl(web_view, 25, 25)); EXPECT_EQ("image", HitTestElementId(web_view, 75, 25)); EXPECT_TRUE(HitTestUrlElement(web_view, 75, 25).IsNull()); EXPECT_EQ(image_url, HitTestAbsoluteUrl(web_view, 75, 25)); } TEST_F(WebViewTest, BrokenImage) { URLTestHelpers::RegisterMockedErrorURLLoad( KURL(ToKURL(base_url_), "non_existent.png")); std::string url = RegisterMockedHttpURLLoad("image-broken.html"); WebViewImpl* web_view = web_view_helper_.Initialize(); web_view->GetSettings()->SetLoadsImagesAutomatically(true); LoadFrame(web_view->MainFrameImpl(), url); web_view->Resize(WebSize(400, 400)); std::string image_url = "http://www.test.com/non_existent.png"; EXPECT_EQ("image", HitTestElementId(web_view, 25, 25)); EXPECT_TRUE(HitTestUrlElement(web_view, 25, 25).IsNull()); EXPECT_EQ(image_url, HitTestAbsoluteUrl(web_view, 25, 25)); } TEST_F(WebViewTest, BrokenInputImage) { URLTestHelpers::RegisterMockedErrorURLLoad( KURL(ToKURL(base_url_), "non_existent.png")); std::string url = RegisterMockedHttpURLLoad("input-image-broken.html"); WebViewImpl* web_view = web_view_helper_.Initialize(); web_view->GetSettings()->SetLoadsImagesAutomatically(true); LoadFrame(web_view->MainFrameImpl(), url); web_view->Resize(WebSize(400, 400)); std::string image_url = "http://www.test.com/non_existent.png"; EXPECT_EQ("image", HitTestElementId(web_view, 25, 25)); EXPECT_TRUE(HitTestUrlElement(web_view, 25, 25).IsNull()); EXPECT_EQ(image_url, HitTestAbsoluteUrl(web_view, 25, 25)); } TEST_F(WebViewTest, SetBaseBackgroundColor) { const SkColor kDarkCyan = SkColorSetARGB(0xFF, 0x22, 0x77, 0x88); const SkColor kTranslucentPutty = SkColorSetARGB(0x80, 0xBF, 0xB1, 0x96); WebViewImpl* web_view = web_view_helper_.Initialize(); EXPECT_EQ(SK_ColorWHITE, web_view->BackgroundColor()); web_view->SetBaseBackgroundColor(SK_ColorBLUE); EXPECT_EQ(SK_ColorBLUE, web_view->BackgroundColor()); WebURL base_url = URLTestHelpers::ToKURL("http://example.com/"); FrameTestHelpers::LoadHTMLString(web_view->MainFrameImpl(), "<html><head><style>body " "{background-color:#227788}</style></head></" "html>", base_url); EXPECT_EQ(kDarkCyan, web_view->BackgroundColor()); FrameTestHelpers::LoadHTMLString(web_view->MainFrameImpl(), "<html><head><style>body " "{background-color:rgba(255,0,0,0.5)}</" "style></head></html>", base_url); // Expected: red (50% alpha) blended atop base of SK_ColorBLUE. EXPECT_EQ(0xFF80007F, web_view->BackgroundColor()); web_view->SetBaseBackgroundColor(kTranslucentPutty); // Expected: red (50% alpha) blended atop kTranslucentPutty. Note the alpha. EXPECT_EQ(0xBFE93A31, web_view->BackgroundColor()); web_view->SetBaseBackgroundColor(SK_ColorTRANSPARENT); FrameTestHelpers::LoadHTMLString(web_view->MainFrameImpl(), "<html><head><style>body " "{background-color:transparent}</style></" "head></html>", base_url); // Expected: transparent on top of transparent will still be transparent. EXPECT_EQ(SK_ColorTRANSPARENT, web_view->BackgroundColor()); LocalFrame* frame = web_view->MainFrameImpl()->GetFrame(); // The shutdown() calls are a hack to prevent this test // from violating invariants about frame state during navigation/detach. frame->GetDocument()->Shutdown(); // Creating a new frame view with the background color having 0 alpha. frame->CreateView(IntSize(1024, 768), Color::kTransparent); EXPECT_EQ(SK_ColorTRANSPARENT, frame->View()->BaseBackgroundColor()); frame->View()->Dispose(); const Color transparent_red(100, 0, 0, 0); frame->CreateView(IntSize(1024, 768), transparent_red); EXPECT_EQ(transparent_red, frame->View()->BaseBackgroundColor()); frame->View()->Dispose(); } TEST_F(WebViewTest, SetBaseBackgroundColorBeforeMainFrame) { // Note: this test doesn't use WebViewHelper since it intentionally runs // initialization code between WebView and WebLocalFrame creation. FrameTestHelpers::TestWebViewClient web_view_client; WebViewImpl* web_view = static_cast<WebViewImpl*>(WebView::Create( &web_view_client, mojom::PageVisibilityState::kVisible, nullptr)); EXPECT_NE(SK_ColorBLUE, web_view->BackgroundColor()); // webView does not have a frame yet, but we should still be able to set the // background color. web_view->SetBaseBackgroundColor(SK_ColorBLUE); EXPECT_EQ(SK_ColorBLUE, web_view->BackgroundColor()); FrameTestHelpers::TestWebFrameClient web_frame_client; WebLocalFrame* frame = WebLocalFrame::CreateMainFrame( web_view, &web_frame_client, nullptr, nullptr); web_frame_client.Bind(frame); web_view->Close(); } TEST_F(WebViewTest, SetBaseBackgroundColorAndBlendWithExistingContent) { const SkColor kAlphaRed = SkColorSetARGB(0x80, 0xFF, 0x00, 0x00); const SkColor kAlphaGreen = SkColorSetARGB(0x80, 0x00, 0xFF, 0x00); const int kWidth = 100; const int kHeight = 100; WebViewImpl* web_view = web_view_helper_.Initialize(); // Set WebView background to green with alpha. web_view->SetBaseBackgroundColor(kAlphaGreen); web_view->GetSettings()->SetShouldClearDocumentBackground(false); web_view->Resize(WebSize(kWidth, kHeight)); web_view->UpdateAllLifecyclePhases(); // Set canvas background to red with alpha. SkBitmap bitmap; bitmap.allocN32Pixels(kWidth, kHeight); SkCanvas canvas(bitmap); canvas.clear(kAlphaRed); PaintRecordBuilder builder; // Paint the root of the main frame in the way that CompositedLayerMapping // would. LocalFrameView* view = web_view_helper_.LocalMainFrame()->GetFrameView(); PaintLayer* root_layer = view->GetLayoutView()->Layer(); LayoutRect paint_rect(0, 0, kWidth, kHeight); PaintLayerPaintingInfo painting_info(root_layer, paint_rect, kGlobalPaintNormalPhase, LayoutSize()); view->GetLayoutView()->GetDocument().Lifecycle().AdvanceTo( DocumentLifecycle::kInPaint); PaintLayerPainter(*root_layer) .PaintLayerContents(builder.Context(), painting_info, kPaintLayerPaintingCompositingAllPhases); view->GetLayoutView()->GetDocument().Lifecycle().AdvanceTo( DocumentLifecycle::kPaintClean); builder.EndRecording()->Playback(&canvas); // The result should be a blend of red and green. SkColor color = bitmap.getColor(kWidth / 2, kHeight / 2); EXPECT_TRUE(RedChannel(color)); EXPECT_TRUE(GreenChannel(color)); } TEST_F(WebViewTest, FocusIsInactive) { RegisterMockedHttpURLLoad("visible_iframe.html"); WebViewImpl* web_view = web_view_helper_.InitializeAndLoad(base_url_ + "visible_iframe.html"); web_view->SetFocus(true); web_view->SetIsActive(true); WebLocalFrameImpl* frame = web_view->MainFrameImpl(); EXPECT_TRUE(frame->GetFrame()->GetDocument()->IsHTMLDocument()); Document* document = frame->GetFrame()->GetDocument(); EXPECT_TRUE(document->hasFocus()); web_view->SetFocus(false); web_view->SetIsActive(false); EXPECT_FALSE(document->hasFocus()); web_view->SetFocus(true); web_view->SetIsActive(true); EXPECT_TRUE(document->hasFocus()); web_view->SetFocus(true); web_view->SetIsActive(false); EXPECT_FALSE(document->hasFocus()); web_view->SetFocus(false); web_view->SetIsActive(true); EXPECT_FALSE(document->hasFocus()); web_view->SetIsActive(false); web_view->SetFocus(true); EXPECT_TRUE(document->hasFocus()); web_view->SetIsActive(true); web_view->SetFocus(false); EXPECT_FALSE(document->hasFocus()); } TEST_F(WebViewTest, DocumentHasFocus) { WebViewImpl* web_view = web_view_helper_.Initialize(); web_view->SetFocus(true); WebURL base_url = URLTestHelpers::ToKURL("http://example.com/"); FrameTestHelpers::LoadHTMLString( web_view->MainFrameImpl(), "<input id=input></input>" "<div id=log></div>" "<script>" " document.getElementById('input').addEventListener('focus', () => {" " document.getElementById('log').textContent = 'document.hasFocus(): " "' + document.hasFocus();" " });" " document.getElementById('input').addEventListener('blur', () => {" " document.getElementById('log').textContent = '';" " });" " document.getElementById('input').focus();" "</script>", base_url); WebLocalFrameImpl* frame = web_view->MainFrameImpl(); Document* document = frame->GetFrame()->GetDocument(); WebElement log_element = frame->GetDocument().GetElementById("log"); EXPECT_TRUE(document->hasFocus()); EXPECT_STREQ("document.hasFocus(): true", log_element.TextContent().Utf8().data()); web_view->SetIsActive(false); web_view->SetFocus(false); EXPECT_FALSE(document->hasFocus()); EXPECT_TRUE(log_element.TextContent().IsEmpty()); web_view->SetFocus(true); EXPECT_TRUE(document->hasFocus()); EXPECT_STREQ("document.hasFocus(): true", log_element.TextContent().Utf8().data()); } TEST_F(WebViewTest, ActiveState) { RegisterMockedHttpURLLoad("visible_iframe.html"); WebView* web_view = web_view_helper_.InitializeAndLoad(base_url_ + "visible_iframe.html"); ASSERT_TRUE(web_view); web_view->SetIsActive(true); EXPECT_TRUE(web_view->IsActive()); web_view->SetIsActive(false); EXPECT_FALSE(web_view->IsActive()); web_view->SetIsActive(true); EXPECT_TRUE(web_view->IsActive()); } TEST_F(WebViewTest, HitTestResultAtWithPageScale) { std::string url = base_url_ + "specify_size.html?" + "50px" + ":" + "50px"; URLTestHelpers::RegisterMockedURLLoad( ToKURL(url), test::CoreTestDataPath("specify_size.html")); WebView* web_view = web_view_helper_.InitializeAndLoad(url); web_view->Resize(WebSize(100, 100)); WebPoint hit_point(75, 75); // Image is at top left quandrant, so should not hit it. WebHitTestResult negative_result = web_view->HitTestResultAt(hit_point); EXPECT_FALSE( negative_result.GetNode().To<WebElement>().HasHTMLTagName("img")); negative_result.Reset(); // Scale page up 2x so image should occupy the whole viewport. web_view->SetPageScaleFactor(2.0f); WebHitTestResult positive_result = web_view->HitTestResultAt(hit_point); EXPECT_TRUE(positive_result.GetNode().To<WebElement>().HasHTMLTagName("img")); positive_result.Reset(); } TEST_F(WebViewTest, HitTestResultAtWithPageScaleAndPan) { std::string url = base_url_ + "specify_size.html?" + "50px" + ":" + "50px"; URLTestHelpers::RegisterMockedURLLoad( ToKURL(url), test::CoreTestDataPath("specify_size.html")); WebViewImpl* web_view = web_view_helper_.Initialize(); LoadFrame(web_view->MainFrameImpl(), url); web_view->Resize(WebSize(100, 100)); WebPoint hit_point(75, 75); // Image is at top left quandrant, so should not hit it. WebHitTestResult negative_result = web_view->HitTestResultAt(hit_point); EXPECT_FALSE( negative_result.GetNode().To<WebElement>().HasHTMLTagName("img")); negative_result.Reset(); // Scale page up 2x so image should occupy the whole viewport. web_view->SetPageScaleFactor(2.0f); WebHitTestResult positive_result = web_view->HitTestResultAt(hit_point); EXPECT_TRUE(positive_result.GetNode().To<WebElement>().HasHTMLTagName("img")); positive_result.Reset(); // Pan around the zoomed in page so the image is not visible in viewport. web_view->SetVisualViewportOffset(WebFloatPoint(100, 100)); WebHitTestResult negative_result2 = web_view->HitTestResultAt(hit_point); EXPECT_FALSE( negative_result2.GetNode().To<WebElement>().HasHTMLTagName("img")); negative_result2.Reset(); } TEST_F(WebViewTest, HitTestResultForTapWithTapArea) { std::string url = RegisterMockedHttpURLLoad("hit_test.html"); WebView* web_view = web_view_helper_.InitializeAndLoad(url); web_view->Resize(WebSize(100, 100)); WebPoint hit_point(55, 55); // Image is at top left quandrant, so should not hit it. WebHitTestResult negative_result = web_view->HitTestResultAt(hit_point); EXPECT_FALSE( negative_result.GetNode().To<WebElement>().HasHTMLTagName("img")); negative_result.Reset(); // The tap area is 20 by 20 square, centered at 55, 55. WebSize tap_area(20, 20); WebHitTestResult positive_result = web_view->HitTestResultForTap(hit_point, tap_area); EXPECT_TRUE(positive_result.GetNode().To<WebElement>().HasHTMLTagName("img")); positive_result.Reset(); // Move the hit point the image is just outside the tapped area now. hit_point = WebPoint(61, 61); WebHitTestResult negative_result2 = web_view->HitTestResultForTap(hit_point, tap_area); EXPECT_FALSE( negative_result2.GetNode().To<WebElement>().HasHTMLTagName("img")); negative_result2.Reset(); } TEST_F(WebViewTest, HitTestResultForTapWithTapAreaPageScaleAndPan) { std::string url = RegisterMockedHttpURLLoad("hit_test.html"); WebViewImpl* web_view = web_view_helper_.Initialize(); LoadFrame(web_view->MainFrameImpl(), url); web_view->Resize(WebSize(100, 100)); WebPoint hit_point(55, 55); // Image is at top left quandrant, so should not hit it. WebHitTestResult negative_result = web_view->HitTestResultAt(hit_point); EXPECT_FALSE( negative_result.GetNode().To<WebElement>().HasHTMLTagName("img")); negative_result.Reset(); // The tap area is 20 by 20 square, centered at 55, 55. WebSize tap_area(20, 20); WebHitTestResult positive_result = web_view->HitTestResultForTap(hit_point, tap_area); EXPECT_TRUE(positive_result.GetNode().To<WebElement>().HasHTMLTagName("img")); positive_result.Reset(); // Zoom in and pan around the page so the image is not visible in viewport. web_view->SetPageScaleFactor(2.0f); web_view->SetVisualViewportOffset(WebFloatPoint(100, 100)); WebHitTestResult negative_result2 = web_view->HitTestResultForTap(hit_point, tap_area); EXPECT_FALSE( negative_result2.GetNode().To<WebElement>().HasHTMLTagName("img")); negative_result2.Reset(); } void WebViewTest::TestAutoResize( const WebSize& min_auto_resize, const WebSize& max_auto_resize, const std::string& page_width, const std::string& page_height, int expected_width, int expected_height, HorizontalScrollbarState expected_horizontal_state, VerticalScrollbarState expected_vertical_state) { AutoResizeWebViewClient client; std::string url = base_url_ + "specify_size.html?" + page_width + ":" + page_height; URLTestHelpers::RegisterMockedURLLoad( ToKURL(url), test::CoreTestDataPath("specify_size.html")); WebViewImpl* web_view = web_view_helper_.InitializeAndLoad(url, nullptr, &client); client.GetTestData().SetWebView(web_view); WebLocalFrameImpl* frame = web_view->MainFrameImpl(); LocalFrameView* frame_view = frame->GetFrame()->View(); frame_view->UpdateLayout(); EXPECT_FALSE(frame_view->LayoutPending()); EXPECT_FALSE(frame_view->NeedsLayout()); web_view->EnableAutoResizeMode(min_auto_resize, max_auto_resize); EXPECT_TRUE(frame_view->LayoutPending()); EXPECT_TRUE(frame_view->NeedsLayout()); frame_view->UpdateLayout(); EXPECT_TRUE(frame->GetFrame()->GetDocument()->IsHTMLDocument()); EXPECT_EQ(expected_width, client.GetTestData().Width()); EXPECT_EQ(expected_height, client.GetTestData().Height()); // Android disables main frame scrollbars. #if !defined(OS_ANDROID) EXPECT_EQ(expected_horizontal_state, client.GetTestData().GetHorizontalScrollbarState()); EXPECT_EQ(expected_vertical_state, client.GetTestData().GetVerticalScrollbarState()); #endif // Explicitly reset to break dependency on locally scoped client. web_view_helper_.Reset(); } TEST_F(WebViewTest, AutoResizeMinimumSize) { WebSize min_auto_resize(91, 56); WebSize max_auto_resize(403, 302); std::string page_width = "91px"; std::string page_height = "56px"; int expected_width = 91; int expected_height = 56; TestAutoResize(min_auto_resize, max_auto_resize, page_width, page_height, expected_width, expected_height, kNoHorizontalScrollbar, kNoVerticalScrollbar); } TEST_F(WebViewTest, AutoResizeHeightOverflowAndFixedWidth) { WebSize min_auto_resize(90, 95); WebSize max_auto_resize(90, 100); std::string page_width = "60px"; std::string page_height = "200px"; int expected_width = 90; int expected_height = 100; TestAutoResize(min_auto_resize, max_auto_resize, page_width, page_height, expected_width, expected_height, kNoHorizontalScrollbar, kVisibleVerticalScrollbar); } TEST_F(WebViewTest, AutoResizeFixedHeightAndWidthOverflow) { WebSize min_auto_resize(90, 100); WebSize max_auto_resize(200, 100); std::string page_width = "300px"; std::string page_height = "80px"; int expected_width = 200; int expected_height = 100; TestAutoResize(min_auto_resize, max_auto_resize, page_width, page_height, expected_width, expected_height, kVisibleHorizontalScrollbar, kNoVerticalScrollbar); } // Next three tests disabled for https://bugs.webkit.org/show_bug.cgi?id=92318 . // It seems we can run three AutoResize tests, then the next one breaks. TEST_F(WebViewTest, AutoResizeInBetweenSizes) { WebSize min_auto_resize(90, 95); WebSize max_auto_resize(200, 300); std::string page_width = "100px"; std::string page_height = "200px"; int expected_width = 100; int expected_height = 200; TestAutoResize(min_auto_resize, max_auto_resize, page_width, page_height, expected_width, expected_height, kNoHorizontalScrollbar, kNoVerticalScrollbar); } TEST_F(WebViewTest, AutoResizeOverflowSizes) { WebSize min_auto_resize(90, 95); WebSize max_auto_resize(200, 300); std::string page_width = "300px"; std::string page_height = "400px"; int expected_width = 200; int expected_height = 300; TestAutoResize(min_auto_resize, max_auto_resize, page_width, page_height, expected_width, expected_height, kVisibleHorizontalScrollbar, kVisibleVerticalScrollbar); } TEST_F(WebViewTest, AutoResizeMaxSize) { WebSize min_auto_resize(90, 95); WebSize max_auto_resize(200, 300); std::string page_width = "200px"; std::string page_height = "300px"; int expected_width = 200; int expected_height = 300; TestAutoResize(min_auto_resize, max_auto_resize, page_width, page_height, expected_width, expected_height, kNoHorizontalScrollbar, kNoVerticalScrollbar); } void WebViewTest::TestTextInputType(WebTextInputType expected_type, const std::string& html_file) { RegisterMockedHttpURLLoad(html_file); WebViewImpl* web_view = web_view_helper_.InitializeAndLoad(base_url_ + html_file); WebInputMethodController* controller = web_view->MainFrameImpl()->GetInputMethodController(); EXPECT_EQ(kWebTextInputTypeNone, controller->TextInputType()); EXPECT_EQ(kWebTextInputTypeNone, controller->TextInputInfo().type); web_view->SetInitialFocus(false); EXPECT_EQ(expected_type, controller->TextInputType()); EXPECT_EQ(expected_type, controller->TextInputInfo().type); web_view->ClearFocusedElement(); EXPECT_EQ(kWebTextInputTypeNone, controller->TextInputType()); EXPECT_EQ(kWebTextInputTypeNone, controller->TextInputInfo().type); } TEST_F(WebViewTest, TextInputType) { TestTextInputType(kWebTextInputTypeText, "input_field_default.html"); TestTextInputType(kWebTextInputTypePassword, "input_field_password.html"); TestTextInputType(kWebTextInputTypeEmail, "input_field_email.html"); TestTextInputType(kWebTextInputTypeSearch, "input_field_search.html"); TestTextInputType(kWebTextInputTypeNumber, "input_field_number.html"); TestTextInputType(kWebTextInputTypeTelephone, "input_field_tel.html"); TestTextInputType(kWebTextInputTypeURL, "input_field_url.html"); } TEST_F(WebViewTest, TextInputInfoUpdateStyleAndLayout) { FrameTestHelpers::WebViewHelper web_view_helper; WebViewImpl* web_view_impl = web_view_helper.Initialize(); WebURL base_url = URLTestHelpers::ToKURL("http://example.com/"); // Here, we need to construct a document that has a special property: // Adding id="foo" to the <path> element will trigger creation of an SVG // instance tree for the use <use> element. // This is significant, because SVG instance trees are actually created lazily // during Document::updateStyleAndLayout code, thus incrementing the DOM tree // version and freaking out the EphemeralRange (invalidating it). FrameTestHelpers::LoadHTMLString( web_view_impl->MainFrameImpl(), "<svg height='100%' version='1.1' viewBox='0 0 14 14' width='100%'>" "<use xmlns:xlink='http://www.w3.org/1999/xlink' xlink:href='#foo'></use>" "<path d='M 100 100 L 300 100 L 200 300 z' fill='#000'></path>" "</svg>" "<input>", base_url); web_view_impl->SetInitialFocus(false); // Add id="foo" to <path>, thus triggering the condition described above. Document* document = web_view_impl->MainFrameImpl()->GetFrame()->GetDocument(); document->body() ->QuerySelector("path", ASSERT_NO_EXCEPTION) ->SetIdAttribute("foo"); // This should not DCHECK. EXPECT_EQ(kWebTextInputTypeText, web_view_impl->MainFrameImpl() ->GetInputMethodController() ->TextInputInfo() .type); } void WebViewTest::TestInputMode(WebTextInputMode expected_input_mode, const std::string& html_file) { RegisterMockedHttpURLLoad(html_file); WebViewImpl* web_view_impl = web_view_helper_.InitializeAndLoad(base_url_ + html_file); web_view_impl->SetInitialFocus(false); EXPECT_EQ(expected_input_mode, web_view_impl->MainFrameImpl() ->GetInputMethodController() ->TextInputInfo() .input_mode); } TEST_F(WebViewTest, InputMode) { TestInputMode(WebTextInputMode::kWebTextInputModeDefault, "input_mode_default.html"); TestInputMode(WebTextInputMode::kWebTextInputModeDefault, "input_mode_default_unknown.html"); TestInputMode(WebTextInputMode::kWebTextInputModeNone, "input_mode_type_none.html"); TestInputMode(WebTextInputMode::kWebTextInputModeText, "input_mode_type_text.html"); TestInputMode(WebTextInputMode::kWebTextInputModeTel, "input_mode_type_tel.html"); TestInputMode(WebTextInputMode::kWebTextInputModeUrl, "input_mode_type_url.html"); TestInputMode(WebTextInputMode::kWebTextInputModeEmail, "input_mode_type_email.html"); TestInputMode(WebTextInputMode::kWebTextInputModeNumeric, "input_mode_type_numeric.html"); TestInputMode(WebTextInputMode::kWebTextInputModeDecimal, "input_mode_type_decimal.html"); TestInputMode(WebTextInputMode::kWebTextInputModeSearch, "input_mode_type_search.html"); } TEST_F(WebViewTest, TextInputInfoWithReplacedElements) { std::string url = RegisterMockedHttpURLLoad("div_with_image.html"); URLTestHelpers::RegisterMockedURLLoad( ToKURL("http://www.test.com/foo.png"), test::CoreTestDataPath("white-1x1.png")); WebViewImpl* web_view_impl = web_view_helper_.InitializeAndLoad(url); web_view_impl->SetInitialFocus(false); WebTextInputInfo info = web_view_impl->MainFrameImpl() ->GetInputMethodController() ->TextInputInfo(); EXPECT_EQ("foo\xef\xbf\xbc", info.value.Utf8()); } TEST_F(WebViewTest, SetEditableSelectionOffsetsAndTextInputInfo) { RegisterMockedHttpURLLoad("input_field_populated.html"); WebViewImpl* web_view = web_view_helper_.InitializeAndLoad( base_url_ + "input_field_populated.html"); web_view->SetInitialFocus(false); WebLocalFrameImpl* frame = web_view->MainFrameImpl(); WebInputMethodController* active_input_method_controller = frame->GetInputMethodController(); frame->SetEditableSelectionOffsets(5, 13); EXPECT_EQ("56789abc", frame->SelectionAsText()); WebTextInputInfo info = active_input_method_controller->TextInputInfo(); EXPECT_EQ("0123456789abcdefghijklmnopqrstuvwxyz", info.value); EXPECT_EQ(5, info.selection_start); EXPECT_EQ(13, info.selection_end); EXPECT_EQ(-1, info.composition_start); EXPECT_EQ(-1, info.composition_end); RegisterMockedHttpURLLoad("content_editable_populated.html"); web_view = web_view_helper_.InitializeAndLoad( base_url_ + "content_editable_populated.html"); web_view->SetInitialFocus(false); frame = web_view->MainFrameImpl(); active_input_method_controller = frame->GetInputMethodController(); frame->SetEditableSelectionOffsets(8, 19); EXPECT_EQ("89abcdefghi", frame->SelectionAsText()); info = active_input_method_controller->TextInputInfo(); EXPECT_EQ("0123456789abcdefghijklmnopqrstuvwxyz", info.value); EXPECT_EQ(8, info.selection_start); EXPECT_EQ(19, info.selection_end); EXPECT_EQ(-1, info.composition_start); EXPECT_EQ(-1, info.composition_end); } // Regression test for crbug.com/663645 TEST_F(WebViewTest, FinishComposingTextDoesNotAssert) { RegisterMockedHttpURLLoad("input_field_default.html"); WebViewImpl* web_view = web_view_helper_.InitializeAndLoad( base_url_ + "input_field_default.html"); web_view->SetInitialFocus(false); WebInputMethodController* active_input_method_controller = web_view->MainFrameImpl() ->FrameWidget() ->GetActiveWebInputMethodController(); // The test requires non-empty composition. std::string composition_text("hello"); WebVector<WebImeTextSpan> empty_ime_text_spans; active_input_method_controller->SetComposition( WebString::FromUTF8(composition_text.c_str()), empty_ime_text_spans, WebRange(), 5, 5); // Do arbitrary change to make layout dirty. Document& document = *web_view->MainFrameImpl()->GetFrame()->GetDocument(); Element* br = document.CreateRawElement(HTMLNames::brTag); document.body()->AppendChild(br); // Should not hit assertion when calling // WebInputMethodController::finishComposingText with non-empty composition // and dirty layout. active_input_method_controller->FinishComposingText( WebInputMethodController::kKeepSelection); } TEST_F(WebViewTest, FinishComposingTextCursorPositionChange) { RegisterMockedHttpURLLoad("input_field_populated.html"); WebViewImpl* web_view = web_view_helper_.InitializeAndLoad( base_url_ + "input_field_populated.html"); web_view->SetInitialFocus(false); // Set up a composition that needs to be committed. std::string composition_text("hello"); WebInputMethodController* active_input_method_controller = web_view->MainFrameImpl() ->FrameWidget() ->GetActiveWebInputMethodController(); WebVector<WebImeTextSpan> empty_ime_text_spans; active_input_method_controller->SetComposition( WebString::FromUTF8(composition_text.c_str()), empty_ime_text_spans, WebRange(), 3, 3); WebTextInputInfo info = active_input_method_controller->TextInputInfo(); EXPECT_EQ("hello", std::string(info.value.Utf8().data())); EXPECT_EQ(3, info.selection_start); EXPECT_EQ(3, info.selection_end); EXPECT_EQ(0, info.composition_start); EXPECT_EQ(5, info.composition_end); active_input_method_controller->FinishComposingText( WebInputMethodController::kKeepSelection); info = active_input_method_controller->TextInputInfo(); EXPECT_EQ(3, info.selection_start); EXPECT_EQ(3, info.selection_end); EXPECT_EQ(-1, info.composition_start); EXPECT_EQ(-1, info.composition_end); active_input_method_controller->SetComposition( WebString::FromUTF8(composition_text.c_str()), empty_ime_text_spans, WebRange(), 3, 3); info = active_input_method_controller->TextInputInfo(); EXPECT_EQ("helhellolo", std::string(info.value.Utf8().data())); EXPECT_EQ(6, info.selection_start); EXPECT_EQ(6, info.selection_end); EXPECT_EQ(3, info.composition_start); EXPECT_EQ(8, info.composition_end); active_input_method_controller->FinishComposingText( WebInputMethodController::kDoNotKeepSelection); info = active_input_method_controller->TextInputInfo(); EXPECT_EQ(8, info.selection_start); EXPECT_EQ(8, info.selection_end); EXPECT_EQ(-1, info.composition_start); EXPECT_EQ(-1, info.composition_end); } TEST_F(WebViewTest, SetCompositionForNewCaretPositions) { RegisterMockedHttpURLLoad("input_field_populated.html"); WebViewImpl* web_view = web_view_helper_.InitializeAndLoad( base_url_ + "input_field_populated.html"); web_view->SetInitialFocus(false); WebInputMethodController* active_input_method_controller = web_view->MainFrameImpl() ->FrameWidget() ->GetActiveWebInputMethodController(); WebVector<WebImeTextSpan> empty_ime_text_spans; active_input_method_controller->CommitText("hello", empty_ime_text_spans, WebRange(), 0); active_input_method_controller->CommitText("world", empty_ime_text_spans, WebRange(), -5); WebTextInputInfo info = active_input_method_controller->TextInputInfo(); EXPECT_EQ("helloworld", std::string(info.value.Utf8().data())); EXPECT_EQ(5, info.selection_start); EXPECT_EQ(5, info.selection_end); EXPECT_EQ(-1, info.composition_start); EXPECT_EQ(-1, info.composition_end); // Set up a composition that needs to be committed. std::string composition_text("ABC"); // Caret is on the left of composing text. active_input_method_controller->SetComposition( WebString::FromUTF8(composition_text.c_str()), empty_ime_text_spans, WebRange(), 0, 0); info = active_input_method_controller->TextInputInfo(); EXPECT_EQ("helloABCworld", std::string(info.value.Utf8().data())); EXPECT_EQ(5, info.selection_start); EXPECT_EQ(5, info.selection_end); EXPECT_EQ(5, info.composition_start); EXPECT_EQ(8, info.composition_end); // Caret is on the right of composing text. active_input_method_controller->SetComposition( WebString::FromUTF8(composition_text.c_str()), empty_ime_text_spans, WebRange(), 3, 3); info = active_input_method_controller->TextInputInfo(); EXPECT_EQ("helloABCworld", std::string(info.value.Utf8().data())); EXPECT_EQ(8, info.selection_start); EXPECT_EQ(8, info.selection_end); EXPECT_EQ(5, info.composition_start); EXPECT_EQ(8, info.composition_end); // Caret is between composing text and left boundary. active_input_method_controller->SetComposition( WebString::FromUTF8(composition_text.c_str()), empty_ime_text_spans, WebRange(), -2, -2); info = active_input_method_controller->TextInputInfo(); EXPECT_EQ("helloABCworld", std::string(info.value.Utf8().data())); EXPECT_EQ(3, info.selection_start); EXPECT_EQ(3, info.selection_end); EXPECT_EQ(5, info.composition_start); EXPECT_EQ(8, info.composition_end); // Caret is between composing text and right boundary. active_input_method_controller->SetComposition( WebString::FromUTF8(composition_text.c_str()), empty_ime_text_spans, WebRange(), 5, 5); info = active_input_method_controller->TextInputInfo(); EXPECT_EQ("helloABCworld", std::string(info.value.Utf8().data())); EXPECT_EQ(10, info.selection_start); EXPECT_EQ(10, info.selection_end); EXPECT_EQ(5, info.composition_start); EXPECT_EQ(8, info.composition_end); // Caret is on the left boundary. active_input_method_controller->SetComposition( WebString::FromUTF8(composition_text.c_str()), empty_ime_text_spans, WebRange(), -5, -5); info = active_input_method_controller->TextInputInfo(); EXPECT_EQ("helloABCworld", std::string(info.value.Utf8().data())); EXPECT_EQ(0, info.selection_start); EXPECT_EQ(0, info.selection_end); EXPECT_EQ(5, info.composition_start); EXPECT_EQ(8, info.composition_end); // Caret is on the right boundary. active_input_method_controller->SetComposition( WebString::FromUTF8(composition_text.c_str()), empty_ime_text_spans, WebRange(), 8, 8); info = active_input_method_controller->TextInputInfo(); EXPECT_EQ("helloABCworld", std::string(info.value.Utf8().data())); EXPECT_EQ(13, info.selection_start); EXPECT_EQ(13, info.selection_end); EXPECT_EQ(5, info.composition_start); EXPECT_EQ(8, info.composition_end); // Caret exceeds the left boundary. active_input_method_controller->SetComposition( WebString::FromUTF8(composition_text.c_str()), empty_ime_text_spans, WebRange(), -100, -100); info = active_input_method_controller->TextInputInfo(); EXPECT_EQ("helloABCworld", std::string(info.value.Utf8().data())); EXPECT_EQ(0, info.selection_start); EXPECT_EQ(0, info.selection_end); EXPECT_EQ(5, info.composition_start); EXPECT_EQ(8, info.composition_end); // Caret exceeds the right boundary. active_input_method_controller->SetComposition( WebString::FromUTF8(composition_text.c_str()), empty_ime_text_spans, WebRange(), 100, 100); info = active_input_method_controller->TextInputInfo(); EXPECT_EQ("helloABCworld", std::string(info.value.Utf8().data())); EXPECT_EQ(13, info.selection_start); EXPECT_EQ(13, info.selection_end); EXPECT_EQ(5, info.composition_start); EXPECT_EQ(8, info.composition_end); } TEST_F(WebViewTest, SetCompositionWithEmptyText) { RegisterMockedHttpURLLoad("input_field_populated.html"); WebViewImpl* web_view = web_view_helper_.InitializeAndLoad( base_url_ + "input_field_populated.html"); web_view->SetInitialFocus(false); WebInputMethodController* active_input_method_controller = web_view->MainFrameImpl() ->FrameWidget() ->GetActiveWebInputMethodController(); WebVector<WebImeTextSpan> empty_ime_text_spans; active_input_method_controller->CommitText("hello", empty_ime_text_spans, WebRange(), 0); WebTextInputInfo info = active_input_method_controller->TextInputInfo(); EXPECT_EQ("hello", std::string(info.value.Utf8().data())); EXPECT_EQ(5, info.selection_start); EXPECT_EQ(5, info.selection_end); EXPECT_EQ(-1, info.composition_start); EXPECT_EQ(-1, info.composition_end); active_input_method_controller->SetComposition( WebString::FromUTF8(""), empty_ime_text_spans, WebRange(), 0, 0); info = active_input_method_controller->TextInputInfo(); EXPECT_EQ("hello", std::string(info.value.Utf8().data())); EXPECT_EQ(5, info.selection_start); EXPECT_EQ(5, info.selection_end); EXPECT_EQ(-1, info.composition_start); EXPECT_EQ(-1, info.composition_end); active_input_method_controller->SetComposition( WebString::FromUTF8(""), empty_ime_text_spans, WebRange(), -2, -2); info = active_input_method_controller->TextInputInfo(); EXPECT_EQ("hello", std::string(info.value.Utf8().data())); EXPECT_EQ(3, info.selection_start); EXPECT_EQ(3, info.selection_end); EXPECT_EQ(-1, info.composition_start); EXPECT_EQ(-1, info.composition_end); } TEST_F(WebViewTest, CommitTextForNewCaretPositions) { RegisterMockedHttpURLLoad("input_field_populated.html"); WebViewImpl* web_view = web_view_helper_.InitializeAndLoad( base_url_ + "input_field_populated.html"); web_view->SetInitialFocus(false); WebInputMethodController* active_input_method_controller = web_view->MainFrameImpl() ->FrameWidget() ->GetActiveWebInputMethodController(); WebVector<WebImeTextSpan> empty_ime_text_spans; // Caret is on the left of composing text. active_input_method_controller->CommitText("ab", empty_ime_text_spans, WebRange(), -2); WebTextInputInfo info = active_input_method_controller->TextInputInfo(); EXPECT_EQ("ab", std::string(info.value.Utf8().data())); EXPECT_EQ(0, info.selection_start); EXPECT_EQ(0, info.selection_end); EXPECT_EQ(-1, info.composition_start); EXPECT_EQ(-1, info.composition_end); // Caret is on the right of composing text. active_input_method_controller->CommitText("c", empty_ime_text_spans, WebRange(), 1); info = active_input_method_controller->TextInputInfo(); EXPECT_EQ("cab", std::string(info.value.Utf8().data())); EXPECT_EQ(2, info.selection_start); EXPECT_EQ(2, info.selection_end); EXPECT_EQ(-1, info.composition_start); EXPECT_EQ(-1, info.composition_end); // Caret is on the left boundary. active_input_method_controller->CommitText("def", empty_ime_text_spans, WebRange(), -5); info = active_input_method_controller->TextInputInfo(); EXPECT_EQ("cadefb", std::string(info.value.Utf8().data())); EXPECT_EQ(0, info.selection_start); EXPECT_EQ(0, info.selection_end); EXPECT_EQ(-1, info.composition_start); EXPECT_EQ(-1, info.composition_end); // Caret is on the right boundary. active_input_method_controller->CommitText("g", empty_ime_text_spans, WebRange(), 6); info = active_input_method_controller->TextInputInfo(); EXPECT_EQ("gcadefb", std::string(info.value.Utf8().data())); EXPECT_EQ(7, info.selection_start); EXPECT_EQ(7, info.selection_end); EXPECT_EQ(-1, info.composition_start); EXPECT_EQ(-1, info.composition_end); // Caret exceeds the left boundary. active_input_method_controller->CommitText("hi", empty_ime_text_spans, WebRange(), -100); info = active_input_method_controller->TextInputInfo(); EXPECT_EQ("gcadefbhi", std::string(info.value.Utf8().data())); EXPECT_EQ(0, info.selection_start); EXPECT_EQ(0, info.selection_end); EXPECT_EQ(-1, info.composition_start); EXPECT_EQ(-1, info.composition_end); // Caret exceeds the right boundary. active_input_method_controller->CommitText("jk", empty_ime_text_spans, WebRange(), 100); info = active_input_method_controller->TextInputInfo(); EXPECT_EQ("jkgcadefbhi", std::string(info.value.Utf8().data())); EXPECT_EQ(11, info.selection_start); EXPECT_EQ(11, info.selection_end); EXPECT_EQ(-1, info.composition_start); EXPECT_EQ(-1, info.composition_end); } TEST_F(WebViewTest, CommitTextWhileComposing) { RegisterMockedHttpURLLoad("input_field_populated.html"); WebViewImpl* web_view = web_view_helper_.InitializeAndLoad( base_url_ + "input_field_populated.html"); web_view->SetInitialFocus(false); WebInputMethodController* active_input_method_controller = web_view->MainFrameImpl() ->FrameWidget() ->GetActiveWebInputMethodController(); WebVector<WebImeTextSpan> empty_ime_text_spans; active_input_method_controller->SetComposition( WebString::FromUTF8("abc"), empty_ime_text_spans, WebRange(), 0, 0); WebTextInputInfo info = active_input_method_controller->TextInputInfo(); EXPECT_EQ("abc", std::string(info.value.Utf8().data())); EXPECT_EQ(0, info.selection_start); EXPECT_EQ(0, info.selection_end); EXPECT_EQ(0, info.composition_start); EXPECT_EQ(3, info.composition_end); // Deletes ongoing composition, inserts the specified text and moves the // caret. active_input_method_controller->CommitText("hello", empty_ime_text_spans, WebRange(), -2); info = active_input_method_controller->TextInputInfo(); EXPECT_EQ("hello", std::string(info.value.Utf8().data())); EXPECT_EQ(3, info.selection_start); EXPECT_EQ(3, info.selection_end); EXPECT_EQ(-1, info.composition_start); EXPECT_EQ(-1, info.composition_end); active_input_method_controller->SetComposition( WebString::FromUTF8("abc"), empty_ime_text_spans, WebRange(), 0, 0); info = active_input_method_controller->TextInputInfo(); EXPECT_EQ("helabclo", std::string(info.value.Utf8().data())); EXPECT_EQ(3, info.selection_start); EXPECT_EQ(3, info.selection_end); EXPECT_EQ(3, info.composition_start); EXPECT_EQ(6, info.composition_end); // Deletes ongoing composition and moves the caret. active_input_method_controller->CommitText("", empty_ime_text_spans, WebRange(), 2); info = active_input_method_controller->TextInputInfo(); EXPECT_EQ("hello", std::string(info.value.Utf8().data())); EXPECT_EQ(5, info.selection_start); EXPECT_EQ(5, info.selection_end); EXPECT_EQ(-1, info.composition_start); EXPECT_EQ(-1, info.composition_end); // Inserts the specified text and moves the caret. active_input_method_controller->CommitText("world", empty_ime_text_spans, WebRange(), -5); info = active_input_method_controller->TextInputInfo(); EXPECT_EQ("helloworld", std::string(info.value.Utf8().data())); EXPECT_EQ(5, info.selection_start); EXPECT_EQ(5, info.selection_end); EXPECT_EQ(-1, info.composition_start); EXPECT_EQ(-1, info.composition_end); // Only moves the caret. active_input_method_controller->CommitText("", empty_ime_text_spans, WebRange(), 5); info = active_input_method_controller->TextInputInfo(); EXPECT_EQ("helloworld", std::string(info.value.Utf8().data())); EXPECT_EQ(10, info.selection_start); EXPECT_EQ(10, info.selection_end); EXPECT_EQ(-1, info.composition_start); EXPECT_EQ(-1, info.composition_end); } TEST_F(WebViewTest, FinishCompositionDoesNotRevealSelection) { RegisterMockedHttpURLLoad("form_with_input.html"); WebViewImpl* web_view = web_view_helper_.InitializeAndLoad(base_url_ + "form_with_input.html"); web_view->Resize(WebSize(800, 600)); web_view->SetInitialFocus(false); EXPECT_EQ(0, web_view->MainFrameImpl()->GetScrollOffset().width); EXPECT_EQ(0, web_view->MainFrameImpl()->GetScrollOffset().height); // Set up a composition from existing text that needs to be committed. Vector<ImeTextSpan> empty_ime_text_spans; WebLocalFrameImpl* frame = web_view->MainFrameImpl(); frame->GetFrame()->GetInputMethodController().SetCompositionFromExistingText( empty_ime_text_spans, 0, 3); // Scroll the input field out of the viewport. Element* element = static_cast<Element*>( web_view->MainFrameImpl()->GetDocument().GetElementById("btn")); element->scrollIntoView(); float offset_height = web_view->MainFrameImpl()->GetScrollOffset().height; EXPECT_EQ(0, web_view->MainFrameImpl()->GetScrollOffset().width); EXPECT_LT(0, offset_height); WebTextInputInfo info = frame->GetInputMethodController()->TextInputInfo(); EXPECT_EQ("hello", std::string(info.value.Utf8().data())); // Verify that the input field is not scrolled back into the viewport. frame->FrameWidget() ->GetActiveWebInputMethodController() ->FinishComposingText(WebInputMethodController::kDoNotKeepSelection); EXPECT_EQ(0, web_view->MainFrameImpl()->GetScrollOffset().width); EXPECT_EQ(offset_height, web_view->MainFrameImpl()->GetScrollOffset().height); } TEST_F(WebViewTest, InsertNewLinePlacementAfterFinishComposingText) { RegisterMockedHttpURLLoad("text_area_populated.html"); WebViewImpl* web_view = web_view_helper_.InitializeAndLoad( base_url_ + "text_area_populated.html"); web_view->SetInitialFocus(false); WebVector<WebImeTextSpan> empty_ime_text_spans; WebLocalFrameImpl* frame = web_view->MainFrameImpl(); WebInputMethodController* active_input_method_controller = frame->GetInputMethodController(); frame->SetEditableSelectionOffsets(4, 4); frame->SetCompositionFromExistingText(8, 12, empty_ime_text_spans); WebTextInputInfo info = active_input_method_controller->TextInputInfo(); EXPECT_EQ("0123456789abcdefghijklmnopqrstuvwxyz", std::string(info.value.Utf8().data())); EXPECT_EQ(4, info.selection_start); EXPECT_EQ(4, info.selection_end); EXPECT_EQ(8, info.composition_start); EXPECT_EQ(12, info.composition_end); active_input_method_controller->FinishComposingText( WebInputMethodController::kKeepSelection); info = active_input_method_controller->TextInputInfo(); EXPECT_EQ(4, info.selection_start); EXPECT_EQ(4, info.selection_end); EXPECT_EQ(-1, info.composition_start); EXPECT_EQ(-1, info.composition_end); std::string composition_text("\n"); active_input_method_controller->CommitText( WebString::FromUTF8(composition_text.c_str()), empty_ime_text_spans, WebRange(), 0); info = active_input_method_controller->TextInputInfo(); EXPECT_EQ(5, info.selection_start); EXPECT_EQ(5, info.selection_end); EXPECT_EQ(-1, info.composition_start); EXPECT_EQ(-1, info.composition_end); EXPECT_EQ("0123\n456789abcdefghijklmnopqrstuvwxyz", std::string(info.value.Utf8().data())); } TEST_F(WebViewTest, ExtendSelectionAndDelete) { RegisterMockedHttpURLLoad("input_field_populated.html"); WebViewImpl* web_view = web_view_helper_.InitializeAndLoad( base_url_ + "input_field_populated.html"); WebLocalFrameImpl* frame = web_view->MainFrameImpl(); web_view->SetInitialFocus(false); frame->SetEditableSelectionOffsets(10, 10); frame->ExtendSelectionAndDelete(5, 8); WebInputMethodController* active_input_method_controller = frame->GetInputMethodController(); WebTextInputInfo info = active_input_method_controller->TextInputInfo(); EXPECT_EQ("01234ijklmnopqrstuvwxyz", std::string(info.value.Utf8().data())); EXPECT_EQ(5, info.selection_start); EXPECT_EQ(5, info.selection_end); frame->ExtendSelectionAndDelete(10, 0); info = active_input_method_controller->TextInputInfo(); EXPECT_EQ("ijklmnopqrstuvwxyz", std::string(info.value.Utf8().data())); } TEST_F(WebViewTest, DeleteSurroundingText) { RegisterMockedHttpURLLoad("input_field_populated.html"); WebView* web_view = web_view_helper_.InitializeAndLoad( base_url_ + "input_field_populated.html"); WebLocalFrameImpl* frame = ToWebLocalFrameImpl(web_view->MainFrame()); WebInputMethodController* active_input_method_controller = frame->GetInputMethodController(); web_view->SetInitialFocus(false); frame->SetEditableSelectionOffsets(10, 10); frame->DeleteSurroundingText(5, 8); WebTextInputInfo info = active_input_method_controller->TextInputInfo(); EXPECT_EQ("01234ijklmnopqrstuvwxyz", std::string(info.value.Utf8().data())); EXPECT_EQ(5, info.selection_start); EXPECT_EQ(5, info.selection_end); frame->SetEditableSelectionOffsets(5, 10); frame->DeleteSurroundingText(3, 5); info = active_input_method_controller->TextInputInfo(); EXPECT_EQ("01ijklmstuvwxyz", std::string(info.value.Utf8().data())); EXPECT_EQ(2, info.selection_start); EXPECT_EQ(7, info.selection_end); frame->SetEditableSelectionOffsets(5, 5); frame->DeleteSurroundingText(10, 0); info = active_input_method_controller->TextInputInfo(); EXPECT_EQ("lmstuvwxyz", std::string(info.value.Utf8().data())); EXPECT_EQ(0, info.selection_start); EXPECT_EQ(0, info.selection_end); frame->DeleteSurroundingText(0, 20); info = active_input_method_controller->TextInputInfo(); EXPECT_EQ("", std::string(info.value.Utf8().data())); EXPECT_EQ(0, info.selection_start); EXPECT_EQ(0, info.selection_end); frame->DeleteSurroundingText(10, 10); info = active_input_method_controller->TextInputInfo(); EXPECT_EQ("", std::string(info.value.Utf8().data())); EXPECT_EQ(0, info.selection_start); EXPECT_EQ(0, info.selection_end); } TEST_F(WebViewTest, SetCompositionFromExistingText) { RegisterMockedHttpURLLoad("input_field_populated.html"); WebViewImpl* web_view = web_view_helper_.InitializeAndLoad( base_url_ + "input_field_populated.html"); web_view->SetInitialFocus(false); WebVector<WebImeTextSpan> ime_text_spans(static_cast<size_t>(1)); ime_text_spans[0] = WebImeTextSpan(WebImeTextSpan::Type::kComposition, 0, 4, ui::mojom::ImeTextSpanThickness::kThin, 0); WebLocalFrameImpl* frame = web_view->MainFrameImpl(); WebInputMethodController* active_input_method_controller = frame->GetInputMethodController(); frame->SetEditableSelectionOffsets(4, 10); frame->SetCompositionFromExistingText(8, 12, ime_text_spans); WebTextInputInfo info = active_input_method_controller->TextInputInfo(); EXPECT_EQ(4, info.selection_start); EXPECT_EQ(10, info.selection_end); EXPECT_EQ(8, info.composition_start); EXPECT_EQ(12, info.composition_end); WebVector<WebImeTextSpan> empty_ime_text_spans; frame->SetCompositionFromExistingText(0, 0, empty_ime_text_spans); info = active_input_method_controller->TextInputInfo(); EXPECT_EQ(4, info.selection_start); EXPECT_EQ(10, info.selection_end); EXPECT_EQ(-1, info.composition_start); EXPECT_EQ(-1, info.composition_end); } TEST_F(WebViewTest, SetCompositionFromExistingTextInTextArea) { RegisterMockedHttpURLLoad("text_area_populated.html"); WebViewImpl* web_view = web_view_helper_.InitializeAndLoad( base_url_ + "text_area_populated.html"); web_view->SetInitialFocus(false); WebVector<WebImeTextSpan> ime_text_spans(static_cast<size_t>(1)); ime_text_spans[0] = WebImeTextSpan(WebImeTextSpan::Type::kComposition, 0, 4, ui::mojom::ImeTextSpanThickness::kThin, 0); WebLocalFrameImpl* frame = web_view->MainFrameImpl(); WebInputMethodController* active_input_method_controller = frame->FrameWidget()->GetActiveWebInputMethodController(); frame->SetEditableSelectionOffsets(27, 27); std::string new_line_text("\n"); WebVector<WebImeTextSpan> empty_ime_text_spans; active_input_method_controller->CommitText( WebString::FromUTF8(new_line_text.c_str()), empty_ime_text_spans, WebRange(), 0); WebTextInputInfo info = active_input_method_controller->TextInputInfo(); EXPECT_EQ("0123456789abcdefghijklmnopq\nrstuvwxyz", std::string(info.value.Utf8().data())); frame->SetEditableSelectionOffsets(31, 31); frame->SetCompositionFromExistingText(30, 34, ime_text_spans); info = active_input_method_controller->TextInputInfo(); EXPECT_EQ("0123456789abcdefghijklmnopq\nrstuvwxyz", std::string(info.value.Utf8().data())); EXPECT_EQ(31, info.selection_start); EXPECT_EQ(31, info.selection_end); EXPECT_EQ(30, info.composition_start); EXPECT_EQ(34, info.composition_end); std::string composition_text("yolo"); active_input_method_controller->CommitText( WebString::FromUTF8(composition_text.c_str()), empty_ime_text_spans, WebRange(), 0); info = active_input_method_controller->TextInputInfo(); EXPECT_EQ("0123456789abcdefghijklmnopq\nrsyoloxyz", std::string(info.value.Utf8().data())); EXPECT_EQ(34, info.selection_start); EXPECT_EQ(34, info.selection_end); EXPECT_EQ(-1, info.composition_start); EXPECT_EQ(-1, info.composition_end); } TEST_F(WebViewTest, SetCompositionFromExistingTextInRichText) { RegisterMockedHttpURLLoad("content_editable_rich_text.html"); WebViewImpl* web_view = web_view_helper_.InitializeAndLoad( base_url_ + "content_editable_rich_text.html"); web_view->SetInitialFocus(false); WebVector<WebImeTextSpan> ime_text_spans(static_cast<size_t>(1)); ime_text_spans[0] = WebImeTextSpan(WebImeTextSpan::Type::kComposition, 0, 4, ui::mojom::ImeTextSpanThickness::kThin, 0); WebLocalFrameImpl* frame = web_view->MainFrameImpl(); frame->SetEditableSelectionOffsets(1, 1); WebDocument document = web_view->MainFrameImpl()->GetDocument(); EXPECT_FALSE(document.GetElementById("bold").IsNull()); frame->SetCompositionFromExistingText(0, 4, ime_text_spans); EXPECT_FALSE(document.GetElementById("bold").IsNull()); } TEST_F(WebViewTest, SetEditableSelectionOffsetsKeepsComposition) { RegisterMockedHttpURLLoad("input_field_populated.html"); WebViewImpl* web_view = web_view_helper_.InitializeAndLoad( base_url_ + "input_field_populated.html"); web_view->SetInitialFocus(false); std::string composition_text_first("hello "); std::string composition_text_second("world"); WebVector<WebImeTextSpan> empty_ime_text_spans; WebInputMethodController* active_input_method_controller = web_view->MainFrameImpl() ->FrameWidget() ->GetActiveWebInputMethodController(); active_input_method_controller->CommitText( WebString::FromUTF8(composition_text_first.c_str()), empty_ime_text_spans, WebRange(), 0); active_input_method_controller->SetComposition( WebString::FromUTF8(composition_text_second.c_str()), empty_ime_text_spans, WebRange(), 5, 5); WebTextInputInfo info = active_input_method_controller->TextInputInfo(); EXPECT_EQ("hello world", std::string(info.value.Utf8().data())); EXPECT_EQ(11, info.selection_start); EXPECT_EQ(11, info.selection_end); EXPECT_EQ(6, info.composition_start); EXPECT_EQ(11, info.composition_end); WebLocalFrameImpl* frame = web_view->MainFrameImpl(); frame->SetEditableSelectionOffsets(6, 6); info = active_input_method_controller->TextInputInfo(); EXPECT_EQ("hello world", std::string(info.value.Utf8().data())); EXPECT_EQ(6, info.selection_start); EXPECT_EQ(6, info.selection_end); EXPECT_EQ(6, info.composition_start); EXPECT_EQ(11, info.composition_end); frame->SetEditableSelectionOffsets(8, 8); info = active_input_method_controller->TextInputInfo(); EXPECT_EQ("hello world", std::string(info.value.Utf8().data())); EXPECT_EQ(8, info.selection_start); EXPECT_EQ(8, info.selection_end); EXPECT_EQ(6, info.composition_start); EXPECT_EQ(11, info.composition_end); frame->SetEditableSelectionOffsets(11, 11); info = active_input_method_controller->TextInputInfo(); EXPECT_EQ("hello world", std::string(info.value.Utf8().data())); EXPECT_EQ(11, info.selection_start); EXPECT_EQ(11, info.selection_end); EXPECT_EQ(6, info.composition_start); EXPECT_EQ(11, info.composition_end); frame->SetEditableSelectionOffsets(6, 11); info = active_input_method_controller->TextInputInfo(); EXPECT_EQ("hello world", std::string(info.value.Utf8().data())); EXPECT_EQ(6, info.selection_start); EXPECT_EQ(11, info.selection_end); EXPECT_EQ(6, info.composition_start); EXPECT_EQ(11, info.composition_end); frame->SetEditableSelectionOffsets(2, 2); info = active_input_method_controller->TextInputInfo(); EXPECT_EQ("hello world", std::string(info.value.Utf8().data())); EXPECT_EQ(2, info.selection_start); EXPECT_EQ(2, info.selection_end); // Composition range should be reset by browser process or keyboard apps. EXPECT_EQ(6, info.composition_start); EXPECT_EQ(11, info.composition_end); } TEST_F(WebViewTest, IsSelectionAnchorFirst) { RegisterMockedHttpURLLoad("input_field_populated.html"); WebViewImpl* web_view = web_view_helper_.InitializeAndLoad( base_url_ + "input_field_populated.html"); WebLocalFrame* frame = web_view->MainFrameImpl(); web_view->SetInitialFocus(false); frame->SetEditableSelectionOffsets(4, 10); EXPECT_TRUE(frame->IsSelectionAnchorFirst()); WebRect anchor; WebRect focus; web_view->SelectionBounds(anchor, focus); frame->SelectRange(WebPoint(focus.x, focus.y), WebPoint(anchor.x, anchor.y)); EXPECT_FALSE(frame->IsSelectionAnchorFirst()); } TEST_F( WebViewTest, MoveFocusToNextFocusableElementInFormWithKeyEventListenersAndNonEditableElements) { const std::string test_file = "advance_focus_in_form_with_key_event_listeners.html"; RegisterMockedHttpURLLoad(test_file); WebViewImpl* web_view = web_view_helper_.InitializeAndLoad(base_url_ + test_file); web_view->SetInitialFocus(false); Document* document = web_view->MainFrameImpl()->GetFrame()->GetDocument(); WebInputMethodController* active_input_method_controller = web_view->MainFrameImpl() ->FrameWidget() ->GetActiveWebInputMethodController(); const int default_text_input_flags = kWebTextInputFlagNone; struct FocusedElement { AtomicString element_id; int next_previous_flags; } focused_elements[] = { {"input1", default_text_input_flags | kWebTextInputFlagHaveNextFocusableElement}, {"contenteditable1", kWebTextInputFlagHaveNextFocusableElement | kWebTextInputFlagHavePreviousFocusableElement}, {"input2", default_text_input_flags | kWebTextInputFlagHaveNextFocusableElement | kWebTextInputFlagHavePreviousFocusableElement}, {"textarea1", default_text_input_flags | kWebTextInputFlagHaveNextFocusableElement | kWebTextInputFlagHavePreviousFocusableElement}, {"input3", default_text_input_flags | kWebTextInputFlagHaveNextFocusableElement | kWebTextInputFlagHavePreviousFocusableElement}, {"textarea2", default_text_input_flags | kWebTextInputFlagHavePreviousFocusableElement}, }; // Forward Navigation in form1 with NEXT Element* input1 = document->getElementById("input1"); input1->focus(); Element* current_focus = nullptr; Element* next_focus = nullptr; int next_previous_flags; for (size_t i = 0; i < arraysize(focused_elements); ++i) { current_focus = document->getElementById(focused_elements[i].element_id); EXPECT_EQ(current_focus, document->FocusedElement()); next_previous_flags = active_input_method_controller->ComputeWebTextInputNextPreviousFlags(); EXPECT_EQ(focused_elements[i].next_previous_flags, next_previous_flags); next_focus = document->GetPage()->GetFocusController().NextFocusableElementInForm( current_focus, kWebFocusTypeForward); if (next_focus) { EXPECT_EQ(next_focus->GetIdAttribute(), focused_elements[i + 1].element_id); } web_view->MainFrameImpl()->AdvanceFocusInForm(kWebFocusTypeForward); } // Now focus will stay on previous focus itself, because it has no next // element. EXPECT_EQ(current_focus, document->FocusedElement()); // Backward Navigation in form1 with PREVIOUS for (size_t i = arraysize(focused_elements); i-- > 0;) { current_focus = document->getElementById(focused_elements[i].element_id); EXPECT_EQ(current_focus, document->FocusedElement()); next_previous_flags = active_input_method_controller->ComputeWebTextInputNextPreviousFlags(); EXPECT_EQ(focused_elements[i].next_previous_flags, next_previous_flags); next_focus = document->GetPage()->GetFocusController().NextFocusableElementInForm( current_focus, kWebFocusTypeBackward); if (next_focus) { EXPECT_EQ(next_focus->GetIdAttribute(), focused_elements[i - 1].element_id); } web_view->MainFrameImpl()->AdvanceFocusInForm(kWebFocusTypeBackward); } // Now focus will stay on previous focus itself, because it has no previous // element. EXPECT_EQ(current_focus, document->FocusedElement()); // Setting a non editable element as focus in form1, and ensuring editable // navigation is fine in forward and backward. Element* button1 = document->getElementById("button1"); button1->focus(); next_previous_flags = active_input_method_controller->ComputeWebTextInputNextPreviousFlags(); EXPECT_EQ(kWebTextInputFlagHaveNextFocusableElement | kWebTextInputFlagHavePreviousFocusableElement, next_previous_flags); next_focus = document->GetPage()->GetFocusController().NextFocusableElementInForm( button1, kWebFocusTypeForward); EXPECT_EQ(next_focus->GetIdAttribute(), "contenteditable1"); web_view->MainFrameImpl()->AdvanceFocusInForm(kWebFocusTypeForward); Element* content_editable1 = document->getElementById("contenteditable1"); EXPECT_EQ(content_editable1, document->FocusedElement()); button1->focus(); next_focus = document->GetPage()->GetFocusController().NextFocusableElementInForm( button1, kWebFocusTypeBackward); EXPECT_EQ(next_focus->GetIdAttribute(), "input1"); web_view->MainFrameImpl()->AdvanceFocusInForm(kWebFocusTypeBackward); EXPECT_EQ(input1, document->FocusedElement()); Element* anchor1 = document->getElementById("anchor1"); anchor1->focus(); next_previous_flags = active_input_method_controller->ComputeWebTextInputNextPreviousFlags(); // No Next/Previous element for elements outside form. EXPECT_EQ(0, next_previous_flags); next_focus = document->GetPage()->GetFocusController().NextFocusableElementInForm( anchor1, kWebFocusTypeForward); EXPECT_EQ(next_focus, nullptr); web_view->MainFrameImpl()->AdvanceFocusInForm(kWebFocusTypeForward); // Since anchor is not a form control element, next/previous element will // be null, hence focus will stay same as it is. EXPECT_EQ(anchor1, document->FocusedElement()); next_focus = document->GetPage()->GetFocusController().NextFocusableElementInForm( anchor1, kWebFocusTypeBackward); EXPECT_EQ(next_focus, nullptr); web_view->MainFrameImpl()->AdvanceFocusInForm(kWebFocusTypeBackward); EXPECT_EQ(anchor1, document->FocusedElement()); // Navigation of elements which is not part of any forms. Element* text_area3 = document->getElementById("textarea3"); text_area3->focus(); next_previous_flags = active_input_method_controller->ComputeWebTextInputNextPreviousFlags(); // No Next/Previous element for elements outside form. EXPECT_EQ(default_text_input_flags, next_previous_flags); next_focus = document->GetPage()->GetFocusController().NextFocusableElementInForm( text_area3, kWebFocusTypeForward); EXPECT_EQ(next_focus, nullptr); web_view->MainFrameImpl()->AdvanceFocusInForm(kWebFocusTypeForward); // No Next/Previous element to this element because it's not part of any // form. Hence focus won't change wrt NEXT/PREVIOUS. EXPECT_EQ(text_area3, document->FocusedElement()); next_focus = document->GetPage()->GetFocusController().NextFocusableElementInForm( text_area3, kWebFocusTypeBackward); EXPECT_EQ(next_focus, nullptr); web_view->MainFrameImpl()->AdvanceFocusInForm(kWebFocusTypeBackward); EXPECT_EQ(text_area3, document->FocusedElement()); // Navigation from an element which is part of a form but not an editable // element. Element* button2 = document->getElementById("button2"); button2->focus(); next_previous_flags = active_input_method_controller->ComputeWebTextInputNextPreviousFlags(); // No Next element for this element, due to last element outside the form. EXPECT_EQ(kWebTextInputFlagHavePreviousFocusableElement, next_previous_flags); next_focus = document->GetPage()->GetFocusController().NextFocusableElementInForm( button2, kWebFocusTypeForward); EXPECT_EQ(next_focus, nullptr); web_view->MainFrameImpl()->AdvanceFocusInForm(kWebFocusTypeForward); // No Next element to this element because it's not part of any form. // Hence focus won't change wrt NEXT. EXPECT_EQ(button2, document->FocusedElement()); Element* text_area2 = document->getElementById("textarea2"); next_focus = document->GetPage()->GetFocusController().NextFocusableElementInForm( button2, kWebFocusTypeBackward); EXPECT_EQ(next_focus, text_area2); web_view->MainFrameImpl()->AdvanceFocusInForm(kWebFocusTypeBackward); // Since button is a form control element from form1, ensuring focus is set // at correct position. EXPECT_EQ(text_area2, document->FocusedElement()); Element* content_editable2 = document->getElementById("contenteditable2"); document->SetFocusedElement( content_editable2, FocusParams(SelectionBehaviorOnFocus::kNone, kWebFocusTypeNone, nullptr)); next_previous_flags = active_input_method_controller->ComputeWebTextInputNextPreviousFlags(); // No Next/Previous element for elements outside form. EXPECT_EQ(0, next_previous_flags); next_focus = document->GetPage()->GetFocusController().NextFocusableElementInForm( content_editable2, kWebFocusTypeForward); EXPECT_EQ(next_focus, nullptr); web_view->MainFrameImpl()->AdvanceFocusInForm(kWebFocusTypeForward); // No Next/Previous element to this element because it's not part of any // form. Hence focus won't change wrt NEXT/PREVIOUS. EXPECT_EQ(content_editable2, document->FocusedElement()); next_focus = document->GetPage()->GetFocusController().NextFocusableElementInForm( content_editable2, kWebFocusTypeBackward); EXPECT_EQ(next_focus, nullptr); web_view->MainFrameImpl()->AdvanceFocusInForm(kWebFocusTypeBackward); EXPECT_EQ(content_editable2, document->FocusedElement()); // Navigation of elements which is having invalid form attribute and hence // not part of any forms. Element* text_area4 = document->getElementById("textarea4"); text_area4->focus(); next_previous_flags = active_input_method_controller->ComputeWebTextInputNextPreviousFlags(); // No Next/Previous element for elements which is having invalid form // attribute. EXPECT_EQ(default_text_input_flags, next_previous_flags); next_focus = document->GetPage()->GetFocusController().NextFocusableElementInForm( text_area4, kWebFocusTypeForward); EXPECT_EQ(next_focus, nullptr); web_view->MainFrameImpl()->AdvanceFocusInForm(kWebFocusTypeForward); // No Next/Previous element to this element because it's not part of any // form. Hence focus won't change wrt NEXT/PREVIOUS. EXPECT_EQ(text_area4, document->FocusedElement()); next_focus = document->GetPage()->GetFocusController().NextFocusableElementInForm( text_area4, kWebFocusTypeBackward); EXPECT_EQ(next_focus, nullptr); web_view->MainFrameImpl()->AdvanceFocusInForm(kWebFocusTypeBackward); EXPECT_EQ(text_area4, document->FocusedElement()); web_view_helper_.Reset(); } TEST_F( WebViewTest, MoveFocusToNextFocusableElementInFormWithNonEditableNonFormControlElements) { const std::string test_file = "advance_focus_in_form_with_key_event_listeners.html"; RegisterMockedHttpURLLoad(test_file); WebViewImpl* web_view = web_view_helper_.InitializeAndLoad(base_url_ + test_file); web_view->SetInitialFocus(false); Document* document = web_view->MainFrameImpl()->GetFrame()->GetDocument(); WebInputMethodController* active_input_method_controller = web_view->MainFrameImpl() ->FrameWidget() ->GetActiveWebInputMethodController(); const int default_text_input_flags = kWebTextInputFlagNone; struct FocusedElement { const char* element_id; int next_previous_flags; } focused_elements[] = { {"textarea5", default_text_input_flags | kWebTextInputFlagHaveNextFocusableElement}, {"input4", default_text_input_flags | kWebTextInputFlagHaveNextFocusableElement | kWebTextInputFlagHavePreviousFocusableElement}, {"contenteditable3", kWebTextInputFlagHaveNextFocusableElement | kWebTextInputFlagHavePreviousFocusableElement}, {"input5", kWebTextInputFlagHavePreviousFocusableElement}, }; // Forward Navigation in form2 with NEXT Element* text_area5 = document->getElementById("textarea5"); text_area5->focus(); Element* current_focus = nullptr; Element* next_focus = nullptr; int next_previous_flags; for (size_t i = 0; i < arraysize(focused_elements); ++i) { current_focus = document->getElementById(focused_elements[i].element_id); EXPECT_EQ(current_focus, document->FocusedElement()); next_previous_flags = active_input_method_controller->ComputeWebTextInputNextPreviousFlags(); EXPECT_EQ(focused_elements[i].next_previous_flags, next_previous_flags); next_focus = document->GetPage()->GetFocusController().NextFocusableElementInForm( current_focus, kWebFocusTypeForward); if (next_focus) { EXPECT_EQ(next_focus->GetIdAttribute(), focused_elements[i + 1].element_id); } web_view->MainFrameImpl()->AdvanceFocusInForm(kWebFocusTypeForward); } // Now focus will stay on previous focus itself, because it has no next // element. EXPECT_EQ(current_focus, document->FocusedElement()); // Backward Navigation in form1 with PREVIOUS for (size_t i = arraysize(focused_elements); i-- > 0;) { current_focus = document->getElementById(focused_elements[i].element_id); EXPECT_EQ(current_focus, document->FocusedElement()); next_previous_flags = active_input_method_controller->ComputeWebTextInputNextPreviousFlags(); EXPECT_EQ(focused_elements[i].next_previous_flags, next_previous_flags); next_focus = document->GetPage()->GetFocusController().NextFocusableElementInForm( current_focus, kWebFocusTypeBackward); if (next_focus) { EXPECT_EQ(next_focus->GetIdAttribute(), focused_elements[i - 1].element_id); } web_view->MainFrameImpl()->AdvanceFocusInForm(kWebFocusTypeBackward); } // Now focus will stay on previous focus itself, because it has no previous // element. EXPECT_EQ(current_focus, document->FocusedElement()); // Setting a non editable element as focus in form1, and ensuring editable // navigation is fine in forward and backward. Element* anchor2 = document->getElementById("anchor2"); anchor2->focus(); next_previous_flags = active_input_method_controller->ComputeWebTextInputNextPreviousFlags(); // No Next/Previous element for non-form control elements inside form. EXPECT_EQ(0, next_previous_flags); next_focus = document->GetPage()->GetFocusController().NextFocusableElementInForm( anchor2, kWebFocusTypeForward); EXPECT_EQ(next_focus, nullptr); web_view->MainFrameImpl()->AdvanceFocusInForm(kWebFocusTypeForward); // Since anchor is not a form control element, next/previous element will // be null, hence focus will stay same as it is. EXPECT_EQ(anchor2, document->FocusedElement()); next_focus = document->GetPage()->GetFocusController().NextFocusableElementInForm( anchor2, kWebFocusTypeBackward); EXPECT_EQ(next_focus, nullptr); web_view->MainFrameImpl()->AdvanceFocusInForm(kWebFocusTypeBackward); EXPECT_EQ(anchor2, document->FocusedElement()); web_view_helper_.Reset(); } TEST_F(WebViewTest, MoveFocusToNextFocusableElementInFormWithTabIndexElements) { const std::string test_file = "advance_focus_in_form_with_tabindex_elements.html"; RegisterMockedHttpURLLoad(test_file); WebViewImpl* web_view = web_view_helper_.InitializeAndLoad(base_url_ + test_file); web_view->SetInitialFocus(false); Document* document = web_view->MainFrameImpl()->GetFrame()->GetDocument(); WebInputMethodController* active_input_method_controller = web_view->MainFrameImpl() ->FrameWidget() ->GetActiveWebInputMethodController(); const int default_text_input_flags = kWebTextInputFlagNone; struct FocusedElement { const char* element_id; int next_previous_flags; } focused_elements[] = { {"textarea6", default_text_input_flags | kWebTextInputFlagHaveNextFocusableElement}, {"input5", default_text_input_flags | kWebTextInputFlagHaveNextFocusableElement | kWebTextInputFlagHavePreviousFocusableElement}, {"contenteditable4", kWebTextInputFlagHaveNextFocusableElement | kWebTextInputFlagHavePreviousFocusableElement}, {"input6", default_text_input_flags | kWebTextInputFlagHavePreviousFocusableElement}, }; // Forward Navigation in form with NEXT which has tabindex attribute // which differs visual order. Element* text_area6 = document->getElementById("textarea6"); text_area6->focus(); Element* current_focus = nullptr; Element* next_focus = nullptr; int next_previous_flags; for (size_t i = 0; i < arraysize(focused_elements); ++i) { current_focus = document->getElementById(focused_elements[i].element_id); EXPECT_EQ(current_focus, document->FocusedElement()); next_previous_flags = active_input_method_controller->ComputeWebTextInputNextPreviousFlags(); EXPECT_EQ(focused_elements[i].next_previous_flags, next_previous_flags); next_focus = document->GetPage()->GetFocusController().NextFocusableElementInForm( current_focus, kWebFocusTypeForward); if (next_focus) { EXPECT_EQ(next_focus->GetIdAttribute(), focused_elements[i + 1].element_id); } web_view->MainFrameImpl()->AdvanceFocusInForm(kWebFocusTypeForward); } // No next editable element which is focusable with proper tab index, hence // staying on previous focus. EXPECT_EQ(current_focus, document->FocusedElement()); // Backward Navigation in form with PREVIOUS which has tabindex attribute // which differs visual order. for (size_t i = arraysize(focused_elements); i-- > 0;) { current_focus = document->getElementById(focused_elements[i].element_id); EXPECT_EQ(current_focus, document->FocusedElement()); next_previous_flags = active_input_method_controller->ComputeWebTextInputNextPreviousFlags(); EXPECT_EQ(focused_elements[i].next_previous_flags, next_previous_flags); next_focus = document->GetPage()->GetFocusController().NextFocusableElementInForm( current_focus, kWebFocusTypeBackward); if (next_focus) { EXPECT_EQ(next_focus->GetIdAttribute(), focused_elements[i - 1].element_id); } web_view->MainFrameImpl()->AdvanceFocusInForm(kWebFocusTypeBackward); } // Now focus will stay on previous focus itself, because it has no previous // element. EXPECT_EQ(current_focus, document->FocusedElement()); // Setting an element which has invalid tabindex and ensuring it is not // modifying further navigation. Element* content_editable5 = document->getElementById("contenteditable5"); content_editable5->focus(); Element* input6 = document->getElementById("input6"); next_focus = document->GetPage()->GetFocusController().NextFocusableElementInForm( content_editable5, kWebFocusTypeForward); EXPECT_EQ(next_focus, input6); web_view->MainFrameImpl()->AdvanceFocusInForm(kWebFocusTypeForward); EXPECT_EQ(input6, document->FocusedElement()); content_editable5->focus(); next_focus = document->GetPage()->GetFocusController().NextFocusableElementInForm( content_editable5, kWebFocusTypeBackward); EXPECT_EQ(next_focus, text_area6); web_view->MainFrameImpl()->AdvanceFocusInForm(kWebFocusTypeBackward); EXPECT_EQ(text_area6, document->FocusedElement()); web_view_helper_.Reset(); } TEST_F(WebViewTest, MoveFocusToNextFocusableElementInFormWithDisabledAndReadonlyElements) { const std::string test_file = "advance_focus_in_form_with_disabled_and_readonly_elements.html"; RegisterMockedHttpURLLoad(test_file); WebViewImpl* web_view = web_view_helper_.InitializeAndLoad(base_url_ + test_file); web_view->SetInitialFocus(false); Document* document = web_view->MainFrameImpl()->GetFrame()->GetDocument(); WebInputMethodController* active_input_method_controller = web_view->MainFrameImpl() ->FrameWidget() ->GetActiveWebInputMethodController(); struct FocusedElement { const char* element_id; int next_previous_flags; } focused_elements[] = { {"contenteditable6", kWebTextInputFlagHaveNextFocusableElement}, {"contenteditable7", kWebTextInputFlagHavePreviousFocusableElement}, }; // Forward Navigation in form with NEXT which has has disabled/enabled // elements which will gets skipped during navigation. Element* content_editable6 = document->getElementById("contenteditable6"); content_editable6->focus(); Element* current_focus = nullptr; Element* next_focus = nullptr; int next_previous_flags; for (size_t i = 0; i < arraysize(focused_elements); ++i) { current_focus = document->getElementById(focused_elements[i].element_id); EXPECT_EQ(current_focus, document->FocusedElement()); next_previous_flags = active_input_method_controller->ComputeWebTextInputNextPreviousFlags(); EXPECT_EQ(focused_elements[i].next_previous_flags, next_previous_flags); next_focus = document->GetPage()->GetFocusController().NextFocusableElementInForm( current_focus, kWebFocusTypeForward); if (next_focus) { EXPECT_EQ(next_focus->GetIdAttribute(), focused_elements[i + 1].element_id); } web_view->MainFrameImpl()->AdvanceFocusInForm(kWebFocusTypeForward); } // No next editable element which is focusable, hence staying on previous // focus. EXPECT_EQ(current_focus, document->FocusedElement()); // Backward Navigation in form with PREVIOUS which has has // disabled/enabled elements which will gets skipped during navigation. for (size_t i = arraysize(focused_elements); i-- > 0;) { current_focus = document->getElementById(focused_elements[i].element_id); EXPECT_EQ(current_focus, document->FocusedElement()); next_previous_flags = active_input_method_controller->ComputeWebTextInputNextPreviousFlags(); EXPECT_EQ(focused_elements[i].next_previous_flags, next_previous_flags); next_focus = document->GetPage()->GetFocusController().NextFocusableElementInForm( current_focus, kWebFocusTypeBackward); if (next_focus) { EXPECT_EQ(next_focus->GetIdAttribute(), focused_elements[i - 1].element_id); } web_view->MainFrameImpl()->AdvanceFocusInForm(kWebFocusTypeBackward); } // Now focus will stay on previous focus itself, because it has no previous // element. EXPECT_EQ(current_focus, document->FocusedElement()); web_view_helper_.Reset(); } TEST_F(WebViewTest, ExitingDeviceEmulationResetsPageScale) { RegisterMockedHttpURLLoad("200-by-300.html"); WebViewImpl* web_view_impl = web_view_helper_.InitializeAndLoad(base_url_ + "200-by-300.html"); web_view_impl->Resize(WebSize(200, 300)); float page_scale_expected = web_view_impl->PageScaleFactor(); WebDeviceEmulationParams params; params.screen_position = WebDeviceEmulationParams::kDesktop; params.device_scale_factor = 0; params.scale = 1; web_view_impl->EnableDeviceEmulation(params); web_view_impl->SetPageScaleFactor(2); web_view_impl->DisableDeviceEmulation(); EXPECT_EQ(page_scale_expected, web_view_impl->PageScaleFactor()); } TEST_F(WebViewTest, HistoryResetScrollAndScaleState) { RegisterMockedHttpURLLoad("200-by-300.html"); WebViewImpl* web_view_impl = web_view_helper_.InitializeAndLoad(base_url_ + "200-by-300.html"); web_view_impl->Resize(WebSize(100, 150)); web_view_impl->UpdateAllLifecyclePhases(); EXPECT_EQ(0, web_view_impl->MainFrameImpl()->GetScrollOffset().width); EXPECT_EQ(0, web_view_impl->MainFrameImpl()->GetScrollOffset().height); // Make the page scale and scroll with the given paremeters. web_view_impl->SetPageScaleFactor(2.0f); web_view_impl->MainFrameImpl()->SetScrollOffset(WebSize(94, 111)); EXPECT_EQ(2.0f, web_view_impl->PageScaleFactor()); EXPECT_EQ(94, web_view_impl->MainFrameImpl()->GetScrollOffset().width); EXPECT_EQ(111, web_view_impl->MainFrameImpl()->GetScrollOffset().height); LocalFrame* main_frame_local = ToLocalFrame(web_view_impl->GetPage()->MainFrame()); main_frame_local->Loader().SaveScrollState(); EXPECT_EQ(2.0f, main_frame_local->Loader() .GetDocumentLoader() ->GetHistoryItem() ->GetViewState() ->page_scale_factor_); EXPECT_EQ(94, main_frame_local->Loader() .GetDocumentLoader() ->GetHistoryItem() ->GetViewState() ->scroll_offset_.Width()); EXPECT_EQ(111, main_frame_local->Loader() .GetDocumentLoader() ->GetHistoryItem() ->GetViewState() ->scroll_offset_.Height()); // Confirm that resetting the page state resets the saved scroll position. web_view_impl->ResetScrollAndScaleState(); EXPECT_EQ(1.0f, web_view_impl->PageScaleFactor()); EXPECT_EQ(0, web_view_impl->MainFrameImpl()->GetScrollOffset().width); EXPECT_EQ(0, web_view_impl->MainFrameImpl()->GetScrollOffset().height); EXPECT_EQ(nullptr, main_frame_local->Loader() .GetDocumentLoader() ->GetHistoryItem() ->GetViewState()); } TEST_F(WebViewTest, BackForwardRestoreScroll) { RegisterMockedHttpURLLoad("back_forward_restore_scroll.html"); WebViewImpl* web_view_impl = web_view_helper_.InitializeAndLoad( base_url_ + "back_forward_restore_scroll.html"); web_view_impl->Resize(WebSize(640, 480)); web_view_impl->UpdateAllLifecyclePhases(); // Emulate a user scroll web_view_impl->MainFrameImpl()->SetScrollOffset(WebSize(0, 900)); LocalFrame* main_frame_local = ToLocalFrame(web_view_impl->GetPage()->MainFrame()); Persistent<HistoryItem> item1 = main_frame_local->Loader().GetDocumentLoader()->GetHistoryItem(); // Click an anchor main_frame_local->Loader().StartNavigation(FrameLoadRequest( main_frame_local->GetDocument(), ResourceRequest(main_frame_local->GetDocument()->CompleteURL("#a")))); Persistent<HistoryItem> item2 = main_frame_local->Loader().GetDocumentLoader()->GetHistoryItem(); // Go back, then forward, then back again. main_frame_local->Loader().CommitNavigation( FrameLoadRequest(nullptr, item1->GenerateResourceRequest( mojom::FetchCacheMode::kDefault)), kFrameLoadTypeBackForward, item1.Get(), kHistorySameDocumentLoad); main_frame_local->Loader().CommitNavigation( FrameLoadRequest(nullptr, item2->GenerateResourceRequest( mojom::FetchCacheMode::kDefault)), kFrameLoadTypeBackForward, item2.Get(), kHistorySameDocumentLoad); main_frame_local->Loader().CommitNavigation( FrameLoadRequest(nullptr, item1->GenerateResourceRequest( mojom::FetchCacheMode::kDefault)), kFrameLoadTypeBackForward, item1.Get(), kHistorySameDocumentLoad); // Click a different anchor main_frame_local->Loader().StartNavigation(FrameLoadRequest( main_frame_local->GetDocument(), ResourceRequest(main_frame_local->GetDocument()->CompleteURL("#b")))); Persistent<HistoryItem> item3 = main_frame_local->Loader().GetDocumentLoader()->GetHistoryItem(); // Go back, then forward. The scroll position should be properly set on the // forward navigation. main_frame_local->Loader().CommitNavigation( FrameLoadRequest(nullptr, item1->GenerateResourceRequest( mojom::FetchCacheMode::kDefault)), kFrameLoadTypeBackForward, item1.Get(), kHistorySameDocumentLoad); main_frame_local->Loader().CommitNavigation( FrameLoadRequest(nullptr, item3->GenerateResourceRequest( mojom::FetchCacheMode::kDefault)), kFrameLoadTypeBackForward, item3.Get(), kHistorySameDocumentLoad); EXPECT_EQ(0, web_view_impl->MainFrameImpl()->GetScrollOffset().width); EXPECT_GT(web_view_impl->MainFrameImpl()->GetScrollOffset().height, 2000); } // Tests that we restore scroll and scale *after* the fullscreen styles are // removed and the page is laid out. http://crbug.com/625683. TEST_F(WebViewTest, FullscreenResetScrollAndScaleFullscreenStyles) { RegisterMockedHttpURLLoad("fullscreen_style.html"); WebViewImpl* web_view_impl = web_view_helper_.InitializeAndLoad(base_url_ + "fullscreen_style.html"); web_view_impl->Resize(WebSize(800, 600)); web_view_impl->UpdateAllLifecyclePhases(); // Scroll the page down. web_view_impl->MainFrameImpl()->SetScrollOffset(WebSize(0, 2000)); ASSERT_EQ(2000, web_view_impl->MainFrameImpl()->GetScrollOffset().height); // Enter fullscreen. LocalFrame* frame = web_view_impl->MainFrameImpl()->GetFrame(); Element* element = frame->GetDocument()->getElementById("fullscreenElement"); std::unique_ptr<UserGestureIndicator> gesture = Frame::NotifyUserActivation(frame); Fullscreen::RequestFullscreen(*element); web_view_impl->DidEnterFullscreen(); web_view_impl->UpdateAllLifecyclePhases(); // Sanity-check. There should be no scrolling possible. ASSERT_EQ(0, web_view_impl->MainFrameImpl()->GetScrollOffset().height); ASSERT_EQ(0, web_view_impl->MainFrameImpl() ->GetFrameView() ->MaximumScrollOffset() .Height()); // Confirm that after exiting and doing a layout, the scroll and scale // parameters are reset. The page sets display: none on overflowing elements // while in fullscreen so if we try to restore before the style and layout // is applied the offsets will be clamped. web_view_impl->DidExitFullscreen(); EXPECT_TRUE(web_view_impl->MainFrameImpl()->GetFrameView()->NeedsLayout()); web_view_impl->UpdateAllLifecyclePhases(); EXPECT_EQ(2000, web_view_impl->MainFrameImpl()->GetScrollOffset().height); } // Tests that exiting and immediately reentering fullscreen doesn't cause the // scroll and scale restoration to occur when we enter fullscreen again. TEST_F(WebViewTest, FullscreenResetScrollAndScaleExitAndReenter) { RegisterMockedHttpURLLoad("fullscreen_style.html"); WebViewImpl* web_view_impl = web_view_helper_.InitializeAndLoad(base_url_ + "fullscreen_style.html"); web_view_impl->Resize(WebSize(800, 600)); web_view_impl->UpdateAllLifecyclePhases(); // Scroll the page down. web_view_impl->MainFrameImpl()->SetScrollOffset(WebSize(0, 2000)); ASSERT_EQ(2000, web_view_impl->MainFrameImpl()->GetScrollOffset().height); // Enter fullscreen. LocalFrame* frame = web_view_impl->MainFrameImpl()->GetFrame(); Element* element = frame->GetDocument()->getElementById("fullscreenElement"); std::unique_ptr<UserGestureIndicator> gesture = Frame::NotifyUserActivation(frame); Fullscreen::RequestFullscreen(*element); web_view_impl->DidEnterFullscreen(); web_view_impl->UpdateAllLifecyclePhases(); // Sanity-check. There should be no scrolling possible. ASSERT_EQ(0, web_view_impl->MainFrameImpl()->GetScrollOffset().height); ASSERT_EQ(0, web_view_impl->MainFrameImpl() ->GetFrameView() ->MaximumScrollOffset() .Height()); // Exit and, without performing a layout, reenter fullscreen again. We // shouldn't try to restore the scroll and scale values when we layout to // enter fullscreen. web_view_impl->DidExitFullscreen(); Fullscreen::RequestFullscreen(*element); web_view_impl->DidEnterFullscreen(); web_view_impl->UpdateAllLifecyclePhases(); // Sanity-check. There should be no scrolling possible. ASSERT_EQ(0, web_view_impl->MainFrameImpl()->GetScrollOffset().height); ASSERT_EQ(0, web_view_impl->MainFrameImpl() ->GetFrameView() ->MaximumScrollOffset() .Height()); // When we exit now, we should restore the original scroll value. web_view_impl->DidExitFullscreen(); web_view_impl->UpdateAllLifecyclePhases(); EXPECT_EQ(2000, web_view_impl->MainFrameImpl()->GetScrollOffset().height); } TEST_F(WebViewTest, EnterFullscreenResetScrollAndScaleState) { RegisterMockedHttpURLLoad("200-by-300.html"); WebViewImpl* web_view_impl = web_view_helper_.InitializeAndLoad(base_url_ + "200-by-300.html"); web_view_impl->Resize(WebSize(100, 150)); web_view_impl->UpdateAllLifecyclePhases(); EXPECT_EQ(0, web_view_impl->MainFrameImpl()->GetScrollOffset().width); EXPECT_EQ(0, web_view_impl->MainFrameImpl()->GetScrollOffset().height); // Make the page scale and scroll with the given paremeters. web_view_impl->SetPageScaleFactor(2.0f); web_view_impl->MainFrameImpl()->SetScrollOffset(WebSize(94, 111)); web_view_impl->SetVisualViewportOffset(WebFloatPoint(12, 20)); EXPECT_EQ(2.0f, web_view_impl->PageScaleFactor()); EXPECT_EQ(94, web_view_impl->MainFrameImpl()->GetScrollOffset().width); EXPECT_EQ(111, web_view_impl->MainFrameImpl()->GetScrollOffset().height); EXPECT_EQ(12, web_view_impl->VisualViewportOffset().x); EXPECT_EQ(20, web_view_impl->VisualViewportOffset().y); LocalFrame* frame = web_view_impl->MainFrameImpl()->GetFrame(); Element* element = frame->GetDocument()->body(); std::unique_ptr<UserGestureIndicator> gesture = Frame::NotifyUserActivation(frame); Fullscreen::RequestFullscreen(*element); web_view_impl->DidEnterFullscreen(); // Page scale factor must be 1.0 during fullscreen for elements to be sized // properly. EXPECT_EQ(1.0f, web_view_impl->PageScaleFactor()); // Make sure fullscreen nesting doesn't disrupt scroll/scale saving. Element* other_element = frame->GetDocument()->getElementById("content"); Fullscreen::RequestFullscreen(*other_element); // Confirm that exiting fullscreen restores the parameters. web_view_impl->DidExitFullscreen(); web_view_impl->UpdateAllLifecyclePhases(); EXPECT_EQ(2.0f, web_view_impl->PageScaleFactor()); EXPECT_EQ(94, web_view_impl->MainFrameImpl()->GetScrollOffset().width); EXPECT_EQ(111, web_view_impl->MainFrameImpl()->GetScrollOffset().height); EXPECT_EQ(12, web_view_impl->VisualViewportOffset().x); EXPECT_EQ(20, web_view_impl->VisualViewportOffset().y); } class PrintWebViewClient : public FrameTestHelpers::TestWebViewClient { public: PrintWebViewClient() : print_called_(false) {} // WebViewClient methods void PrintPage(WebLocalFrame*) override { print_called_ = true; } bool PrintCalled() const { return print_called_; } private: bool print_called_; }; TEST_F(WebViewTest, PrintWithXHRInFlight) { PrintWebViewClient client; RegisterMockedHttpURLLoad("print_with_xhr_inflight.html"); WebViewImpl* web_view_impl = web_view_helper_.InitializeAndLoad( base_url_ + "print_with_xhr_inflight.html", nullptr, &client); ASSERT_TRUE(ToLocalFrame(web_view_impl->GetPage()->MainFrame()) ->GetDocument() ->LoadEventFinished()); EXPECT_TRUE(client.PrintCalled()); web_view_helper_.Reset(); } static void DragAndDropURL(WebViewImpl* web_view, const std::string& url) { WebDragData drag_data; drag_data.Initialize(); WebDragData::Item item; item.storage_type = WebDragData::Item::kStorageTypeString; item.string_type = "text/uri-list"; item.string_data = WebString::FromUTF8(url); drag_data.AddItem(item); const WebFloatPoint client_point(0, 0); const WebFloatPoint screen_point(0, 0); WebFrameWidget* widget = web_view->MainFrameImpl()->FrameWidget(); widget->DragTargetDragEnter(drag_data, client_point, screen_point, kWebDragOperationCopy, 0); widget->DragTargetDrop(drag_data, client_point, screen_point, 0); FrameTestHelpers::PumpPendingRequestsForFrameToLoad(web_view->MainFrame()); } TEST_F(WebViewTest, DragDropURL) { RegisterMockedHttpURLLoad("foo.html"); RegisterMockedHttpURLLoad("bar.html"); const std::string foo_url = base_url_ + "foo.html"; const std::string bar_url = base_url_ + "bar.html"; WebViewImpl* web_view = web_view_helper_.InitializeAndLoad(foo_url); ASSERT_TRUE(web_view); // Drag and drop barUrl and verify that we've navigated to it. DragAndDropURL(web_view, bar_url); EXPECT_EQ(bar_url, web_view->MainFrameImpl()->GetDocument().Url().GetString().Utf8()); // Drag and drop fooUrl and verify that we've navigated back to it. DragAndDropURL(web_view, foo_url); EXPECT_EQ(foo_url, web_view->MainFrameImpl()->GetDocument().Url().GetString().Utf8()); // Disable navigation on drag-and-drop. web_view->SettingsImpl()->SetNavigateOnDragDrop(false); // Attempt to drag and drop to barUrl and verify that no navigation has // occurred. DragAndDropURL(web_view, bar_url); EXPECT_EQ(foo_url, web_view->MainFrameImpl()->GetDocument().Url().GetString().Utf8()); } bool WebViewTest::TapElement(WebInputEvent::Type type, Element* element) { if (!element || !element->GetLayoutObject()) return false; DCHECK(web_view_helper_.GetWebView()); element->scrollIntoViewIfNeeded(); // TODO(bokan): Technically incorrect, event positions should be in viewport // space. crbug.com/371902. FloatPoint center( web_view_helper_.GetWebView() ->MainFrameImpl() ->GetFrameView() ->ContentsToScreen( element->GetLayoutObject()->AbsoluteBoundingBoxRect()) .Center()); WebGestureEvent event(type, WebInputEvent::kNoModifiers, WebInputEvent::GetStaticTimeStampForTests(), kWebGestureDeviceTouchscreen); event.SetPositionInWidget(center); web_view_helper_.GetWebView()->HandleInputEvent( WebCoalescedInputEvent(event)); RunPendingTasks(); return true; } bool WebViewTest::TapElementById(WebInputEvent::Type type, const WebString& id) { DCHECK(web_view_helper_.GetWebView()); Element* element = static_cast<Element*>( web_view_helper_.LocalMainFrame()->GetDocument().GetElementById(id)); return TapElement(type, element); } IntSize WebViewTest::PrintICBSizeFromPageSize(const FloatSize& page_size) { // The expected layout size comes from the calculation done in // ResizePageRectsKeepingRatio() which is used from PrintContext::begin() to // scale the page size. const float ratio = page_size.Height() / (float)page_size.Width(); const int icb_width = floor(page_size.Width() * PrintContext::kPrintingMinimumShrinkFactor); const int icb_height = floor(icb_width * ratio); return IntSize(icb_width, icb_height); } TEST_F(WebViewTest, ClientTapHandling) { TapHandlingWebViewClient client; WebView* web_view = web_view_helper_.InitializeAndLoad("about:blank", nullptr, &client); WebGestureEvent event(WebInputEvent::kGestureTap, WebInputEvent::kNoModifiers, WebInputEvent::GetStaticTimeStampForTests(), kWebGestureDeviceTouchscreen); event.SetPositionInWidget(WebFloatPoint(3, 8)); web_view->HandleInputEvent(WebCoalescedInputEvent(event)); RunPendingTasks(); EXPECT_EQ(3, client.TapX()); EXPECT_EQ(8, client.TapY()); client.Reset(); event.SetType(WebInputEvent::kGestureLongPress); event.SetPositionInWidget(WebFloatPoint(25, 7)); web_view->HandleInputEvent(WebCoalescedInputEvent(event)); RunPendingTasks(); EXPECT_EQ(25, client.LongpressX()); EXPECT_EQ(7, client.LongpressY()); // Explicitly reset to break dependency on locally scoped client. web_view_helper_.Reset(); } TEST_F(WebViewTest, ClientTapHandlingNullWebViewClient) { // Note: this test doesn't use WebViewHelper since WebViewHelper creates an // internal WebViewClient on demand if the supplied WebViewClient is null. WebViewImpl* web_view = static_cast<WebViewImpl*>( WebView::Create(nullptr, mojom::PageVisibilityState::kVisible, nullptr)); FrameTestHelpers::TestWebFrameClient web_frame_client; FrameTestHelpers::TestWebWidgetClient web_widget_client; WebLocalFrame* local_frame = WebLocalFrame::CreateMainFrame( web_view, &web_frame_client, nullptr, nullptr); web_frame_client.Bind(local_frame); blink::WebFrameWidget::Create(&web_widget_client, local_frame); WebGestureEvent event(WebInputEvent::kGestureTap, WebInputEvent::kNoModifiers, WebInputEvent::GetStaticTimeStampForTests(), kWebGestureDeviceTouchscreen); event.SetPositionInWidget(WebFloatPoint(3, 8)); EXPECT_EQ(WebInputEventResult::kNotHandled, web_view->HandleInputEvent(WebCoalescedInputEvent(event))); web_view->Close(); } TEST_F(WebViewTest, LongPressEmptyDiv) { RegisterMockedHttpURLLoad("long_press_empty_div.html"); WebViewImpl* web_view = web_view_helper_.InitializeAndLoad( base_url_ + "long_press_empty_div.html"); web_view->SettingsImpl()->SetAlwaysShowContextMenuOnTouch(false); web_view->Resize(WebSize(500, 300)); web_view->UpdateAllLifecyclePhases(); RunPendingTasks(); WebGestureEvent event(WebInputEvent::kGestureLongPress, WebInputEvent::kNoModifiers, WebInputEvent::GetStaticTimeStampForTests(), kWebGestureDeviceTouchscreen); event.SetPositionInWidget(WebFloatPoint(250, 150)); EXPECT_EQ(WebInputEventResult::kNotHandled, web_view->HandleInputEvent(WebCoalescedInputEvent(event))); } TEST_F(WebViewTest, LongPressEmptyDivAlwaysShow) { RegisterMockedHttpURLLoad("long_press_empty_div.html"); WebViewImpl* web_view = web_view_helper_.InitializeAndLoad( base_url_ + "long_press_empty_div.html"); web_view->SettingsImpl()->SetAlwaysShowContextMenuOnTouch(true); web_view->Resize(WebSize(500, 300)); web_view->UpdateAllLifecyclePhases(); RunPendingTasks(); WebGestureEvent event(WebInputEvent::kGestureLongPress, WebInputEvent::kNoModifiers, WebInputEvent::GetStaticTimeStampForTests(), kWebGestureDeviceTouchscreen); event.SetPositionInWidget(WebFloatPoint(250, 150)); EXPECT_EQ(WebInputEventResult::kHandledSystem, web_view->HandleInputEvent(WebCoalescedInputEvent(event))); } TEST_F(WebViewTest, LongPressObject) { RegisterMockedHttpURLLoad("long_press_object.html"); WebViewImpl* web_view = web_view_helper_.InitializeAndLoad(base_url_ + "long_press_object.html"); web_view->SettingsImpl()->SetAlwaysShowContextMenuOnTouch(true); web_view->Resize(WebSize(500, 300)); web_view->UpdateAllLifecyclePhases(); RunPendingTasks(); WebGestureEvent event(WebInputEvent::kGestureLongPress, WebInputEvent::kNoModifiers, WebInputEvent::GetStaticTimeStampForTests(), kWebGestureDeviceTouchscreen); event.SetPositionInWidget(WebFloatPoint(10, 10)); EXPECT_NE(WebInputEventResult::kHandledSystem, web_view->HandleInputEvent(WebCoalescedInputEvent(event))); HTMLElement* element = ToHTMLElement( web_view->MainFrameImpl()->GetDocument().GetElementById("obj")); EXPECT_FALSE(element->CanStartSelection()); } TEST_F(WebViewTest, LongPressObjectFallback) { RegisterMockedHttpURLLoad("long_press_object_fallback.html"); WebViewImpl* web_view = web_view_helper_.InitializeAndLoad( base_url_ + "long_press_object_fallback.html"); web_view->SettingsImpl()->SetAlwaysShowContextMenuOnTouch(true); web_view->Resize(WebSize(500, 300)); web_view->UpdateAllLifecyclePhases(); RunPendingTasks(); WebGestureEvent event(WebInputEvent::kGestureLongPress, WebInputEvent::kNoModifiers, WebInputEvent::GetStaticTimeStampForTests(), kWebGestureDeviceTouchscreen); event.SetPositionInWidget(WebFloatPoint(10, 10)); EXPECT_EQ(WebInputEventResult::kHandledSystem, web_view->HandleInputEvent(WebCoalescedInputEvent(event))); HTMLElement* element = ToHTMLElement( web_view->MainFrameImpl()->GetDocument().GetElementById("obj")); EXPECT_TRUE(element->CanStartSelection()); } TEST_F(WebViewTest, LongPressImage) { RegisterMockedHttpURLLoad("long_press_image.html"); WebViewImpl* web_view = web_view_helper_.InitializeAndLoad(base_url_ + "long_press_image.html"); web_view->SettingsImpl()->SetAlwaysShowContextMenuOnTouch(false); web_view->Resize(WebSize(500, 300)); web_view->UpdateAllLifecyclePhases(); RunPendingTasks(); WebGestureEvent event(WebInputEvent::kGestureLongPress, WebInputEvent::kNoModifiers, WebInputEvent::GetStaticTimeStampForTests(), kWebGestureDeviceTouchscreen); event.SetPositionInWidget(WebFloatPoint(10, 10)); EXPECT_EQ(WebInputEventResult::kHandledSystem, web_view->HandleInputEvent(WebCoalescedInputEvent(event))); } TEST_F(WebViewTest, LongPressVideo) { RegisterMockedHttpURLLoad("long_press_video.html"); WebViewImpl* web_view = web_view_helper_.InitializeAndLoad(base_url_ + "long_press_video.html"); web_view->SettingsImpl()->SetAlwaysShowContextMenuOnTouch(false); web_view->Resize(WebSize(500, 300)); web_view->UpdateAllLifecyclePhases(); RunPendingTasks(); WebGestureEvent event(WebInputEvent::kGestureLongPress, WebInputEvent::kNoModifiers, WebInputEvent::GetStaticTimeStampForTests(), kWebGestureDeviceTouchscreen); event.SetPositionInWidget(WebFloatPoint(10, 10)); EXPECT_EQ(WebInputEventResult::kHandledSystem, web_view->HandleInputEvent(WebCoalescedInputEvent(event))); } TEST_F(WebViewTest, LongPressLink) { RegisterMockedHttpURLLoad("long_press_link.html"); WebViewImpl* web_view = web_view_helper_.InitializeAndLoad(base_url_ + "long_press_link.html"); web_view->SettingsImpl()->SetAlwaysShowContextMenuOnTouch(false); web_view->Resize(WebSize(500, 300)); web_view->UpdateAllLifecyclePhases(); RunPendingTasks(); WebGestureEvent event(WebInputEvent::kGestureLongPress, WebInputEvent::kNoModifiers, WebInputEvent::GetStaticTimeStampForTests(), kWebGestureDeviceTouchscreen); event.SetPositionInWidget(WebFloatPoint(500, 300)); EXPECT_EQ(WebInputEventResult::kHandledSystem, web_view->HandleInputEvent(WebCoalescedInputEvent(event))); } // Tests that we send touchcancel when drag start by long press. TEST_F(WebViewTest, TouchCancelOnStartDragging) { RegisterMockedHttpURLLoad("long_press_draggable_div.html"); URLTestHelpers::RegisterMockedURLLoad( ToKURL("http://www.test.com/foo.png"), test::CoreTestDataPath("white-1x1.png")); WebViewImpl* web_view = web_view_helper_.InitializeAndLoad( base_url_ + "long_press_draggable_div.html"); web_view->SettingsImpl()->SetTouchDragDropEnabled(true); web_view->Resize(WebSize(500, 300)); web_view->UpdateAllLifecyclePhases(); RunPendingTasks(); WebPointerEvent pointer_down( WebInputEvent::kPointerDown, WebPointerProperties(1, WebPointerProperties::PointerType::kTouch), 5, 5); pointer_down.SetPositionInWidget(250, 8); web_view->HandleInputEvent(WebCoalescedInputEvent(pointer_down)); web_view->DispatchBufferedTouchEvents(); WebString target_id = WebString::FromUTF8("target"); // Send long press to start dragging EXPECT_TRUE(TapElementById(WebInputEvent::kGestureLongPress, target_id)); EXPECT_STREQ("dragstart", web_view->MainFrameImpl()->GetDocument().Title().Utf8().data()); // Check pointer cancel is sent to dom. WebPointerEvent pointer_cancel( WebInputEvent::kPointerCancel, WebPointerProperties(1, WebPointerProperties::PointerType::kTouch), 5, 5); pointer_cancel.SetPositionInWidget(250, 8); EXPECT_NE(WebInputEventResult::kHandledSuppressed, web_view->HandleInputEvent(WebCoalescedInputEvent(pointer_cancel))); web_view->DispatchBufferedTouchEvents(); EXPECT_STREQ("touchcancel", web_view->MainFrameImpl()->GetDocument().Title().Utf8().data()); } TEST_F(WebViewTest, showContextMenuOnLongPressingLinks) { RegisterMockedHttpURLLoad("long_press_links_and_images.html"); URLTestHelpers::RegisterMockedURLLoad( ToKURL("http://www.test.com/foo.png"), test::CoreTestDataPath("white-1x1.png")); WebViewImpl* web_view = web_view_helper_.InitializeAndLoad( base_url_ + "long_press_links_and_images.html"); web_view->SettingsImpl()->SetTouchDragDropEnabled(true); web_view->Resize(WebSize(500, 300)); web_view->UpdateAllLifecyclePhases(); RunPendingTasks(); WebString anchor_tag_id = WebString::FromUTF8("anchorTag"); WebString image_tag_id = WebString::FromUTF8("imageTag"); EXPECT_TRUE(TapElementById(WebInputEvent::kGestureLongPress, anchor_tag_id)); EXPECT_STREQ("anchor contextmenu", web_view->MainFrameImpl()->GetDocument().Title().Utf8().data()); EXPECT_TRUE(TapElementById(WebInputEvent::kGestureLongPress, image_tag_id)); EXPECT_STREQ("image contextmenu", web_view->MainFrameImpl()->GetDocument().Title().Utf8().data()); } TEST_F(WebViewTest, LongPressEmptyEditableSelection) { RegisterMockedHttpURLLoad("long_press_empty_editable_selection.html"); WebViewImpl* web_view = web_view_helper_.InitializeAndLoad( base_url_ + "long_press_empty_editable_selection.html"); web_view->SettingsImpl()->SetAlwaysShowContextMenuOnTouch(false); web_view->Resize(WebSize(500, 300)); web_view->UpdateAllLifecyclePhases(); RunPendingTasks(); WebGestureEvent event(WebInputEvent::kGestureLongPress, WebInputEvent::kNoModifiers, WebInputEvent::GetStaticTimeStampForTests(), kWebGestureDeviceTouchscreen); event.SetPositionInWidget(WebFloatPoint(10, 10)); EXPECT_EQ(WebInputEventResult::kHandledSystem, web_view->HandleInputEvent(WebCoalescedInputEvent(event))); } TEST_F(WebViewTest, LongPressEmptyNonEditableSelection) { RegisterMockedHttpURLLoad("long_press_image.html"); WebViewImpl* web_view = web_view_helper_.InitializeAndLoad(base_url_ + "long_press_image.html"); web_view->Resize(WebSize(500, 500)); web_view->UpdateAllLifecyclePhases(); RunPendingTasks(); WebGestureEvent event(WebInputEvent::kGestureLongPress, WebInputEvent::kNoModifiers, WebInputEvent::GetStaticTimeStampForTests(), kWebGestureDeviceTouchscreen); event.SetPositionInWidget(WebFloatPoint(300, 300)); WebLocalFrameImpl* frame = web_view->MainFrameImpl(); EXPECT_EQ(WebInputEventResult::kHandledSystem, web_view->HandleInputEvent(WebCoalescedInputEvent(event))); EXPECT_TRUE(frame->SelectionAsText().IsEmpty()); } TEST_F(WebViewTest, LongPressSelection) { RegisterMockedHttpURLLoad("longpress_selection.html"); WebViewImpl* web_view = web_view_helper_.InitializeAndLoad( base_url_ + "longpress_selection.html"); web_view->Resize(WebSize(500, 300)); web_view->UpdateAllLifecyclePhases(); RunPendingTasks(); WebString target = WebString::FromUTF8("target"); WebString onselectstartfalse = WebString::FromUTF8("onselectstartfalse"); WebLocalFrameImpl* frame = web_view->MainFrameImpl(); EXPECT_TRUE( TapElementById(WebInputEvent::kGestureLongPress, onselectstartfalse)); EXPECT_EQ("", std::string(frame->SelectionAsText().Utf8().data())); EXPECT_TRUE(TapElementById(WebInputEvent::kGestureLongPress, target)); EXPECT_EQ("testword", std::string(frame->SelectionAsText().Utf8().data())); } TEST_F(WebViewTest, FinishComposingTextDoesNotDismissHandles) { RegisterMockedHttpURLLoad("longpress_selection.html"); WebViewImpl* web_view = web_view_helper_.InitializeAndLoad( base_url_ + "longpress_selection.html"); web_view->Resize(WebSize(500, 300)); web_view->UpdateAllLifecyclePhases(); RunPendingTasks(); WebString target = WebString::FromUTF8("target"); WebLocalFrameImpl* frame = web_view->MainFrameImpl(); WebInputMethodController* active_input_method_controller = frame->FrameWidget()->GetActiveWebInputMethodController(); EXPECT_TRUE(TapElementById(WebInputEvent::kGestureTap, target)); WebVector<WebImeTextSpan> empty_ime_text_spans; frame->SetEditableSelectionOffsets(8, 8); EXPECT_TRUE(active_input_method_controller->SetComposition( "12345", empty_ime_text_spans, WebRange(), 8, 13)); EXPECT_TRUE(frame->GetFrame()->GetInputMethodController().HasComposition()); EXPECT_EQ("", std::string(frame->SelectionAsText().Utf8().data())); EXPECT_FALSE(frame->GetFrame()->Selection().IsHandleVisible()); EXPECT_TRUE(frame->GetFrame()->GetInputMethodController().HasComposition()); EXPECT_TRUE(TapElementById(WebInputEvent::kGestureLongPress, target)); EXPECT_EQ("testword12345", std::string(frame->SelectionAsText().Utf8().data())); EXPECT_TRUE(frame->GetFrame()->Selection().IsHandleVisible()); EXPECT_TRUE(frame->GetFrame()->GetInputMethodController().HasComposition()); // Check that finishComposingText(KeepSelection) does not dismiss handles. active_input_method_controller->FinishComposingText( WebInputMethodController::kKeepSelection); EXPECT_TRUE(frame->GetFrame()->Selection().IsHandleVisible()); } #if !defined(OS_MACOSX) TEST_F(WebViewTest, TouchDoesntSelectEmptyTextarea) { RegisterMockedHttpURLLoad("longpress_textarea.html"); WebViewImpl* web_view = web_view_helper_.InitializeAndLoad(base_url_ + "longpress_textarea.html"); web_view->Resize(WebSize(500, 300)); web_view->UpdateAllLifecyclePhases(); RunPendingTasks(); WebString blanklinestextbox = WebString::FromUTF8("blanklinestextbox"); WebLocalFrameImpl* frame = web_view->MainFrameImpl(); // Long-press on carriage returns. EXPECT_TRUE( TapElementById(WebInputEvent::kGestureLongPress, blanklinestextbox)); EXPECT_TRUE(frame->SelectionAsText().IsEmpty()); // Double-tap on carriage returns. WebGestureEvent event(WebInputEvent::kGestureTap, WebInputEvent::kNoModifiers, WebInputEvent::GetStaticTimeStampForTests(), kWebGestureDeviceTouchscreen); event.SetPositionInWidget(WebFloatPoint(100, 25)); event.data.tap.tap_count = 2; web_view->HandleInputEvent(WebCoalescedInputEvent(event)); EXPECT_TRUE(frame->SelectionAsText().IsEmpty()); HTMLTextAreaElement* text_area_element = ToHTMLTextAreaElement( web_view->MainFrameImpl()->GetDocument().GetElementById( blanklinestextbox)); text_area_element->setValue("hello"); // Long-press past last word of textbox. EXPECT_TRUE( TapElementById(WebInputEvent::kGestureLongPress, blanklinestextbox)); EXPECT_TRUE(frame->SelectionAsText().IsEmpty()); // Double-tap past last word of textbox. web_view->HandleInputEvent(WebCoalescedInputEvent(event)); EXPECT_TRUE(frame->SelectionAsText().IsEmpty()); } #endif TEST_F(WebViewTest, LongPressImageTextarea) { RegisterMockedHttpURLLoad("longpress_image_contenteditable.html"); WebViewImpl* web_view = web_view_helper_.InitializeAndLoad( base_url_ + "longpress_image_contenteditable.html"); web_view->Resize(WebSize(500, 300)); web_view->UpdateAllLifecyclePhases(); RunPendingTasks(); WebString image = WebString::FromUTF8("purpleimage"); EXPECT_TRUE(TapElementById(WebInputEvent::kGestureLongPress, image)); WebRange range = web_view->MainFrameImpl() ->GetInputMethodController() ->GetSelectionOffsets(); EXPECT_FALSE(range.IsNull()); EXPECT_EQ(0, range.StartOffset()); EXPECT_EQ(1, range.length()); } TEST_F(WebViewTest, BlinkCaretAfterLongPress) { RegisterMockedHttpURLLoad("blink_caret_on_typing_after_long_press.html"); WebViewImpl* web_view = web_view_helper_.InitializeAndLoad( base_url_ + "blink_caret_on_typing_after_long_press.html"); web_view->Resize(WebSize(640, 480)); web_view->UpdateAllLifecyclePhases(); RunPendingTasks(); WebString target = WebString::FromUTF8("target"); WebLocalFrameImpl* main_frame = web_view->MainFrameImpl(); EXPECT_TRUE(TapElementById(WebInputEvent::kGestureLongPress, target)); EXPECT_FALSE(main_frame->GetFrame()->Selection().IsCaretBlinkingSuspended()); } TEST_F(WebViewTest, BlinkCaretOnClosingContextMenu) { RegisterMockedHttpURLLoad("form.html"); WebViewImpl* web_view = web_view_helper_.InitializeAndLoad(base_url_ + "form.html"); web_view->SetInitialFocus(false); RunPendingTasks(); // We suspend caret blinking when pressing with mouse right button. // Note that we do not send MouseUp event here since it will be consumed // by the context menu once it shows up. WebMouseEvent mouse_event(WebInputEvent::kMouseDown, WebInputEvent::kNoModifiers, WebInputEvent::GetStaticTimeStampForTests()); mouse_event.button = WebMouseEvent::Button::kRight; mouse_event.SetPositionInWidget(1, 1); mouse_event.click_count = 1; web_view->HandleInputEvent(WebCoalescedInputEvent(mouse_event)); RunPendingTasks(); WebLocalFrameImpl* main_frame = web_view->MainFrameImpl(); EXPECT_TRUE(main_frame->GetFrame()->Selection().IsCaretBlinkingSuspended()); // Caret blinking is still suspended after showing context menu. web_view->GetWidget()->ShowContextMenu(kMenuSourceMouse); EXPECT_TRUE(main_frame->GetFrame()->Selection().IsCaretBlinkingSuspended()); // Caret blinking will be resumed only after context menu is closed. web_view->DidCloseContextMenu(); EXPECT_FALSE(main_frame->GetFrame()->Selection().IsCaretBlinkingSuspended()); } TEST_F(WebViewTest, SelectionOnReadOnlyInput) { RegisterMockedHttpURLLoad("selection_readonly.html"); WebViewImpl* web_view = web_view_helper_.InitializeAndLoad(base_url_ + "selection_readonly.html"); web_view->Resize(WebSize(640, 480)); web_view->UpdateAllLifecyclePhases(); RunPendingTasks(); std::string test_word = "This text should be selected."; WebLocalFrameImpl* frame = web_view->MainFrameImpl(); EXPECT_EQ(test_word, std::string(frame->SelectionAsText().Utf8().data())); WebRange range = web_view->MainFrameImpl() ->GetInputMethodController() ->GetSelectionOffsets(); EXPECT_FALSE(range.IsNull()); EXPECT_EQ(0, range.StartOffset()); EXPECT_EQ(static_cast<int>(test_word.length()), range.length()); } TEST_F(WebViewTest, KeyDownScrollsHandled) { RegisterMockedHttpURLLoad("content-width-1000.html"); WebViewImpl* web_view = web_view_helper_.InitializeAndLoad(base_url_ + "content-width-1000.html"); web_view->Resize(WebSize(100, 100)); web_view->UpdateAllLifecyclePhases(); RunPendingTasks(); WebKeyboardEvent key_event(WebInputEvent::kRawKeyDown, WebInputEvent::kNoModifiers, WebInputEvent::GetStaticTimeStampForTests()); // RawKeyDown pagedown should be handled. key_event.windows_key_code = VKEY_NEXT; EXPECT_EQ(WebInputEventResult::kHandledSystem, web_view->HandleInputEvent(WebCoalescedInputEvent(key_event))); key_event.SetType(WebInputEvent::kKeyUp); web_view->HandleInputEvent(WebCoalescedInputEvent(key_event)); // Coalesced KeyDown arrow-down should be handled. key_event.windows_key_code = VKEY_DOWN; key_event.SetType(WebInputEvent::kKeyDown); EXPECT_EQ(WebInputEventResult::kHandledSystem, web_view->HandleInputEvent(WebCoalescedInputEvent(key_event))); key_event.SetType(WebInputEvent::kKeyUp); web_view->HandleInputEvent(WebCoalescedInputEvent(key_event)); // Ctrl-Home should be handled... key_event.windows_key_code = VKEY_HOME; key_event.SetModifiers(WebInputEvent::kControlKey); key_event.SetType(WebInputEvent::kRawKeyDown); EXPECT_EQ(WebInputEventResult::kNotHandled, web_view->HandleInputEvent(WebCoalescedInputEvent(key_event))); key_event.SetType(WebInputEvent::kKeyUp); web_view->HandleInputEvent(WebCoalescedInputEvent(key_event)); // But Ctrl-Down should not. key_event.windows_key_code = VKEY_DOWN; key_event.SetModifiers(WebInputEvent::kControlKey); key_event.SetType(WebInputEvent::kRawKeyDown); EXPECT_EQ(WebInputEventResult::kNotHandled, web_view->HandleInputEvent(WebCoalescedInputEvent(key_event))); key_event.SetType(WebInputEvent::kKeyUp); web_view->HandleInputEvent(WebCoalescedInputEvent(key_event)); // Shift, meta, and alt should not be handled. key_event.windows_key_code = VKEY_NEXT; key_event.SetModifiers(WebInputEvent::kShiftKey); key_event.SetType(WebInputEvent::kRawKeyDown); EXPECT_EQ(WebInputEventResult::kNotHandled, web_view->HandleInputEvent(WebCoalescedInputEvent(key_event))); key_event.SetType(WebInputEvent::kKeyUp); web_view->HandleInputEvent(WebCoalescedInputEvent(key_event)); key_event.windows_key_code = VKEY_NEXT; key_event.SetModifiers(WebInputEvent::kMetaKey); key_event.SetType(WebInputEvent::kRawKeyDown); EXPECT_EQ(WebInputEventResult::kNotHandled, web_view->HandleInputEvent(WebCoalescedInputEvent(key_event))); key_event.SetType(WebInputEvent::kKeyUp); web_view->HandleInputEvent(WebCoalescedInputEvent(key_event)); key_event.windows_key_code = VKEY_NEXT; key_event.SetModifiers(WebInputEvent::kAltKey); key_event.SetType(WebInputEvent::kRawKeyDown); EXPECT_EQ(WebInputEventResult::kNotHandled, web_view->HandleInputEvent(WebCoalescedInputEvent(key_event))); key_event.SetType(WebInputEvent::kKeyUp); web_view->HandleInputEvent(WebCoalescedInputEvent(key_event)); // System-key labeled Alt-Down (as in Windows) should do nothing, // but non-system-key labeled Alt-Down (as in Mac) should be handled // as a page-down. key_event.windows_key_code = VKEY_DOWN; key_event.SetModifiers(WebInputEvent::kAltKey); key_event.is_system_key = true; key_event.SetType(WebInputEvent::kRawKeyDown); EXPECT_EQ(WebInputEventResult::kNotHandled, web_view->HandleInputEvent(WebCoalescedInputEvent(key_event))); key_event.SetType(WebInputEvent::kKeyUp); web_view->HandleInputEvent(WebCoalescedInputEvent(key_event)); key_event.windows_key_code = VKEY_DOWN; key_event.SetModifiers(WebInputEvent::kAltKey); key_event.is_system_key = false; key_event.SetType(WebInputEvent::kRawKeyDown); EXPECT_EQ(WebInputEventResult::kHandledSystem, web_view->HandleInputEvent(WebCoalescedInputEvent(key_event))); key_event.SetType(WebInputEvent::kKeyUp); web_view->HandleInputEvent(WebCoalescedInputEvent(key_event)); } class MiddleClickAutoscrollWebWidgetClient : public FrameTestHelpers::TestWebWidgetClient { public: // WebWidgetClient methods void DidChangeCursor(const WebCursorInfo& cursor) override { last_cursor_type_ = cursor.type; } int GetLastCursorType() const { return last_cursor_type_; } private: int last_cursor_type_ = 0; }; TEST_F(WebViewTest, MiddleClickAutoscrollCursor) { MiddleClickAutoscrollWebWidgetClient client; ScopedMiddleClickAutoscrollForTest middle_click_autoscroll(true); RegisterMockedHttpURLLoad("content-width-1000.html"); WebViewImpl* web_view = web_view_helper_.InitializeAndLoad( base_url_ + "content-width-1000.html", nullptr, nullptr, &client); web_view->Resize(WebSize(100, 100)); web_view->UpdateAllLifecyclePhases(); RunPendingTasks(); WebMouseEvent mouse_event(WebInputEvent::kMouseDown, WebInputEvent::kNoModifiers, WebInputEvent::GetStaticTimeStampForTests()); mouse_event.button = WebMouseEvent::Button::kMiddle; mouse_event.SetPositionInWidget(1, 1); mouse_event.click_count = 1; // Start middle-click autoscroll. web_view->HandleInputEvent(WebCoalescedInputEvent(mouse_event)); mouse_event.SetType(WebInputEvent::kMouseUp); web_view->HandleInputEvent(WebCoalescedInputEvent(mouse_event)); EXPECT_EQ(MiddlePanningCursor().GetType(), client.GetLastCursorType()); LocalFrame* local_frame = ToWebLocalFrameImpl(web_view->MainFrame())->GetFrame(); // Even if a plugin tries to change the cursor type, that should be ignored // during middle-click autoscroll. web_view->GetChromeClient().SetCursorForPlugin(WebCursorInfo(PointerCursor()), local_frame); EXPECT_EQ(MiddlePanningCursor().GetType(), client.GetLastCursorType()); // End middle-click autoscroll. mouse_event.SetType(WebInputEvent::kMouseDown); web_view->HandleInputEvent(WebCoalescedInputEvent(mouse_event)); mouse_event.SetType(WebInputEvent::kMouseUp); web_view->HandleInputEvent(WebCoalescedInputEvent(mouse_event)); web_view->GetChromeClient().SetCursorForPlugin(WebCursorInfo(IBeamCursor()), local_frame); EXPECT_EQ(IBeamCursor().GetType(), client.GetLastCursorType()); } static void ConfigueCompositingWebView(WebSettings* settings) { settings->SetPreferCompositingToLCDTextEnabled(true); } TEST_F(WebViewTest, ShowPressOnTransformedLink) { FrameTestHelpers::WebViewHelper web_view_helper; WebViewImpl* web_view_impl = web_view_helper.Initialize( nullptr, nullptr, nullptr, &ConfigueCompositingWebView); int page_width = 640; int page_height = 480; web_view_impl->Resize(WebSize(page_width, page_height)); WebURL base_url = URLTestHelpers::ToKURL("http://example.com/"); FrameTestHelpers::LoadHTMLString( web_view_impl->MainFrameImpl(), "<a href='http://www.test.com' style='position: absolute; left: 20px; " "top: 20px; width: 200px; transform:translateZ(0);'>A link to " "highlight</a>", base_url); WebGestureEvent event(WebInputEvent::kGestureShowPress, WebInputEvent::kNoModifiers, WebInputEvent::GetStaticTimeStampForTests(), kWebGestureDeviceTouchscreen); event.SetPositionInWidget(WebFloatPoint(20, 20)); // Just make sure we don't hit any asserts. web_view_impl->HandleInputEvent(WebCoalescedInputEvent(event)); } class MockAutofillClient : public WebAutofillClient { public: MockAutofillClient() : text_changes_(0), text_changes_from_user_gesture_(0), user_gesture_notifications_count_(0) {} ~MockAutofillClient() override = default; void TextFieldDidChange(const WebFormControlElement&) override { ++text_changes_; if (UserGestureIndicator::ProcessingUserGesture()) ++text_changes_from_user_gesture_; } void UserGestureObserved() override { ++user_gesture_notifications_count_; } void ClearChangeCounts() { text_changes_ = 0; } int TextChanges() { return text_changes_; } int TextChangesFromUserGesture() { return text_changes_from_user_gesture_; } int GetUserGestureNotificationsCount() { return user_gesture_notifications_count_; } private: int text_changes_; int text_changes_from_user_gesture_; int user_gesture_notifications_count_; }; TEST_F(WebViewTest, LosingFocusDoesNotTriggerAutofillTextChange) { RegisterMockedHttpURLLoad("input_field_populated.html"); MockAutofillClient client; WebViewImpl* web_view = web_view_helper_.InitializeAndLoad( base_url_ + "input_field_populated.html"); WebLocalFrameImpl* frame = web_view->MainFrameImpl(); frame->SetAutofillClient(&client); web_view->SetInitialFocus(false); // Set up a composition that needs to be committed. WebVector<WebImeTextSpan> empty_ime_text_spans; frame->SetEditableSelectionOffsets(4, 10); frame->SetCompositionFromExistingText(8, 12, empty_ime_text_spans); WebTextInputInfo info = frame->GetInputMethodController()->TextInputInfo(); EXPECT_EQ(4, info.selection_start); EXPECT_EQ(10, info.selection_end); EXPECT_EQ(8, info.composition_start); EXPECT_EQ(12, info.composition_end); // Clear the focus and track that the subsequent composition commit does not // trigger a text changed notification for autofill. client.ClearChangeCounts(); web_view->SetFocus(false); EXPECT_EQ(0, client.TextChanges()); frame->SetAutofillClient(nullptr); } static void VerifySelectionAndComposition(WebViewImpl* web_view, int selection_start, int selection_end, int composition_start, int composition_end, const char* fail_message) { WebTextInputInfo info = web_view->MainFrameImpl()->GetInputMethodController()->TextInputInfo(); EXPECT_EQ(selection_start, info.selection_start) << fail_message; EXPECT_EQ(selection_end, info.selection_end) << fail_message; EXPECT_EQ(composition_start, info.composition_start) << fail_message; EXPECT_EQ(composition_end, info.composition_end) << fail_message; } TEST_F(WebViewTest, CompositionNotCancelledByBackspace) { RegisterMockedHttpURLLoad("composition_not_cancelled_by_backspace.html"); MockAutofillClient client; WebViewImpl* web_view = web_view_helper_.InitializeAndLoad( base_url_ + "composition_not_cancelled_by_backspace.html"); WebLocalFrameImpl* frame = web_view->MainFrameImpl(); frame->SetAutofillClient(&client); web_view->SetInitialFocus(false); // Test both input elements. for (int i = 0; i < 2; ++i) { // Select composition and do sanity check. WebVector<WebImeTextSpan> empty_ime_text_spans; frame->SetEditableSelectionOffsets(6, 6); WebInputMethodController* active_input_method_controller = frame->FrameWidget()->GetActiveWebInputMethodController(); EXPECT_TRUE(active_input_method_controller->SetComposition( "fghij", empty_ime_text_spans, WebRange(), 0, 5)); frame->SetEditableSelectionOffsets(11, 11); VerifySelectionAndComposition(web_view, 11, 11, 6, 11, "initial case"); // Press Backspace and verify composition didn't get cancelled. This is to // verify the fix for crbug.com/429916. WebKeyboardEvent key_event(WebInputEvent::kRawKeyDown, WebInputEvent::kNoModifiers, WebInputEvent::GetStaticTimeStampForTests()); key_event.dom_key = Platform::Current()->DomKeyEnumFromString("\b"); key_event.windows_key_code = VKEY_BACK; web_view->HandleInputEvent(WebCoalescedInputEvent(key_event)); frame->SetEditableSelectionOffsets(6, 6); EXPECT_TRUE(active_input_method_controller->SetComposition( "fghi", empty_ime_text_spans, WebRange(), 0, 4)); frame->SetEditableSelectionOffsets(10, 10); VerifySelectionAndComposition(web_view, 10, 10, 6, 10, "after pressing Backspace"); key_event.SetType(WebInputEvent::kKeyUp); web_view->HandleInputEvent(WebCoalescedInputEvent(key_event)); web_view->AdvanceFocus(false); } frame->SetAutofillClient(nullptr); } TEST_F(WebViewTest, FinishComposingTextDoesntTriggerAutofillTextChange) { RegisterMockedHttpURLLoad("input_field_populated.html"); MockAutofillClient client; WebViewImpl* web_view = web_view_helper_.InitializeAndLoad( base_url_ + "input_field_populated.html"); WebLocalFrameImpl* frame = web_view->MainFrameImpl(); frame->SetAutofillClient(&client); web_view->SetInitialFocus(false); WebDocument document = web_view->MainFrameImpl()->GetDocument(); HTMLFormControlElement* form = ToHTMLFormControlElement(document.GetElementById("sample")); WebInputMethodController* active_input_method_controller = frame->FrameWidget()->GetActiveWebInputMethodController(); // Set up a composition that needs to be committed. std::string composition_text("testingtext"); WebVector<WebImeTextSpan> empty_ime_text_spans; active_input_method_controller->SetComposition( WebString::FromUTF8(composition_text.c_str()), empty_ime_text_spans, WebRange(), 0, composition_text.length()); WebTextInputInfo info = active_input_method_controller->TextInputInfo(); EXPECT_EQ(0, info.selection_start); EXPECT_EQ((int)composition_text.length(), info.selection_end); EXPECT_EQ(0, info.composition_start); EXPECT_EQ((int)composition_text.length(), info.composition_end); form->SetAutofilled(true); client.ClearChangeCounts(); active_input_method_controller->FinishComposingText( WebInputMethodController::kKeepSelection); EXPECT_EQ(0, client.TextChanges()); EXPECT_TRUE(form->IsAutofilled()); frame->SetAutofillClient(nullptr); } TEST_F(WebViewTest, SetCompositionFromExistingTextDoesntTriggerAutofillTextChange) { RegisterMockedHttpURLLoad("input_field_populated.html"); MockAutofillClient client; WebViewImpl* web_view = web_view_helper_.InitializeAndLoad( base_url_ + "input_field_populated.html"); WebLocalFrameImpl* frame = web_view->MainFrameImpl(); frame->SetAutofillClient(&client); web_view->SetInitialFocus(false); WebVector<WebImeTextSpan> empty_ime_text_spans; client.ClearChangeCounts(); frame->SetCompositionFromExistingText(8, 12, empty_ime_text_spans); WebTextInputInfo info = frame->GetInputMethodController()->TextInputInfo(); EXPECT_EQ("0123456789abcdefghijklmnopqrstuvwxyz", std::string(info.value.Utf8().data())); EXPECT_EQ(8, info.composition_start); EXPECT_EQ(12, info.composition_end); EXPECT_EQ(0, client.TextChanges()); WebDocument document = web_view->MainFrameImpl()->GetDocument(); EXPECT_EQ(WebString::FromUTF8("none"), document.GetElementById("inputEvent").FirstChild().NodeValue()); frame->SetAutofillClient(nullptr); } class ViewCreatingWebViewClient : public FrameTestHelpers::TestWebViewClient { public: ViewCreatingWebViewClient() : did_focus_called_(false) {} // WebViewClient methods WebView* CreateView(WebLocalFrame* opener, const WebURLRequest&, const WebWindowFeatures&, const WebString& name, WebNavigationPolicy, bool, WebSandboxFlags) override { return web_view_helper_.InitializeWithOpener(opener); } // WebWidgetClient methods void DidFocus(WebLocalFrame*) override { did_focus_called_ = true; } bool DidFocusCalled() const { return did_focus_called_; } WebView* CreatedWebView() const { return web_view_helper_.GetWebView(); } private: FrameTestHelpers::WebViewHelper web_view_helper_; bool did_focus_called_; }; TEST_F(WebViewTest, DoNotFocusCurrentFrameOnNavigateFromLocalFrame) { ViewCreatingWebViewClient client; FrameTestHelpers::WebViewHelper web_view_helper; WebViewImpl* web_view_impl = web_view_helper.Initialize(nullptr, &client); WebURL base_url = URLTestHelpers::ToKURL("http://example.com/"); FrameTestHelpers::LoadHTMLString( web_view_impl->MainFrameImpl(), "<html><body><iframe src=\"about:blank\"></iframe></body></html>", base_url); // Make a request from a local frame. WebURLRequest web_url_request_with_target_start; LocalFrame* local_frame = ToWebLocalFrameImpl(web_view_impl->MainFrame()->FirstChild())->GetFrame(); FrameLoadRequest request_with_target_start( local_frame->GetDocument(), web_url_request_with_target_start.ToResourceRequest(), "_top"); local_frame->Loader().StartNavigation(request_with_target_start); EXPECT_FALSE(client.DidFocusCalled()); web_view_helper.Reset(); // Remove dependency on locally scoped client. } TEST_F(WebViewTest, FocusExistingFrameOnNavigate) { ViewCreatingWebViewClient client; FrameTestHelpers::WebViewHelper web_view_helper; WebViewImpl* web_view_impl = web_view_helper.Initialize(nullptr, &client); WebLocalFrameImpl* frame = web_view_impl->MainFrameImpl(); frame->SetName("_start"); // Make a request that will open a new window WebURLRequest web_url_request; FrameLoadRequest request(nullptr, web_url_request.ToResourceRequest(), "_blank"); ToLocalFrame(web_view_impl->GetPage()->MainFrame()) ->Loader() .StartNavigation(request); ASSERT_TRUE(client.CreatedWebView()); EXPECT_FALSE(client.DidFocusCalled()); // Make a request from the new window that will navigate the original window. // The original window should be focused. WebURLRequest web_url_request_with_target_start; FrameLoadRequest request_with_target_start( nullptr, web_url_request_with_target_start.ToResourceRequest(), "_start"); ToLocalFrame(static_cast<WebViewImpl*>(client.CreatedWebView()) ->GetPage() ->MainFrame()) ->Loader() .StartNavigation(request_with_target_start); EXPECT_TRUE(client.DidFocusCalled()); web_view_helper.Reset(); // Remove dependency on locally scoped client. } TEST_F(WebViewTest, DispatchesFocusOutFocusInOnViewToggleFocus) { RegisterMockedHttpURLLoad("focusout_focusin_events.html"); WebViewImpl* web_view = web_view_helper_.InitializeAndLoad( base_url_ + "focusout_focusin_events.html"); web_view->SetFocus(true); web_view->SetFocus(false); web_view->SetFocus(true); WebElement element = web_view->MainFrameImpl()->GetDocument().GetElementById("message"); EXPECT_STREQ("focusoutfocusin", element.TextContent().Utf8().data()); } TEST_F(WebViewTest, DispatchesDomFocusOutDomFocusInOnViewToggleFocus) { RegisterMockedHttpURLLoad("domfocusout_domfocusin_events.html"); WebViewImpl* web_view = web_view_helper_.InitializeAndLoad( base_url_ + "domfocusout_domfocusin_events.html"); web_view->SetFocus(true); web_view->SetFocus(false); web_view->SetFocus(true); WebElement element = web_view->MainFrameImpl()->GetDocument().GetElementById("message"); EXPECT_STREQ("DOMFocusOutDOMFocusIn", element.TextContent().Utf8().data()); } static void OpenDateTimeChooser(WebView* web_view, HTMLInputElement* input_element) { input_element->focus(); WebKeyboardEvent key_event(WebInputEvent::kRawKeyDown, WebInputEvent::kNoModifiers, WebInputEvent::GetStaticTimeStampForTests()); key_event.dom_key = Platform::Current()->DomKeyEnumFromString(" "); key_event.windows_key_code = VKEY_SPACE; web_view->HandleInputEvent(WebCoalescedInputEvent(key_event)); key_event.SetType(WebInputEvent::kKeyUp); web_view->HandleInputEvent(WebCoalescedInputEvent(key_event)); } // TODO(crbug.com/605112) This test is crashing on Android (Nexus 4) bot. #if defined(OS_ANDROID) TEST_F(WebViewTest, DISABLED_ChooseValueFromDateTimeChooser) { #else TEST_F(WebViewTest, ChooseValueFromDateTimeChooser) { #endif ScopedInputMultipleFieldsUIForTest input_multiple_fields_ui(false); DateTimeChooserWebViewClient client; std::string url = RegisterMockedHttpURLLoad("date_time_chooser.html"); WebViewImpl* web_view_impl = web_view_helper_.InitializeAndLoad(url, nullptr, &client); Document* document = web_view_impl->MainFrameImpl()->GetFrame()->GetDocument(); HTMLInputElement* input_element; input_element = ToHTMLInputElement(document->getElementById("date")); OpenDateTimeChooser(web_view_impl, input_element); client.ChooserCompletion()->DidChooseValue(0); client.ClearChooserCompletion(); EXPECT_STREQ("1970-01-01", input_element->value().Utf8().data()); OpenDateTimeChooser(web_view_impl, input_element); client.ChooserCompletion()->DidChooseValue( std::numeric_limits<double>::quiet_NaN()); client.ClearChooserCompletion(); EXPECT_STREQ("", input_element->value().Utf8().data()); input_element = ToHTMLInputElement(document->getElementById("datetimelocal")); OpenDateTimeChooser(web_view_impl, input_element); client.ChooserCompletion()->DidChooseValue(0); client.ClearChooserCompletion(); EXPECT_STREQ("1970-01-01T00:00", input_element->value().Utf8().data()); OpenDateTimeChooser(web_view_impl, input_element); client.ChooserCompletion()->DidChooseValue( std::numeric_limits<double>::quiet_NaN()); client.ClearChooserCompletion(); EXPECT_STREQ("", input_element->value().Utf8().data()); input_element = ToHTMLInputElement(document->getElementById("month")); OpenDateTimeChooser(web_view_impl, input_element); client.ChooserCompletion()->DidChooseValue(0); client.ClearChooserCompletion(); EXPECT_STREQ("1970-01", input_element->value().Utf8().data()); OpenDateTimeChooser(web_view_impl, input_element); client.ChooserCompletion()->DidChooseValue( std::numeric_limits<double>::quiet_NaN()); client.ClearChooserCompletion(); EXPECT_STREQ("", input_element->value().Utf8().data()); input_element = ToHTMLInputElement(document->getElementById("time")); OpenDateTimeChooser(web_view_impl, input_element); client.ChooserCompletion()->DidChooseValue(0); client.ClearChooserCompletion(); EXPECT_STREQ("00:00", input_element->value().Utf8().data()); OpenDateTimeChooser(web_view_impl, input_element); client.ChooserCompletion()->DidChooseValue( std::numeric_limits<double>::quiet_NaN()); client.ClearChooserCompletion(); EXPECT_STREQ("", input_element->value().Utf8().data()); input_element = ToHTMLInputElement(document->getElementById("week")); OpenDateTimeChooser(web_view_impl, input_element); client.ChooserCompletion()->DidChooseValue(0); client.ClearChooserCompletion(); EXPECT_STREQ("1970-W01", input_element->value().Utf8().data()); OpenDateTimeChooser(web_view_impl, input_element); client.ChooserCompletion()->DidChooseValue( std::numeric_limits<double>::quiet_NaN()); client.ClearChooserCompletion(); EXPECT_STREQ("", input_element->value().Utf8().data()); // Clear the WebViewClient from the webViewHelper to avoid use-after-free in // the WebViewHelper destructor. web_view_helper_.Reset(); } TEST_F(WebViewTest, DispatchesFocusBlurOnViewToggle) { RegisterMockedHttpURLLoad("focus_blur_events.html"); WebViewImpl* web_view = web_view_helper_.InitializeAndLoad(base_url_ + "focus_blur_events.html"); web_view->SetFocus(true); web_view->SetFocus(false); web_view->SetFocus(true); WebElement element = web_view->MainFrameImpl()->GetDocument().GetElementById("message"); // Expect not to see duplication of events. EXPECT_STREQ("blurfocus", element.TextContent().Utf8().data()); } class CreateChildCounterFrameClient : public FrameTestHelpers::TestWebFrameClient { public: CreateChildCounterFrameClient() : count_(0) {} WebLocalFrame* CreateChildFrame(WebLocalFrame* parent, WebTreeScopeType, const WebString& name, const WebString& fallback_name, WebSandboxFlags, const ParsedFeaturePolicy&, const WebFrameOwnerProperties&) override; int Count() const { return count_; } private: int count_; }; WebLocalFrame* CreateChildCounterFrameClient::CreateChildFrame( WebLocalFrame* parent, WebTreeScopeType scope, const WebString& name, const WebString& fallback_name, WebSandboxFlags sandbox_flags, const ParsedFeaturePolicy& container_policy, const WebFrameOwnerProperties& frame_owner_properties) { ++count_; return TestWebFrameClient::CreateChildFrame( parent, scope, name, fallback_name, sandbox_flags, container_policy, frame_owner_properties); } TEST_F(WebViewTest, ChangeDisplayMode) { RegisterMockedHttpURLLoad("display_mode.html"); WebView* web_view = web_view_helper_.InitializeAndLoad(base_url_ + "display_mode.html"); std::string content = WebFrameContentDumper::DumpWebViewAsText(web_view, 21).Utf8(); EXPECT_EQ("regular-ui", content); web_view->SetDisplayMode(kWebDisplayModeMinimalUi); content = WebFrameContentDumper::DumpWebViewAsText(web_view, 21).Utf8(); EXPECT_EQ("minimal-ui", content); web_view_helper_.Reset(); } TEST_F(WebViewTest, AddFrameInCloseUnload) { CreateChildCounterFrameClient frame_client; RegisterMockedHttpURLLoad("add_frame_in_unload.html"); web_view_helper_.InitializeAndLoad(base_url_ + "add_frame_in_unload.html", &frame_client); web_view_helper_.Reset(); EXPECT_EQ(0, frame_client.Count()); } TEST_F(WebViewTest, AddFrameInCloseURLUnload) { CreateChildCounterFrameClient frame_client; RegisterMockedHttpURLLoad("add_frame_in_unload.html"); web_view_helper_.InitializeAndLoad(base_url_ + "add_frame_in_unload.html", &frame_client); web_view_helper_.LocalMainFrame()->DispatchUnloadEvent(); EXPECT_EQ(0, frame_client.Count()); web_view_helper_.Reset(); } TEST_F(WebViewTest, AddFrameInNavigateUnload) { CreateChildCounterFrameClient frame_client; RegisterMockedHttpURLLoad("add_frame_in_unload.html"); web_view_helper_.InitializeAndLoad(base_url_ + "add_frame_in_unload.html", &frame_client); FrameTestHelpers::LoadFrame(web_view_helper_.GetWebView()->MainFrameImpl(), "about:blank"); EXPECT_EQ(0, frame_client.Count()); web_view_helper_.Reset(); } TEST_F(WebViewTest, AddFrameInChildInNavigateUnload) { CreateChildCounterFrameClient frame_client; RegisterMockedHttpURLLoad("add_frame_in_unload_wrapper.html"); RegisterMockedHttpURLLoad("add_frame_in_unload.html"); web_view_helper_.InitializeAndLoad( base_url_ + "add_frame_in_unload_wrapper.html", &frame_client); FrameTestHelpers::LoadFrame(web_view_helper_.GetWebView()->MainFrameImpl(), "about:blank"); EXPECT_EQ(1, frame_client.Count()); web_view_helper_.Reset(); } class TouchEventHandlerWebWidgetClient : public FrameTestHelpers::TestWebWidgetClient { public: // WebWidgetClient methods void HasTouchEventHandlers(bool state) override { // Only count the times the state changes. if (state != has_touch_event_handler_) has_touch_event_handler_count_[state]++; has_touch_event_handler_ = state; } // Local methods TouchEventHandlerWebWidgetClient() : has_touch_event_handler_count_(), has_touch_event_handler_(false) {} int GetAndResetHasTouchEventHandlerCallCount(bool state) { int value = has_touch_event_handler_count_[state]; has_touch_event_handler_count_[state] = 0; return value; } private: int has_touch_event_handler_count_[2]; bool has_touch_event_handler_; }; // This test verifies that WebWidgetClient::hasTouchEventHandlers is called // accordingly for various calls to EventHandlerRegistry::did{Add|Remove| // RemoveAll}EventHandler(..., TouchEvent). Verifying that those calls are made // correctly is the job of LayoutTests/fast/events/event-handler-count.html. TEST_F(WebViewTest, HasTouchEventHandlers) { TouchEventHandlerWebWidgetClient client; // We need to create a LayerTreeView for the client before loading the page, // otherwise ChromeClient will default to assuming there are touch handlers. WebLayerTreeView* layer_tree_view = client.InitializeLayerTreeView(); std::string url = RegisterMockedHttpURLLoad("has_touch_event_handlers.html"); WebViewImpl* web_view_impl = web_view_helper_.InitializeAndLoad(url, nullptr, nullptr, &client); ASSERT_TRUE(layer_tree_view); const EventHandlerRegistry::EventHandlerClass kTouchEvent = EventHandlerRegistry::kTouchStartOrMoveEventBlocking; // The page is initialized with at least one no-handlers call. // In practice we get two such calls because WebViewHelper::initializeAndLoad // first initializes an empty frame, and then loads a document into it, so // there are two FrameLoader::commitProvisionalLoad calls. EXPECT_EQ(0, client.GetAndResetHasTouchEventHandlerCallCount(false)); EXPECT_EQ(0, client.GetAndResetHasTouchEventHandlerCallCount(true)); // Adding the first document handler results in a has-handlers call. Document* document = web_view_impl->MainFrameImpl()->GetFrame()->GetDocument(); EventHandlerRegistry* registry = &document->GetFrame()->GetEventHandlerRegistry(); registry->DidAddEventHandler(*document, kTouchEvent); EXPECT_EQ(0, client.GetAndResetHasTouchEventHandlerCallCount(false)); EXPECT_EQ(1, client.GetAndResetHasTouchEventHandlerCallCount(true)); // Adding another handler has no effect. registry->DidAddEventHandler(*document, kTouchEvent); EXPECT_EQ(0, client.GetAndResetHasTouchEventHandlerCallCount(false)); EXPECT_EQ(0, client.GetAndResetHasTouchEventHandlerCallCount(true)); // Removing the duplicate handler has no effect. registry->DidRemoveEventHandler(*document, kTouchEvent); EXPECT_EQ(0, client.GetAndResetHasTouchEventHandlerCallCount(false)); EXPECT_EQ(0, client.GetAndResetHasTouchEventHandlerCallCount(true)); // Removing the final handler results in a no-handlers call. registry->DidRemoveEventHandler(*document, kTouchEvent); EXPECT_EQ(1, client.GetAndResetHasTouchEventHandlerCallCount(false)); EXPECT_EQ(0, client.GetAndResetHasTouchEventHandlerCallCount(true)); // Adding a handler on a div results in a has-handlers call. Element* parent_div = document->getElementById("parentdiv"); DCHECK(parent_div); registry->DidAddEventHandler(*parent_div, kTouchEvent); EXPECT_EQ(0, client.GetAndResetHasTouchEventHandlerCallCount(false)); EXPECT_EQ(1, client.GetAndResetHasTouchEventHandlerCallCount(true)); // Adding a duplicate handler on the div, clearing all document handlers // (of which there are none) and removing the extra handler on the div // all have no effect. registry->DidAddEventHandler(*parent_div, kTouchEvent); registry->DidRemoveAllEventHandlers(*document); registry->DidRemoveEventHandler(*parent_div, kTouchEvent); EXPECT_EQ(0, client.GetAndResetHasTouchEventHandlerCallCount(false)); EXPECT_EQ(0, client.GetAndResetHasTouchEventHandlerCallCount(true)); // Removing the final handler on the div results in a no-handlers call. registry->DidRemoveEventHandler(*parent_div, kTouchEvent); EXPECT_EQ(1, client.GetAndResetHasTouchEventHandlerCallCount(false)); EXPECT_EQ(0, client.GetAndResetHasTouchEventHandlerCallCount(true)); // Adding two handlers then clearing them in a single call results in a // has-handlers then no-handlers call. registry->DidAddEventHandler(*parent_div, kTouchEvent); EXPECT_EQ(0, client.GetAndResetHasTouchEventHandlerCallCount(false)); EXPECT_EQ(1, client.GetAndResetHasTouchEventHandlerCallCount(true)); registry->DidAddEventHandler(*parent_div, kTouchEvent); EXPECT_EQ(0, client.GetAndResetHasTouchEventHandlerCallCount(false)); EXPECT_EQ(0, client.GetAndResetHasTouchEventHandlerCallCount(true)); registry->DidRemoveAllEventHandlers(*parent_div); EXPECT_EQ(1, client.GetAndResetHasTouchEventHandlerCallCount(false)); EXPECT_EQ(0, client.GetAndResetHasTouchEventHandlerCallCount(true)); // Adding a handler inside of a child iframe results in a has-handlers call. Element* child_frame = document->getElementById("childframe"); DCHECK(child_frame); Document* child_document = ToHTMLIFrameElement(child_frame)->contentDocument(); Element* child_div = child_document->getElementById("childdiv"); DCHECK(child_div); registry->DidAddEventHandler(*child_div, kTouchEvent); EXPECT_EQ(0, client.GetAndResetHasTouchEventHandlerCallCount(false)); EXPECT_EQ(1, client.GetAndResetHasTouchEventHandlerCallCount(true)); // Adding and clearing handlers in the parent doc or elsewhere in the child // doc has no impact. registry->DidAddEventHandler(*document, kTouchEvent); registry->DidAddEventHandler(*child_frame, kTouchEvent); registry->DidAddEventHandler(*child_document, kTouchEvent); registry->DidRemoveAllEventHandlers(*document); registry->DidRemoveAllEventHandlers(*child_frame); registry->DidRemoveAllEventHandlers(*child_document); EXPECT_EQ(0, client.GetAndResetHasTouchEventHandlerCallCount(false)); EXPECT_EQ(0, client.GetAndResetHasTouchEventHandlerCallCount(true)); // Removing the final handler inside the child frame results in a no-handlers // call. registry->DidRemoveAllEventHandlers(*child_div); EXPECT_EQ(1, client.GetAndResetHasTouchEventHandlerCallCount(false)); EXPECT_EQ(0, client.GetAndResetHasTouchEventHandlerCallCount(true)); // Adding a handler inside the child frame results in a has-handlers call. registry->DidAddEventHandler(*child_document, kTouchEvent); EXPECT_EQ(0, client.GetAndResetHasTouchEventHandlerCallCount(false)); EXPECT_EQ(1, client.GetAndResetHasTouchEventHandlerCallCount(true)); // Adding a handler in the parent document and removing the one in the frame // has no effect. registry->DidAddEventHandler(*child_frame, kTouchEvent); registry->DidRemoveEventHandler(*child_document, kTouchEvent); registry->DidRemoveAllEventHandlers(*child_document); registry->DidRemoveAllEventHandlers(*document); EXPECT_EQ(0, client.GetAndResetHasTouchEventHandlerCallCount(false)); EXPECT_EQ(0, client.GetAndResetHasTouchEventHandlerCallCount(true)); // Now removing the handler in the parent document results in a no-handlers // call. registry->DidRemoveEventHandler(*child_frame, kTouchEvent); EXPECT_EQ(1, client.GetAndResetHasTouchEventHandlerCallCount(false)); EXPECT_EQ(0, client.GetAndResetHasTouchEventHandlerCallCount(true)); // Free the webView before the TouchEventHandlerWebViewClient gets freed. web_view_helper_.Reset(); } // This test checks that deleting nodes which have only non-JS-registered touch // handlers also removes them from the event handler registry. Note that this // is different from detaching and re-attaching the same node, which is covered // by layout tests under fast/events/. TEST_F(WebViewTest, DeleteElementWithRegisteredHandler) { std::string url = RegisterMockedHttpURLLoad("simple_div.html"); WebViewImpl* web_view_impl = web_view_helper_.InitializeAndLoad(url); Persistent<Document> document = web_view_impl->MainFrameImpl()->GetFrame()->GetDocument(); Element* div = document->getElementById("div"); EventHandlerRegistry& registry = document->GetFrame()->GetEventHandlerRegistry(); registry.DidAddEventHandler(*div, EventHandlerRegistry::kScrollEvent); EXPECT_TRUE(registry.HasEventHandlers(EventHandlerRegistry::kScrollEvent)); DummyExceptionStateForTesting exception_state; div->remove(exception_state); // For oilpan we have to force a GC to ensure the event handlers have been // removed when checking below. We do a precise GC (collectAllGarbage does not // scan the stack) to ensure the div element dies. This is also why the // Document is in a Persistent since we want that to stay around. ThreadState::Current()->CollectAllGarbage(); EXPECT_FALSE(registry.HasEventHandlers(EventHandlerRegistry::kScrollEvent)); } // This test verifies the text input flags are correctly exposed to script. TEST_F(WebViewTest, TextInputFlags) { std::string url = RegisterMockedHttpURLLoad("text_input_flags.html"); WebViewImpl* web_view_impl = web_view_helper_.InitializeAndLoad(url); web_view_impl->SetInitialFocus(false); WebLocalFrameImpl* frame = web_view_impl->MainFrameImpl(); WebInputMethodController* active_input_method_controller = frame->GetInputMethodController(); Document* document = frame->GetFrame()->GetDocument(); // (A) <input> // (A.1) Verifies autocorrect/autocomplete/spellcheck flags are Off and // autocapitalize is set to none. HTMLInputElement* input_element = ToHTMLInputElement(document->getElementById("input")); document->SetFocusedElement( input_element, FocusParams(SelectionBehaviorOnFocus::kNone, kWebFocusTypeNone, nullptr)); web_view_impl->SetFocus(true); WebTextInputInfo info1 = active_input_method_controller->TextInputInfo(); EXPECT_EQ(kWebTextInputFlagAutocompleteOff | kWebTextInputFlagAutocorrectOff | kWebTextInputFlagSpellcheckOff | kWebTextInputFlagAutocapitalizeNone, info1.flags); // (A.2) Verifies autocorrect/autocomplete/spellcheck flags are On and // autocapitalize is set to sentences. input_element = ToHTMLInputElement(document->getElementById("input2")); document->SetFocusedElement( input_element, FocusParams(SelectionBehaviorOnFocus::kNone, kWebFocusTypeNone, nullptr)); web_view_impl->SetFocus(true); WebTextInputInfo info2 = active_input_method_controller->TextInputInfo(); EXPECT_EQ(kWebTextInputFlagAutocompleteOn | kWebTextInputFlagAutocorrectOn | kWebTextInputFlagSpellcheckOn | kWebTextInputFlagAutocapitalizeSentences, info2.flags); // (B) <textarea> Verifies the default text input flags are // WebTextInputFlagAutocapitalizeSentences. HTMLTextAreaElement* text_area_element = ToHTMLTextAreaElement(document->getElementById("textarea")); document->SetFocusedElement( text_area_element, FocusParams(SelectionBehaviorOnFocus::kNone, kWebFocusTypeNone, nullptr)); web_view_impl->SetFocus(true); WebTextInputInfo info3 = active_input_method_controller->TextInputInfo(); EXPECT_EQ(kWebTextInputFlagAutocapitalizeSentences, info3.flags); // (C) Verifies the WebTextInputInfo's don't equal. EXPECT_FALSE(info1.Equals(info2)); EXPECT_FALSE(info2.Equals(info3)); // Free the webView before freeing the NonUserInputTextUpdateWebViewClient. web_view_helper_.Reset(); } // Check that the WebAutofillClient is correctly notified about first user // gestures after load, following various input events. TEST_F(WebViewTest, FirstUserGestureObservedKeyEvent) { RegisterMockedHttpURLLoad("form.html"); MockAutofillClient client; WebViewImpl* web_view = web_view_helper_.InitializeAndLoad(base_url_ + "form.html"); WebLocalFrameImpl* frame = web_view->MainFrameImpl(); frame->SetAutofillClient(&client); web_view->SetInitialFocus(false); EXPECT_EQ(0, client.GetUserGestureNotificationsCount()); WebKeyboardEvent key_event(WebInputEvent::kRawKeyDown, WebInputEvent::kNoModifiers, WebInputEvent::GetStaticTimeStampForTests()); key_event.dom_key = Platform::Current()->DomKeyEnumFromString(" "); key_event.windows_key_code = VKEY_SPACE; web_view->HandleInputEvent(WebCoalescedInputEvent(key_event)); key_event.SetType(WebInputEvent::kKeyUp); web_view->HandleInputEvent(WebCoalescedInputEvent(key_event)); EXPECT_EQ(2, client.GetUserGestureNotificationsCount()); frame->SetAutofillClient(nullptr); } TEST_F(WebViewTest, FirstUserGestureObservedMouseEvent) { RegisterMockedHttpURLLoad("form.html"); MockAutofillClient client; WebViewImpl* web_view = web_view_helper_.InitializeAndLoad(base_url_ + "form.html"); WebLocalFrameImpl* frame = web_view->MainFrameImpl(); frame->SetAutofillClient(&client); web_view->SetInitialFocus(false); EXPECT_EQ(0, client.GetUserGestureNotificationsCount()); WebMouseEvent mouse_event(WebInputEvent::kMouseDown, WebInputEvent::kNoModifiers, WebInputEvent::GetStaticTimeStampForTests()); mouse_event.button = WebMouseEvent::Button::kLeft; mouse_event.SetPositionInWidget(1, 1); mouse_event.click_count = 1; web_view->HandleInputEvent(WebCoalescedInputEvent(mouse_event)); mouse_event.SetType(WebInputEvent::kMouseUp); web_view->HandleInputEvent(WebCoalescedInputEvent(mouse_event)); EXPECT_EQ(1, client.GetUserGestureNotificationsCount()); frame->SetAutofillClient(nullptr); } TEST_F(WebViewTest, CompositionIsUserGesture) { RegisterMockedHttpURLLoad("input_field_populated.html"); WebViewImpl* web_view = web_view_helper_.InitializeAndLoad( base_url_ + "input_field_populated.html"); WebLocalFrameImpl* frame = web_view->MainFrameImpl(); MockAutofillClient client; frame->SetAutofillClient(&client); web_view->SetInitialFocus(false); EXPECT_TRUE( frame->FrameWidget()->GetActiveWebInputMethodController()->SetComposition( WebString::FromUTF8(std::string("hello").c_str()), WebVector<WebImeTextSpan>(), WebRange(), 3, 3)); EXPECT_EQ(1, client.TextChangesFromUserGesture()); EXPECT_FALSE(UserGestureIndicator::ProcessingUserGesture()); EXPECT_TRUE(frame->HasMarkedText()); frame->SetAutofillClient(nullptr); } // Currently, SelectionAsText() is built upon TextIterator, but // WebFrameContentDumper is built upon TextDumperForTests. Their results can // be different, making the test fail. // TODO(crbug.com/781434): Build a selection serializer upon TextDumperForTests. TEST_F(WebViewTest, DISABLED_CompareSelectAllToContentAsText) { RegisterMockedHttpURLLoad("longpress_selection.html"); WebViewImpl* web_view = web_view_helper_.InitializeAndLoad( base_url_ + "longpress_selection.html"); WebLocalFrameImpl* frame = web_view->MainFrameImpl(); frame->ExecuteScript(WebScriptSource( WebString::FromUTF8("document.execCommand('SelectAll', false, null)"))); std::string actual = frame->SelectionAsText().Utf8(); const int kMaxOutputCharacters = 1024; std::string expected = WebFrameContentDumper::DumpWebViewAsText(web_view, kMaxOutputCharacters) .Utf8(); EXPECT_EQ(expected, actual); } TEST_F(WebViewTest, AutoResizeSubtreeLayout) { std::string url = RegisterMockedHttpURLLoad("subtree-layout.html"); WebViewImpl* web_view = web_view_helper_.Initialize(); web_view->EnableAutoResizeMode(WebSize(200, 200), WebSize(200, 200)); LoadFrame(web_view->MainFrameImpl(), url); LocalFrameView* frame_view = web_view_helper_.LocalMainFrame()->GetFrameView(); // Auto-resizing used to DCHECK(needsLayout()) in LayoutBlockFlow::layout. // This EXPECT is merely a dummy. The real test is that we don't trigger // asserts in debug builds. EXPECT_FALSE(frame_view->NeedsLayout()); }; TEST_F(WebViewTest, PreferredSize) { std::string url = base_url_ + "specify_size.html?100px:100px"; URLTestHelpers::RegisterMockedURLLoad( ToKURL(url), test::CoreTestDataPath("specify_size.html")); WebView* web_view = web_view_helper_.InitializeAndLoad(url); WebSize size = web_view->ContentsPreferredMinimumSize(); EXPECT_EQ(100, size.width); EXPECT_EQ(100, size.height); web_view->SetZoomLevel(WebView::ZoomFactorToZoomLevel(2.0)); size = web_view->ContentsPreferredMinimumSize(); EXPECT_EQ(200, size.width); EXPECT_EQ(200, size.height); // Verify that both width and height are rounded (in this case up) web_view->SetZoomLevel(WebView::ZoomFactorToZoomLevel(0.9995)); size = web_view->ContentsPreferredMinimumSize(); EXPECT_EQ(100, size.width); EXPECT_EQ(100, size.height); // Verify that both width and height are rounded (in this case down) web_view->SetZoomLevel(WebView::ZoomFactorToZoomLevel(1.0005)); size = web_view->ContentsPreferredMinimumSize(); EXPECT_EQ(100, size.width); EXPECT_EQ(100, size.height); url = base_url_ + "specify_size.html?1.5px:1.5px"; URLTestHelpers::RegisterMockedURLLoad( ToKURL(url), test::CoreTestDataPath("specify_size.html")); web_view = web_view_helper_.InitializeAndLoad(url); web_view->SetZoomLevel(WebView::ZoomFactorToZoomLevel(1)); size = web_view->ContentsPreferredMinimumSize(); EXPECT_EQ(2, size.width); EXPECT_EQ(2, size.height); } TEST_F(WebViewTest, PreferredSizeDirtyLayout) { std::string url = base_url_ + "specify_size.html?100px:100px"; URLTestHelpers::RegisterMockedURLLoad( ToKURL(url), test::CoreTestDataPath("specify_size.html")); WebViewImpl* web_view = web_view_helper_.InitializeAndLoad(url); WebElement document_element = web_view->MainFrameImpl()->GetDocument().DocumentElement(); WebSize size = web_view->ContentsPreferredMinimumSize(); EXPECT_EQ(100, size.width); EXPECT_EQ(100, size.height); document_element.SetAttribute("style", "display: none"); size = web_view->ContentsPreferredMinimumSize(); EXPECT_EQ(0, size.width); EXPECT_EQ(0, size.height); } TEST_F(WebViewTest, PreferredSizeWithGrid) { WebViewImpl* web_view = web_view_helper_.Initialize(); WebURL base_url = URLTestHelpers::ToKURL("http://example.com/"); FrameTestHelpers::LoadHTMLString(web_view->MainFrameImpl(), R"HTML(<!DOCTYPE html> <style> html { writing-mode: vertical-rl; } body { margin: 0px; } </style> <div style="width: 100px;"> <div style="display: grid; width: 100%;"> <div style="writing-mode: horizontal-tb; height: 100px;"></div> </div> </div> )HTML", base_url); WebSize size = web_view->ContentsPreferredMinimumSize(); EXPECT_EQ(100, size.width); EXPECT_EQ(100, size.height); } TEST_F(WebViewTest, PreferredSizeWithGridMinWidth) { WebViewImpl* web_view = web_view_helper_.Initialize(); WebURL base_url = URLTestHelpers::ToKURL("http://example.com/"); FrameTestHelpers::LoadHTMLString(web_view->MainFrameImpl(), R"HTML(<!DOCTYPE html> <body style="margin: 0px;"> <div style="display: inline-grid; min-width: 200px;"> <div>item</div> </div> </body> )HTML", base_url); WebSize size = web_view->ContentsPreferredMinimumSize(); EXPECT_EQ(200, size.width); } TEST_F(WebViewTest, PreferredSizeWithGridMinWidthFlexibleTracks) { WebViewImpl* web_view = web_view_helper_.Initialize(); WebURL base_url = URLTestHelpers::ToKURL("http://example.com/"); FrameTestHelpers::LoadHTMLString(web_view->MainFrameImpl(), R"HTML(<!DOCTYPE html> <body style="margin: 0px;"> <div style="display: inline-grid; min-width: 200px; grid-template-columns: 1fr;"> <div>item</div> </div> </body> )HTML", base_url); WebSize size = web_view->ContentsPreferredMinimumSize(); EXPECT_EQ(200, size.width); } #if BUILDFLAG(ENABLE_UNHANDLED_TAP) // Helps set up any test that uses a mock Mojo implementation. class MojoTestHelper { public: MojoTestHelper(const String& test_file, FrameTestHelpers::WebViewHelper& web_view_helper) : web_view_helper_(web_view_helper) { web_view_ = web_view_helper.InitializeAndLoad( WebString(test_file).Utf8(), &web_frame_client_, &web_view_client_); } ~MojoTestHelper() { web_view_helper_.Reset(); // Remove dependency on locally scoped client. } // Bind the test API to a service with the given |name| and repeating Bind // method given by |callback|. void BindTestApi( const String& name, base::RepeatingCallback<void(mojo::ScopedMessagePipeHandle)> callback) { // Set up our Mock Mojo API. test_api_.reset(new service_manager::InterfaceProvider::TestApi( web_frame_client_.GetInterfaceProvider())); test_api_->SetBinderForName(WebString(name).Utf8(), callback); } WebViewImpl* WebView() const { return web_view_; } private: WebViewImpl* web_view_; FrameTestHelpers::WebViewHelper& web_view_helper_; FrameTestHelpers::TestWebFrameClient web_frame_client_; FrameTestHelpers::TestWebViewClient web_view_client_; std::unique_ptr<service_manager::InterfaceProvider::TestApi> test_api_; }; // Mock implementation of the UnhandledTapNotifier Mojo receiver, for testing // the ShowUnhandledTapUIIfNeeded notification. class MockUnhandledTapNotifierImpl : public mojom::blink::UnhandledTapNotifier { public: MockUnhandledTapNotifierImpl() : binding_(this) {} ~MockUnhandledTapNotifierImpl() override = default; void Bind(mojo::ScopedMessagePipeHandle handle) { binding_.Bind(mojom::blink::UnhandledTapNotifierRequest(std::move(handle))); } void ShowUnhandledTapUIIfNeeded( mojom::blink::UnhandledTapInfoPtr unhandled_tap_info) override { was_unhandled_tap_ = true; tapped_position_ = unhandled_tap_info->tapped_position_in_viewport; element_text_run_length_ = unhandled_tap_info->element_text_run_length; font_size_ = unhandled_tap_info->font_size_in_pixels; } bool WasUnhandledTap() const { return was_unhandled_tap_; } int GetTappedXPos() const { return tapped_position_.X(); } int GetTappedYPos() const { return tapped_position_.Y(); } int GetFontSize() const { return font_size_; } int GetElementTextRunLength() const { return element_text_run_length_; } void Reset() { was_unhandled_tap_ = false; tapped_position_ = IntPoint(); element_text_run_length_ = 0; font_size_ = 0; binding_.Close(); } private: bool was_unhandled_tap_ = false; IntPoint tapped_position_; int element_text_run_length_ = 0; int font_size_ = 0; mojo::Binding<mojom::blink::UnhandledTapNotifier> binding_; }; // A Test Fixture for testing ShowUnhandledTapUIIfNeeded usages. class ShowUnhandledTapTest : public WebViewTest { public: void SetUp() override { WebViewTest::SetUp(); std::string test_file = "show_unhandled_tap.html"; RegisterMockedHttpURLLoad("Ahem.ttf"); RegisterMockedHttpURLLoad(test_file); mojo_test_helper_.reset(new MojoTestHelper( WebString::FromUTF8(base_url_ + test_file), web_view_helper_)); web_view_ = mojo_test_helper_->WebView(); web_view_->Resize(WebSize(500, 300)); web_view_->UpdateAllLifecyclePhases(); RunPendingTasks(); mojo_test_helper_->BindTestApi( mojom::blink::UnhandledTapNotifier::Name_, WTF::BindRepeating(&MockUnhandledTapNotifierImpl::Bind, WTF::Unretained(&mock_notifier_))); } protected: // Tap on the given element by ID. void Tap(const String& element_id) { mock_notifier_.Reset(); EXPECT_TRUE(TapElementById(WebInputEvent::kGestureTap, element_id)); } // Set up a test script for the given |operation| with the given |handler|. void SetTestScript(const String& operation, const String& handler) { String test_key = operation + "-" + handler; web_view_->MainFrameImpl()->ExecuteScript( WebScriptSource(String("setTest('" + test_key + "');"))); } // Test each mouse event combination with the given |handler|, and verify the // |expected| outcome. void TestEachMouseEvent(const String& handler, bool expected) { SetTestScript("mousedown", handler); Tap("target"); EXPECT_EQ(expected, mock_notifier_.WasUnhandledTap()); SetTestScript("mouseup", handler); Tap("target"); EXPECT_EQ(expected, mock_notifier_.WasUnhandledTap()); SetTestScript("click", handler); Tap("target"); EXPECT_EQ(expected, mock_notifier_.WasUnhandledTap()); } WebViewImpl* web_view_; MockUnhandledTapNotifierImpl mock_notifier_; private: std::unique_ptr<MojoTestHelper> mojo_test_helper_; }; TEST_F(ShowUnhandledTapTest, ShowUnhandledTapUIIfNeeded) { // Scroll the bottom into view so we can distinguish window coordinates from // document coordinates. Tap("bottom"); EXPECT_TRUE(mock_notifier_.WasUnhandledTap()); EXPECT_EQ(64, mock_notifier_.GetTappedXPos()); EXPECT_EQ(278, mock_notifier_.GetTappedYPos()); EXPECT_EQ(16, mock_notifier_.GetFontSize()); EXPECT_EQ(7, mock_notifier_.GetElementTextRunLength()); // Test basic tap handling and notification. Tap("target"); EXPECT_TRUE(mock_notifier_.WasUnhandledTap()); EXPECT_EQ(144, mock_notifier_.GetTappedXPos()); EXPECT_EQ(82, mock_notifier_.GetTappedYPos()); // Test correct conversion of coordinates to viewport space under pinch-zoom. web_view_->SetPageScaleFactor(2); web_view_->SetVisualViewportOffset(WebFloatPoint(50, 20)); Tap("target"); EXPECT_TRUE(mock_notifier_.WasUnhandledTap()); EXPECT_EQ(188, mock_notifier_.GetTappedXPos()); EXPECT_EQ(124, mock_notifier_.GetTappedYPos()); EXPECT_EQ(16, mock_notifier_.GetFontSize()); EXPECT_EQ(28, mock_notifier_.GetElementTextRunLength()); } TEST_F(ShowUnhandledTapTest, ShowUnhandledTapUIIfNeededWithMutateDom) { // Test dom mutation. TestEachMouseEvent("mutateDom", FALSE); // Test without any DOM mutation. TestEachMouseEvent("none", TRUE); } TEST_F(ShowUnhandledTapTest, ShowUnhandledTapUIIfNeededWithMutateStyle) { // Test style mutation. TestEachMouseEvent("mutateStyle", FALSE); // Test checkbox:indeterminate style mutation. TestEachMouseEvent("mutateIndeterminate", FALSE); // Test click div with :active style. Tap("style_active"); EXPECT_FALSE(mock_notifier_.WasUnhandledTap()); } TEST_F(ShowUnhandledTapTest, ShowUnhandledTapUIIfNeededWithPreventDefault) { // Test swallowing. TestEachMouseEvent("preventDefault", FALSE); // Test without any preventDefault. TestEachMouseEvent("none", TRUE); } TEST_F(ShowUnhandledTapTest, ShowUnhandledTapUIIfNeededWithNonTriggeringNodes) { Tap("image"); EXPECT_FALSE(mock_notifier_.WasUnhandledTap()); Tap("editable"); EXPECT_FALSE(mock_notifier_.WasUnhandledTap()); Tap("focusable"); EXPECT_FALSE(mock_notifier_.WasUnhandledTap()); } TEST_F(ShowUnhandledTapTest, ShowUnhandledTapUIIfNeededWithTextSizes) { Tap("large"); EXPECT_TRUE(mock_notifier_.WasUnhandledTap()); EXPECT_EQ(20, mock_notifier_.GetFontSize()); Tap("small"); EXPECT_TRUE(mock_notifier_.WasUnhandledTap()); EXPECT_EQ(10, mock_notifier_.GetFontSize()); } #endif // BUILDFLAG(ENABLE_UNHANDLED_TAP) TEST_F(WebViewTest, StopLoadingIfJavaScriptURLReturnsNoStringResult) { ViewCreatingWebViewClient client; FrameTestHelpers::WebViewHelper main_web_view; main_web_view.InitializeAndLoad("about:blank", nullptr, &client); WebLocalFrame* frame = main_web_view.GetWebView()->MainFrameImpl(); v8::HandleScope scope(v8::Isolate::GetCurrent()); v8::Local<v8::Value> v8_value = frame->ExecuteScriptAndReturnValue(WebScriptSource( "var win = window.open('javascript:false'); win.document")); ASSERT_TRUE(v8_value->IsObject()); Document* document = V8Document::ToImplWithTypeCheck(v8::Isolate::GetCurrent(), v8_value); ASSERT_TRUE(document); EXPECT_FALSE(document->GetFrame()->IsLoading()); } #if defined(OS_MACOSX) TEST_F(WebViewTest, WebSubstringUtil) { RegisterMockedHttpURLLoad("content_editable_populated.html"); WebViewImpl* web_view = web_view_helper_.InitializeAndLoad( base_url_ + "content_editable_populated.html"); web_view->GetSettings()->SetDefaultFontSize(12); web_view->Resize(WebSize(400, 400)); WebLocalFrameImpl* frame = web_view->MainFrameImpl(); WebPoint baseline_point; NSAttributedString* result = WebSubstringUtil::AttributedSubstringInRange( frame, 10, 3, &baseline_point); ASSERT_TRUE(!!result); WebPoint point(baseline_point.x, baseline_point.y); result = WebSubstringUtil::AttributedWordAtPoint(frame->FrameWidget(), point, baseline_point); ASSERT_TRUE(!!result); web_view->SetZoomLevel(3); result = WebSubstringUtil::AttributedSubstringInRange(frame, 5, 5, &baseline_point); ASSERT_TRUE(!!result); point = WebPoint(baseline_point.x, baseline_point.y); result = WebSubstringUtil::AttributedWordAtPoint(frame->FrameWidget(), point, baseline_point); ASSERT_TRUE(!!result); } TEST_F(WebViewTest, WebSubstringUtilPinchZoom) { RegisterMockedHttpURLLoad("content_editable_populated.html"); WebViewImpl* web_view = web_view_helper_.InitializeAndLoad( base_url_ + "content_editable_populated.html"); web_view->GetSettings()->SetDefaultFontSize(12); web_view->Resize(WebSize(400, 400)); WebLocalFrameImpl* frame = web_view->MainFrameImpl(); NSAttributedString* result = nil; WebPoint baseline_point; result = WebSubstringUtil::AttributedSubstringInRange(frame, 10, 3, &baseline_point); ASSERT_TRUE(!!result); web_view->SetPageScaleFactor(3); WebPoint point_after_zoom; result = WebSubstringUtil::AttributedSubstringInRange(frame, 10, 3, &point_after_zoom); ASSERT_TRUE(!!result); // We won't have moved by a full factor of 3 because of the translations, but // we should move by a factor of >2. EXPECT_LT(2 * baseline_point.x, point_after_zoom.x); EXPECT_LT(2 * baseline_point.y, point_after_zoom.y); } TEST_F(WebViewTest, WebSubstringUtilIframe) { RegisterMockedHttpURLLoad("single_iframe.html"); RegisterMockedHttpURLLoad("visible_iframe.html"); WebViewImpl* web_view = web_view_helper_.InitializeAndLoad(base_url_ + "single_iframe.html"); web_view->GetSettings()->SetDefaultFontSize(12); web_view->GetSettings()->SetJavaScriptEnabled(true); web_view->Resize(WebSize(400, 400)); WebLocalFrameImpl* main_frame = web_view->MainFrameImpl(); WebLocalFrameImpl* child_frame = WebLocalFrameImpl::FromFrame( ToLocalFrame(main_frame->GetFrame()->Tree().FirstChild())); WebPoint baseline_point; NSAttributedString* result = WebSubstringUtil::AttributedSubstringInRange( child_frame, 11, 7, &baseline_point); ASSERT_NE(result, nullptr); WebPoint point(baseline_point.x, baseline_point.y); result = WebSubstringUtil::AttributedWordAtPoint(main_frame->FrameWidget(), point, baseline_point); ASSERT_NE(result, nullptr); int y_before_change = baseline_point.y; // Now move the <iframe> down by 100px. main_frame->ExecuteScript(WebScriptSource( "document.querySelector('iframe').style.marginTop = '100px';")); point = WebPoint(point.x, point.y + 100); result = WebSubstringUtil::AttributedWordAtPoint(main_frame->FrameWidget(), point, baseline_point); ASSERT_NE(result, nullptr); EXPECT_EQ(y_before_change, baseline_point.y - 100); } #endif TEST_F(WebViewTest, PasswordFieldEditingIsUserGesture) { RegisterMockedHttpURLLoad("input_field_password.html"); MockAutofillClient client; WebViewImpl* web_view = web_view_helper_.InitializeAndLoad( base_url_ + "input_field_password.html"); WebLocalFrameImpl* frame = web_view->MainFrameImpl(); frame->SetAutofillClient(&client); web_view->SetInitialFocus(false); WebVector<WebImeTextSpan> empty_ime_text_spans; EXPECT_TRUE( frame->FrameWidget()->GetActiveWebInputMethodController()->CommitText( WebString::FromUTF8(std::string("hello").c_str()), empty_ime_text_spans, WebRange(), 0)); EXPECT_EQ(1, client.TextChangesFromUserGesture()); EXPECT_FALSE(UserGestureIndicator::ProcessingUserGesture()); frame->SetAutofillClient(nullptr); } // Verify that a WebView created with a ScopedPagePauser already on the // stack defers its loads. TEST_F(WebViewTest, CreatedDuringPagePause) { { WebViewImpl* web_view = web_view_helper_.Initialize(); EXPECT_FALSE(web_view->GetPage()->Paused()); } { ScopedPagePauser pauser; WebViewImpl* web_view = web_view_helper_.Initialize(); EXPECT_TRUE(web_view->GetPage()->Paused()); } } // Make sure the SubframeBeforeUnloadUseCounter is only incremented on subframe // unloads. crbug.com/635029. TEST_F(WebViewTest, SubframeBeforeUnloadUseCounter) { RegisterMockedHttpURLLoad("visible_iframe.html"); RegisterMockedHttpURLLoad("single_iframe.html"); WebViewImpl* web_view = web_view_helper_.InitializeAndLoad(base_url_ + "single_iframe.html"); WebLocalFrame* frame = web_view_helper_.LocalMainFrame(); Document* document = ToLocalFrame(web_view_helper_.GetWebView()->GetPage()->MainFrame()) ->GetDocument(); // Add a beforeunload handler in the main frame. Make sure firing // beforeunload doesn't increment the subframe use counter. { frame->ExecuteScript( WebScriptSource("addEventListener('beforeunload', function() {});")); web_view->MainFrame()->ToWebLocalFrame()->DispatchBeforeUnloadEvent(false); EXPECT_FALSE(UseCounter::IsCounted(*document, WebFeature::kSubFrameBeforeUnloadFired)); } // Add a beforeunload handler in the iframe and dispatch. Make sure we do // increment the use counter for subframe beforeunloads. { frame->ExecuteScript(WebScriptSource( "document.getElementsByTagName('iframe')[0].contentWindow." "addEventListener('beforeunload', function() {});")); web_view->MainFrame() ->FirstChild() ->ToWebLocalFrame() ->DispatchBeforeUnloadEvent(false); Document* child_document = ToLocalFrame(web_view_helper_.GetWebView() ->GetPage() ->MainFrame() ->Tree() .FirstChild()) ->GetDocument(); EXPECT_TRUE(UseCounter::IsCounted(*child_document, WebFeature::kSubFrameBeforeUnloadFired)); } } // Verify that page loads are deferred until all ScopedPageLoadDeferrers are // destroyed. TEST_F(WebViewTest, NestedPagePauses) { WebViewImpl* web_view = web_view_helper_.Initialize(); EXPECT_FALSE(web_view->GetPage()->Paused()); { ScopedPagePauser pauser; EXPECT_TRUE(web_view->GetPage()->Paused()); { ScopedPagePauser pauser2; EXPECT_TRUE(web_view->GetPage()->Paused()); } EXPECT_TRUE(web_view->GetPage()->Paused()); } EXPECT_FALSE(web_view->GetPage()->Paused()); } TEST_F(WebViewTest, ClosingPageIsPaused) { WebViewImpl* web_view = web_view_helper_.Initialize(); Page* page = web_view_helper_.GetWebView()->GetPage(); EXPECT_FALSE(page->Paused()); web_view->SetOpenedByDOM(); LocalFrame* main_frame = ToLocalFrame(page->MainFrame()); EXPECT_FALSE(main_frame->DomWindow()->closed()); main_frame->DomWindow()->close(nullptr); // The window should be marked closed... EXPECT_TRUE(main_frame->DomWindow()->closed()); // EXPECT_TRUE(page->isClosing()); // ...but not yet detached. EXPECT_TRUE(main_frame->GetPage()); { ScopedPagePauser pauser; EXPECT_TRUE(page->Paused()); } } TEST_F(WebViewTest, ForceAndResetViewport) { RegisterMockedHttpURLLoad("200-by-300.html"); WebViewImpl* web_view_impl = web_view_helper_.InitializeAndLoad(base_url_ + "200-by-300.html"); web_view_impl->Resize(WebSize(100, 150)); SetViewportSize(WebSize(100, 150)); VisualViewport* visual_viewport = &web_view_impl->GetPage()->GetVisualViewport(); DevToolsEmulator* dev_tools_emulator = web_view_impl->GetDevToolsEmulator(); TransformationMatrix expected_matrix; expected_matrix.MakeIdentity(); EXPECT_EQ(expected_matrix, web_view_impl->GetDeviceEmulationTransformForTesting()); EXPECT_FALSE(dev_tools_emulator->VisibleContentRectForPainting()); EXPECT_TRUE(visual_viewport->ContainerLayer()->MasksToBounds()); // Override applies transform, sets visibleContentRect, and disables // visual viewport clipping. dev_tools_emulator->ForceViewport(WebFloatPoint(50, 55), 2.f); expected_matrix.MakeIdentity().Scale(2.f).Translate(-50, -55); EXPECT_EQ(expected_matrix, web_view_impl->GetDeviceEmulationTransformForTesting()); EXPECT_EQ(IntRect(50, 55, 50, 75), *dev_tools_emulator->VisibleContentRectForPainting()); EXPECT_FALSE(visual_viewport->ContainerLayer()->MasksToBounds()); // Setting new override discards previous one. dev_tools_emulator->ForceViewport(WebFloatPoint(5.4f, 10.5f), 1.5f); expected_matrix.MakeIdentity().Scale(1.5f).Translate(-5.4f, -10.5f); EXPECT_EQ(expected_matrix, web_view_impl->GetDeviceEmulationTransformForTesting()); EXPECT_EQ(IntRect(5, 10, 68, 101), *dev_tools_emulator->VisibleContentRectForPainting()); EXPECT_FALSE(visual_viewport->ContainerLayer()->MasksToBounds()); // Clearing override restores original transform, visibleContentRect and // visual viewport clipping. dev_tools_emulator->ResetViewport(); expected_matrix.MakeIdentity(); EXPECT_EQ(expected_matrix, web_view_impl->GetDeviceEmulationTransformForTesting()); EXPECT_FALSE(dev_tools_emulator->VisibleContentRectForPainting()); EXPECT_TRUE(visual_viewport->ContainerLayer()->MasksToBounds()); } TEST_F(WebViewTest, ViewportOverrideIntegratesDeviceMetricsOffsetAndScale) { RegisterMockedHttpURLLoad("200-by-300.html"); WebViewImpl* web_view_impl = web_view_helper_.InitializeAndLoad(base_url_ + "200-by-300.html"); web_view_impl->Resize(WebSize(100, 150)); TransformationMatrix expected_matrix; expected_matrix.MakeIdentity(); EXPECT_EQ(expected_matrix, web_view_impl->GetDeviceEmulationTransformForTesting()); WebDeviceEmulationParams emulation_params; emulation_params.scale = 2.f; web_view_impl->EnableDeviceEmulation(emulation_params); expected_matrix.MakeIdentity().Scale(2.f); EXPECT_EQ(expected_matrix, web_view_impl->GetDeviceEmulationTransformForTesting()); // Device metrics offset and scale are applied before viewport override. web_view_impl->GetDevToolsEmulator()->ForceViewport(WebFloatPoint(5, 10), 1.5f); expected_matrix.MakeIdentity() .Scale(1.5f) .Translate(-5, -10) .Scale(2.f); EXPECT_EQ(expected_matrix, web_view_impl->GetDeviceEmulationTransformForTesting()); } TEST_F(WebViewTest, ViewportOverrideAdaptsToScaleAndScroll) { RegisterMockedHttpURLLoad("200-by-300.html"); WebViewImpl* web_view_impl = web_view_helper_.InitializeAndLoad(base_url_ + "200-by-300.html"); web_view_impl->Resize(WebSize(100, 150)); SetViewportSize(WebSize(100, 150)); LocalFrameView* frame_view = web_view_impl->MainFrameImpl()->GetFrame()->View(); DevToolsEmulator* dev_tools_emulator = web_view_impl->GetDevToolsEmulator(); TransformationMatrix expected_matrix; expected_matrix.MakeIdentity(); EXPECT_EQ(expected_matrix, web_view_impl->GetDeviceEmulationTransformForTesting()); // Initial transform takes current page scale and scroll position into // account. web_view_impl->SetPageScaleFactor(1.5f); frame_view->LayoutViewportScrollableArea()->SetScrollOffset( ScrollOffset(100, 150), kProgrammaticScroll, kScrollBehaviorInstant); dev_tools_emulator->ForceViewport(WebFloatPoint(50, 55), 2.f); expected_matrix.MakeIdentity() .Scale(2.f) .Translate(-50, -55) .Translate(100, 150) .Scale(1. / 1.5f); EXPECT_EQ(expected_matrix, web_view_impl->GetDeviceEmulationTransformForTesting()); // Page scroll and scale are irrelevant for visibleContentRect. EXPECT_EQ(IntRect(50, 55, 50, 75), *dev_tools_emulator->VisibleContentRectForPainting()); // Transform adapts to scroll changes. frame_view->LayoutViewportScrollableArea()->SetScrollOffset( ScrollOffset(50, 55), kProgrammaticScroll, kScrollBehaviorInstant); expected_matrix.MakeIdentity() .Scale(2.f) .Translate(-50, -55) .Translate(50, 55) .Scale(1. / 1.5f); EXPECT_EQ(expected_matrix, web_view_impl->GetDeviceEmulationTransformForTesting()); // visibleContentRect doesn't change. EXPECT_EQ(IntRect(50, 55, 50, 75), *dev_tools_emulator->VisibleContentRectForPainting()); // Transform adapts to page scale changes. web_view_impl->SetPageScaleFactor(2.f); expected_matrix.MakeIdentity() .Scale(2.f) .Translate(-50, -55) .Translate(50, 55) .Scale(1. / 2.f); EXPECT_EQ(expected_matrix, web_view_impl->GetDeviceEmulationTransformForTesting()); // visibleContentRect doesn't change. EXPECT_EQ(IntRect(50, 55, 50, 75), *dev_tools_emulator->VisibleContentRectForPainting()); } TEST_F(WebViewTest, ResizeForPrintingViewportUnits) { WebViewImpl* web_view = web_view_helper_.Initialize(); web_view->Resize(WebSize(800, 600)); WebURL base_url = URLTestHelpers::ToKURL("http://example.com/"); FrameTestHelpers::LoadHTMLString(web_view->MainFrameImpl(), "<style>" " body { margin: 0px; }" " #vw { width: 100vw; height: 100vh; }" "</style>" "<div id=vw></div>", base_url); WebLocalFrameImpl* frame = web_view->MainFrameImpl(); Document* document = frame->GetFrame()->GetDocument(); Element* vw_element = document->getElementById("vw"); EXPECT_EQ(800, vw_element->OffsetWidth()); FloatSize page_size(300, 360); WebPrintParams print_params; print_params.print_content_area.width = page_size.Width(); print_params.print_content_area.height = page_size.Height(); IntSize expected_size = PrintICBSizeFromPageSize(page_size); frame->PrintBegin(print_params, WebNode()); EXPECT_EQ(expected_size.Width(), vw_element->OffsetWidth()); EXPECT_EQ(expected_size.Height(), vw_element->OffsetHeight()); web_view->Resize(FlooredIntSize(page_size)); EXPECT_EQ(expected_size.Width(), vw_element->OffsetWidth()); EXPECT_EQ(expected_size.Height(), vw_element->OffsetHeight()); web_view->Resize(WebSize(800, 600)); frame->PrintEnd(); EXPECT_EQ(800, vw_element->OffsetWidth()); } TEST_F(WebViewTest, WidthMediaQueryWithPageZoomAfterPrinting) { WebViewImpl* web_view = web_view_helper_.Initialize(); web_view->Resize(WebSize(800, 600)); web_view->SetZoomLevel(WebView::ZoomFactorToZoomLevel(2.0)); WebURL base_url = URLTestHelpers::ToKURL("http://example.com/"); FrameTestHelpers::LoadHTMLString(web_view->MainFrameImpl(), "<style>" " @media (max-width: 600px) {" " div { color: green }" " }" "</style>" "<div id=d></div>", base_url); WebLocalFrameImpl* frame = web_view->MainFrameImpl(); Document* document = frame->GetFrame()->GetDocument(); Element* div = document->getElementById("d"); EXPECT_EQ(MakeRGB(0, 128, 0), div->GetComputedStyle()->VisitedDependentColor( GetCSSPropertyColor())); FloatSize page_size(300, 360); WebPrintParams print_params; print_params.print_content_area.width = page_size.Width(); print_params.print_content_area.height = page_size.Height(); frame->PrintBegin(print_params, WebNode()); frame->PrintEnd(); EXPECT_EQ(MakeRGB(0, 128, 0), div->GetComputedStyle()->VisitedDependentColor( GetCSSPropertyColor())); } TEST_F(WebViewTest, ViewportUnitsPrintingWithPageZoom) { WebViewImpl* web_view = web_view_helper_.Initialize(); web_view->Resize(WebSize(800, 600)); web_view->SetZoomLevel(WebView::ZoomFactorToZoomLevel(2.0)); WebURL base_url = URLTestHelpers::ToKURL("http://example.com/"); FrameTestHelpers::LoadHTMLString(web_view->MainFrameImpl(), "<style>" " body { margin: 0 }" " #t1 { width: 100% }" " #t2 { width: 100vw }" "</style>" "<div id=t1></div>" "<div id=t2></div>", base_url); WebLocalFrameImpl* frame = web_view->MainFrameImpl(); Document* document = frame->GetFrame()->GetDocument(); Element* t1 = document->getElementById("t1"); Element* t2 = document->getElementById("t2"); EXPECT_EQ(400, t1->OffsetWidth()); EXPECT_EQ(400, t2->OffsetWidth()); FloatSize page_size(600, 720); int expected_width = PrintICBSizeFromPageSize(page_size).Width(); WebPrintParams print_params; print_params.print_content_area.width = page_size.Width(); print_params.print_content_area.height = page_size.Height(); frame->PrintBegin(print_params, WebNode()); EXPECT_EQ(expected_width, t1->OffsetWidth()); EXPECT_EQ(expected_width, t2->OffsetWidth()); frame->PrintEnd(); } TEST_F(WebViewTest, DeviceEmulationResetScrollbars) { WebViewImpl* web_view = web_view_helper_.Initialize(); web_view->Resize(WebSize(800, 600)); WebURL base_url = URLTestHelpers::ToKURL("http://example.com/"); FrameTestHelpers::LoadHTMLString(web_view->MainFrameImpl(), "<!doctype html>" "<meta name='viewport'" " content='width=device-width'>" "<style>" " body {margin: 0px; height:3000px;}" "</style>", base_url); web_view->UpdateAllLifecyclePhases(); WebLocalFrameImpl* frame = web_view->MainFrameImpl(); auto* frame_view = frame->GetFrameView(); EXPECT_FALSE(frame_view->VisualViewportSuppliesScrollbars()); EXPECT_NE(nullptr, frame_view->LayoutViewportScrollableArea()->VerticalScrollbar()); WebDeviceEmulationParams params; params.screen_position = WebDeviceEmulationParams::kMobile; params.device_scale_factor = 0; params.scale = 1; web_view->EnableDeviceEmulation(params); // The visual viewport should now proivde the scrollbars instead of the view. EXPECT_TRUE(frame_view->VisualViewportSuppliesScrollbars()); EXPECT_EQ(nullptr, frame_view->VerticalScrollbar()); web_view->DisableDeviceEmulation(); // The view should once again provide the scrollbars. EXPECT_FALSE(frame_view->VisualViewportSuppliesScrollbars()); EXPECT_NE(nullptr, frame_view->LayoutViewportScrollableArea()->VerticalScrollbar()); } TEST_F(WebViewTest, SetZoomLevelWhilePluginFocused) { class PluginCreatingWebFrameClient : public FrameTestHelpers::TestWebFrameClient { public: // WebFrameClient overrides: WebPlugin* CreatePlugin(const WebPluginParams& params) override { return new FakeWebPlugin(params); } }; PluginCreatingWebFrameClient frame_client; WebViewImpl* web_view = web_view_helper_.Initialize(&frame_client); WebURL base_url = URLTestHelpers::ToKURL("https://example.com/"); FrameTestHelpers::LoadHTMLString( web_view->MainFrameImpl(), "<!DOCTYPE html><html><body>" "<object type='application/x-webkit-test-plugin'></object>" "</body></html>", base_url); // Verify the plugin is loaded. LocalFrame* main_frame = web_view->MainFrameImpl()->GetFrame(); HTMLObjectElement* plugin_element = ToHTMLObjectElement(main_frame->GetDocument()->body()->firstChild()); EXPECT_TRUE(plugin_element->OwnedPlugin()); // Focus the plugin element, and then change the zoom level on the WebView. plugin_element->focus(); EXPECT_FLOAT_EQ(1.0f, main_frame->PageZoomFactor()); web_view->SetZoomLevel(-1.0); // Even though the plugin is focused, the entire frame's zoom factor should // still be updated. EXPECT_FLOAT_EQ(5.0f / 6.0f, main_frame->PageZoomFactor()); web_view_helper_.Reset(); // Remove dependency on locally scoped client. } // Tests that a layout update that detaches a plugin doesn't crash if the // plugin tries to execute script while being destroyed. TEST_F(WebViewTest, DetachPluginInLayout) { class ScriptInDestroyPlugin : public FakeWebPlugin { public: ScriptInDestroyPlugin(WebLocalFrame* frame, const WebPluginParams& params) : FakeWebPlugin(params), frame_(frame) {} // WebPlugin overrides: void Destroy() override { frame_->ExecuteScript(WebScriptSource("console.log('done')")); // Deletes this. FakeWebPlugin::Destroy(); } private: WebLocalFrame* frame_; // Unowned }; class PluginCreatingWebFrameClient : public FrameTestHelpers::TestWebFrameClient { public: // WebFrameClient overrides: WebPlugin* CreatePlugin(const WebPluginParams& params) override { return new ScriptInDestroyPlugin(Frame(), params); } void DidAddMessageToConsole(const WebConsoleMessage& message, const WebString& source_name, unsigned source_line, const WebString& stack_trace) override { message_ = message.text; } const String& Message() const { return message_; } private: String message_; }; PluginCreatingWebFrameClient frame_client; WebViewImpl* web_view = web_view_helper_.Initialize(&frame_client); WebURL base_url = URLTestHelpers::ToKURL("https://example.com/"); FrameTestHelpers::LoadHTMLString( web_view->MainFrameImpl(), "<!DOCTYPE html><html><body>" "<object type='application/x-webkit-test-plugin'></object>" "</body></html>", base_url); // Verify the plugin is loaded. LocalFrame* main_frame = web_view->MainFrameImpl()->GetFrame(); HTMLObjectElement* plugin_element = ToHTMLObjectElement(main_frame->GetDocument()->body()->firstChild()); EXPECT_TRUE(plugin_element->OwnedPlugin()); plugin_element->style()->setCSSText(main_frame->GetDocument(), "display: none", ASSERT_NO_EXCEPTION); EXPECT_TRUE(plugin_element->OwnedPlugin()); web_view->UpdateAllLifecyclePhases(); EXPECT_FALSE(plugin_element->OwnedPlugin()); EXPECT_EQ("done", frame_client.Message()); web_view_helper_.Reset(); // Remove dependency on locally scoped client. } // Check that first input delay is correctly reported to the document. TEST_F(WebViewTest, FirstInputDelayReported) { WebViewImpl* web_view = web_view_helper_.Initialize(); WebURL base_url = URLTestHelpers::ToKURL("http://example.com/"); FrameTestHelpers::LoadHTMLString(web_view->MainFrameImpl(), "<html><body></body></html>", base_url); LocalFrame* main_frame = web_view->MainFrameImpl()->GetFrame(); ASSERT_NE(nullptr, main_frame); Document* document = main_frame->GetDocument(); ASSERT_NE(nullptr, document); WTF::ScopedMockClock clock; clock.Advance(TimeDelta::FromMilliseconds(70)); InteractiveDetector* interactive_detector( InteractiveDetector::From(*document)); ASSERT_NE(nullptr, interactive_detector); EXPECT_TRUE(interactive_detector->GetFirstInputDelay().is_zero()); WebKeyboardEvent key_event1(WebInputEvent::kRawKeyDown, WebInputEvent::kNoModifiers, WebInputEvent::GetStaticTimeStampForTests()); key_event1.dom_key = Platform::Current()->DomKeyEnumFromString(" "); key_event1.windows_key_code = VKEY_SPACE; key_event1.SetTimeStamp(CurrentTimeTicks()); clock.Advance(TimeDelta::FromMilliseconds(50)); web_view->HandleInputEvent(WebCoalescedInputEvent(key_event1)); EXPECT_NEAR(50, interactive_detector->GetFirstInputDelay().InMillisecondsF(), 0.01); EXPECT_EQ(70, interactive_detector->GetFirstInputTimestamp() .since_origin() .InMillisecondsF()); // Sending a second event won't change the FirstInputDelay. WebKeyboardEvent key_event2(WebInputEvent::kRawKeyDown, WebInputEvent::kNoModifiers, WebInputEvent::GetStaticTimeStampForTests()); key_event2.dom_key = Platform::Current()->DomKeyEnumFromString(" "); key_event2.windows_key_code = VKEY_SPACE; clock.Advance(TimeDelta::FromMilliseconds(60)); key_event2.SetTimeStamp(CurrentTimeTicks()); web_view->HandleInputEvent(WebCoalescedInputEvent(key_event2)); EXPECT_NEAR(50, interactive_detector->GetFirstInputDelay().InMillisecondsF(), 0.01); EXPECT_EQ(70, interactive_detector->GetFirstInputTimestamp() .since_origin() .InMillisecondsF()); } // Check that first input delay is correctly reported to the document when the // first input is a pointer down event, and we receive a pointer up event. TEST_F(WebViewTest, PointerDownUpFirstInputDelay) { WebViewImpl* web_view = web_view_helper_.Initialize(); WebURL base_url = URLTestHelpers::ToKURL("http://example.com/"); FrameTestHelpers::LoadHTMLString(web_view->MainFrameImpl(), "<html><body></body></html>", base_url); LocalFrame* main_frame = web_view->MainFrameImpl()->GetFrame(); ASSERT_NE(nullptr, main_frame); Document* document = main_frame->GetDocument(); ASSERT_NE(nullptr, document); WTF::ScopedMockClock clock; clock.Advance(TimeDelta::FromMilliseconds(70)); InteractiveDetector* interactive_detector( InteractiveDetector::From(*document)); ASSERT_NE(nullptr, interactive_detector); WebPointerEvent pointer_down( WebInputEvent::kPointerDown, WebPointerProperties(1, WebPointerProperties::PointerType::kTouch), 5, 5); pointer_down.SetTimeStamp(CurrentTimeTicks()); clock.Advance(TimeDelta::FromMilliseconds(50)); web_view->HandleInputEvent(WebCoalescedInputEvent(pointer_down)); // We don't know if this pointer event will result in a scroll or not, so we // can't report its delay. We don't consider a scroll to be meaningful input. EXPECT_TRUE(interactive_detector->GetFirstInputDelay().is_zero()); // When we receive a pointer up, we report the delay of the pointer down. WebPointerEvent pointer_up( WebInputEvent::kPointerUp, WebPointerProperties(1, WebPointerProperties::PointerType::kTouch), 5, 5); clock.Advance(TimeDelta::FromMilliseconds(60)); pointer_up.SetTimeStamp(CurrentTimeTicks()); web_view->HandleInputEvent(WebCoalescedInputEvent(pointer_up)); EXPECT_NEAR(50, interactive_detector->GetFirstInputDelay().InMillisecondsF(), 0.01); EXPECT_EQ(70, interactive_detector->GetFirstInputTimestamp() .since_origin() .InMillisecondsF()); } // Check that first input delay isn't reported to the document when the // first input is a pointer down event followed by a pointer cancel event. TEST_F(WebViewTest, PointerDownCancelFirstInputDelay) { WebViewImpl* web_view = web_view_helper_.Initialize(); WebURL base_url = URLTestHelpers::ToKURL("http://example.com/"); FrameTestHelpers::LoadHTMLString(web_view->MainFrameImpl(), "<html><body></body></html>", base_url); LocalFrame* main_frame = web_view->MainFrameImpl()->GetFrame(); ASSERT_NE(nullptr, main_frame); Document* document = main_frame->GetDocument(); ASSERT_NE(nullptr, document); WTF::ScopedMockClock clock; InteractiveDetector* interactive_detector( InteractiveDetector::From(*document)); ASSERT_NE(nullptr, interactive_detector); WebPointerEvent pointer_down( WebInputEvent::kPointerDown, WebPointerProperties(1, WebPointerProperties::PointerType::kTouch), 5, 5); pointer_down.SetTimeStamp(CurrentTimeTicks()); clock.Advance(TimeDelta::FromMilliseconds(50)); web_view->HandleInputEvent(WebCoalescedInputEvent(pointer_down)); // We don't know if this pointer event will result in a scroll or not, so we // can't report its delay. We don't consider a scroll to be meaningful input. EXPECT_TRUE(interactive_detector->GetFirstInputDelay().is_zero()); // When we receive a pointer up, we report the delay of the pointer down. WebPointerEvent pointer_cancel( WebInputEvent::kPointerCancel, WebPointerProperties(1, WebPointerProperties::PointerType::kTouch), 5, 5); clock.Advance(TimeDelta::FromMilliseconds(60)); pointer_cancel.SetTimeStamp(CurrentTimeTicks()); web_view->HandleInputEvent(WebCoalescedInputEvent(pointer_cancel)); // We received a pointer cancel, so this is a scroll gesture. No meaningful // input has occurred yet. EXPECT_TRUE(interactive_detector->GetFirstInputDelay().is_zero()); EXPECT_TRUE(interactive_detector->GetFirstInputTimestamp().is_null()); } // Check that the input delay is correctly reported to the document. TEST_F(WebViewTest, FirstInputDelayExcludesProcessingTime) { // We need a way for JS to advance the mock clock. Hook into console.log, so // that logging advances the clock by 6 seconds. class MockClockAdvancingWebFrameClient : public FrameTestHelpers::TestWebFrameClient { public: MockClockAdvancingWebFrameClient(WTF::ScopedMockClock* mock_clock) : mock_clock_(mock_clock) {} // WebFrameClient overrides: void DidAddMessageToConsole(const WebConsoleMessage& message, const WebString& source_name, unsigned source_line, const WebString& stack_trace) override { mock_clock_->Advance(TimeDelta::FromMilliseconds(6000)); } private: WTF::ScopedMockClock* mock_clock_; }; WTF::ScopedMockClock clock; // Page load timing logic depends on the time not being zero. clock.Advance(TimeDelta::FromMilliseconds(1)); MockClockAdvancingWebFrameClient frame_client(&clock); WebViewImpl* web_view = web_view_helper_.Initialize(&frame_client); WebURL base_url = URLTestHelpers::ToKURL("http://example.com/"); FrameTestHelpers::LoadHTMLString(web_view->MainFrameImpl(), "<html><body></body></html>", base_url); LocalFrame* main_frame = web_view->MainFrameImpl()->GetFrame(); ASSERT_NE(nullptr, main_frame); Document* document = main_frame->GetDocument(); ASSERT_NE(nullptr, document); WebLocalFrame* frame = web_view_helper_.LocalMainFrame(); // console.log will advance the mock clock. frame->ExecuteScript( WebScriptSource("document.addEventListener('keydown', " "() => {console.log('advancing timer');})")); InteractiveDetector* interactive_detector( InteractiveDetector::From(*document)); ASSERT_NE(nullptr, interactive_detector); WebKeyboardEvent key_event(WebInputEvent::kRawKeyDown, WebInputEvent::kNoModifiers, WebInputEvent::GetStaticTimeStampForTests()); key_event.dom_key = Platform::Current()->DomKeyEnumFromString(" "); key_event.windows_key_code = VKEY_SPACE; key_event.SetTimeStamp(CurrentTimeTicks()); clock.Advance(TimeDelta::FromMilliseconds(5000)); web_view->HandleInputEvent(WebCoalescedInputEvent(key_event)); TimeDelta first_input_delay = interactive_detector->GetFirstInputDelay(); EXPECT_EQ(5000, first_input_delay.InMillisecondsF()); web_view_helper_.Reset(); // Remove dependency on locally scoped client. } } // namespace blink
41.578827
87
0.735396
[ "geometry", "object", "vector", "transform" ]
4aaac5b2babef5a0de91d3256c437f5f2b3e03fd
615
cpp
C++
workspace/environment.cpp
5cript/minide
0964ae51512eb7ba1ee44d828d27e5b73da32245
[ "MIT" ]
null
null
null
workspace/environment.cpp
5cript/minide
0964ae51512eb7ba1ee44d828d27e5b73da32245
[ "MIT" ]
1
2018-01-26T00:06:19.000Z
2018-01-26T00:06:54.000Z
workspace/environment.cpp
5cript/minide
0964ae51512eb7ba1ee44d828d27e5b73da32245
[ "MIT" ]
null
null
null
#include "environment.hpp" #include <cstdio> extern char **environ; namespace MinIDE { //##################################################################################################################### //std::vector <std::string> getEnvironmentVariables() //{ //} //--------------------------------------------------------------------------------------------------------------------- //void setEnvironment(Environment const& environment) //{ //} //##################################################################################################################### }
29.285714
120
0.247154
[ "vector" ]
4ab58a0333fce6d87583ab9d82270ac526ccb12e
2,056
hpp
C++
src/Event/RepeatingEvent.hpp
pokorj54/Command-line-calendar
de2c8a89917bd4cb69547427a6ec1bced218c5ad
[ "MIT" ]
null
null
null
src/Event/RepeatingEvent.hpp
pokorj54/Command-line-calendar
de2c8a89917bd4cb69547427a6ec1bced218c5ad
[ "MIT" ]
null
null
null
src/Event/RepeatingEvent.hpp
pokorj54/Command-line-calendar
de2c8a89917bd4cb69547427a6ec1bced218c5ad
[ "MIT" ]
null
null
null
#ifndef RepeatingEvent_d990ac2d48434e71bdd81c9412620e6f #define RepeatingEvent_d990ac2d48434e71bdd81c9412620e6f #include "Event.hpp" #include "../Helpers/DateTime.hpp" #include <iostream> /** * @brief Abstract class that provides additional interface and united methods for repeating events * */ class RepeatingEvent: public Event { protected: std::size_t repeats; /** * @brief Commont part for method FillWithVirtualEvents * * @param periode number of time intervals in which is RepeaTingEvent repetiotion measured * @param t time adding method that symbolizes in which time units is repeat interval defined */ void _FillWithVirtualEvents(std::vector<VirtualEvent> & putHere, const DateTime & from, const DateTime & to, std::shared_ptr<Event> & ptr, int periode, DateTime::TimeAddMethod t) const; /** * @brief Commont part for method SplitShift * * @param periode number of time intervals in which is RepeaTingEvent repetiotion measured * @param t time adding method that symbolizes in which time units is repeat interval defined */ std::shared_ptr<Event> _SplitShift(const TimeSpan & ts, int from, const std::shared_ptr<Person> & owner, int periode, DateTime::TimeAddMethod t); public: RepeatingEvent(const std::string & name, const std::string & place, const DateTime & start, const TimeSpan & duration, const std::shared_ptr<Person> & owner, std::size_t repeats = 0); virtual ~RepeatingEvent() = default; /** * @brief Makes RepeatingEvent object of the same type but different information * */ virtual std::shared_ptr<Event> MakeSimilar(const std::string & name, const std::string & place, const DateTime & start, const TimeSpan & duration, const std::shared_ptr<Person> & owner, std::size_t repeats) const = 0; }; #endif //RepeatingEvent_d990ac2d48434e71bdd81c9412620e6f
42.833333
103
0.674611
[ "object", "vector" ]
4ab718555d3ce98ebdd50030bfac556ed3295e56
7,549
cpp
C++
Modules/REPlatform/Sources/REPlatform/Scene/Private/Utils/ImageTools.cpp
stinvi/dava.engine
2b396ca49cdf10cdc98ad8a9ffcf7768a05e285e
[ "BSD-3-Clause" ]
26
2018-09-03T08:48:22.000Z
2022-02-14T05:14:50.000Z
Modules/REPlatform/Sources/REPlatform/Scene/Private/Utils/ImageTools.cpp
ANHELL-blitz/dava.engine
ed83624326f000866e29166c7f4cccfed1bb41d4
[ "BSD-3-Clause" ]
null
null
null
Modules/REPlatform/Sources/REPlatform/Scene/Private/Utils/ImageTools.cpp
ANHELL-blitz/dava.engine
ed83624326f000866e29166c7f4cccfed1bb41d4
[ "BSD-3-Clause" ]
45
2018-05-11T06:47:17.000Z
2022-02-03T11:30:55.000Z
#include "REPlatform/Scene/Utils/ImageTools.h" #include <Base/GlobalEnum.h> #include <FileSystem/FileSystem.h> #include <Render/GPUFamilyDescriptor.h> #include <Render/Image/ImageConvert.h> #include <Render/Image/ImageSystem.h> #include <Render/PixelFormatDescriptor.h> namespace DAVA { namespace ImageTools { void SaveImage(Image* image, const FilePath& pathname) { ImageSystem::Save(pathname, image, image->format); } Image* LoadImage(const FilePath& pathname) { return ImageSystem::LoadSingleMip(pathname); } uint32 GetTexturePhysicalSize(const TextureDescriptor* descriptor, const eGPUFamily forGPU, uint32 baseMipMaps) { uint32 size = 0; Vector<FilePath> files; if (descriptor->IsCubeMap() && forGPU == GPU_ORIGIN) { Vector<FilePath> faceNames; descriptor->GetFacePathnames(faceNames); files.reserve(faceNames.size()); for (auto& faceName : faceNames) { if (!faceName.IsEmpty()) files.push_back(faceName); } } else { descriptor->CreateLoadPathnamesForGPU(forGPU, files); } FileSystem* fileSystem = FileSystem::Instance(); for (const FilePath& imagePathname : files) { if (fileSystem->Exists(imagePathname) && fileSystem->IsFile(imagePathname)) { ImageInfo info = ImageSystem::GetImageInfo(imagePathname); if (!info.IsEmpty()) { uint32 m = Min(baseMipMaps, info.mipmapsCount - 1); for (; m < info.mipmapsCount; ++m) { uint32 w = Max(info.width >> m, 1u); uint32 h = Max(info.height >> m, 1u); size += ImageUtils::GetSizeInBytes(w, h, info.format); } } else { Logger::Error("ImageTools::[GetTexturePhysicalSize] Can't detect type of file %s", imagePathname.GetStringValue().c_str()); } } } return size; } void ConvertImage(const TextureDescriptor* descriptor, const eGPUFamily forGPU, TextureConverter::eConvertQuality quality) { if (!descriptor || descriptor->compression[forGPU].format == FORMAT_INVALID) { return; } TextureConverter::ConvertTexture(*descriptor, forGPU, true, quality); } bool SplitImage(const FilePath& pathname) { ScopedPtr<Image> loadedImage(ImageSystem::LoadSingleMip(pathname)); if (!loadedImage) { Logger::Error("Can't load image %s", pathname.GetAbsolutePathname().c_str()); return false; } if (loadedImage->GetPixelFormat() != FORMAT_RGBA8888) { Logger::Error("Incorrect image format %s. Must be RGBA8888", PixelFormatDescriptor::GetPixelFormatString(loadedImage->GetPixelFormat())); return false; } Channels channels = CreateSplittedImages(loadedImage); FilePath folder(pathname.GetDirectory()); SaveImage(channels.red, folder + "r.png"); SaveImage(channels.green, folder + "g.png"); SaveImage(channels.blue, folder + "b.png"); SaveImage(channels.alpha, folder + "a.png"); return true; } bool MergeImages(const FilePath& folder) { DVASSERT(folder.IsDirectoryPathname()); ScopedPtr<Image> r(LoadImage(folder + "r.png")); ScopedPtr<Image> g(LoadImage(folder + "g.png")); ScopedPtr<Image> b(LoadImage(folder + "b.png")); ScopedPtr<Image> a(LoadImage(folder + "a.png")); Channels channels(r, g, b, a); if (channels.IsEmpty()) { Logger::Error("Can't load one or more channel images from folder %s", folder.GetAbsolutePathname().c_str()); return false; } if (!channels.HasFormat(FORMAT_A8)) { Logger::Error("Can't merge images. Source format must be Grayscale 8bit"); return false; } if (!channels.ChannelesResolutionEqual()) { Logger::Error("Can't merge images. Source images must have same size"); return false; } ScopedPtr<Image> mergedImage(CreateMergedImage(channels)); ImageSystem::Save(folder + "merged.png", mergedImage); return true; } Channels CreateSplittedImages(Image* originalImage) { ScopedPtr<Image> r(Image::Create(originalImage->width, originalImage->height, FORMAT_A8)); ScopedPtr<Image> g(Image::Create(originalImage->width, originalImage->height, FORMAT_A8)); ScopedPtr<Image> b(Image::Create(originalImage->width, originalImage->height, FORMAT_A8)); ScopedPtr<Image> a(Image::Create(originalImage->width, originalImage->height, FORMAT_A8)); int32 size = originalImage->width * originalImage->height; int32 pixelSizeInBytes = PixelFormatDescriptor::GetPixelFormatSizeInBits(FORMAT_RGBA8888) / 8; for (int32 i = 0; i < size; ++i) { int32 offset = i * pixelSizeInBytes; r->data[i] = originalImage->data[offset]; g->data[i] = originalImage->data[offset + 1]; b->data[i] = originalImage->data[offset + 2]; a->data[i] = originalImage->data[offset + 3]; } return Channels(r, g, b, a); } Image* CreateMergedImage(const Channels& channels) { if (!channels.ChannelesResolutionEqual() || !channels.HasFormat(FORMAT_A8)) { return nullptr; } Image* mergedImage = Image::Create(channels.red->width, channels.red->height, FORMAT_RGBA8888); int32 size = mergedImage->width * mergedImage->height; int32 pixelSizeInBytes = PixelFormatDescriptor::GetPixelFormatSizeInBits(FORMAT_RGBA8888) / 8; for (int32 i = 0; i < size; ++i) { int32 offset = i * pixelSizeInBytes; mergedImage->data[offset] = channels.red->data[i]; mergedImage->data[offset + 1] = channels.green->data[i]; mergedImage->data[offset + 2] = channels.blue->data[i]; mergedImage->data[offset + 3] = channels.alpha->data[i]; } return mergedImage; } void SetChannel(Image* image, eComponentsRGBA channel, uint8 value) { if (image->format != FORMAT_RGBA8888) { return; } int32 size = image->width * image->height; static const int32 pixelSizeInBytes = 4; int32 offset = channel; for (int32 i = 0; i < size; ++i, offset += pixelSizeInBytes) { image->data[offset] = value; } } QImage FromDavaImage(const FilePath& pathname) { auto image = LoadImage(pathname); if (image) { QImage img = FromDavaImage(image); SafeRelease(image); return img; } return QImage(); } QImage FromDavaImage(const Image* image) { DVASSERT(image != nullptr); if (image->format == FORMAT_RGBA8888) { QImage qtImage(image->width, image->height, QImage::Format_RGBA8888); Memcpy(qtImage.bits(), image->data, image->dataSize); return qtImage; } else if (ImageConvert::CanConvertFromTo(image->format, FORMAT_RGBA8888)) { ScopedPtr<Image> newImage(Image::Create(image->width, image->height, FORMAT_RGBA8888)); bool converted = ImageConvert::ConvertImage(image, newImage); if (converted) { return FromDavaImage(newImage); } else { Logger::Error("[%s]: Error converting from %s", __FUNCTION__, GlobalEnumMap<PixelFormat>::Instance()->ToString(image->format)); return QImage(); } } else { Logger::Error("[%s]: Converting from %s is not implemented", __FUNCTION__, GlobalEnumMap<PixelFormat>::Instance()->ToString(image->format)); return QImage(); } } } // namespace ImageTools } // namespace DAVA
30.686992
148
0.64088
[ "render", "vector" ]
4aba29effb033d85ccdb4a04a5bfccc66a8182fd
1,133
cpp
C++
codeforce3/546C - Soldier and Cards.cpp
khaled-farouk/My_problem_solving_solutions
46ed6481fc9b424d0714bc717cd0ba050a6638ef
[ "MIT" ]
null
null
null
codeforce3/546C - Soldier and Cards.cpp
khaled-farouk/My_problem_solving_solutions
46ed6481fc9b424d0714bc717cd0ba050a6638ef
[ "MIT" ]
null
null
null
codeforce3/546C - Soldier and Cards.cpp
khaled-farouk/My_problem_solving_solutions
46ed6481fc9b424d0714bc717cd0ba050a6638ef
[ "MIT" ]
null
null
null
#include <iostream> #include <queue> #include <vector> #include <map> #include <algorithm> using namespace std; int N; queue<int> solider1; queue<int> solider2; vector<pair<queue<int>, queue<int> > > vis; void BFS() { int cost = 0; while (solider1.size() != 0 && solider2.size() != 0) { int x = solider1.front(); solider1.pop(); int y = solider2.front(); solider2.pop(); if (x > y) { solider1.push(y); solider1.push(x); } else { solider2.push(x); solider2.push(y); } if(find(vis.begin(), vis.end(), make_pair(solider1, solider2)) == vis.end()) { vis.push_back(make_pair(solider1, solider2)); } else { cout << -1 << endl; return; } cost++; } cout << cost << ' '; if (!solider1.empty()) { cout << 1 << endl; } else { cout << 2 << endl; } } int main() { cin >> N; int tmp; cin >> tmp; for (int i = 0; i < tmp; i++) { int tmp; cin >> tmp; solider1.push(tmp); } cin >> tmp; for (int i = 0; i < tmp; i++) { int tmp; cin >> tmp; solider2.push(tmp); } BFS(); return 0; }
15.106667
81
0.516328
[ "vector" ]
385b67730054b229b4a6c0dcea901cd46e414ff5
1,587
cpp
C++
C+=.cpp
manu-karenite/Codeforces-Solutions
c963a0186c6530ea8a785780fc4d68ed539e8c6e
[ "MIT" ]
1
2021-04-07T05:13:21.000Z
2021-04-07T05:13:21.000Z
C+=.cpp
manu-karenite/Codeforces-Solutions
c963a0186c6530ea8a785780fc4d68ed539e8c6e
[ "MIT" ]
null
null
null
C+=.cpp
manu-karenite/Codeforces-Solutions
c963a0186c6530ea8a785780fc4d68ed539e8c6e
[ "MIT" ]
null
null
null
/* This code is written by Manavesh Narendra E-mail : manu.karenite@gmail.com LinkedIn : https://www.linkedin.com/in/manavesh-narendra-489833196/ */ #include <bits/stdc++.h> using namespace std; #define loop(i,a,b) for(int i=a;i<b;i++) int main() { int test; cin>>test; while(test--) { int a ; int b; int n; cin>>a>>b>>n; int great = max(a,b); int less = min(a,b); vector<int> v; v.push_back(great+less); if(v[0]>n) { cout<<1<<endl; } else { v.push_back(great+less+great); if(v[1]>n) { cout<<2<<endl; } else { // main code write here //not on 2 , meaning must be greater than2 int i =1; while(v[i]<=n) //loop runs { i++; v.push_back(v[i-1]+v[i-2]); if(v[i]>n) { cout<<i+1<<endl; break; } } } } } return 0; }
24.415385
71
0.281033
[ "vector" ]
3864f65372f1091f2f7c590be2c739e398e0f1b9
3,476
cpp
C++
Code/RDGeneral/testConcurrentQueue.cpp
kazuyaujihara/rdkit
06027dcd05674787b61f27ba46ec0d42a6037540
[ "BSD-3-Clause" ]
1,609
2015-01-05T02:41:13.000Z
2022-03-30T21:57:24.000Z
Code/RDGeneral/testConcurrentQueue.cpp
kazuyaujihara/rdkit
06027dcd05674787b61f27ba46ec0d42a6037540
[ "BSD-3-Clause" ]
3,412
2015-01-06T12:13:33.000Z
2022-03-31T17:25:41.000Z
Code/RDGeneral/testConcurrentQueue.cpp
bp-kelley/rdkit
e0de7c9622ce73894b1e7d9568532f6d5638058a
[ "BSD-3-Clause" ]
811
2015-01-11T03:33:48.000Z
2022-03-28T11:57:49.000Z
#ifdef RDK_THREADSAFE_SSS #include <RDGeneral/Invariant.h> #include <RDGeneral/RDLog.h> #include <functional> #include <iomanip> #include <sstream> #include "ConcurrentQueue.h" using namespace RDKit; //! method for testing basic ConcurrentQueue operations void testPushAndPop() { ConcurrentQueue<int>* q = new ConcurrentQueue<int>(4); int e1, e2, e3; TEST_ASSERT(q->isEmpty()); q->push(1); q->push(2); q->push(3); TEST_ASSERT(!q->isEmpty()); TEST_ASSERT(q->pop(e1)); TEST_ASSERT(q->pop(e2)); TEST_ASSERT(q->pop(e3)); TEST_ASSERT(e1 == 1); TEST_ASSERT(e2 == 2); TEST_ASSERT(e3 == 3); TEST_ASSERT(q->isEmpty()); delete (q); } void produce(ConcurrentQueue<int>& q, const int numToProduce) { for (int i = 0; i < numToProduce; ++i) { q.push(i); } } void consume(ConcurrentQueue<int>& q, std::vector<int>& result) { int element; while (q.pop(element)) { result.push_back(element); } } //! multithreaded testing for ConcurrentQueue bool testProducerConsumer(const int numProducerThreads, const int numConsumerThreads) { ConcurrentQueue<int> q(5); TEST_ASSERT(q.isEmpty()); const int numToProduce = 10; std::vector<std::thread> producers(numProducerThreads); std::vector<std::thread> consumers(numConsumerThreads); std::vector<std::vector<int>> results(numConsumerThreads); //! start producer threads for (int i = 0; i < numProducerThreads; i++) { producers[i] = std::thread(produce, std::ref(q), numToProduce); } //! start consumer threads for (int i = 0; i < numConsumerThreads; i++) { consumers[i] = std::thread(consume, std::ref(q), std::ref(results[i])); } std::for_each(producers.begin(), producers.end(), std::mem_fn(&std::thread::join)); //! the producer is done producing q.setDone(); std::for_each(consumers.begin(), consumers.end(), std::mem_fn(&std::thread::join)); TEST_ASSERT(q.isEmpty()); std::vector<int> frequency(numToProduce, 0); for (auto& result : results) { for (auto& element : result) { frequency[element] += 1; } } for (auto& freq : frequency) { if (freq != numProducerThreads) { return false; } } return true; } void testMultipleTimes() { const int trials = 10000; //! Single Producer, Single Consumer for (int i = 0; i < trials; i++) { bool result = testProducerConsumer(1, 1); TEST_ASSERT(result); } //! Single Producer, Multiple Consumer for (int i = 0; i < trials; i++) { bool result = testProducerConsumer(1, 5); TEST_ASSERT(result); } //! Multiple Producer, Single Consumer for (int i = 0; i < trials; i++) { bool result = testProducerConsumer(5, 1); TEST_ASSERT(result); } //! Multiple Producer, Multiple Consumer for (int i = 0; i < trials; i++) { bool result = testProducerConsumer(2, 4); TEST_ASSERT(result); } } int main() { RDLog::InitLogs(); BOOST_LOG(rdErrorLog) << "\n-----------------------------------------\n"; testPushAndPop(); BOOST_LOG(rdErrorLog) << "Finished: testPushAndPop() \n"; BOOST_LOG(rdErrorLog) << "\n-----------------------------------------\n"; #ifdef RDK_TEST_MULTITHREADED BOOST_LOG(rdErrorLog) << "\n-----------------------------------------\n"; testMultipleTimes(); BOOST_LOG(rdErrorLog) << "Finished: testMultipleTimes() \n"; BOOST_LOG(rdErrorLog) << "\n-----------------------------------------\n"; #endif return 0; } #endif
24.828571
75
0.613636
[ "vector" ]
38693cf5550133b69f2d37ddf9590d327c05c9c0
1,431
cpp
C++
Installation/test/Installation/test_TBB.cpp
ffteja/cgal
c1c7f4ad9a4cd669e33ca07a299062a461581812
[ "CC0-1.0" ]
3,227
2015-03-05T00:19:18.000Z
2022-03-31T08:20:35.000Z
Installation/test/Installation/test_TBB.cpp
ffteja/cgal
c1c7f4ad9a4cd669e33ca07a299062a461581812
[ "CC0-1.0" ]
5,574
2015-03-05T00:01:56.000Z
2022-03-31T15:08:11.000Z
Installation/test/Installation/test_TBB.cpp
ffteja/cgal
c1c7f4ad9a4cd669e33ca07a299062a461581812
[ "CC0-1.0" ]
1,274
2015-03-05T00:01:12.000Z
2022-03-31T14:47:56.000Z
//#undef CGAL_LINKED_WITH_TBB #include <CGAL/tags.h> #ifdef CGAL_LINKED_WITH_TBB # include <tbb/blocked_range.h> # include <tbb/parallel_for.h> #endif #include <iostream> #include <vector> #ifdef CGAL_LINKED_WITH_TBB class Change_array_functor { public: Change_array_functor(std::vector<int> &v) : m_v(v) {} void operator() (const tbb::blocked_range<size_t>& r) const { for(size_t i = r.begin(); i != r.end(); i++ ) m_v[i] *= 10; } private: std::vector<int> &m_v; }; void change_array(std::vector<int> &v, CGAL::Parallel_tag) { std::cout << "[Parallel] Using a tbb::parallel_for loop..."; tbb::parallel_for( tbb::blocked_range<std::size_t>(0, v.size()), Change_array_functor(v) ); std::cout << " done." << std::endl; } #endif void change_array(std::vector<int> &v, CGAL::Sequential_tag) { std::cout << "[Sequential] Using a sequential for loop..."; std::vector<int>::iterator it = v.begin(), it_end = v.end(); for ( ; it != it_end ; ++it) *it *= 10; std::cout << " done." << std::endl; } int main() { std::vector<int> v; for (int i = 0 ; i < 10000 ; ++i) v.push_back(i); std::cout << "Trying to call the sequential algorithm => "; change_array(v, CGAL::Sequential_tag()); std::cout << "Trying to call the parallel algorithm => "; change_array(v, CGAL::Parallel_tag()); /*for (int i = 0 ; i < 100 ; ++i) std::cerr << v[i] << " ";*/ return 0; }
21.681818
62
0.61775
[ "vector" ]
386ab099c22d2099b7bf416bd27211f614d906c7
7,581
cpp
C++
demo/cpp/squares.cpp
berak/opencv_smallfry
fd8f64980dff0527523791984d6cb3dfcd2bc9bc
[ "BSD-3-Clause" ]
57
2015-02-16T06:43:24.000Z
2022-03-16T06:21:36.000Z
demo/cpp/squares.cpp
berak/opencv_smallfry
fd8f64980dff0527523791984d6cb3dfcd2bc9bc
[ "BSD-3-Clause" ]
4
2016-03-08T09:51:09.000Z
2021-03-29T10:18:55.000Z
demo/cpp/squares.cpp
berak/opencv_smallfry
fd8f64980dff0527523791984d6cb3dfcd2bc9bc
[ "BSD-3-Clause" ]
27
2015-03-28T19:55:34.000Z
2022-01-09T15:03:15.000Z
// The "Square Detector" program. // It loads several images sequentially and tries to find squares in // each image #include "opencv2/core.hpp" #include "opencv2/imgproc.hpp" #include "opencv2/imgcodecs.hpp" #include "opencv2/highgui.hpp" #include <iostream> #include <math.h> #include <string.h> using namespace cv; using namespace std; static void help() { cout << "\nA program using pyramid scaling, Canny, contours, contour simpification and\n" "memory storage (it's got it all folks) to find\n" "squares in a list of images pic1-6.png\n" "Returns sequence of squares detected on the image.\n" "the sequence is stored in the specified memory storage\n" "Call:\n" "./squares [file_name (optional)]\n" "Using OpenCV version " << CV_VERSION << "\n" << endl; } int thresh = 50, N = 11; const char* wndname = "Square Detection Demo"; // helper function: // finds a cosine of angle between vectors // from pt0->pt1 and from pt0->pt2 static double angle( Point pt1, Point pt2, Point pt0 ) { double dx1 = pt1.x - pt0.x; double dy1 = pt1.y - pt0.y; double dx2 = pt2.x - pt0.x; double dy2 = pt2.y - pt0.y; return (dx1*dx2 + dy1*dy2)/sqrt((dx1*dx1 + dy1*dy1)*(dx2*dx2 + dy2*dy2) + 1e-10); } // returns sequence of squares detected on the image. // the sequence is stored in the specified memory storage static void findSquares( const Mat& image, vector<vector<Point> >& squares ) { squares.clear(); Mat pyr, timg, gray0(image.size(), CV_8U), gray; // down-scale and upscale the image to filter out the noise pyrDown(image, pyr, Size(image.cols/2, image.rows/2)); pyrUp(pyr, timg, image.size()); vector<vector<Point> > contours; // find squares in every color plane of the image for( int c = 1; c < 2; c++ ) { int ch[] = {c, 0}; mixChannels(&timg, 1, &gray0, 1, ch, 1); // try several threshold levels for( int l = 0; l < N; l++ ) { // hack: use Canny instead of zero threshold level. // Canny helps to catch squares with gradient shading if( l == 0 ) { // apply Canny. Take the upper threshold from slider // and set the lower to 0 (which forces edges merging) Canny(gray0, gray, 0, thresh, 5); // dilate canny output to remove potential // holes between edge segments dilate(gray, gray, Mat(), Point(-1,-1)); } else { // apply threshold if l!=0: // tgray(x,y) = gray(x,y) < (l+1)*255/N ? 255 : 0 gray = gray0 >= (l+1)*255/N; } // find contours and store them all as a list findContours(gray, contours, RETR_LIST, CHAIN_APPROX_SIMPLE); vector<Point> approx; // test each contour for( size_t i = 0; i < contours.size(); i++ ) { // approximate contour with accuracy proportional // to the contour perimeter approxPolyDP(Mat(contours[i]), approx, arcLength(Mat(contours[i]), true)*0.02, true); // square contours should have 4 vertices after approximation // relatively large area (to filter out noisy contours) // and be convex. // Note: absolute value of an area is used because // area may be positive or negative - in accordance with the // contour orientation if( approx.size() == 4 && fabs(contourArea(Mat(approx))) > 1000 && isContourConvex(Mat(approx)) ) { double maxCosine = 0; for( int j = 2; j < 5; j++ ) { // find the maximum cosine of the angle between joint edges double cosine = fabs(angle(approx[j%4], approx[j-2], approx[j-1])); maxCosine = MAX(maxCosine, cosine); } // if cosines of all angles are small // (all angles are ~90 degree) then write quandrange // vertices to resultant sequence if( maxCosine < 0.5 ) squares.push_back(approx); } } } } } // // 0 1 // 3 2 // int index_cw(Point q, const vector<Point> &pt) { int left=0, top=0; for (Point p:pt) { if (q.x < p.x) left++; if (q.y < p.y) top++; } return (left>=2 && top>=2) ? 0: (left<2 && top>=2) ? 1: (left<2 && top<2) ? 2 : 3; } vector<Point2f> sort_cw(const vector<Point> &pt) { vector<Point2f> npt(pt.size()); for (Point p:pt) { int i = index_cw(p,pt); npt[i] = p; } return npt; } int cluster(const vector<vector<Point>> &rects, vector<int> &labels, double eps) { return cv::partition(rects,labels,[eps](const vector<Point> &a, const vector<Point> &b){return norm(a,b)<eps;}); } void centers(const vector<vector<Point>> &rects, const vector<int> &labels, int C, vector<vector<Point>> &center) { center.resize(C,vector<Point>(4)); vector<int> ct(C,0); for (int i=0; i<rects.size(); i++) { int id = labels[i]; CV_Assert(id<C); center[id][0] += rects[i][0]; center[id][1] += rects[i][1]; center[id][2] += rects[i][2]; center[id][3] += rects[i][3]; ct[id] ++; } for (int i=0; i<center.size(); i++) { center[i][0] /= ct[i]; center[i][1] /= ct[i]; center[i][2] /= ct[i]; center[i][3] /= ct[i]; } } // the function draws all the squares in the image static void drawSquares( Mat& image, const vector<vector<Point> >& squares ) { int R=8; int Z=120; Size S(Z,Z); vector<Point2f> dst { Point2f(0,0), Point2f(Z,0), Point2f(Z,Z), Point2f(0,Z) }; vector<int> labels; int n = cluster(squares, labels, 108); cout << squares.size() << " squares and " << n << " clusters" << endl; vector<vector<Point> > center; centers(squares,labels,n,center); //squares = center; cout << "cen " << center.size() << endl; vector<Mat> crops; for( size_t i = 0; i < center.size(); i++ ) { vector<Point2f> pt = sort_cw(center[i]); cout << i << " " << Mat(center[i]).t() << " " << Mat(pt).t() << endl; Mat proj = getPerspectiveTransform(pt, dst); Mat warped; warpPerspective(image, warped, proj, S,INTER_LINEAR); crops.push_back(warped); } cout << "crops " << crops.size() << endl; Mat crp(0,R*Z,image.type()); Mat row(Z,0,image.type()); for( size_t i = 0; i < crops.size(); i++ ) { hconcat(row,crops[i],row); if (i%R == (R-1)) { vconcat(crp,row,crp); row.create(Z,0,image.type()); } } imshow(wndname, image); if (crp.rows && crp.cols) imshow("cropped", crp); else if (row.rows && row.cols) imshow("cropped", row); } int main(int argc, char** argv) { static const char* names[] = { "books.png", 0 }; // help(); if( argc > 1) { names[0] = argv[1]; names[1] = "0"; } namedWindow( wndname, 1 ); vector<vector<Point> > squares; for( int i = 0; names[i] != 0; i++ ) { Mat image = imread(names[i], 1); if( image.empty() ) { cout << "Couldn't load " << names[i] << endl; continue; } findSquares(image, squares); drawSquares(image, squares); char c = (char)waitKey(); if( c == 27 ) break; } return 0; }
29.383721
115
0.543596
[ "vector" ]
386e775905f2f933e64aeaafa8dbf423d56b7436
13,136
cpp
C++
instance.cpp
barrystyle/dashdeb
45988ecbbaf01203c529ee090fae1fd4553cb6fe
[ "MIT" ]
null
null
null
instance.cpp
barrystyle/dashdeb
45988ecbbaf01203c529ee090fae1fd4553cb6fe
[ "MIT" ]
null
null
null
instance.cpp
barrystyle/dashdeb
45988ecbbaf01203c529ee090fae1fd4553cb6fe
[ "MIT" ]
null
null
null
#include <script/interpreter.h> #include <util/strencodings.h> #include <policy/policy.h> #include <streams.h> #include <pubkey.h> #include <value.h> #include <vector> #include <instance.h> static bool DecodeHexTx(CMutableTransaction& tx, const std::string& strHexTx) { if (!IsHex(strHexTx)) { fprintf(stderr, "found nonhex characters in input\n"); return false; } std::vector<unsigned char> txData(ParseHex(strHexTx)); CDataStream ssData(txData, SER_NETWORK, PROTOCOL_VERSION); ssData >> tx; return true; } CTransactionRef parse_tx(const char* p) { std::vector<unsigned char> txData; if (!TryHex(p, txData)) { fprintf(stderr, "failed to parse tx hex string\n"); return nullptr; } //! convert to string for native dash routine std::string hexData(p); CMutableTransaction mtx; if (!DecodeHexTx(mtx, hexData)) { fprintf(stderr, "error with transaction (unknown)\n"); return nullptr; } CTransactionRef tx = MakeTransactionRef(CTransaction(mtx)); return tx; } bool Instance::parse_transaction(const char* txdata, bool parse_amounts) { // parse until we run out of amounts, if requested const char* p = txdata; if (parse_amounts) { while (1) { const char* c = p; while (*c && *c != ',' && *c != ':') ++c; if (!*c) { if (amounts.size() == 0) { // no amounts provided break; } fprintf(stderr, "error: tx hex missing from input\n"); return false; } char* s = strndup(p, c-p); std::string ss = s; free(s); CAmount a; if (!ParseFixedPoint(ss, 8, &a)) { fprintf(stderr, "failed to parse amount: %s\n", ss.c_str()); return false; } amounts.push_back(a); p = c + 1; if (*c == ':') break; } } tx = parse_tx(p); if (!tx) return false; while (amounts.size() < tx->vin.size()) amounts.push_back(0); return true; } bool Instance::parse_input_transaction(const char* txdata, int select_index) { txin = parse_tx(txdata); if (!txin) return false; if (tx) { const uint256& txin_hash = txin->GetHash(); if (select_index > -1) { // verify index is valid if (select_index >= tx->vin.size()) { fprintf(stderr, "error: the selected index %d is out of bounds (must be less than %zu, the number of inputs in the transaction)\n", select_index, tx->vin.size()); return false; } if (txin_hash != tx->vin[select_index].prevout.hash) { fprintf(stderr, "error: the selected index (%d) of the transaction refers to txid %s, but the input transaction has txid %s\n", select_index, tx->vin[select_index].prevout.hash.ToString().c_str(), txin_hash.ToString().c_str()); return false; } txin_index = select_index; txin_vout_index = tx->vin[select_index].prevout.n; } else { // figure out index from tx vin int64_t i = 0; for (const auto& input : tx->vin) { if (input.prevout.hash == txin_hash) { txin_index = i; txin_vout_index = input.prevout.n; break; } i++; } if (txin_index == -1) { fprintf(stderr, "error: the input transaction %s is not found in any of the inputs for the provided transaction %s\n", txin_hash.ToString().c_str(), tx->GetHash().ToString().c_str()); return false; } } } return true; } bool Instance::parse_script(const char* script_str) { std::vector<unsigned char> scriptData = Value(script_str).data_value(); script = CScript(scriptData.begin(), scriptData.end()); // for (const auto& keymap : COMPILER_CTX.keymap) { // auto cs = keymap.first.c_str(); // auto key = Value(std::vector<uint8_t>(keymap.second.begin(), keymap.second.end())).data; // auto sig = Value((std::string("sig:") + keymap.first).c_str()).data_value(); // pretend_valid_map[sig] = key; // pretend_valid_pubkeys.insert(key); // printf("info: provide sig:%s as signature for %s [%s=%s]\n", cs, cs, HexStr(sig).c_str(), HexStr(key).c_str()); // } // try { // msenv = new MSEnv(script, true); // } catch (const std::exception& ex) { // printf("miniscript failed to parse script; miniscript support disabled\n"); // msenv = nullptr; // } return script.HasValidOps(); } bool Instance::parse_script(const std::vector<uint8_t>& script_data) { script = CScript(script_data.begin(), script_data.end()); return script.HasValidOps(); } bool Instance::parse_pretend_valid_expr(const char* expr) { const char* p = expr; const char* c = p; valtype sig; uint160 keyid; bool got_sig = false; // COMPILER_CTX.symbolic_outputs = true; while (*c) { while (*c && *c != ',' && *c != ':') ++c; char* cs = strndup(p, c-p); Value v = Value(cs); valtype s = v.data_value(); free(cs); switch (*c) { case ':': if (got_sig) { fprintf(stderr, "parse error (unexpected colon) near %s\n", p); return false; } sig = s; got_sig = true; break; case ',': case 0: if (!got_sig) { fprintf(stderr, "parse error (missing signature) near %s\n", p); return false; } got_sig = false; v.do_hash160(); keyid = uint160(v.data_value()); // pretend_valid_map[sig] = s; pretend_valid_pubkeys.insert(s); auto key = CPubKey(ParseHex(p)); if (!key.IsFullyValid()) { fprintf(stderr, "invalid pubkey %s\n", p); return false; } pretend_valid_pubkeys.insert(valtype(key.begin(), key.end())); // note: we override below; this may lead to issues pretend_valid_map[sig] = valtype(key.begin(), key.end()); break; } p = c = c + (*c != 0); } return true; } void Instance::parse_stack_args(const std::vector<const char*> args) { for (auto& v : args) { auto z = Value(v).data_value(); stack.push_back(z); // if (z.size() == 33) { // // add if valid pubkey // CompilerContext::Key key; // COMPILER_CTX.FromPKBytes(z.begin(), z.end(), key); // } } } void Instance::parse_stack_args(size_t argc, char* const* argv, size_t starting_index) { for (int i = starting_index; i < argc; i++) { stack.push_back(Value(argv[i]).data_value()); } } bool Instance::setup_environment(unsigned int flags) { if (tx) { if (txin && txin_index > -1) { std::vector<CTxOut> spent_outputs; spent_outputs.emplace_back(txin->vout[txin_index]); if (tx->vin.size() == 1) { txdata.Init(*tx.get(), std::move(spent_outputs)); } } checker = new TransactionSignatureChecker(tx.get(), txin_index > -1 ? txin_index : 0, amounts[txin_index > -1 ? txin_index : 0], txdata); } else { checker = new BaseSignatureChecker(); } execdata.m_codeseparator_pos = 0xFFFFFFFFUL; execdata.m_codeseparator_pos_init = true; env = new InterpreterEnv(stack, script, flags, *checker, sigver, &error); env->successor_script = successor_script; env->pretend_valid_map = pretend_valid_map; env->pretend_valid_pubkeys = pretend_valid_pubkeys; env->done &= successor_script.size() == 0; env->execdata = execdata; env->tce = tce; return env->operational; } bool Instance::at_end() { return env->done; } bool Instance::at_start() { return env->pc == env->script.begin(); } std::string Instance::error_string() { return exception_string == "" ? ScriptErrorString(*env->serror) : "exception thrown: " + exception_string; } bool Instance::step(size_t steps) { exception_string = ""; while (steps > 0) { if (env->done) return false; try { if (!StepScript(*env)) return false; } catch (const std::exception& ex) { exception_string = ex.what(); return false; } steps--; } return true; } bool Instance::rewind() { if (env->pc == env->script.begin()) { return false; } if (env->done) { env->done = false; } return RewindScript(*env); } bool Instance::eval(const size_t argc, char* const* argv) { if (argc < 1) return false; CScript script; for (int i = 0; i < argc; i++) { const char* v = argv[i]; const size_t vlen = strlen(v); // empty strings are ignored if (!v[0]) continue; // number? int n = atoi(v); if (n != 0) { // verify char buf[vlen + 1]; sprintf(buf, "%d", n); if (!strcmp(buf, v)) { // verified; is it > 3 chars and can it be a hexstring too? if (vlen > 3 && !(vlen & 1)) { std::vector<unsigned char> pushData; if (TryHex(v, pushData)) { // it can; warn about using 0x for hex if (VALUE_WARN) btc_logf("warning: ambiguous input %s is interpreted as a numeric value; use 0x%s to force into hexadecimal interpretation\n", v, v); } } // can it be an opcode too? if (n < 16) { if (VALUE_WARN) btc_logf("warning: ambiguous input %s is interpreted as a numeric value (%s), not as an opcode (OP_%s). Use OP_%s to force into op code interpretation\n", v, v, v, v); } script << (int64_t)n; continue; } } // hex string? if (!(vlen & 1)) { std::vector<unsigned char> pushData; if (TryHex(v, pushData)) { script << pushData; continue; } } opcodetype opc = GetOpCode(v); if (opc != OP_INVALIDOPCODE) { script << opc; continue; } fprintf(stderr, "error: invalid opcode %s\n", v); return false; } CScript::const_iterator it = script.begin(); while (it != script.end()) { if (!StepScript(*env, it, &script)) { fprintf(stderr, "Error: %s\n", ScriptErrorString(*env->serror).c_str()); return false; } } return true; } bool Instance::configure_tx_txin() { opcodetype opcode; std::vector<uint8_t> pushval; // no script and no stack; autogenerate from tx/txin // the script is the witness stack, last entry, or scriptpubkey // the stack is the witness stack minus last entry, in order, or the results of executing the scriptSig amounts[txin_index] = txin->vout[txin_vout_index].nValue; btc_logf("input tx index = %" PRId64 "; tx input vout = %" PRId64 "; value = %" PRId64 "\n", txin_index, txin_vout_index, amounts[txin_index]); auto& scriptSig = tx->vin[txin_index].scriptSig; CScript scriptPubKey = txin->vout[txin_vout_index].scriptPubKey; std::vector<const char*> push_del; // legacy sigver = SigVersion::BASE; script = scriptSig; successor_script = scriptPubKey; parse_stack_args(push_del); while (!push_del.empty()) { delete push_del.back(); push_del.pop_back(); } // // extract pubkeys from script // CScript::const_iterator it = script.begin(); // while (script.GetOp(it, opcode, pushval)) { // if (pushval.size() == 33) { // // add if valid pubkey // CompilerContext::Key key; // COMPILER_CTX.FromPKBytes(pushval.begin(), pushval.end(), key); // } // } // try { // msenv = new MSEnv(successor_script, true); // } catch (const std::exception& ex) { // printf("miniscript failed to parse script; miniscript support disabled\n"); // msenv = nullptr; // } return true; } uint256 Instance::calc_sighash() { uint256 hash; std::vector<CTxOut> spent_outputs; spent_outputs.emplace_back(txin->vout[txin_vout_index]); txdata = PrecomputedTransactionData(); txdata.Init(*tx.get(), std::move(spent_outputs)); if (sigver == SigVersion::BASE) sigver = SigVersion::TAPROOT; // bool ret = SignatureHashSchnorr(sighash, execdata, *txTo, nIn, hashtype, sigversion, this->txdata); if (!SignatureHashSchnorr(hash, execdata, *tx, txin_index, 0x00, sigver, txdata)) { fprintf(stderr, "Failed to generate schnorr signature hash!\n"); exit(1); } return hash; }
34.751323
243
0.554278
[ "vector" ]
38737b78025c8248f18e74601f1b3a411141edc8
4,463
cpp
C++
src/formatter.cpp
slowptr/tuxdump
a9ac4cec89198b855cb8da15a5e286f11a352bed
[ "MIT" ]
27
2018-08-19T13:49:21.000Z
2021-12-16T23:52:14.000Z
src/formatter.cpp
slowptr/tuxdump
a9ac4cec89198b855cb8da15a5e286f11a352bed
[ "MIT" ]
9
2018-09-22T23:17:34.000Z
2022-01-29T11:04:27.000Z
src/formatter.cpp
slowptr/tuxdump
a9ac4cec89198b855cb8da15a5e286f11a352bed
[ "MIT" ]
7
2018-09-16T13:04:20.000Z
2022-02-26T11:18:39.000Z
#include "formatter.h" #include "logger.h" #include <fmt/time.h> #include <rapidjson/document.h> #include <libconfig.h++> bool Formatter::LoadFormat(const char* fmt) { if (!strcmp(fmt, "json")) { return true; } m_bJson = false; libconfig::Config cfg; try { cfg.readFile("formats.cfg"); } catch (const libconfig::FileIOException& fioex) { Logger::Error("Failed to open file: \"formats.cfg\""); return false; } catch (const libconfig::ParseException& pex) { Logger::Error("Parse exception: {}\nFile: {}:{}\n", pex.getError(), "formats.cfg", pex.getLine()); return false; } try { libconfig::Setting& formats = cfg.lookup("formats"); libconfig::Setting& entry = formats.lookup(fmt); if (!entry.lookupValue("table_begin", m_fmtTableBegin)) { return false; } if (!entry.lookupValue("table_end", m_fmtTableEnd)) { return false; } if (!entry.lookupValue("offset", m_fmtOffset)) { return false; } entry.lookupValue("strip_table_prefix", m_fmtRemovePrefix); entry.lookupValue("header", m_fmtHeader); entry.lookupValue("footer", m_fmtFooter); entry.lookupValue("timestamp", m_fmtTimestamp); entry.lookupValue("indent", m_fmtIndent); entry.lookupValue("default_depth", m_depth); if (entry.exists("replace_chars")) { for (const libconfig::Setting& pair : entry.lookup("replace_chars")) { const char* before = pair[0]; if (pair.getLength() == 2) { const char* after = pair[1]; m_fmtReplaceChars.push_back({before[0], after[0]}); } else { m_fmtReplaceChars.push_back({before[0], 0}); } } } } catch (const libconfig::SettingNotFoundException& snfex) { Logger::Error("{}: {}", snfex.what(), snfex.getPath()); return false; } return true; } void Formatter::Indent() { for (int depth = 0; depth < m_depth; ++depth) { fmt::print(stdout, m_fmtIndent); } } void Formatter::PrintRecursive(rapidjson::Value::ConstMemberIterator object) { std::string scope = object->name.GetString(); if (object->value.IsObject()) { if (!scope.compare(0, 3, "DT_")) { scope.erase(0, 3); } Indent(); fmt::print(stdout, m_fmtTableBegin, scope); m_depth++; for (auto it = object->value.MemberBegin(); it != object->value.MemberEnd(); ++it) { PrintRecursive(it); } m_depth--; Indent(); fmt::print(stdout, m_fmtTableEnd, scope); } else if (object->value.IsInt()) { for (const std::pair<char, char>& replacements : m_fmtReplaceChars) { size_t pos = scope.find(replacements.first); while (pos != std::string::npos) { if (!replacements.second) { scope.erase(pos, 1); pos = scope.find(replacements.first, pos); } else { scope[pos] = replacements.second; pos = scope.find(replacements.first, pos + 1); } } } Indent(); fmt::print(stdout, m_fmtOffset, scope, object->value.GetUint()); } } void Formatter::Print(const std::string& json, const std::string& label) { if (m_bJson) { puts(json.c_str()); return; } try { fmt::print(stdout, m_fmtHeader, label); } catch(const fmt::v5::format_error& fex) { Logger::Warn("Header didn't supply {{0}}. Writing without input."); fmt::print(stdout, m_fmtHeader); } Indent(); try { std::time_t t = std::time(nullptr); fmt::print(stdout, m_fmtTimestamp, *std::localtime(&t), "checkers"); } catch (const fmt::format_error& fex) { Logger::Warn("Timestamp format missing or invalid. Skipping."); } rapidjson::Document doc; doc.Parse(json.c_str()); for (auto it = doc.MemberBegin(); it != doc.MemberEnd(); ++it) { PrintRecursive(it); } try { fmt::print(stdout, m_fmtFooter, label); } catch(const fmt::v5::format_error& fex) { Logger::Warn("Footer didn't supply {{0}}. Writing without input."); fmt::print(stdout, m_fmtFooter); } }
30.360544
92
0.553215
[ "object" ]
38781da46f30c131dab770c374fd806cc4a0d717
830
cpp
C++
src/model.cpp
blagodarin/playground3d
69e251807dbcf6e311f200583e9cc5d5f320b7af
[ "Apache-2.0" ]
null
null
null
src/model.cpp
blagodarin/playground3d
69e251807dbcf6e311f200583e9cc5d5f320b7af
[ "Apache-2.0" ]
null
null
null
src/model.cpp
blagodarin/playground3d
69e251807dbcf6e311f200583e9cc5d5f320b7af
[ "Apache-2.0" ]
null
null
null
// This file is part of Playground3D. // Copyright (C) Sergei Blagodarin. // SPDX-License-Identifier: Apache-2.0 #include "model.hpp" #include <yttrium/geometry/matrix.h> #include <yttrium/renderer/material.h> #include <yttrium/renderer/mesh.h> #include <yttrium/renderer/modifiers.h> #include <yttrium/renderer/pass.h> #include <yttrium/renderer/resource_loader.h> Model::Model(Yt::ResourceLoader& resource_loader, std::string_view mesh, std::string_view material) : _mesh{ resource_loader.load_mesh(mesh) } , _material{ resource_loader.load_material(material) } { } Model::~Model() = default; void Model::draw(Yt::RenderPass& pass) { Yt::PushMaterial material{ pass, _material.get() }; material.set_uniform("u_model", pass.model_matrix()); material.set_uniform("u_mvp", pass.full_matrix()); pass.draw_mesh(*_mesh); }
28.62069
99
0.751807
[ "mesh", "geometry", "model" ]
3879123391083d50be0ff965f7234f7dea4c0114
3,485
cc
C++
src/path_team_test.cc
joy13975/elfin-solver
dac70d97beed208191fbb0e6a5139f68f8362755
[ "MIT" ]
null
null
null
src/path_team_test.cc
joy13975/elfin-solver
dac70d97beed208191fbb0e6a5139f68f8362755
[ "MIT" ]
35
2018-12-11T11:58:36.000Z
2019-09-08T06:10:47.000Z
src/path_team_test.cc
joy13975/elfin-solver
dac70d97beed208191fbb0e6a5139f68f8362755
[ "MIT" ]
null
null
null
#include "path_team.h" #include "test_data.h" #include "test_stat.h" #include "input_manager.h" #include "path_generator.h" #include "scoring.h" namespace elfin { /* tests */ TestStat PathTeam::test() { TestStat ts; auto construction_test = [&](std::string const & spec_file, tests::Recipe const & recipe) { // Load the spec file so we have a criterion to score against. InputManager::setup_test({"--spec_file", spec_file}); Spec const spec(OPTIONS); TRACE_NOMSG(spec.work_packages().size() != 1); auto& wp = *begin(spec.work_packages()); TRACE_NOMSG(wp->n_work_area_keys() != 1); auto& wv = wp->work_area_keys(); TRACE_NOMSG(wv.size() != 1); auto& wa = wv.at(0); PathTeam team(wa, OPTIONS.seed); team.implement_recipe(recipe); size_t const n_free_terms = team.free_terms_.size(); TRACE(n_free_terms != 2, "%zu\n", n_free_terms); ts.tests++; float const score = team.score(); if (not scoring::almost_eq(score, 0)) { ts.errors++; JUtil.error("PathTeam construction test of %s failed.\n" "Expected score 0\nGot score: %f\n", spec_file.c_str(), score); auto const& const_points = team.gen_path().collect_points(); std::ostringstream const_oss; const_oss << "Constructed points:\n"; auto team_pg = team.gen_path(); while (not team_pg.is_done()) { const_oss << *team_pg.next() << "\n"; } JUtil.error(const_oss.str().c_str()); std::ostringstream inp_oss; auto const& [ui_key, inp_points] = *begin(wa->path_map); inp_oss << "Spec module point:\n"; for (auto& p : inp_points) { inp_oss << p << "\n"; } JUtil.error(inp_oss.str().c_str()); } }; // Short construction test. construction_test("examples/quarter_snake_free.json", tests::QUARTER_SNAKE_FREE_RECIPE); // Long construction test. construction_test("examples/half_snake_free.json", tests::HALF_SNAKE_FREE_RECIPE); // Mutation test. { JUtil.warn("TODO: PathTeam mutation operator tests\n"); } // Checksum test. { ts.tests++; PathTeam team(nullptr, OPTIONS.seed); // Don't call the public implement_recipe() because that in turn calls // calc_score(), which requires non nullptr work_area_. team.virtual_implement_recipe(tests::H_1H_RECIPE, FirstLastNodeKeyCallback(), Transform()); team.calc_checksum(); auto const cksm1 = team.checksum(); team.virtual_implement_recipe(tests::H_1H_CHAIN_CHANGED_RECIPE, FirstLastNodeKeyCallback(), Transform()); team.calc_checksum(); auto const cksm2 = team.checksum(); if (cksm1 == cksm2) { ts.errors++; JUtil.error("PathTeam checksum test failed. 0x%x vs 0x%x\n", cksm1, cksm2); } } return ts; } } /* elfin */
31.396396
79
0.52109
[ "transform" ]
387d0361e9bcd476de6ba4e5c446bcaec453c20f
4,797
cpp
C++
app/JniSample/app/src/main/cpp/static_field_tester.cpp
sulewicz/jpp
8d6d694a834faec92314cb0c638636f4f4bda013
[ "MIT" ]
null
null
null
app/JniSample/app/src/main/cpp/static_field_tester.cpp
sulewicz/jpp
8d6d694a834faec92314cb0c638636f4f4bda013
[ "MIT" ]
null
null
null
app/JniSample/app/src/main/cpp/static_field_tester.cpp
sulewicz/jpp
8d6d694a834faec92314cb0c638636f4f4bda013
[ "MIT" ]
null
null
null
#include <jni.h> #include "jpp/jpp.h" extern "C" JNIEXPORT jobject JNICALL Java_org_coderoller_jnisample_testers_StaticFieldTester_setAndGetObjectField(JNIEnv *env, jclass type, jobject o) { jpp::Env jpp_env(env); jpp::Class class_object = jpp_env.wrap(type); jpp::Class field_class = jpp_env.find_class("java/lang/Object"); jpp::Object value_object = jpp_env.wrap(field_class, o); class_object.set("sObject", value_object); auto ret = class_object.get("sObject", field_class); return (jobject) ret; } template<typename Ret> static Ret access_and_modify_field(JNIEnv *env, jclass type, const char *field_name, Ret value) { jpp::Env jpp_env(env); jpp::Class class_object = jpp_env.wrap(type); class_object.set(field_name, value); auto ret = class_object.get<Ret>(field_name); return ret; } extern "C" JNIEXPORT jboolean JNICALL Java_org_coderoller_jnisample_testers_StaticFieldTester_setAndGetBooleanField(JNIEnv *env, jclass type, jboolean b) { return access_and_modify_field(env, type, "sBoolean", b); } extern "C" JNIEXPORT jbyte JNICALL Java_org_coderoller_jnisample_testers_StaticFieldTester_setAndGetByteField(JNIEnv *env, jclass type, jbyte b) { return access_and_modify_field(env, type, "sByte", b); } extern "C" JNIEXPORT jchar JNICALL Java_org_coderoller_jnisample_testers_StaticFieldTester_setAndGetCharField(JNIEnv *env, jclass type, jchar c) { return access_and_modify_field(env, type, "sChar", c); } extern "C" JNIEXPORT jshort JNICALL Java_org_coderoller_jnisample_testers_StaticFieldTester_setAndGetShortField(JNIEnv *env, jclass type, jshort s) { return access_and_modify_field(env, type, "sShort", s); } extern "C" JNIEXPORT jint JNICALL Java_org_coderoller_jnisample_testers_StaticFieldTester_setAndGetIntField(JNIEnv *env, jclass type, jint i) { return access_and_modify_field(env, type, "sInt", i); } extern "C" JNIEXPORT jlong JNICALL Java_org_coderoller_jnisample_testers_StaticFieldTester_setAndGetLongField(JNIEnv *env, jclass type, jlong l) { return access_and_modify_field(env, type, "sLong", l); } extern "C" JNIEXPORT jfloat JNICALL Java_org_coderoller_jnisample_testers_StaticFieldTester_setAndGetFloatField(JNIEnv *env, jclass type, jfloat f) { return access_and_modify_field(env, type, "sFloat", f); } extern "C" JNIEXPORT jdouble JNICALL Java_org_coderoller_jnisample_testers_StaticFieldTester_setAndGetDoubleField(JNIEnv *env, jclass type, jdouble d) { return access_and_modify_field(env, type, "sDouble", d); } extern "C" JNIEXPORT jobjectArray JNICALL Java_org_coderoller_jnisample_testers_StaticFieldTester_setAndGetObjectArrayField(JNIEnv *env, jclass type, jobjectArray o) { jpp::Env jpp_env(env); jpp::Class class_object = jpp_env.wrap(type); jpp::Class field_class = jpp_env.find_array_class("java/lang/Object"); jpp::Object value_object = jpp_env.wrap(field_class, o); class_object.set("sObjectArray", value_object); auto ret = (jpp::Array<jpp::Object>) class_object.get("sObjectArray", field_class); return (jobjectArray) ret.create_local_ref(); } extern "C" JNIEXPORT jbyteArray JNICALL Java_org_coderoller_jnisample_testers_StaticFieldTester_setAndGetByteArrayField(JNIEnv *env, jclass type, jbyteArray b) { jpp::Env jpp_env(env); jpp::Class class_object = jpp_env.wrap(type); jpp::Class field_class = jpp_env.find_array_class<jbyte>(); jpp::Object value_object = jpp_env.wrap(field_class, b); class_object.set("sByteArray", value_object); auto ret = (jpp::Array<jbyte>) class_object.get("sByteArray", field_class); return (jbyteArray) ret.create_local_ref(); }
42.830357
101
0.592037
[ "object" ]
38833244c998cd6ff8ca49464a75b739197d563a
2,886
hpp
C++
Code/Engine/UI/WidgetGroup.hpp
ntaylorbishop/Copycat
c02f2881f0700a33a2630fd18bc409177d80b8cd
[ "MIT" ]
2
2017-10-02T03:18:55.000Z
2018-11-21T16:30:36.000Z
Code/Engine/UI/WidgetGroup.hpp
ntaylorbishop/Copycat
c02f2881f0700a33a2630fd18bc409177d80b8cd
[ "MIT" ]
null
null
null
Code/Engine/UI/WidgetGroup.hpp
ntaylorbishop/Copycat
c02f2881f0700a33a2630fd18bc409177d80b8cd
[ "MIT" ]
null
null
null
#pragma once #include "Engine/General/Core/EngineCommon.hpp" #include "Engine/EventSystem/NamedProperties.hpp" #include "Engine/UI/Utils/UISystemEnums.hpp" #include "ThirdParty/Parsers/xmlParser.h" class WidgetBase; class WidgetGroup { public: //CREATION static void CreateWidgetGroupFromXML(const XMLNode& widgetGroupNode, WidgetGroup* parentWidgetGroup); //STRUCTORS WidgetGroup(const XMLNode& widgetGroupNode, WidgetGroup* parentWidgetGroup); WidgetGroup() = default; ~WidgetGroup(); //WIDGETS void AddWidget(WidgetBase* newWidget) { m_widgets.push_back(newWidget); } //UPDATE RENDER void Update(float deltaSeconds); void Render() const; private: //GET PROPERTY template <typename T> bool GetProperty(const String& propertyName, eWidgetState widgetState, T& outProperty) const; bool m_isHidden = false; std::vector<WidgetBase*> m_widgets; String m_widgetGroupName; std::map<eWidgetState, NamedProperties*> m_groupProperties; friend class WidgetBase; friend class RadioWidget; }; ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //TYPEDEFS ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// typedef std::map<eWidgetState, NamedProperties*>::const_iterator WidgetGroupPropertiesMapConstIterator; typedef std::map<eWidgetState, NamedProperties*>::iterator WidgetGroupPropertiesMapIterator; typedef std::pair<eWidgetState, NamedProperties*> WidgetGroupPropertiesMapPair; ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //GET PROPERTY ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //--------------------------------------------------------------------------------------------------------------------------- //GET PROPERTY template <typename T> bool WidgetGroup::GetProperty(const String& propertyName, eWidgetState widgetState, T& outProperty) const { WidgetGroupPropertiesMapConstIterator propertiesIt = m_groupProperties.find(widgetState); if (propertiesIt != m_groupProperties.end()) { NamedProperties* stateSpecificProperties = propertiesIt->second; ePropertyGetResult didGetProperty = stateSpecificProperties->GetProperty(propertyName, outProperty); if (didGetProperty == PGR_SUCCESS) { return true; } } propertiesIt = m_groupProperties.find(WIDGET_STATE_DEFAULT); ASSERT_OR_DIE(propertiesIt != m_groupProperties.end(), "ERROR: No default properties defined for WidgetGroup."); NamedProperties* defaultProperties = propertiesIt->second; ePropertyGetResult didGetProperty = defaultProperties->GetProperty(propertyName, outProperty); if (didGetProperty == PGR_SUCCESS) { return true; } return false; }
33.952941
125
0.620929
[ "render", "vector" ]